Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Accounts updated subscription #302

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 39 additions & 10 deletions backend-rust/src/graphql_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ use prometheus_client::registry::Registry;
use sqlx::{postgres::types::PgInterval, PgPool};
use std::{error::Error, str::FromStr, sync::Arc};
use tokio::{net::TcpListener, sync::broadcast};
use tokio_stream::wrappers::errors::BroadcastStreamRecvError;
use tokio_util::sync::CancellationToken;
use transaction_metrics::TransactionMetricsQuery;

Expand Down Expand Up @@ -997,42 +998,56 @@ LIMIT 30", // WHERE slot_time > (LOCALTIMESTAMP - $1::interval)
}

pub struct Subscription {
pub block_added: broadcast::Receiver<Arc<Block>>,
pub block_added: broadcast::Receiver<Block>,
pub accounts_updated: broadcast::Receiver<AccountsUpdatedSubscriptionItem>,
}

impl Subscription {
pub fn new() -> (Self, SubscriptionContext) {
let (block_added_sender, block_added) = broadcast::channel(100);
let (accounts_updated_sender, accounts_updated) = broadcast::channel(100);
(
Subscription {
block_added,
accounts_updated,
},
SubscriptionContext {
block_added_sender,
accounts_updated_sender,
},
)
}
}

#[Subscription]
impl Subscription {
async fn block_added(
&self,
) -> impl Stream<Item = Result<Arc<Block>, tokio_stream::wrappers::errors::BroadcastStreamRecvError>>
{
async fn block_added(&self) -> impl Stream<Item = Result<Block, BroadcastStreamRecvError>> {
tokio_stream::wrappers::BroadcastStream::new(self.block_added.resubscribe())
}

async fn accounts_updated(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The query at the front-end includes an additional accountAddress query variable:


{
    "id": "1",
    "type": "start",
    "payload": {
        "key": "...",
        "query": "subscription accountsUpdatedSubscription($accountAddress: String!) {\n  accountsUpdated(accountAddress: $accountAddress) {\n    address\n  }\n}",
        "variables": {
            "accountAddress": "4dT5vPrnnpwVrXZgmYLtHrDLvBYhtzheaK4fDWbJewqRCGQKWz"
        },
        "context": {
            "url": "https://api-ccdscan.testnet.concordium.com/graphql",
            "preferGetMethod": false,
            "suspense": false,
            "requestPolicy": "cache-first",
            "meta": {
                "cacheOutcome": "miss"
            }
        }
    }
}

Copy link
Contributor Author

@Victor-N-Suadicani Victor-N-Suadicani Nov 22, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right - but what am I supposed to do with that input string? 🤔

In the C# code, it seems it's the "topic" of the subscription? Not sure what that means.

public class Subscription
{
    [Subscribe]
    [Topic("{accountAddress}")]
    public AccountsUpdatedSubscriptionItem AccountsUpdated(
        string accountAddress, 
        [EventMessage] AccountsUpdatedSubscriptionItem message) => message;

    [Subscribe]
    public Block BlockAdded([EventMessage] Block block) => block;
}

&self,
) -> impl Stream<Item = Result<AccountsUpdatedSubscriptionItem, BroadcastStreamRecvError>> {
tokio_stream::wrappers::BroadcastStream::new(self.accounts_updated.resubscribe())
}
}

pub struct SubscriptionContext {
block_added_sender: broadcast::Sender<Arc<Block>>,
block_added_sender: broadcast::Sender<Block>,
accounts_updated_sender: broadcast::Sender<AccountsUpdatedSubscriptionItem>,
}

impl SubscriptionContext {
const ACCOUNTS_UPDATED_CHANNEL: &'static str = "accounts_updated";
const BLOCK_ADDED_CHANNEL: &'static str = "block_added";

pub async fn listen(self, pool: PgPool, stop_signal: CancellationToken) -> anyhow::Result<()> {
let mut listener = sqlx::postgres::PgListener::connect_with(&pool)
.await
.context("Failed to create a postgreSQL listener")?;

listener
.listen_all([Self::BLOCK_ADDED_CHANNEL])
.listen_all([Self::BLOCK_ADDED_CHANNEL, Self::ACCOUNTS_UPDATED_CHANNEL])
.await
.context("Failed to listen to postgreSQL notifications")?;

Expand All @@ -1045,22 +1060,36 @@ impl SubscriptionContext {
let block_height = BlockHeight::from_str(notification.payload())
.context("Failed to parse payload of block added")?;
let block = Block::query_by_height(&pool, block_height).await?;
self.block_added_sender.send(Arc::new(block))?;
self.block_added_sender.send(block)?;
}

Self::ACCOUNTS_UPDATED_CHANNEL => {
self.accounts_updated_sender.send(AccountsUpdatedSubscriptionItem {
address: notification.payload().to_string(),
})?;
}

unknown => {
anyhow::bail!("Unknown channel {}", unknown);
anyhow::bail!("Received notification on unknown channel: {unknown}");
}
}
}
})
.await;

if let Some(result) = exit {
result.context("Failed listening")?;
}

Ok(())
}
}

#[derive(Clone, Debug, SimpleObject)]
pub struct AccountsUpdatedSubscriptionItem {
address: String,
}

/// The UnsignedLong scalar type represents a unsigned 64-bit numeric
/// non-fractional value greater than or equal to 0.
#[derive(
Expand Down Expand Up @@ -1214,7 +1243,7 @@ struct Versions {
backend_versions: String,
}

#[derive(Debug, sqlx::FromRow)]
#[derive(Debug, Clone, sqlx::FromRow)]
pub struct Block {
hash: BlockHash,
height: BlockHeight,
Expand Down