diff --git a/Cargo.lock b/Cargo.lock index 21699b4046d..5f7a17f65e6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1290,34 +1290,6 @@ dependencies = [ "num-traits", ] -[[package]] -name = "arrow-flight" -version = "59.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68365401e834743d708094927e2ca727a32d639fe900df04b936e07a36701b74" -dependencies = [ - "arrow-arith", - "arrow-array", - "arrow-buffer", - "arrow-cast", - "arrow-data", - "arrow-ipc", - "arrow-ord", - "arrow-row", - "arrow-schema", - "arrow-select", - "arrow-string", - "base64", - "bytes", - "futures 0.3.31", - "once_cell", - "paste", - "prost", - "prost-types", - "tonic", - "tonic-prost", -] - [[package]] name = "arrow-ipc" version = "59.0.0" @@ -3837,7 +3809,6 @@ dependencies = [ "tempfile", "thiserror 2.0.18", "tokio", - "tokio-util", "tower 0.5.2", "url", "walkdir", @@ -3849,11 +3820,8 @@ name = "graph" version = "0.45.0" dependencies = [ "Inflector", - "ahash", "alloy", "anyhow", - "arrow", - "arrow-flight", "async-stream", "async-trait", "atomic_refcell", @@ -3874,7 +3842,6 @@ dependencies = [ "futures 0.3.31", "graph_derive", "graphql-tools", - "half", "hex", "hex-literal", "http 0.2.12", @@ -3884,7 +3851,6 @@ dependencies = [ "hyper-util", "indoc", "itertools 0.15.0", - "lazy-regex", "lazy_static", "lru_time_cache", "maplit", @@ -3916,8 +3882,7 @@ dependencies = [ "slog-async", "slog-envlogger", "slog-term", - "sqlparser 0.57.0", - "sqlparser 0.62.0", + "sqlparser", "stable-hash 0.3.4", "stable-hash 0.4.4", "strum_macros 0.28.0", @@ -3926,7 +3891,6 @@ dependencies = [ "tokio", "tokio-retry", "tokio-stream", - "tokio-util", "toml 1.1.2+spec-1.1.0", "tonic", "tonic-prost", @@ -3995,26 +3959,19 @@ version = "0.45.0" dependencies = [ "alloy", "anyhow", - "arrow", "async-trait", "bytes", - "chrono", - "futures 0.3.31", "graph", "graph-chain-ethereum", "graph-chain-near", "graph-runtime-wasm", - "indoc", "itertools 0.15.0", "parking_lot", - "prometheus", "serde_yaml", "slog", - "strum 0.28.0", "thiserror 2.0.18", "tokio", "tokio-retry", - "tokio-util", "tower 0.5.3", "tower-test", "wiremock", @@ -4068,7 +4025,6 @@ dependencies = [ "shellexpand", "termcolor", "tokio", - "tokio-util", "url", ] @@ -4192,7 +4148,7 @@ dependencies = [ "serde", "serde_json", "serde_yaml", - "sqlparser 0.62.0", + "sqlparser", "stable-hash 0.3.4", "thiserror 2.0.18", "tokio", @@ -4222,7 +4178,6 @@ dependencies = [ "slog-term", "tokio", "tokio-stream", - "tokio-util", ] [[package]] @@ -5225,29 +5180,6 @@ dependencies = [ "libc", ] -[[package]] -name = "lazy-regex" -version = "3.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6bae91019476d3ec7147de9aa291cadb6d870abf2f3015d2da73a90325ac1496" -dependencies = [ - "lazy-regex-proc_macros", - "once_cell", - "regex", -] - -[[package]] -name = "lazy-regex-proc_macros" -version = "3.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4de9c1e1439d8b7b3061b2d209809f447ca33241733d9a3c01eabf2dc8d94358" -dependencies = [ - "proc-macro2", - "quote", - "regex", - "syn 2.0.118", -] - [[package]] name = "lazy_static" version = "1.5.0" @@ -7879,17 +7811,6 @@ dependencies = [ "der", ] -[[package]] -name = "sqlparser" -version = "0.57.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07c5f081b292a3d19637f0b32a79e28ff14a9fd23ef47bd7fce08ff5de221eca" -dependencies = [ - "log", - "recursive", - "sqlparser_derive 0.3.0", -] - [[package]] name = "sqlparser" version = "0.62.0" @@ -7898,18 +7819,7 @@ checksum = "13c6d1b651dc4edf07eead2a0c6c78016ce971bc2c10da5266861b13f25e7cec" dependencies = [ "log", "recursive", - "sqlparser_derive 0.5.0", -] - -[[package]] -name = "sqlparser_derive" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da5fc6819faabb412da764b99d3b713bb55083c11e7e0c00144d386cd6a1939c" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.118", + "sqlparser_derive", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index a956a514a95..7fbe10a6d19 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -116,21 +116,13 @@ tower = { version = "0.5.1", features = ["full"] } wasmparser = "0.118.1" wasmtime = { version = "46.0.0", features = ["async"] } rand = { version = "0.9.2", features = ["os_rng"] } -prometheus = "0.14.0" url = "2.5.8" -# Dependencies related to Amp subgraphs -ahash = "0.8.11" arrow = { version = "=59.0.0" } -arrow-flight = { version = "=59.0.0", features = ["flight-sql-experimental"] } parquet = { version = "=59.0.0" } futures = "0.3.31" -half = "2.7.1" indoc = "2.0.7" -lazy-regex = "3.6.0" parking_lot = "0.12.4" -sqlparser-latest = { version = "0.57.0", package = "sqlparser", features = ["visitor"] } -tokio-util = "0.7.15" [workspace.lints.clippy] too_many_arguments = "allow" diff --git a/chain/ethereum/src/runtime/runtime_adapter.rs b/chain/ethereum/src/runtime/runtime_adapter.rs index a5d68a761a7..7ff79ab0e97 100644 --- a/chain/ethereum/src/runtime/runtime_adapter.rs +++ b/chain/ethereum/src/runtime/runtime_adapter.rs @@ -180,7 +180,6 @@ impl blockchain::RuntimeAdapter for RuntimeAdapter { create_host_fns(abis, archive, call_cache, eth_adapters, eth_call_gas) } data_source::DataSource::Offchain(_) => vec![], - data_source::DataSource::Amp(_) => vec![], }; Ok(host_fns) diff --git a/core/Cargo.toml b/core/Cargo.toml index a4b38367213..a5713eda1d5 100644 --- a/core/Cargo.toml +++ b/core/Cargo.toml @@ -18,18 +18,10 @@ tower = { git = "https://github.com/tower-rs/tower.git", features = ["full"] } thiserror = { workspace = true } anyhow = "1.0" -# Dependencies related to Amp subgraphs alloy.workspace = true -arrow.workspace = true -chrono.workspace = true -futures.workspace = true -indoc.workspace = true itertools.workspace = true parking_lot.workspace = true -prometheus.workspace = true slog.workspace = true -strum.workspace = true -tokio-util.workspace = true [dev-dependencies] tower-test = { git = "https://github.com/tower-rs/tower.git" } diff --git a/core/src/amp_subgraph/manager.rs b/core/src/amp_subgraph/manager.rs deleted file mode 100644 index 61ec421ca17..00000000000 --- a/core/src/amp_subgraph/manager.rs +++ /dev/null @@ -1,171 +0,0 @@ -use std::sync::Arc; - -use alloy::primitives::BlockNumber; -use anyhow::Context; -use async_trait::async_trait; -use graph::{ - amp, - components::{ - link_resolver::{LinkResolver, LinkResolverContext}, - metrics::MetricsRegistry, - store::{DeploymentLocator, SubgraphStore}, - subgraph::SubgraphInstanceManager, - }, - env::EnvVars, - log::factory::LoggerFactory, - prelude::CheapClone, -}; -use slog::{debug, error}; -use tokio_util::sync::CancellationToken; - -use super::{Metrics, Monitor, runner}; - -/// Manages Amp subgraph runner futures. -/// -/// Creates and schedules Amp subgraph runner futures for execution on demand. -/// Also handles stopping previously started Amp subgraph runners. -pub struct Manager { - logger_factory: LoggerFactory, - metrics_registry: Arc, - env_vars: Arc, - monitor: Monitor, - subgraph_store: Arc, - link_resolver: Arc, - amp_client: Arc, -} - -impl Manager -where - SS: SubgraphStore, - NC: amp::Client, -{ - /// Creates a new Amp subgraph manager. - pub fn new( - logger_factory: &LoggerFactory, - metrics_registry: Arc, - env_vars: Arc, - cancel_token: &CancellationToken, - subgraph_store: Arc, - link_resolver: Arc, - amp_client: Arc, - ) -> Self { - let logger = logger_factory.component_logger("AmpSubgraphManager", None); - let logger_factory = logger_factory.with_parent(logger); - - let monitor = Monitor::new(&logger_factory, cancel_token); - - Self { - logger_factory, - metrics_registry, - env_vars, - monitor, - subgraph_store, - link_resolver, - amp_client, - } - } -} - -#[async_trait] -impl SubgraphInstanceManager for Manager -where - SS: SubgraphStore, - NC: amp::Client + Send + Sync + 'static, -{ - async fn start_subgraph( - self: Arc, - deployment: DeploymentLocator, - stop_block: Option, - ) { - let manager = self.cheap_clone(); - - self.monitor.start( - deployment.cheap_clone(), - Box::new(move |cancel_token| { - Box::pin(async move { - let logger = manager.logger_factory.subgraph_logger(&deployment); - - let store = manager - .subgraph_store - .cheap_clone() - .writable(logger.cheap_clone(), deployment.id, Vec::new().into()) - .await - .context("failed to create writable store")?; - - let metrics = Metrics::new( - &logger, - manager.metrics_registry.cheap_clone(), - store.cheap_clone(), - deployment.hash.cheap_clone(), - ); - - let link_resolver = manager - .link_resolver - .for_manifest(&deployment.hash.to_string()) - .context("failed to create link resolver")?; - - let manifest_bytes = link_resolver - .cat( - &LinkResolverContext::new(&deployment.hash, &logger), - &deployment.hash.to_ipfs_link(), - ) - .await - .context("failed to load subgraph manifest")?; - - let raw_manifest = serde_yaml::from_slice(&manifest_bytes) - .context("failed to parse subgraph manifest")?; - - let mut manifest = amp::Manifest::resolve::( - &logger, - manager.link_resolver.cheap_clone(), - manager.amp_client.cheap_clone(), - manager.env_vars.max_spec_version.cheap_clone(), - deployment.hash.cheap_clone(), - raw_manifest, - ) - .await?; - - if let Some(stop_block) = stop_block { - for data_source in manifest.data_sources.iter_mut() { - data_source.source.end_block = stop_block as BlockNumber; - } - } - - store - .start_subgraph_deployment(&logger) - .await - .context("failed to start subgraph deployment")?; - - let runner_context = runner::Context::new( - &logger, - &manager.env_vars.amp, - manager.amp_client.cheap_clone(), - store, - deployment.hash.cheap_clone(), - manifest, - metrics, - ); - - let runner_result = runner::new_runner(runner_context, cancel_token).await; - - match manager.subgraph_store.stop_subgraph(&deployment).await { - Ok(()) => { - debug!(logger, "Subgraph writer stopped"); - } - Err(e) => { - error!(logger, "Failed to stop subgraph writer"; - "e" => ?e - ); - } - } - - runner_result - }) - }), - ); - } - - async fn stop_subgraph(&self, deployment: DeploymentLocator) { - self.monitor.stop(deployment); - } -} diff --git a/core/src/amp_subgraph/metrics.rs b/core/src/amp_subgraph/metrics.rs deleted file mode 100644 index 7088cf9a48f..00000000000 --- a/core/src/amp_subgraph/metrics.rs +++ /dev/null @@ -1,267 +0,0 @@ -use std::{sync::Arc, time::Duration}; - -use alloy::primitives::BlockNumber; -use graph::{ - cheap_clone::CheapClone, - components::{ - metrics::{MetricsRegistry, stopwatch::StopwatchMetrics}, - store::WritableStore, - }, - prelude::DeploymentHash, -}; -use indoc::indoc; -use prometheus::{IntCounter, IntGauge}; -use slog::Logger; - -/// Contains metrics specific to a deployment. -pub(super) struct Metrics { - pub(super) deployment_status: DeploymentStatus, - pub(super) deployment_head: DeploymentHead, - pub(super) deployment_target: DeploymentTarget, - pub(super) deployment_synced: DeploymentSynced, - pub(super) indexing_duration: IndexingDuration, - pub(super) blocks_processed: BlocksProcessed, - pub(super) stopwatch: StopwatchMetrics, -} - -impl Metrics { - /// Creates new deployment specific metrics. - pub(super) fn new( - logger: &Logger, - metrics_registry: Arc, - store: Arc, - deployment: DeploymentHash, - ) -> Self { - let stopwatch = StopwatchMetrics::new( - logger.cheap_clone(), - deployment.cheap_clone(), - "process", - metrics_registry.cheap_clone(), - store.shard().to_string(), - ); - - let const_labels = [ - ("deployment", deployment.to_string()), - ("shard", store.shard().to_string()), - ]; - - Self { - deployment_status: DeploymentStatus::new(&metrics_registry, const_labels.clone()), - deployment_head: DeploymentHead::new(&metrics_registry, const_labels.clone()), - deployment_target: DeploymentTarget::new(&metrics_registry, const_labels.clone()), - deployment_synced: DeploymentSynced::new(&metrics_registry, const_labels.clone()), - indexing_duration: IndexingDuration::new(&metrics_registry, const_labels.clone()), - blocks_processed: BlocksProcessed::new(&metrics_registry, const_labels.clone()), - stopwatch, - } - } -} - -/// Reports the current indexing status of a deployment. -pub(super) struct DeploymentStatus(IntGauge); - -impl DeploymentStatus { - const STATUS_STARTING: i64 = 1; - const STATUS_RUNNING: i64 = 2; - const STATUS_STOPPED: i64 = 3; - const STATUS_FAILED: i64 = 4; - - fn new( - metrics_registry: &MetricsRegistry, - const_labels: impl IntoIterator, - ) -> Self { - let int_gauge = metrics_registry - .new_int_gauge( - "deployment_status", - indoc!( - " - Indicates the current indexing status of a deployment. - Possible values: - 1 - graph-node is preparing to start indexing; - 2 - deployment is being indexed; - 3 - indexing is stopped by request; - 4 - indexing failed; - " - ), - const_labels, - ) - .expect("failed to register `deployment_status` gauge"); - - Self(int_gauge) - } - - /// Records that the graph-node is preparing to start indexing. - pub fn starting(&self) { - self.0.set(Self::STATUS_STARTING); - } - - /// Records that the deployment is being indexed. - pub fn running(&self) { - self.0.set(Self::STATUS_RUNNING); - } - - /// Records that the indexing stopped by request. - pub fn stopped(&self) { - self.0.set(Self::STATUS_STOPPED); - } - - /// Records that the indexing failed. - pub fn failed(&self) { - self.0.set(Self::STATUS_FAILED); - } -} - -/// Tracks the most recent block number processed by a deployment. -pub(super) struct DeploymentHead(IntGauge); - -impl DeploymentHead { - fn new( - metrics_registry: &MetricsRegistry, - const_labels: impl IntoIterator, - ) -> Self { - let int_gauge = metrics_registry - .new_int_gauge( - "deployment_head", - "Tracks the most recent block number processed by a deployment", - const_labels - .into_iter() - .map(|(k, v)| (k.to_string(), v.to_string())) - // TODO: Pass the network from the Amp manifest - .chain([("network".to_string(), "".to_string())]), - ) - .expect("failed to register `deployment_head` gauge"); - - Self(int_gauge) - } - - /// Updates the most recent block number processed by this deployment. - pub(super) fn update(&self, new_most_recent_block_number: BlockNumber) { - self.0.set( - i64::try_from(new_most_recent_block_number) - .expect("new most recent block number does not fit into `i64`"), - ); - } -} - -/// Tracks the maximum block number currently available for indexing within a deployment. -pub(super) struct DeploymentTarget(IntGauge); - -impl DeploymentTarget { - fn new( - metrics_registry: &MetricsRegistry, - const_labels: impl IntoIterator, - ) -> Self { - let int_gauge = metrics_registry - .new_int_gauge( - "deployment_target", - "Tracks the maximum block number currently available for indexing within a deployment", - const_labels, - ) - .expect("failed to register `amp_deployment_target` gauge"); - - Self(int_gauge) - } - - /// Updates the target block number of this deployment. - pub(super) fn update(&self, new_target_block_number: BlockNumber) { - self.0.set( - i64::try_from(new_target_block_number) - .expect("new target block number does not fit into `i64`"), - ); - } -} - -/// Indicates whether a deployment has reached the chain head or the end block since it was deployed. -pub(super) struct DeploymentSynced(IntGauge); - -impl DeploymentSynced { - const NOT_SYNCED: i64 = 0; - const SYNCED: i64 = 1; - - pub fn new( - metrics_registry: &MetricsRegistry, - const_labels: impl IntoIterator, - ) -> Self { - let int_gauge = metrics_registry - .new_int_gauge( - "deployment_synced", - indoc!( - " - Indicates whether a deployment has reached the chain head or the end block since it was deployed. - Possible values: - 0 - deployment is not synced; - 1 - deployment is synced; - " - ), - const_labels, - ) - .expect("failed to register `deployment_synced` gauge"); - - Self(int_gauge) - } - - /// Records the current sync status of this deployment. - pub fn record(&self, synced: bool) { - self.0.set(if synced { - Self::SYNCED - } else { - Self::NOT_SYNCED - }); - } -} - -/// Tracks the total duration in seconds of deployment indexing. -#[derive(Clone)] -pub(super) struct IndexingDuration(IntCounter); - -impl IndexingDuration { - fn new( - metrics_registry: &MetricsRegistry, - const_labels: impl IntoIterator, - ) -> Self { - let int_counter = metrics_registry - .new_int_counter( - "deployment_indexing_duration_seconds", - "Tracks the total duration in seconds of deployment indexing", - const_labels, - ) - .expect("failed to register `amp_deployment_indexing_duration_seconds` counter"); - - Self(int_counter) - } - - /// Records a new indexing duration of this deployment. - pub(super) fn record(&self, duration: Duration) { - self.0.inc_by(duration.as_secs()) - } -} - -/// Tracks the total number of blocks processed by a deployment. -pub(super) struct BlocksProcessed(IntCounter); - -impl BlocksProcessed { - fn new( - metrics_registry: &MetricsRegistry, - const_labels: impl IntoIterator, - ) -> Self { - let int_counter = metrics_registry - .new_int_counter( - "deployment_blocks_processed_count", - "Tracks the total number of blocks processed by a deployment", - const_labels, - ) - .expect("failed to register `deployment_blocks_processed_count` counter"); - - Self(int_counter) - } - - /// Records a new processed block. - pub(super) fn record_one(&self) { - self.record(1); - } - - /// Records the new processed blocks. - pub(super) fn record(&self, number_of_blocks_processed: usize) { - self.0.inc_by(number_of_blocks_processed as u64); - } -} diff --git a/core/src/amp_subgraph/mod.rs b/core/src/amp_subgraph/mod.rs deleted file mode 100644 index 3d3846742aa..00000000000 --- a/core/src/amp_subgraph/mod.rs +++ /dev/null @@ -1,8 +0,0 @@ -mod manager; -mod metrics; -mod monitor; -mod runner; - -use self::{metrics::Metrics, monitor::Monitor}; - -pub use self::manager::Manager; diff --git a/core/src/amp_subgraph/monitor.rs b/core/src/amp_subgraph/monitor.rs deleted file mode 100644 index 314f464c0d1..00000000000 --- a/core/src/amp_subgraph/monitor.rs +++ /dev/null @@ -1,563 +0,0 @@ -//! This module is responsible for executing subgraph runner futures. -//! -//! # Terminology used in this module -//! -//! `active subgraph` - A subgraph that was started and is still kept in memory in the list of started subgraphs. -//! `running subgraph` - A subgraph that has an instance that is making progress or stopping. -//! `subgraph instance` - A background task that executes the subgraph runner future. - -use std::{ - collections::{HashMap, hash_map::Entry}, - fmt, - sync::{ - Arc, - atomic::{AtomicU32, Ordering::SeqCst}, - }, - time::Duration, -}; - -use anyhow::Result; -use futures::future::BoxFuture; -use graph::{ - cheap_clone::CheapClone, components::store::DeploymentLocator, log::factory::LoggerFactory, -}; -use slog::{Logger, debug, error, info, warn}; -use tokio::{ - sync::mpsc::{self, error::SendError}, - task::JoinHandle, - time::timeout, -}; -use tokio_util::sync::CancellationToken; - -/// Represents the maximum amount of time a subgraph instance is allowed to run -/// after it receives a cancel signal. -/// -/// If a subgraph instance does not complete its execution in this amount of time -/// it is considered unresponsive and is aborted. -const SUBGRAPH_INSTANCE_GRACE_PERIOD: Duration = { - if cfg!(test) { - Duration::from_millis(300) - } else if cfg!(debug_assertions) { - Duration::from_secs(30) - } else { - Duration::from_secs(300) - } -}; - -/// Represents the subgraph runner future. -/// -/// This is the future that performs the subgraph indexing. -/// It is expected to return only on deterministic failures or when indexing is completed. -/// All retry functionality must be handled internally by this future. -pub(super) type BoxRunner = - Box BoxFuture<'static, Result<()>> + Send + 'static>; - -/// Manages the lifecycle of subgraph runners. -/// -/// Ensures that there is at most one subgraph instance running -/// for any subgraph deployment at any point in time. -/// Handles starting, stopping and restarting subgraphs. -pub(super) struct Monitor { - logger_factory: Arc, - - /// Every subgraph instance is assigned a cancel token derived from this token. - /// - /// This means that the `Monitor` can send cancel signals to all subgraph instances at once, - /// and to each subgraph instance individually. - cancel_token: CancellationToken, - - /// The channel that is used to send subgraph commands. - /// - /// Every subgraph start and stop request results in a command that is sent to the - /// background task that manages the subgraph instances. - command_tx: mpsc::UnboundedSender, - - /// When a subgraph starts it is assigned a sequential ID. - /// The ID is then kept in memory in the list of active subgraphs. - /// - /// When the subgraph completes execution it should be removed from the - /// list of active subgraphs, so that it can be restarted. - /// - /// This ID is required to be able to check if the active subgraph - /// is the same subgraph instance that was stopped. - /// - /// If the IDs do not match, it means that the subgraph was force restarted, - /// ignoring the state of the previous subgraph instance, or that the subgraph - /// was restarted after the previous subgraph instance completed its execution - /// but before the remove request was processed. - subgraph_instance_id: Arc, -} - -impl Monitor { - /// Creates a new subgraph monitor. - /// - /// Spawns a background task that manages the subgraph start and stop requests. - /// - /// A new cancel token is derived from the `cancel_token` and only the derived token is used by the - /// subgraph monitor and its background task. - pub(super) fn new(logger_factory: &LoggerFactory, cancel_token: &CancellationToken) -> Self { - let logger = logger_factory.component_logger("AmpSubgraphMonitor", None); - let logger_factory = Arc::new(logger_factory.with_parent(logger)); - - // A derived token makes sure it is not possible to accidentally cancel the parent token - let cancel_token = cancel_token.child_token(); - - // It is safe to use an unbounded channel here, because it's pretty much unrealistic that the - // command processor will fall behind so much that the channel buffer will take up all the memory. - // The command processor is non-blocking and delegates long-running processes to detached tasks. - let (command_tx, command_rx) = mpsc::unbounded_channel::(); - - tokio::spawn(Self::command_processor( - logger_factory.cheap_clone(), - cancel_token.cheap_clone(), - command_tx.clone(), - command_rx, - )); - - Self { - logger_factory, - cancel_token, - command_tx, - subgraph_instance_id: Arc::new(AtomicU32::new(0)), - } - } - - /// Starts a subgraph. - /// - /// Sends a subgraph start request to this subgraph monitor that - /// eventually starts the subgraph. - /// - /// # Behaviour - /// - /// - If the subgraph is not active, it starts when the request is processed - /// - If the subgraph is active, it stops, and then restarts - /// - Ensures that there is only one subgraph instance for this subgraph deployment - /// - Multiple consecutive calls in a short time period force restart the subgraph, - /// aborting the active subgraph instance - pub(super) fn start(&self, deployment: DeploymentLocator, runner: BoxRunner) { - let logger = self - .logger_factory - .subgraph_logger(&deployment) - .new(slog::o!("method" => "start")); - - info!(logger, "Starting subgraph"); - log_send_error( - &logger, - self.command_tx.send(Command::Start { - id: self.subgraph_instance_id.fetch_add(1, SeqCst), - deployment, - runner, - }), - ); - } - - /// Stops the subgraph. - /// - /// Sends a subgraph stop request to this subgraph monitor that - /// eventually stops the subgraph. - /// - /// # Behaviour - /// - /// - If the subgraph is not active does nothing - /// - If the subgraph is active, sends a cancel signal that gracefully stops the subgraph - /// - If the subgraph fails to stop after an extended period of time it aborts - pub(super) fn stop(&self, deployment: DeploymentLocator) { - let logger = self - .logger_factory - .subgraph_logger(&deployment) - .new(slog::o!("method" => "stop")); - - info!(logger, "Stopping subgraph"); - log_send_error(&logger, self.command_tx.send(Command::Stop { deployment })); - } - - /// Processes commands sent through the command channel. - /// - /// Tracks active subgraphs and keeps a list of pending start commands. - /// Pending start commands are start commands that execute after the related subgraph stops. - async fn command_processor( - logger_factory: Arc, - cancel_token: CancellationToken, - command_tx: mpsc::UnboundedSender, - mut command_rx: mpsc::UnboundedReceiver, - ) { - let logger = logger_factory.component_logger("CommandProcessor", None); - let mut subgraph_instances: HashMap = HashMap::new(); - let mut pending_start_commands: HashMap = HashMap::new(); - - loop { - tokio::select! { - Some(command) = command_rx.recv() => { - match &command { - Command::Start { .. } => { - Self::process_start_command( - &logger_factory, - &cancel_token, - &mut subgraph_instances, - &mut pending_start_commands, - &command_tx, - command - ); - }, - Command::Stop { .. } => { - Self::process_stop_command( - &logger_factory, - &mut subgraph_instances, - &mut pending_start_commands, - command - ); - }, - Command::Clear { .. } => { - Self::process_clear_command( - &logger_factory, - &mut subgraph_instances, - &mut pending_start_commands, - &command_tx, - command - ); - }, - } - }, - _ = cancel_token.cancelled() => { - debug!(logger, "Stopping command processor"); - - // All active subgraphs will shutdown gracefully - // because their cancel tokens are derived from this cancelled token. - return; - } - } - } - } - - /// Starts a subgraph. - /// - /// # Behaviour - /// - /// - If the subgraph is not active, it starts right away - /// - If the subgraph is active, a cancel signal is sent to the active subgraph instance - /// and this start request is stored in the list of pending start commands - /// - If the subgraph is active and there is already a pending start command, - /// the active subgraph instance aborts, and the subgraph force restarts right away - /// - If the subgraph is active, but its instance is not actually running, - /// the subgraph starts right away - fn process_start_command( - logger_factory: &LoggerFactory, - cancel_token: &CancellationToken, - subgraph_instances: &mut HashMap, - pending_start_commands: &mut HashMap, - command_tx: &mpsc::UnboundedSender, - command: Command, - ) { - let Command::Start { - id, - deployment, - runner, - } = command - else { - unreachable!(); - }; - - let logger = logger_factory.subgraph_logger(&deployment); - let command_logger = logger.new(slog::o!("command" => "start")); - - let cancel_token = cancel_token.child_token(); - let pending_start_command = pending_start_commands.remove(&deployment); - - match subgraph_instances.entry(deployment.cheap_clone()) { - Entry::Vacant(entry) => { - debug!(command_logger, "Subgraph is not active, starting"); - - let subgraph_instance = Self::start_subgraph( - logger, - cancel_token, - id, - deployment, - runner, - command_tx.clone(), - ); - - entry.insert(subgraph_instance); - } - Entry::Occupied(mut entry) => { - let subgraph_instance = entry.get_mut(); - subgraph_instance.cancel_token.cancel(); - - if pending_start_command.is_some() { - debug!(command_logger, "Subgraph is active, force restarting"); - - subgraph_instance.handle.abort(); - - *subgraph_instance = Self::start_subgraph( - logger, - cancel_token, - id, - deployment, - runner, - command_tx.clone(), - ); - - return; - } - - if subgraph_instance.handle.is_finished() { - debug!(command_logger, "Subgraph is not running, starting"); - - *subgraph_instance = Self::start_subgraph( - logger, - cancel_token, - id, - deployment, - runner, - command_tx.clone(), - ); - - return; - } - - debug!(command_logger, "Gracefully restarting subgraph"); - - pending_start_commands.insert( - deployment.cheap_clone(), - Command::Start { - id, - deployment, - runner, - }, - ); - } - } - } - - /// Stops a subgraph. - /// - /// # Behaviour - /// - /// - If the subgraph is not active, does nothing - /// - If the subgraph is active, sends a cancel signal to the active subgraph instance - fn process_stop_command( - logger_factory: &LoggerFactory, - subgraph_instances: &mut HashMap, - pending_start_commands: &mut HashMap, - command: Command, - ) { - let Command::Stop { deployment } = command else { - unreachable!(); - }; - - let logger = logger_factory - .subgraph_logger(&deployment) - .new(slog::o!("command" => "stop")); - - if let Some(subgraph_instance) = subgraph_instances.get(&deployment) { - debug!(logger, "Sending cancel signal"); - subgraph_instance.cancel_token.cancel(); - } else { - debug!(logger, "Subgraph is not active"); - } - - pending_start_commands.remove(&deployment); - } - - /// Removes a subgraph from the list of active subgraphs allowing the subgraph to be restarted. - fn process_clear_command( - logger_factory: &LoggerFactory, - subgraph_instances: &mut HashMap, - pending_start_commands: &mut HashMap, - command_tx: &mpsc::UnboundedSender, - command: Command, - ) { - let Command::Clear { id, deployment } = command else { - unreachable!(); - }; - - let logger = logger_factory - .subgraph_logger(&deployment) - .new(slog::o!("command" => "clear")); - - match subgraph_instances.get(&deployment) { - Some(subgraph_instance) if subgraph_instance.id == id => { - debug!(logger, "Removing active subgraph"); - subgraph_instances.remove(&deployment); - } - Some(_subgraph_instance) => { - debug!(logger, "Active subgraph does not need to be removed"); - return; - } - None => { - debug!(logger, "Subgraph is not active"); - } - } - - if let Some(pending_start_command) = pending_start_commands.remove(&deployment) { - debug!(logger, "Resending a pending start command"); - log_send_error(&logger, command_tx.send(pending_start_command)); - } - } - - /// Spawns a background task that executes the subgraph runner future. - /// - /// An additional background task is spawned to handle the graceful shutdown of the subgraph runner, - /// and to ensure correct behaviour even if the subgraph runner panics. - fn start_subgraph( - logger: Logger, - cancel_token: CancellationToken, - id: u32, - deployment: DeploymentLocator, - runner: BoxRunner, - command_tx: mpsc::UnboundedSender, - ) -> SubgraphInstance { - let mut runner_handle = tokio::spawn({ - let logger = logger.new(slog::o!("process" => "subgraph_runner")); - let cancel_token = cancel_token.cheap_clone(); - - async move { - info!(logger, "Subgraph started"); - - match runner(cancel_token).await { - Ok(()) => { - info!(logger, "Subgraph stopped"); - } - Err(e) => { - error!(logger, "Subgraph failed"; - "error" => ?e - ); - } - } - } - }); - - let supervisor_handle = tokio::spawn({ - let logger = logger.new(slog::o!("process" => "subgraph_supervisor")); - let cancel_token = cancel_token.cheap_clone(); - - fn handle_runner_result(logger: &Logger, result: Result<(), tokio::task::JoinError>) { - match result { - Ok(()) => { - debug!(logger, "Subgraph completed execution"); - } - Err(e) if e.is_panic() => { - error!(logger, "Subgraph panicked"; - "error" => ?e - ); - } - Err(e) => { - error!(logger, "Subgraph failed"; - "error" => ?e - ); - } - } - } - - async move { - debug!(logger, "Subgraph supervisor started"); - - tokio::select! { - _ = cancel_token.cancelled() => { - debug!(logger, "Received cancel signal, waiting for subgraph to stop"); - - match timeout(SUBGRAPH_INSTANCE_GRACE_PERIOD, &mut runner_handle).await { - Ok(result) => { - handle_runner_result(&logger, result); - }, - Err(_) => { - warn!(logger, "Subgraph did not stop after grace period, aborting"); - - runner_handle.abort(); - let _ = runner_handle.await; - - warn!(logger, "Subgraph aborted"); - } - } - }, - result = &mut runner_handle => { - handle_runner_result(&logger, result); - cancel_token.cancel(); - } - } - - debug!(logger, "Sending clear command"); - log_send_error(&logger, command_tx.send(Command::Clear { id, deployment })); - } - }); - - SubgraphInstance { - id, - handle: supervisor_handle, - cancel_token, - } - } -} - -impl Drop for Monitor { - fn drop(&mut self) { - // Send cancel signals to all active subgraphs so that they don't remain without an associated monitor - self.cancel_token.cancel(); - } -} - -/// Represents a background task that executes the subgraph runner future. -struct SubgraphInstance { - id: u32, - handle: JoinHandle<()>, - cancel_token: CancellationToken, -} - -/// Every command used by the subgraph monitor. -enum Command { - /// A request to start executing the subgraph runner future. - Start { - id: u32, - deployment: DeploymentLocator, - runner: BoxRunner, - }, - - /// A request to stop executing the subgraph runner future. - Stop { deployment: DeploymentLocator }, - - /// A request to remove the subgraph from the list of active subgraphs. - Clear { - id: u32, - deployment: DeploymentLocator, - }, -} - -impl fmt::Debug for Command { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::Start { - id, - deployment, - runner: _, - } => f - .debug_struct("Start") - .field("id", id) - .field("deployment", deployment) - .finish_non_exhaustive(), - Self::Stop { deployment } => f - .debug_struct("Stop") - .field("deployment", deployment) - .finish(), - Self::Clear { id, deployment } => f - .debug_struct("Clear") - .field("id", id) - .field("deployment", deployment) - .finish(), - } - } -} - -fn log_send_error(logger: &Logger, result: Result<(), SendError>) { - match result { - Ok(()) => { - // No need to log anything - } - - // This should only happen if the parent cancel token of the subgraph monitor was cancelled - Err(e) => { - error!(logger, "Failed to send command"; - "command" => ?e.0, - "error" => ?e - ); - } - } -} diff --git a/core/src/amp_subgraph/runner/compat.rs b/core/src/amp_subgraph/runner/compat.rs deleted file mode 100644 index f7152965cf3..00000000000 --- a/core/src/amp_subgraph/runner/compat.rs +++ /dev/null @@ -1,52 +0,0 @@ -//! This is a temporary compatibility module until the graph-node is fully migrated to `alloy`. - -use alloy::primitives::{BlockHash, BlockNumber}; -use chrono::{DateTime, Utc}; - -mod legacy { - pub(super) use graph::{ - blockchain::{BlockHash, BlockPtr, BlockTime}, - components::store::BlockNumber, - data::store::scalar::Timestamp, - }; -} - -pub(super) trait Compat { - fn compat(&self) -> T; -} - -impl Compat for BlockNumber { - fn compat(&self) -> legacy::BlockNumber { - (*self).try_into().unwrap() - } -} - -impl Compat for legacy::BlockNumber { - fn compat(&self) -> BlockNumber { - (*self).try_into().unwrap() - } -} - -impl Compat for BlockHash { - fn compat(&self) -> legacy::BlockHash { - legacy::BlockHash(self.0.into()) - } -} - -impl Compat for legacy::BlockHash { - fn compat(&self) -> BlockHash { - BlockHash::from_slice(&self.0) - } -} - -impl Compat for DateTime { - fn compat(&self) -> legacy::BlockTime { - legacy::Timestamp(*self).into() - } -} - -impl Compat for (BlockNumber, BlockHash) { - fn compat(&self) -> legacy::BlockPtr { - legacy::BlockPtr::new(self.1.compat(), self.0.compat()) - } -} diff --git a/core/src/amp_subgraph/runner/context.rs b/core/src/amp_subgraph/runner/context.rs deleted file mode 100644 index d8b5b7b638e..00000000000 --- a/core/src/amp_subgraph/runner/context.rs +++ /dev/null @@ -1,97 +0,0 @@ -use std::sync::Arc; - -use alloy::primitives::{BlockHash, BlockNumber}; -use graph::{ - amp::{Codec, Manifest, log::Logger as _}, - cheap_clone::CheapClone, - components::store::WritableStore, - data::subgraph::DeploymentHash, - env::AmpEnv, - util::backoff::ExponentialBackoff, -}; -use slog::Logger; - -use super::Compat; -use crate::amp_subgraph::Metrics; - -pub(in super::super) struct Context { - pub(super) logger: Logger, - pub(super) client: Arc, - pub(super) store: Arc, - pub(super) buffer_size: usize, - pub(super) block_range: usize, - pub(super) backoff: ExponentialBackoff, - pub(super) deployment: DeploymentHash, - pub(super) manifest: Manifest, - pub(super) metrics: Metrics, - pub(super) codec: Codec, -} - -impl Context { - pub(in super::super) fn new( - logger: &Logger, - env: &AmpEnv, - client: Arc, - store: Arc, - deployment: DeploymentHash, - manifest: Manifest, - metrics: Metrics, - ) -> Self { - let logger = logger.component("AmpSubgraphRunner"); - let backoff = ExponentialBackoff::new(env.query_retry_min_delay, env.query_retry_max_delay); - let codec = Codec::new(manifest.schema.cheap_clone()); - - Self { - logger, - client, - store, - buffer_size: env.buffer_size, - block_range: env.block_range, - backoff, - deployment, - manifest, - metrics, - codec, - } - } - - pub(super) fn indexing_completed(&self) -> bool { - let Some(last_synced_block) = self.latest_synced_block() else { - return false; - }; - - self.manifest - .data_sources - .iter() - .all(|data_source| last_synced_block >= data_source.source.end_block) - } - - pub(super) fn latest_synced_block(&self) -> Option { - self.latest_synced_block_ptr() - .map(|(block_number, _)| block_number) - } - - pub(super) fn latest_synced_block_ptr(&self) -> Option<(BlockNumber, BlockHash)> { - self.store - .block_ptr() - .map(|block_ptr| (block_ptr.number.compat(), block_ptr.hash.compat())) - } - - pub(super) fn start_block(&self) -> BlockNumber { - self.manifest - .data_sources - .iter() - .map(|data_source| data_source.source.start_block) - .min() - .unwrap() - } - - pub(super) fn end_block(&self) -> BlockNumber { - self.manifest - .data_sources - .iter() - .map(|data_source| data_source.source.end_block) - .max() - .unwrap() - } -} diff --git a/core/src/amp_subgraph/runner/data_processing.rs b/core/src/amp_subgraph/runner/data_processing.rs deleted file mode 100644 index d5bf991d505..00000000000 --- a/core/src/amp_subgraph/runner/data_processing.rs +++ /dev/null @@ -1,267 +0,0 @@ -use std::sync::Arc; - -use alloy::primitives::{BlockHash, BlockNumber}; -use anyhow::anyhow; -use arrow::array::RecordBatch; -use chrono::{DateTime, Utc}; -use graph::{ - amp::{ - codec::{DecodeOutput, DecodedEntity, Decoder, utils::auto_block_timestamp_decoder}, - stream_aggregator::{RecordBatchGroup, RecordBatchGroups, StreamRecordBatch}, - }, - blockchain::block_stream::FirehoseCursor, - cheap_clone::CheapClone, - components::store::{EntityCache, EntityLfuCache, ModificationsAndCache, SeqGenerator}, -}; -use slog::{debug, trace}; - -use super::{Compat, Context, Error, data_stream::TablePtr}; - -pub(super) async fn process_record_batch_groups( - cx: &mut Context, - mut entity_lfu_cache: EntityLfuCache, - record_batch_groups: RecordBatchGroups, - stream_table_ptr: Arc<[TablePtr]>, - latest_block: BlockNumber, -) -> Result { - if record_batch_groups.is_empty() { - debug!(cx.logger, "Received no record batch groups"); - return Ok(entity_lfu_cache); - } - - let from_block = record_batch_groups - .first_key_value() - .map(|((block, _), _)| *block) - .unwrap(); - - let to_block = record_batch_groups - .last_key_value() - .map(|((block, _), _)| *block) - .unwrap(); - - debug!(cx.logger, "Processing record batch groups"; - "from_block" => from_block, - "to_block" => to_block - ); - - for ((block_number, block_hash), record_batch_group) in record_batch_groups { - trace!(cx.logger, "Processing record batch group"; - "block" => block_number, - "record_batches_count" => record_batch_group.record_batches.len() - ); - - entity_lfu_cache = process_record_batch_group( - cx, - entity_lfu_cache, - block_number, - block_hash, - record_batch_group, - &stream_table_ptr, - latest_block, - ) - .await - .map_err(|e| { - e.context(format!( - "failed to process record batch group at block '{block_number}'" - )) - })?; - - cx.metrics.deployment_head.update(block_number); - cx.metrics.blocks_processed.record_one(); - - trace!(cx.logger, "Completed processing record batch group"; - "block" => block_number - ); - } - - debug!(cx.logger, "Completed processing record batch groups"; - "from_block" => from_block, - "to_block" => to_block - ); - - Ok(entity_lfu_cache) -} - -async fn process_record_batch_group( - cx: &mut Context, - entity_lfu_cache: EntityLfuCache, - block_number: BlockNumber, - block_hash: BlockHash, - record_batch_group: RecordBatchGroup, - stream_table_ptr: &[TablePtr], - latest_block: BlockNumber, -) -> Result { - let _section = cx - .metrics - .stopwatch - .start_section("process_record_batch_group"); - - let RecordBatchGroup { record_batches } = record_batch_group; - - if record_batches.is_empty() { - debug!(cx.logger, "Record batch group is empty"); - return Ok(entity_lfu_cache); - } - - let mut entity_cache = EntityCache::with_current( - cx.store.cheap_clone(), - entity_lfu_cache, - SeqGenerator::new(block_number.compat()), - ); - - let block_timestamp = if cx.manifest.schema.has_aggregations() { - decode_block_timestamp(&record_batches) - .map_err(|e| e.context("failed to decode block timestamp"))? - } else { - // TODO: Block timestamp is only required for subgraph aggregations. - // Make it optional at the store level. - DateTime::::MIN_UTC - }; - - for record_batch in record_batches { - let StreamRecordBatch { - stream_index, - record_batch, - } = record_batch; - - process_record_batch( - cx, - &mut entity_cache, - record_batch, - stream_table_ptr[stream_index], - ) - .await - .map_err(|e| { - e.context(format!( - "failed to process record batch for stream '{stream_index}'" - )) - })?; - } - - let section = cx.metrics.stopwatch.start_section("as_modifications"); - let ModificationsAndCache { - modifications, - entity_lfu_cache, - evict_stats: _, - } = entity_cache - .as_modifications(block_number.compat(), &cx.metrics.stopwatch) - .await - .map_err(Error::from) - .map_err(|e| e.context("failed to extract entity modifications from the state"))?; - section.end(); - - let _section = cx.metrics.stopwatch.start_section("transact_block"); - let is_close_to_chain_head = latest_block.saturating_sub(block_number) <= 100; - - cx.store - .transact_block_operations( - (block_number, block_hash).compat(), - block_timestamp.compat(), - FirehoseCursor::None, - modifications, - &cx.metrics.stopwatch, - Vec::new(), - Vec::new(), - Vec::new(), - false, - is_close_to_chain_head, - ) - .await - .map_err(Error::from) - .map_err(|e| e.context("failed to transact block operations"))?; - - if is_close_to_chain_head { - cx.metrics.deployment_synced.record(true); - } - - Ok(entity_lfu_cache) -} - -async fn process_record_batch( - cx: &mut Context, - entity_cache: &mut EntityCache, - record_batch: RecordBatch, - (i, j): TablePtr, -) -> Result<(), Error> { - let _section = cx.metrics.stopwatch.start_section("process_record_batch"); - - let table = &cx.manifest.data_sources[i].transformer.tables[j]; - let entity_name = &table.name; - - let DecodeOutput { - entity_type, - id_type, - decoded_entities, - } = cx - .codec - .decode(record_batch, entity_name.as_str()) - .map_err(|e| { - Error::Deterministic( - e.context(format!("failed to decode entities of type '{entity_name}'")), - ) - })?; - - for decoded_entity in decoded_entities { - let DecodedEntity { - key, - mut entity_data, - } = decoded_entity; - - let key = match key { - Some(key) => key, - None => { - let entity_id = entity_cache.seq_gen.id(id_type).map_err(|e| { - Error::Deterministic(e.context(format!( - "failed to generate a new id for an entity of type '{entity_name}'" - ))) - })?; - - entity_data.push(("id".into(), entity_id.clone().into())); - entity_type.key(entity_id) - } - }; - - let entity_id = key.entity_id.clone(); - let entity = cx.manifest.schema.make_entity(entity_data).map_err(|e| { - Error::Deterministic(anyhow!(e).context(format!( - "failed to create a new entity of type '{entity_name}' with id '{entity_id}'" - ))) - })?; - - entity_cache.set(key, entity, None).await.map_err(|e| { - Error::Deterministic(e.context(format!( - "failed to store a new entity of type '{entity_name}' with id '{entity_id}'" - ))) - })?; - } - - Ok(()) -} - -/// Decodes the block timestamp from the first matching column in `record_batches`. -/// -/// Iterates through the provided record batches and returns the timestamp from -/// the first batch that contains a valid block timestamp column. -/// -/// # Preconditions -/// -/// All entries in `record_batches` must belong to the same record batch group. -fn decode_block_timestamp(record_batches: &[StreamRecordBatch]) -> Result, Error> { - let mut last_error: Option = None; - - for record_batch in record_batches { - match auto_block_timestamp_decoder(&record_batch.record_batch) { - Ok((_, decoder)) => { - return decoder - .decode(0) - .map_err(Error::Deterministic)? - .ok_or_else(|| Error::Deterministic(anyhow!("block timestamp is empty"))); - } - Err(e) => { - last_error = Some(Error::Deterministic(e)); - } - } - } - - Err(last_error.unwrap()) -} diff --git a/core/src/amp_subgraph/runner/data_stream.rs b/core/src/amp_subgraph/runner/data_stream.rs deleted file mode 100644 index 693ae9384a7..00000000000 --- a/core/src/amp_subgraph/runner/data_stream.rs +++ /dev/null @@ -1,232 +0,0 @@ -use std::{collections::HashMap, ops::RangeInclusive, sync::Arc}; - -use alloy::primitives::BlockNumber; -use anyhow::anyhow; -use futures::{ - StreamExt, TryStreamExt, - stream::{self, BoxStream}, -}; -use graph::{ - amp::{ - Client, - client::ResponseBatch, - error::IsDeterministic, - manifest::DataSource, - stream_aggregator::{RecordBatchGroups, StreamAggregator}, - }, - cheap_clone::CheapClone, - prelude::StopwatchMetrics, -}; -use slog::{debug, warn}; - -use super::{Context, Error}; - -pub(super) type TablePtr = (usize, usize); - -pub(super) fn new_data_stream( - cx: &Context, - latest_block: BlockNumber, -) -> BoxStream<'static, Result<(RecordBatchGroups, Arc<[TablePtr]>), Error>> -where - AC: Client + Send + Sync + 'static, -{ - let logger = cx.logger.new(slog::o!("process" => "new_data_stream")); - let client = cx.client.cheap_clone(); - let manifest = cx.manifest.clone(); - let buffer_size = cx.buffer_size; - let block_range = cx.block_range; - let stopwatch = cx.metrics.stopwatch.cheap_clone(); - - debug!(logger, "Creating data stream"; - "from_block" => cx.latest_synced_block().unwrap_or(BlockNumber::MIN), - "to_block" => latest_block, - "start_block" => cx.start_block(), - "block_range" => block_range, - ); - - // State: (latest_queried_block, end_block, is_first) - let initial_state = (cx.latest_synced_block(), BlockNumber::MIN, true); - - stream::unfold( - initial_state, - move |(latest_queried_block, mut end_block, is_first)| { - let block_ranges = next_block_ranges( - &manifest.data_sources, - block_range, - latest_queried_block, - latest_block, - ); - - if block_ranges.is_empty() { - if is_first { - warn!(logger, "There are no unprocessed block ranges"); - } - return futures::future::ready(None); - } - - let start_block = block_ranges.values().map(|r| *r.start()).min().unwrap(); - end_block = end_block.max(block_ranges.values().map(|r| *r.end()).max().unwrap()); - - let (query_streams, table_ptrs) = - build_query_streams(&*client, &logger, &manifest.data_sources, &block_ranges); - - let data_stream = build_data_stream( - &logger, - query_streams, - table_ptrs, - buffer_size, - &stopwatch, - start_block, - ); - - debug!(logger, "Created a new data stream"; - "latest_queried_block" => latest_queried_block, - "start_block" => start_block, - "end_block" => end_block, - ); - futures::future::ready(Some((data_stream, (Some(end_block), end_block, false)))) - }, - ) - .flatten() - .boxed() -} - -fn build_query_streams( - client: &AC, - logger: &slog::Logger, - data_sources: &[DataSource], - block_ranges: &HashMap>, -) -> ( - Vec<(String, BoxStream<'static, Result>)>, - Arc<[TablePtr]>, -) { - let total_queries: usize = data_sources - .iter() - .map(|ds| ds.transformer.tables.len()) - .sum(); - - let mut query_streams = Vec::with_capacity(total_queries); - let mut table_ptrs = Vec::with_capacity(total_queries); - - for (i, data_source) in data_sources.iter().enumerate() { - let Some(block_range) = block_ranges.get(&i) else { - continue; - }; - - for (j, table) in data_source.transformer.tables.iter().enumerate() { - let query = table.query.build_with_block_range(block_range); - let stream = client.query(logger, query, None); - let stream_name = format!("{}.{}", data_source.name, table.name); - - query_streams.push((stream_name, stream)); - table_ptrs.push((i, j)); - } - } - - (query_streams, table_ptrs.into()) -} - -fn build_data_stream( - logger: &slog::Logger, - query_streams: Vec<(String, BoxStream<'static, Result>)>, - table_ptrs: Arc<[TablePtr]>, - buffer_size: usize, - stopwatch: &StopwatchMetrics, - start_block: BlockNumber, -) -> BoxStream<'static, Result<(RecordBatchGroups, Arc<[TablePtr]>), Error>> -where - E: std::error::Error + IsDeterministic + Send + Sync + 'static, -{ - let mut start_block_checked = false; - let mut load_first_record_batch_group_section = - Some(stopwatch.start_section("load_first_record_batch_group")); - - StreamAggregator::new(logger, query_streams, buffer_size) - .map_ok(move |response| (response, table_ptrs.cheap_clone())) - .map_err(Error::from) - .map(move |result| { - if load_first_record_batch_group_section.is_some() { - let _section = load_first_record_batch_group_section.take(); - } - - match result { - Ok(response) => { - if !start_block_checked { - if let Some(((first_block, _), _)) = response.0.first_key_value() - && *first_block < start_block - { - return Err(Error::NonDeterministic(anyhow!("chain reorg"))); - } - - start_block_checked = true; - } - - Ok(response) - } - Err(e) => Err(e), - } - }) - .boxed() -} - -fn next_block_ranges( - data_sources: &[DataSource], - block_range: usize, - latest_queried_block: Option, - latest_block: BlockNumber, -) -> HashMap> { - let block_ranges = data_sources - .iter() - .enumerate() - .filter_map(|(i, data_source)| { - next_block_range(block_range, data_source, latest_queried_block, latest_block) - .map(|block_range| (i, block_range)) - }) - .collect::>(); - - let Some(min_block_range) = block_ranges - .iter() - .min_by_key(|(_, block_range)| *block_range.start()) - .map(|(_, min_block_range)| min_block_range.clone()) - else { - return HashMap::new(); - }; - - block_ranges - .into_iter() - .filter(|(_, block_range)| block_range.start() <= min_block_range.end()) - .collect() -} - -fn next_block_range( - block_range: usize, - data_source: &DataSource, - latest_queried_block: Option, - latest_block: BlockNumber, -) -> Option> { - let start_block = match latest_queried_block { - Some(latest_queried_block) => { - if latest_queried_block >= data_source.source.end_block { - return None; - } - - latest_queried_block + 1 - } - None => data_source.source.start_block, - }; - - let end_block = [ - start_block.saturating_add(block_range as BlockNumber), - data_source.source.end_block, - latest_block, - ] - .into_iter() - .min() - .unwrap(); - - if start_block > end_block { - return None; - } - - Some(start_block..=end_block) -} diff --git a/core/src/amp_subgraph/runner/error.rs b/core/src/amp_subgraph/runner/error.rs deleted file mode 100644 index 8c7077e1c68..00000000000 --- a/core/src/amp_subgraph/runner/error.rs +++ /dev/null @@ -1,43 +0,0 @@ -use graph::amp::error::IsDeterministic; -use thiserror::Error; - -#[derive(Debug, Error)] -pub(super) enum Error { - #[error("runner failed with a non-deterministic error: {0:#}")] - NonDeterministic(#[source] anyhow::Error), - - #[error("runner failed with a deterministic error: {0:#}")] - Deterministic(#[source] anyhow::Error), -} - -impl Error { - pub(super) fn context(self, context: C) -> Self - where - C: std::fmt::Display + Send + Sync + 'static, - { - match self { - Self::NonDeterministic(e) => Self::NonDeterministic(e.context(context)), - Self::Deterministic(e) => Self::Deterministic(e.context(context)), - } - } - - pub(super) fn is_deterministic(&self) -> bool { - match self { - Self::Deterministic(_) => true, - Self::NonDeterministic(_) => false, - } - } -} - -impl From for Error -where - T: std::error::Error + IsDeterministic + Send + Sync + 'static, -{ - fn from(e: T) -> Self { - if e.is_deterministic() { - Self::Deterministic(e.into()) - } else { - Self::NonDeterministic(e.into()) - } - } -} diff --git a/core/src/amp_subgraph/runner/latest_blocks.rs b/core/src/amp_subgraph/runner/latest_blocks.rs deleted file mode 100644 index 17bdc23dd29..00000000000 --- a/core/src/amp_subgraph/runner/latest_blocks.rs +++ /dev/null @@ -1,180 +0,0 @@ -use alloy::primitives::BlockNumber; -use anyhow::anyhow; -use arrow::array::RecordBatch; -use futures::{StreamExt, TryFutureExt, future::try_join_all, stream::BoxStream}; -use graph::amp::{ - Client, - client::ResponseBatch, - codec::{Decoder, utils::block_number_decoder}, - error::IsDeterministic, - manifest::DataSource, -}; -use itertools::Itertools; -use slog::debug; - -use super::{Context, Error}; - -pub(super) type TablePtr = (usize, usize); - -pub(super) struct LatestBlocks(Vec<(TablePtr, BlockNumber)>); - -impl LatestBlocks { - pub(super) async fn load(cx: &Context) -> Result - where - AC: Client, - { - debug!(cx.logger, "Loading latest blocks"); - let _section = cx.metrics.stopwatch.start_section("load_latest_blocks"); - - let latest_block_futs = cx - .manifest - .data_sources - .iter() - .enumerate() - .flat_map(|(i, data_source)| { - data_source - .source - .tables - .iter() - .enumerate() - .map(move |(j, table)| ((i, j), &data_source.source.dataset, table)) - }) - .unique_by(|(_, dataset, table)| (dataset.to_string(), table.to_string())) - .map(|(table_ptr, dataset, table)| { - latest_block(cx, dataset, table) - .map_ok(move |latest_block| (table_ptr, latest_block)) - .map_err(move |e| { - e.context(format!( - "failed to load latest block for '{dataset}.{table}'" - )) - }) - }); - - try_join_all(latest_block_futs).await.map(Self) - } - - pub(super) fn filter_completed(self, cx: &Context) -> Self - where - AC: Client, - { - let latest_synced_block = cx.latest_synced_block(); - - Self( - self.0 - .into_iter() - .filter(|((i, _), _)| { - !indexing_completed(&cx.manifest.data_sources[*i], &latest_synced_block) - }) - .collect(), - ) - } - - pub(super) fn min(&self) -> BlockNumber { - self.0 - .iter() - .min_by_key(|(_, latest_block)| *latest_block) - .map(|(_, latest_block)| *latest_block) - .unwrap() - } - - pub(super) async fn changed(self, cx: &Context) -> Result<(), Error> - where - AC: Client, - { - debug!(cx.logger, "Waiting for new blocks"); - let _section = cx.metrics.stopwatch.start_section("latest_blocks_changed"); - - let min_latest_block = self.min(); - let latest_synced_block = cx.latest_synced_block(); - - let latest_block_changed_futs = self - .0 - .into_iter() - .filter(|(_, latest_block)| *latest_block == min_latest_block) - .filter(|((i, _), _)| { - !indexing_completed(&cx.manifest.data_sources[*i], &latest_synced_block) - }) - .map(|((i, j), latest_block)| { - let source = &cx.manifest.data_sources[i].source; - let dataset = &source.dataset; - let table = &source.tables[j]; - - latest_block_changed(cx, dataset, table, latest_block).map_err(move |e| { - e.context(format!( - "failed to check if the latest block changed in '{dataset}.{table}'" - )) - }) - }); - - let _response = try_join_all(latest_block_changed_futs).await?; - - Ok(()) - } - - pub(super) fn iter(&self) -> impl Iterator { - self.0.iter() - } -} - -fn indexing_completed(data_source: &DataSource, latest_synced_block: &Option) -> bool { - latest_synced_block - .as_ref() - .is_some_and(|latest_synced_block| *latest_synced_block >= data_source.source.end_block) -} - -async fn latest_block( - cx: &Context, - dataset: &str, - table: &str, -) -> Result -where - AC: Client, -{ - let query = format!("SELECT MAX(_block_num) FROM {dataset}.{table}"); - let stream = cx.client.query(&cx.logger, query, None); - let record_batch = read_once(stream).await?; - - let latest_block = block_number_decoder(&record_batch, 0) - .map_err(Error::Deterministic)? - .decode(0) - .map_err(Error::Deterministic)? - .ok_or_else(|| Error::NonDeterministic(anyhow!("table is empty")))?; - - Ok(latest_block) -} - -async fn latest_block_changed( - cx: &Context, - dataset: &str, - table: &str, - latest_block: BlockNumber, -) -> Result<(), Error> -where - AC: Client, -{ - let query = format!( - "SELECT _block_num FROM {dataset}.{table} WHERE _block_num > {latest_block} SETTINGS stream = true" - ); - let stream = cx.client.query(&cx.logger, query, None); - let _record_batch = read_once(stream).await?; - - Ok(()) -} - -async fn read_once( - mut stream: BoxStream<'static, Result>, -) -> Result -where - E: std::error::Error + IsDeterministic + Send + Sync + 'static, -{ - let response = stream - .next() - .await - .ok_or_else(|| Error::NonDeterministic(anyhow!("stream is empty")))? - .map_err(Error::from)?; - - match response { - ResponseBatch::Batch { data } => Ok(data), - _ => Err(Error::NonDeterministic(anyhow!("response is empty"))), - } -} diff --git a/core/src/amp_subgraph/runner/mod.rs b/core/src/amp_subgraph/runner/mod.rs deleted file mode 100644 index 4e0e85294b6..00000000000 --- a/core/src/amp_subgraph/runner/mod.rs +++ /dev/null @@ -1,190 +0,0 @@ -mod compat; -mod context; -mod data_processing; -mod data_stream; -mod error; -mod latest_blocks; -mod reorg_handler; - -use std::time::{Duration, Instant}; - -use anyhow::Result; -use futures::StreamExt; -use graph::{ - amp::Client, cheap_clone::CheapClone, components::store::EntityLfuCache, - data::subgraph::schema::SubgraphError, util::lfu_cache::LfuCache, -}; -use slog::{debug, error, warn}; -use tokio_util::sync::CancellationToken; - -use self::{ - compat::Compat, data_processing::process_record_batch_groups, data_stream::new_data_stream, - error::Error, latest_blocks::LatestBlocks, reorg_handler::check_and_handle_reorg, -}; - -pub(super) use self::context::Context; - -pub(super) async fn new_runner( - mut cx: Context, - cancel_token: CancellationToken, -) -> Result<()> -where - AC: Client + Send + Sync + 'static, -{ - let indexing_duration_handle = tokio::spawn({ - let mut instant = Instant::now(); - let indexing_duration = cx.metrics.indexing_duration.clone(); - - async move { - loop { - tokio::time::sleep(Duration::from_secs(1)).await; - - let prev_instant = std::mem::replace(&mut instant, Instant::now()); - indexing_duration.record(prev_instant.elapsed()); - } - } - }); - - let result = cancel_token - .run_until_cancelled(run_indexing_with_retries(&mut cx)) - .await; - - indexing_duration_handle.abort(); - - match result { - Some(result) => result?, - None => { - debug!(cx.logger, "Processed cancel signal"); - } - } - - cx.metrics.deployment_status.stopped(); - - debug!(cx.logger, "Waiting for the store to finish processing"); - cx.store.flush().await?; - Ok(()) -} - -async fn run_indexing(cx: &mut Context) -> Result<(), Error> -where - AC: Client + Send + Sync + 'static, -{ - cx.metrics.deployment_status.starting(); - - if let Some(latest_synced_block) = cx.latest_synced_block() { - cx.metrics.deployment_head.update(latest_synced_block); - } - - cx.metrics - .deployment_synced - .record(cx.store.is_deployment_synced()); - - loop { - cx.metrics.deployment_status.running(); - - debug!(cx.logger, "Running indexing"; - "latest_synced_block_ptr" => ?cx.latest_synced_block_ptr() - ); - - let mut latest_blocks = LatestBlocks::load(cx).await?; - check_and_handle_reorg(cx, &latest_blocks).await?; - - if cx.indexing_completed() { - cx.metrics.deployment_synced.record(true); - - debug!(cx.logger, "Indexing completed"); - return Ok(()); - } - - latest_blocks = latest_blocks.filter_completed(cx); - let latest_block = latest_blocks.min(); - - cx.metrics - .deployment_target - .update(latest_block.min(cx.end_block())); - - let mut deployment_is_failed = cx.store.health().await?.is_failed(); - let mut entity_lfu_cache: EntityLfuCache = LfuCache::new(); - let mut stream = new_data_stream(cx, latest_block); - - while let Some(result) = stream.next().await { - let (record_batch_groups, stream_table_ptr) = result?; - - entity_lfu_cache = process_record_batch_groups( - cx, - entity_lfu_cache, - record_batch_groups, - stream_table_ptr, - latest_block, - ) - .await?; - - if deployment_is_failed && let Some(block_ptr) = cx.store.block_ptr() { - cx.store.unfail_non_deterministic_error(&block_ptr).await?; - deployment_is_failed = false; - } - } - - // Check if the Amp Flight server has data covering through every data - // source's endBlock. This handles the case where endBlock has no entity - // data — the persisted block pointer never advances to endBlock, but the - // server's latest block confirms all queries have been served. - if latest_block >= cx.end_block() { - cx.metrics.deployment_synced.record(true); - - debug!(cx.logger, "Indexing completed; endBlock reached via server latest block"; - "latest_block" => latest_block, - "end_block" => cx.end_block() - ); - return Ok(()); - } - - debug!(cx.logger, "Completed indexing iteration"; - "latest_synced_block_ptr" => ?cx.latest_synced_block_ptr() - ); - - latest_blocks.changed(cx).await?; - cx.backoff.reset(); - } -} - -async fn run_indexing_with_retries(cx: &mut Context) -> Result<()> -where - AC: Client + Send + Sync + 'static, -{ - loop { - match run_indexing(cx).await { - Ok(()) => return Ok(()), - Err(e) => { - cx.metrics.deployment_status.failed(); - - let deterministic = e.is_deterministic(); - - cx.store - .fail_subgraph(SubgraphError { - subgraph_id: cx.deployment.cheap_clone(), - message: format!("{e:#}"), - block_ptr: None, // TODO: Find a way to propagate the block ptr here - handler: None, - deterministic, - }) - .await?; - - if deterministic { - error!(cx.logger, "Subgraph failed with a deterministic error"; - "e" => ?e - ); - return Err(e.into()); - } - - warn!(cx.logger, "Subgraph failed with a non-deterministic error"; - "e" => ?e, - "retry_delay_seconds" => cx.backoff.delay().as_secs() - ); - - cx.backoff.sleep_async().await; - debug!(cx.logger, "Restarting indexing"); - } - } - } -} diff --git a/core/src/amp_subgraph/runner/reorg_handler.rs b/core/src/amp_subgraph/runner/reorg_handler.rs deleted file mode 100644 index 8f59169304b..00000000000 --- a/core/src/amp_subgraph/runner/reorg_handler.rs +++ /dev/null @@ -1,163 +0,0 @@ -use alloy::primitives::{BlockHash, BlockNumber}; -use anyhow::anyhow; -use futures::{StreamExt, TryFutureExt, future::try_join_all}; -use graph::{ - amp::{ - Client, - client::{LatestBlockBeforeReorg, RequestMetadata, ResponseBatch, ResumeStreamingQuery}, - }, - blockchain::block_stream::FirehoseCursor, -}; -use itertools::Itertools; -use slog::debug; - -use super::{Compat, Context, Error, LatestBlocks}; - -pub(super) async fn check_and_handle_reorg( - cx: &Context, - latest_blocks: &LatestBlocks, -) -> Result<(), Error> -where - AC: Client, -{ - let logger = cx - .logger - .new(slog::o!("process" => "check_and_handle_reorg")); - - let Some((latest_synced_block_number, latest_synced_block_hash)) = cx.latest_synced_block_ptr() - else { - debug!(logger, "There are no synced blocks; Skipping reorg check"); - return Ok(()); - }; - - debug!(logger, "Running reorg check"); - - let Some(latest_block_before_reorg) = detect_deepest_reorg( - cx, - latest_blocks, - latest_synced_block_number, - latest_synced_block_hash, - ) - .await? - else { - debug!(logger, "Successfully checked for reorg: No reorg detected"; - "latest_synced_block" => latest_synced_block_number - ); - return Ok(()); - }; - - let _section = cx.metrics.stopwatch.start_section("handle_reorg"); - - debug!(logger, "Handling reorg"; - "latest_synced_block" => latest_synced_block_number, - "latest_block_before_reorg" => ?latest_block_before_reorg.block_number - ); - - let (block_number, block_hash) = match ( - latest_block_before_reorg.block_number, - latest_block_before_reorg.block_hash, - ) { - (Some(block_number), Some(block_hash)) => (block_number, block_hash), - (_, _) => { - // TODO: Handle reorgs to the genesis block - return Err(Error::Deterministic(anyhow!( - "invalid reorg: rewind to the genesis block not supported" - ))); - } - }; - - if block_number > latest_synced_block_number { - return Err(Error::Deterministic(anyhow!( - "invalid reorg: latest block before reorg cannot be higher than the invalidated block" - ))); - } else if block_number == latest_synced_block_number && block_hash == latest_synced_block_hash { - return Err(Error::Deterministic(anyhow!( - "invalid reorg: latest block before reorg cannot be equal to the invalidated block" - ))); - } - - cx.store - .revert_block_operations((block_number, block_hash).compat(), FirehoseCursor::None) - .await - .map_err(Error::from)?; - - Ok(()) -} - -async fn detect_deepest_reorg( - cx: &Context, - latest_blocks: &LatestBlocks, - latest_synced_block_number: BlockNumber, - latest_synced_block_hash: BlockHash, -) -> Result, Error> -where - AC: Client, -{ - let detect_reorg_futs = latest_blocks - .iter() - .filter(|(_, latest_block)| *latest_block >= latest_synced_block_number) - .map(|((i, j), _)| { - let data_source = &cx.manifest.data_sources[*i]; - let network = &data_source.network; - let dataset = &data_source.source.dataset; - let table = &data_source.source.tables[*j]; - - detect_reorg( - cx, - network, - dataset, - table, - latest_synced_block_number, - latest_synced_block_hash, - ) - .map_err(move |e| e.context(format!("failed to detect reorg in '{dataset}.{table}'"))) - }); - - let deepest_reorg = try_join_all(detect_reorg_futs) - .await? - .into_iter() - .flatten() - .min_by_key(|latest_block_before_reorg| latest_block_before_reorg.block_number); - - Ok(deepest_reorg) -} - -async fn detect_reorg( - cx: &Context, - network: &str, - dataset: &str, - table: &str, - latest_synced_block_number: BlockNumber, - latest_synced_block_hash: BlockHash, -) -> Result, Error> -where - AC: Client, -{ - let query = format!("SELECT _block_num FROM {dataset}.{table} SETTINGS stream = true"); - let mut stream = cx.client.query( - &cx.logger, - query, - Some(RequestMetadata { - resume_streaming_query: Some(vec![ResumeStreamingQuery { - network: network.to_string(), - block_number: latest_synced_block_number, - block_hash: latest_synced_block_hash, - }]), - }), - ); - - let response = stream - .next() - .await - .ok_or_else(|| Error::NonDeterministic(anyhow!("stream is empty")))? - .map_err(Error::from)?; - - match response { - ResponseBatch::Batch { .. } => Ok(None), - ResponseBatch::Reorg(reorg) => reorg - .into_iter() - .exactly_one() - .map_err(|_e| Error::Deterministic(anyhow!("multi-chain datasets are not supported"))) - .map(Some), - } -} diff --git a/core/src/lib.rs b/core/src/lib.rs index 118ce3ebaae..9548c0d42a9 100644 --- a/core/src/lib.rs +++ b/core/src/lib.rs @@ -1,6 +1,5 @@ mod subgraph_manifest; -pub mod amp_subgraph; pub mod polling_monitor; pub mod subgraph; pub mod subgraph_provider; diff --git a/core/src/subgraph/context/instance/mod.rs b/core/src/subgraph/context/instance/mod.rs index 9372791ccda..743cf8f2707 100644 --- a/core/src/subgraph/context/instance/mod.rs +++ b/core/src/subgraph/context/instance/mod.rs @@ -182,7 +182,6 @@ where Ok(Some(host)) } } - DataSource::Amp(_) => unreachable!(), } } diff --git a/core/src/subgraph/instance_manager.rs b/core/src/subgraph/instance_manager.rs index ea301ffc723..fb62f50faf3 100644 --- a/core/src/subgraph/instance_manager.rs +++ b/core/src/subgraph/instance_manager.rs @@ -10,7 +10,6 @@ use std::collections::BTreeSet; use crate::subgraph::runner::SubgraphRunner; use async_trait::async_trait; -use graph::amp; use graph::blockchain::block_stream::{BlockStreamMetrics, TriggersAdapterWrapper}; use graph::blockchain::{Blockchain, BlockchainKind, DataSource, NodeCapabilities}; use graph::components::metrics::gas::GasMetrics; @@ -32,7 +31,7 @@ use super::context::OffchainMonitor; use crate::{subgraph::runner::SubgraphRunnerError, subgraph_manifest}; #[derive(Clone)] -pub struct SubgraphInstanceManager { +pub struct SubgraphInstanceManager { logger_factory: LoggerFactory, subgraph_store: Arc, chains: Arc, @@ -41,7 +40,6 @@ pub struct SubgraphInstanceManager { link_resolver: Arc, ipfs_service: IpfsService, arweave_service: ArweaveService, - amp_client: Option>, static_filters: bool, env_vars: Arc, @@ -59,10 +57,7 @@ pub struct SubgraphInstanceManager { } #[async_trait] -impl SubgraphInstanceManagerTrait for SubgraphInstanceManager -where - NC: amp::Client + Send + Sync + 'static, -{ +impl SubgraphInstanceManagerTrait for SubgraphInstanceManager { async fn start_subgraph( self: Arc, loc: DeploymentLocator, @@ -164,7 +159,7 @@ where } } -impl SubgraphInstanceManager { +impl SubgraphInstanceManager { pub fn new( logger_factory: &LoggerFactory, env_vars: Arc, @@ -175,7 +170,6 @@ impl SubgraphInstanceManager { link_resolver: Arc, ipfs_service: IpfsService, arweave_service: ArweaveService, - amp_client: Option>, static_filters: bool, ) -> Self { let logger = logger_factory.component_logger("SubgraphInstanceManager", None); @@ -189,7 +183,6 @@ impl SubgraphInstanceManager { instances: SubgraphKeepAlive::new(sg_metrics), link_resolver, ipfs_service, - amp_client, static_filters, env_vars, arweave_service, @@ -300,7 +293,6 @@ impl SubgraphInstanceManager { .resolve( &deployment.hash, &link_resolver, - self.amp_client.cheap_clone(), &logger, ENV_VARS.max_spec_version.clone(), ) diff --git a/core/src/subgraph/registrar.rs b/core/src/subgraph/registrar.rs index e9422671e25..eadf9c16c61 100644 --- a/core/src/subgraph/registrar.rs +++ b/core/src/subgraph/registrar.rs @@ -1,11 +1,9 @@ use std::collections::HashSet; use async_trait::async_trait; -use graph::amp; use graph::blockchain::{Blockchain, BlockchainKind, BlockchainMap}; use graph::components::{ link_resolver::LinkResolverContext, - network_provider::AmpChainNames, store::{DeploymentId, DeploymentLocator, SubscriptionManager}, subgraph::Settings, }; @@ -18,28 +16,25 @@ use graph::prelude::{CreateSubgraphResult, SubgraphRegistrar as SubgraphRegistra use graph::util::futures::{RETRY_DEFAULT_LIMIT, retry_strategy}; use tokio_retry::Retry; -pub struct SubgraphRegistrar { +pub struct SubgraphRegistrar { logger: Logger, logger_factory: LoggerFactory, resolver: Arc, provider: Arc

, store: Arc, subscription_manager: Arc, - amp_client: Option>, chains: Arc, node_id: NodeId, version_switching_mode: SubgraphVersionSwitchingMode, assignment_event_stream_cancel_guard: CancelGuard, // cancels on drop settings: Arc, - amp_chain_names: Arc, } -impl SubgraphRegistrar +impl SubgraphRegistrar where P: graph::components::subgraph::SubgraphInstanceManager, S: SubgraphStore, SM: SubscriptionManager, - AC: amp::Client + Send + Sync + 'static, { pub fn new( logger_factory: &LoggerFactory, @@ -47,12 +42,10 @@ where provider: Arc

, store: Arc, subscription_manager: Arc, - amp_client: Option>, chains: Arc, node_id: NodeId, version_switching_mode: SubgraphVersionSwitchingMode, settings: Arc, - amp_chain_names: Arc, ) -> Self { let logger = logger_factory.component_logger("SubgraphRegistrar", None); let logger_factory = logger_factory.with_parent(logger.clone()); @@ -66,13 +59,11 @@ where provider, store, subscription_manager, - amp_client, chains, node_id, version_switching_mode, assignment_event_stream_cancel_guard: CancelGuard::new(), settings, - amp_chain_names, } } @@ -226,12 +217,11 @@ where } #[async_trait] -impl SubgraphRegistrarTrait for SubgraphRegistrar +impl SubgraphRegistrarTrait for SubgraphRegistrar where P: graph::components::subgraph::SubgraphInstanceManager, S: SubgraphStore, SM: SubscriptionManager, - AC: amp::Client + Send + Sync + 'static, { async fn create_subgraph( &self, @@ -303,7 +293,7 @@ where let deployment_locator = match kind { BlockchainKind::Ethereum => { - create_subgraph_version::( + create_subgraph_version::( &logger, self.store.clone(), self.chains.cheap_clone(), @@ -316,14 +306,12 @@ where debug_fork, self.version_switching_mode, &resolver, - self.amp_client.cheap_clone(), history_blocks, - &self.amp_chain_names, ) .await? } BlockchainKind::Near => { - create_subgraph_version::( + create_subgraph_version::( &logger, self.store.clone(), self.chains.cheap_clone(), @@ -336,9 +324,7 @@ where debug_fork, self.version_switching_mode, &resolver, - self.amp_client.cheap_clone(), history_blocks, - &self.amp_chain_names, ) .await? } @@ -454,7 +440,7 @@ async fn resolve_graft_block( }) } -async fn create_subgraph_version( +async fn create_subgraph_version( logger: &Logger, store: Arc, chains: Arc, @@ -467,9 +453,7 @@ async fn create_subgraph_version, version_switching_mode: SubgraphVersionSwitchingMode, resolver: &Arc, - amp_client: Option>, history_blocks_override: Option, - amp_chain_names: &AmpChainNames, ) -> Result { let raw_string = serde_yaml::to_string(&raw).unwrap(); @@ -477,7 +461,6 @@ async fn create_subgraph_version(resolved_name.clone()) + .get::(network_name.clone()) .map_err(SubgraphRegistrarError::NetworkNotSupported)? .cheap_clone(); @@ -581,7 +563,7 @@ async fn create_subgraph_version, - subgraph_store: Arc, - link_resolver: Arc, - /// Stops active subgraph start request tasks. - /// - /// When a subgraph deployment start request is processed, a background task is created - /// to load the subgraph manifest and determine the subgraph processing kind. The processing - /// kind is then used to find the appropriate subgraph instance manager. This token stops - /// all tasks that are still loading manifests or waiting for subgraphs to start. - cancel_token: CancellationToken, + /// Handles the processing of started subgraph deployments. + instance_manager: Arc, - /// Contains the enabled subgraph instance managers. + /// Maintains a list of started subgraphs. /// - /// Only subgraphs for which there is an appropriate instance manager will be started. - instance_managers: SubgraphInstanceManagers, - - /// Maintains a list of started subgraphs with their processing kinds. - /// - /// Used to forward subgraph deployment stop requests to the appropriate subgraph instance manager. + /// Used to ignore duplicate start requests and to stop active start request tasks. assignments: SubgraphAssignments, } @@ -57,71 +33,24 @@ impl SubgraphProvider { /// # Arguments /// - `logger_factory`: Creates loggers for each subgraph deployment start/stop request /// - `count_metrics`: Tracks the number of started subgraph deployments - /// - `subgraph_store`: Loads subgraph manifests to determine the subgraph processing kinds - /// - `link_resolver`: Loads subgraph manifests to determine the subgraph processing kinds - /// - `cancel_token`: Stops active subgraph start request tasks - /// - `instance_managers`: Contains the enabled subgraph instance managers + /// - `instance_manager`: Handles the processing of started subgraph deployments pub fn new( logger_factory: &LoggerFactory, count_metrics: Arc, - subgraph_store: Arc, - link_resolver: Arc, - cancel_token: CancellationToken, - instance_managers: SubgraphInstanceManagers, + instance_manager: Arc, ) -> Self { let logger = logger_factory.component_logger("SubgraphProvider", None); let logger_factory = logger_factory.with_parent(logger.cheap_clone()); - debug!(logger, "Creating subgraph provider"; - "enabled_subgraph_processing_kinds" => instance_managers.0.keys().join(", ") - ); + debug!(logger, "Creating subgraph provider"); Self { logger_factory, count_metrics, - subgraph_store, - link_resolver, - cancel_token, - instance_managers, + instance_manager, assignments: SubgraphAssignments::new(), } } - - /// Starts a subgraph deployment with the appropriate subgraph instance manager. - /// - /// Loads the subgraph manifest for the specified deployment locator, determines - /// the subgraph processing kind, finds the required instance manager, and forwards - /// the start request to that instance manager. Keeps the subgraph processing kind - /// in memory for handling the stop requests. - async fn assign_and_start_subgraph( - &self, - loc: DeploymentLocator, - stop_block: Option, - ) -> Result<(), Error> { - let logger = self.logger_factory.subgraph_logger(&loc); - - let raw_manifest = subgraph_manifest::load_raw_subgraph_manifest( - &logger, - &*self.subgraph_store, - &*self.link_resolver, - &loc.hash, - ) - .await - .map_err(|e| Error::LoadManifest { - loc: loc.cheap_clone(), - source: e, - })?; - - let subgraph_kind = SubgraphProcessingKind::from_manifest(&raw_manifest); - self.assignments.set_subgraph_kind(&loc, subgraph_kind); - - let Some(instance_manager) = self.instance_managers.get(&subgraph_kind) else { - return Err(Error::GetManager { loc, subgraph_kind }); - }; - - instance_manager.start_subgraph(loc, stop_block).await; - Ok(()) - } } #[async_trait::async_trait] @@ -140,39 +69,22 @@ impl SubgraphInstanceManager for SubgraphProvider { self.count_metrics.deployment_count.inc(); let handle = tokio::spawn({ - let provider = self.cheap_clone(); + let instance_manager = self.instance_manager.cheap_clone(); let loc = loc.cheap_clone(); let start_instant = Instant::now(); async move { debug!(logger, "Starting subgraph"); - let fut = provider.assign_and_start_subgraph(loc, stop_block); - match provider.cancel_token.run_until_cancelled(fut).await { - Some(Ok(())) => { - debug!(logger, "Subgraph started"; - "duration_ms" => start_instant.elapsed().as_millis() - ); - } - Some(Err(e)) => { - error!(logger, "Subgraph failed to start"; - "e" => ?e - ); - } - None => { - debug!(logger, "Subgraph start cancelled"); - } - } + instance_manager.start_subgraph(loc, stop_block).await; + + debug!(logger, "Subgraph started"; + "duration_ms" => start_instant.elapsed().as_millis() + ); } }); - self.assignments.add( - loc, - SubgraphAssignment { - handle, - subgraph_kind: None, - }, - ) + self.assignments.add(loc, handle) } async fn stop_subgraph(&self, loc: DeploymentLocator) { @@ -183,11 +95,7 @@ impl SubgraphInstanceManager for SubgraphProvider { debug!(logger, "Stopping subgraph"); - let Some(SubgraphAssignment { - handle, - subgraph_kind, - }) = self.assignments.take(&loc) - else { + let Some(handle) = self.assignments.take(&loc) else { debug!(logger, "Subgraph is not started"); return; }; @@ -195,113 +103,13 @@ impl SubgraphInstanceManager for SubgraphProvider { handle.abort(); self.count_metrics.deployment_count.dec(); - let Some(subgraph_kind) = subgraph_kind else { - debug!(logger, "Unknown subgraph kind"); - return; - }; - - let Some(instance_manager) = self.instance_managers.get(&subgraph_kind) else { - debug!(logger, "Missing instance manager"); - return; - }; - - instance_manager.stop_subgraph(loc).await; + self.instance_manager.stop_subgraph(loc).await; debug!(logger, "Subgraph stopped"); } } -/// Enumerates all possible errors of the subgraph provider. -#[derive(Debug, thiserror::Error)] -enum Error { - #[error("failed to load manifest for '{loc}': {source:#}")] - LoadManifest { - loc: DeploymentLocator, - source: subgraph_manifest::Error, - }, - - #[error("failed to get instance manager for '{loc}' with kind '{subgraph_kind}'")] - GetManager { - loc: DeploymentLocator, - subgraph_kind: SubgraphProcessingKind, - }, -} - -/// Contains a mapping of enabled subgraph instance managers by subgraph processing kinds. -/// -/// Before starting a subgraph, its processing kind is determined from the subgraph manifest. -/// Then, the appropriate instance manager is loaded from this mapping. -#[derive(Default)] -pub struct SubgraphInstanceManagers( - HashMap>, -); - -impl SubgraphInstanceManagers { - /// Creates a new empty subgraph instance manager mapping. - pub fn new() -> Self { - Self(HashMap::new()) - } - - /// Adds a new subgraph instance manager for all subgraphs of the specified processing kind. - pub fn add( - &mut self, - subgraph_kind: SubgraphProcessingKind, - instance_manager: Arc, - ) { - self.0.insert(subgraph_kind, instance_manager); - } - - /// Returns the subgraph instance manager for the specified processing kind. - pub fn get( - &self, - subgraph_kind: &SubgraphProcessingKind, - ) -> Option> { - self.0 - .get(subgraph_kind) - .map(|instance_manager| instance_manager.cheap_clone()) - } -} - -/// Enumerates the supported subgraph processing kinds. -/// -/// Subgraphs may have different processing requirements, and this enum helps to map them -/// to the appropriate instance managers. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, strum::Display)] -#[strum(serialize_all = "snake_case")] -pub enum SubgraphProcessingKind { - /// Represents trigger-based subgraphs. - Trigger, - - /// Represents Amp-powered subgraphs. - Amp, -} - -impl SubgraphProcessingKind { - /// Determines the subgraph processing kind from the subgraph manifest. - fn from_manifest(raw_manifest: &serde_yaml::Mapping) -> Self { - use serde_yaml::Value; - - let is_amp_manifest = raw_manifest - .get("dataSources") - .and_then(Value::as_sequence) - .and_then(|seq| { - seq.iter() - .filter_map(Value::as_mapping) - .filter_map(|map| map.get("kind")) - .filter_map(Value::as_str) - .find(|kind| *kind == amp::manifest::DataSource::KIND) - }) - .is_some(); - - if is_amp_manifest { - return Self::Amp; - } - - Self::Trigger - } -} - -/// Maintains a list of started subgraph deployments with details required for stopping them. -struct SubgraphAssignments(RwLock>); +/// Maintains a list of started subgraph deployments with the handles to their start request tasks. +struct SubgraphAssignments(RwLock>>); impl SubgraphAssignments { /// Creates a new empty list of started subgraph deployments. @@ -310,15 +118,8 @@ impl SubgraphAssignments { } /// Adds a new subgraph deployment to the list of started subgraph deployments. - fn add(&self, loc: DeploymentLocator, subgraph_assignment: SubgraphAssignment) { - self.0.write().insert(loc, subgraph_assignment); - } - - /// Updates the started subgraph deployment with the specified subgraph processing kind. - fn set_subgraph_kind(&self, loc: &DeploymentLocator, subgraph_kind: SubgraphProcessingKind) { - if let Some(subgraph_assignment) = self.0.write().get_mut(loc) { - subgraph_assignment.subgraph_kind = Some(subgraph_kind); - } + fn add(&self, loc: DeploymentLocator, handle: tokio::task::JoinHandle<()>) { + self.0.write().insert(loc, handle); } /// Checks if the subgraph deployment is started. @@ -326,21 +127,8 @@ impl SubgraphAssignments { self.0.read().contains_key(loc) } - /// Removes the subgraph deployment from the list of started subgraph deployments and returns its details. - fn take(&self, loc: &DeploymentLocator) -> Option { + /// Removes the subgraph deployment from the list of started subgraph deployments and returns its start request task handle. + fn take(&self, loc: &DeploymentLocator) -> Option> { self.0.write().remove(loc) } } - -/// Contains the details of a started subgraph deployment. -struct SubgraphAssignment { - /// The handle to the background task that starts this subgraph deployment. - handle: tokio::task::JoinHandle<()>, - - /// The subgraph processing kind of this subgraph deployment. - /// - /// Used to get the appropriate subgraph instance manager to forward the stop request to. - /// - /// Set to `None` until the subgraph manifest is loaded and parsed. - subgraph_kind: Option, -} diff --git a/docs/amp-powered-subgraphs.md b/docs/amp-powered-subgraphs.md deleted file mode 100644 index 60bccdde449..00000000000 --- a/docs/amp-powered-subgraphs.md +++ /dev/null @@ -1,582 +0,0 @@ -# Amp-powered subgraphs - -> [!WARNING] -> This feature is experimental and may change in future releases. - -> [!NOTE] -> This feature is available starting from spec version `1.5.0` - -Amp-powered subgraphs are a new kind of subgraphs with SQL data sources that query and index data from the Amp servers. -They are significantly more efficient than the standard subgraphs, and the indexing time can be reduced from days and weeks, -to minutes and hours in most cases. - -## Prerequisites - -To enable Amp-powered subgraphs, the `GRAPH_AMP_FLIGHT_SERVICE_ADDRESS` ENV variable must be set to a valid Amp Flight gRPC service address. - -Additionally, if authentication is required for the Amp Flight gRPC service, the `GRAPH_AMP_FLIGHT_SERVICE_TOKEN` ENV variable must contain a valid authentication token. - -## Subgraph manifest - -Amp-powered subgraphs introduce a new structure for defining Amp subgraph data sources within the manifest. - -### Spec version - -The minimum spec version for Amp-powered subgraphs is `1.5.0`. - -

-Example YAML: - -```diff -+ specVersion: 1.5.0 - dataSources: - - kind: amp - name: Transfers - network: ethereum-mainnet - source: - dataset: edgeandnode/ethereum_mainnet - tables: - - blocks - - transactions - transformer: - apiVersion: 0.0.1 - tables: - - name: Transfer - file: -``` - -
- -### Data source structure - -### `kind` - -Every Amp data source must have the `kind` set to `amp`, and Amp-powered subgraphs must contain only Amp data sources. -This is used to assign the subgraph to the appropriate indexing process. - -
-Example YAML: - -```diff - specVersion: 1.5.0 -+ dataSources: -+ - kind: amp - name: Transfers - network: ethereum-mainnet - source: - dataset: edgeandnode/ethereum_mainnet - tables: - - blocks - - transactions - transformer: - apiVersion: 0.0.1 - tables: - - name: Transfer - file: -``` - -
- -### `name` - -Every Amp data source must have the `name` set to a non-empty string, containing only numbers, letters, hypens, or underscores. -This name is used for observability purposes and to identify progress and potential errors produced by the data source. - -
-Example YAML: - -```diff - specVersion: 1.5.0 -+ dataSources: - - kind: amp -+ name: Transfers - network: ethereum-mainnet - source: - dataset: edgeandnode/ethereum_mainnet - tables: - - blocks - - transactions - transformer: - apiVersion: 0.0.1 - tables: - - name: Transfer - file: -``` - -
- -### `network` - -Every Amp data source must have the `network` field set to a valid network name. -This is used to validate that the SQL queries for this data source produce results for the expected network. - -> [!NOTE] -> Currently, the SQL queries are required to produce results for a single network in order to maintain compatibility with non-Amp subgraphs. - -
-Example YAML: - -```diff - specVersion: 1.5.0 -+ dataSources: - - kind: amp - name: Transfers -+ network: ethereum-mainnet - source: - dataset: edgeandnode/ethereum_mainnet - tables: - - blocks - - transactions - transformer: - apiVersion: 0.0.1 - tables: - - name: Transfer - file: -``` - -
- -### `source` - -Every Amp data source must have a valid `source` that describes the behavior of SQL queries from this data source. - -### `source.dataset` - -Contains the name of the dataset that can be queried by SQL queries in this data source. -This is used to validate that the SQL queries for this data source only query the expected dataset. - -
-Example YAML: - -```diff - specVersion: 1.5.0 -+ dataSources: - - kind: amp - name: Transfers - network: ethereum-mainnet -+ source: -+ dataset: edgeandnode/ethereum_mainnet - tables: - - blocks - - transactions - transformer: - apiVersion: 0.0.1 - tables: - - name: Transfer - file: -``` - -
- -### `source.tables` - -Contains the names of the tables that can be queried by SQL queries in this data source. -This is used to validate that the SQL queries for this data source only query the expected tables. - -
-Example YAML: - -```diff - specVersion: 1.5.0 -+ dataSources: - - kind: amp - name: Transfers - network: ethereum-mainnet -+ source: - dataset: edgeandnode/ethereum_mainnet -+ tables: -+ - blocks -+ - transactions - transformer: - apiVersion: 0.0.1 - tables: - - name: Transfer - file: -``` - -
- -### Optional `source.address` - -Contains the contract address with which SQL queries in the data source interact. - -Enables SQL query reuse through `sg_source_address()` calls instead of hard-coding the contract address. -SQL queries resolve `sg_source_address()` calls to this contract address. - -
-Example YAML: - -```diff - specVersion: 1.5.0 -+ dataSources: - - kind: amp - name: Transfers - network: ethereum-mainnet -+ source: -+ address: "0xc944E90C64B2c07662A292be6244BDf05Cda44a7" - dataset: edgeandnode/ethereum_mainnet - tables: - - blocks - - transactions - transformer: - apiVersion: 0.0.1 - tables: - - name: Transfer - file: -``` - -
- -### Optional `source.startBlock` - -Contains the minimum block number that SQL queries in the data source can query. -This is used as a starting point for the indexing process. - -_When not provided, defaults to block number `0`._ - -
-Example YAML: - -```diff - specVersion: 1.5.0 -+ dataSources: - - kind: amp - name: Transfers - network: ethereum-mainnet -+ source: -+ startBlock: 11446769 - dataset: edgeandnode/ethereum_mainnet - tables: - - blocks - - transactions - transformer: - apiVersion: 0.0.1 - tables: - - name: Transfer - file: -``` - -
- -### Optional `source.endBlock` - -Contains the maximum block number that SQL queries in the data source can query. -Reaching this block number will complete the indexing process. - -_When not provided, defaults to the maximum possible block number._ - -
-Example YAML: - -```diff - specVersion: 1.5.0 -+ dataSources: - - kind: amp - name: Transfers - network: ethereum-mainnet -+ source: -+ endBlock: 23847939 - dataset: edgeandnode/ethereum_mainnet - tables: - - blocks - - transactions - transformer: - apiVersion: 0.0.1 - tables: - - name: Transfer - file: -``` - -
- -### `transformer` - -Every Amp data source must have a valid `transformer` that describes the transformations of source tables indexed by the Amp-powered subgraph. - -### `transformer.apiVersion` - -Represents the version of this transformer. Each version may contain a different set of features. - -> [!NOTE] -> Currently, only the version `0.0.1` is available. - -
-Example YAML: - -```diff - specVersion: 1.5.0 -+ dataSources: - - kind: amp - name: Transfers - network: ethereum-mainnet - source: - endBlock: 23847939 - dataset: edgeandnode/ethereum_mainnet - tables: - - blocks - - transactions -+ transformer: -+ apiVersion: 0.0.1 - tables: - - name: Transfers - file: -``` - -
- -### Optional `transformer.abis` - -Contains a list of ABIs that SQL queries can reference to extract event signatures. - -Enables the use of `sg_event_signature('CONTRACT_NAME', 'EVENT_NAME')` calls in the -SQL queries which are resolved to full event signatures based on this list. - -_When not provided, defaults to an empty list._ - -
-Example YAML: - -```diff - specVersion: 1.5.0 -+ dataSources: - - kind: amp - name: Transfers - network: ethereum-mainnet - source: - endBlock: 23847939 - dataset: edgeandnode/ethereum_mainnet - tables: - - blocks - - transactions -+ transformer: -+ abis: -+ - name: ERC721 # The name of the contract -+ file: - apiVersion: 0.0.1 - tables: - - name: Transfer - file: -``` - -
- -### `transformer.tables` - -Contains a list of transformed tables that extract data from source tables into subgraph entities. - -### Transformer table structure - -### `transformer.tables[i].name` - -Represents the name of the transformed table. Must reference a valid entity name from the subgraph schema. - -
-Example: - -**GraphQL schema:** - -```graphql -type Block @entity(immutable: true) { - # .. entity fields ... -} -``` - -**YAML manifest:** - -```diff - specVersion: 1.5.0 -+ dataSources: - - kind: amp - name: Blocks - network: ethereum-mainnet - source: - endBlock: 23847939 - dataset: edgeandnode/ethereum_mainnet - tables: - - blocks - - transactions -+ transformer: - apiVersion: 0.0.1 -+ tables: -+ - name: Block - file: -``` - -
- -### `transformer.tables[i].query` - -Contains an inline SQL query that executes on the Amp server. -This is useful for simple SQL queries like `SELECT * FROM "edgeandnode/ethereum_mainnet".blocks;`. -For more complex cases, a separate file containing the SQL query can be used in the `file` field. - -The data resulting from this SQL query execution transforms into subgraph entities. - -_When not provided, the `file` field is used instead._ - -
-Example YAML: - -```diff - specVersion: 1.5.0 -+ dataSources: - - kind: amp - name: Blocks - network: ethereum-mainnet - source: - endBlock: 23847939 - dataset: edgeandnode/ethereum_mainnet - tables: - - blocks - - transactions -+ transformer: - apiVersion: 0.0.1 -+ tables: - - name: Block -+ query: SELECT * FROM "edgeandnode/ethereum_mainnet".blocks; -``` - -
- -### `transformer.tables[i].file` - -Contains the IPFS link to the SQL query that executes on the Amp server. - -The data resulting from this SQL query execution transforms into subgraph entities. - -_Ignored when the `query` field is provided._ -_When not provided, the `query` field is used instead._ - -
-Example YAML: - -```diff - specVersion: 1.5.0 -+ dataSources: - - kind: amp - name: Blocks - network: ethereum-mainnet - source: - endBlock: 23847939 - dataset: edgeandnode/ethereum_mainnet - tables: - - blocks - - transactions -+ transformer: - apiVersion: 0.0.1 -+ tables: - - name: Block -+ file: -``` - -
- -### Amp-powered subgraph examples - -Complete examples on how to create, deploy and query Amp-powered subgraphs are available in a separate repository: -https://github.com/edgeandnode/amp-subgraph-examples - -## SQL query requirements - -### Names - -The names of tables, columns, and aliases must not start with `amp_` as this -prefix is reserved for internal use. - -### Block numbers - -Every SQL query in Amp-powered subgraphs must return the block number for every row. -This is required because subgraphs rely on this information for storing subgraph entities. - -Graph-node will look for block numbers in the following columns: -`_block_num`, `block_num`, `blockNum`, `block`, `block_number`, `blockNumber`. - -Example SQL query: `SELECT _block_num, /* .. other projections .. */ FROM "edgeandnode/ethereum_mainnet".blocks;` - -### Block hashes - -Every SQL query in Amp-powered subgraphs is expected to return the block hash for every row. -This is required because subgraphs rely on this information for storing subgraph entities. - -When a SQL query does not have the block hash projection, graph-node will attempt to get it from the -source tables specified in the subgraph manifest. - -Graph-node will look for block hashes in the following columns: -`hash`, `block_hash`, `blockHash`. - -Example SQL query: `SELECT hash, /* .. other projections .. */ FROM "edgeandnode/ethereum_mainnet".blocks;` - -> [!NOTE] -> If a table does not contain the block hash column, it can be retrieved by joining that table with another that contains the column on the `_block_num` column. - -### Block timestamps - -> [!NOTE] -> Only required for Amp-powered subgraphs that use subgraph aggregations. - -Every SQL query in Amp-powered subgraphs is expected to return the block timestamps for every row. -This is required because subgraphs rely on this information for storing subgraph entities. - -When a SQL query does not have the block timestamps projection, graph-node will attempt to get it from the -source tables specified in the subgraph manifest. - -Graph-node will look for block timestamps in the following columns: -`timestamp`, `block_timestamp`, `blockTimestamp`. - -Example SQL query: `SELECT timestamp, /* .. other projections .. */ FROM "edgeandnode/ethereum_mainnet".blocks;` - -> [!NOTE] -> If a table does not contain the block timestamp column, it can be retrieved by joining that table with another that contains the column on the `_block_num` column. - -## Type conversions - -Amp core SQL data types are converted intuitively to compatible subgraph entity types. - -## Schema generation - -Amp-powered subgraphs support the generation of GraphQL schemas based on the schemas of SQL queries referenced in the subgraph manifest. -This is useful when indexing entities that do not rely on complex relationships, such as contract events. - -The generated subgraph entities are immutable. - -To enable schema generation, simply remove the `schema` field from the subgraph manifest. - -> [!NOTE] -> For more flexibility and control over the schema, a manually created GraphQL schema is preferred. - -## Aggregations - -Amp-powered subgraphs fully support the subgraph aggregations feature. -This allows having complex aggregations on top of data indexed from the Amp servers. - -For more information on using the powerful subgraph aggregations feature, -refer to the [documentation](https://github.com/graphprotocol/graph-node/blob/master/docs/aggregations.md). - -## Composition - -Amp-powered subgraphs fully support the subgraph composition feature. -This allows applying complex subgraph mappings on top of data indexed from the Amp servers. - -For more information on using the powerful subgraph composition feature, -refer to the [documentation](https://github.com/graphprotocol/example-composable-subgraph). - -## ENV variables - -Amp-powered subgraphs feature introduces the following new ENV variables: - -- `GRAPH_AMP_FLIGHT_SERVICE_ADDRESS` – The address of the Amp Flight gRPC service. _Defaults to `None`, which disables support for Amp-powered subgraphs._ -- `GRAPH_AMP_FLIGHT_SERVICE_TOKEN` – Token used to authenticate Amp Flight gRPC service requests. _Defaults to `None`, which disables authentication._ -- `GRAPH_AMP_BUFFER_SIZE` – Maximum number of response batches to buffer in memory per stream for each SQL query. _Defaults to `1,000`._ -- `GRAPH_AMP_BLOCK_RANGE` – Maximum number of blocks to request per stream for each SQL query. _Defaults to `100,000`._ -- `GRAPH_AMP_QUERY_RETRY_MIN_DELAY_SECONDS` – Minimum time to wait before retrying a failed SQL query to the Amp server. _Defaults to `1` second._ -- `GRAPH_AMP_QUERY_RETRY_MAX_DELAY_SECONDS` – Maximum time to wait before retrying a failed SQL query to the Amp server. _Defaults to `600` seconds._ - -## Metrics - -In addition to reporting updates to the existing `deployment_status`, `deployment_head`, `deployment_synced` and `deployment_blocks_processed_count` -metrics, Amp-powered subgraphs feature introduces the following new metrics: - -- `deployment_target` – Tracks the maximum block number currently available for indexing within a deployment. -- `deployment_indexing_duration_seconds` – Tracks the total duration in seconds of deployment indexing. - -Additionally, the `deployment_sync_secs` is extended with new sections specific to the Amp indexing process. diff --git a/docs/config.md b/docs/config.md index db5fc083a5f..2044a81c477 100644 --- a/docs/config.md +++ b/docs/config.md @@ -123,9 +123,6 @@ The configuration for a chain `name` is specified in the section - `shard`: where chain data is stored - `protocol`: the protocol type being indexed, default `ethereum` (alternatively `near`, `cosmos`,`arweave`,`starknet`) -- `amp`: the network name used by AMP for this chain; defaults to the chain name. - Set this when AMP uses a different name than graph-node (e.g., `amp = "ethereum-mainnet"` - on a chain named `mainnet`). - `cache_size`: number of blocks from the chain head for which to keep block data cached. Defaults to the section-level `cache_size`. - `provider`: a list of providers for that chain @@ -209,7 +206,6 @@ ingestor = "block_ingestor_node" cache_size = 500 [chains.mainnet] shard = "vip" -amp = "ethereum-mainnet" # Per-chain RPC tuning (all optional — omitted fields use env var defaults) json_rpc_timeout = 300 request_retries = 15 diff --git a/gnd/Cargo.toml b/gnd/Cargo.toml index 754949a4722..708d04cea44 100644 --- a/gnd/Cargo.toml +++ b/gnd/Cargo.toml @@ -42,7 +42,6 @@ git-testament = { workspace = true } lazy_static = { workspace = true } serde = { workspace = true } tokio = { workspace = true } -tokio-util = { workspace = true } # File watching notify = "8.2.0" diff --git a/gnd/src/commands/build.rs b/gnd/src/commands/build.rs index b33731330aa..6f3d34c06c1 100644 --- a/gnd/src/commands/build.rs +++ b/gnd/src/commands/build.rs @@ -110,9 +110,7 @@ fn get_files_to_watch(manifest_path: &Path, manifest: &Manifest) -> Vec let mut files = vec![manifest_path.to_path_buf()]; // Add schema file - if let Some(schema_path) = &manifest.schema { - files.push(resolve_path(manifest_path, schema_path)); - } + files.push(resolve_path(manifest_path, &manifest.schema)); // Add mapping files for ds in &manifest.data_sources { @@ -164,20 +162,18 @@ async fn build_subgraph(opt: &BuildOpt) -> Result { } // Validate schema before compilation - if let Some(schema_path) = &manifest.schema { - let schema_path = resolve_path(&opt.manifest, schema_path); - let validation_errors = validate_schema(&schema_path, &manifest.spec_version)?; + let schema_path = resolve_path(&opt.manifest, &manifest.schema); + let validation_errors = validate_schema(&schema_path, &manifest.spec_version)?; - if !validation_errors.is_empty() { - eprintln!( - "Schema validation errors:\n{}", - format_schema_errors(&validation_errors) - ); - return Err(anyhow!( - "Schema validation failed with {} error(s)", - validation_errors.len() - )); - } + if !validation_errors.is_empty() { + eprintln!( + "Schema validation errors:\n{}", + format_schema_errors(&validation_errors) + ); + return Err(anyhow!( + "Schema validation failed with {} error(s)", + validation_errors.len() + )); } // Find graph-ts and node_modules @@ -285,10 +281,8 @@ async fn build_subgraph(opt: &BuildOpt) -> Result { } // Copy schema file - if let Some(schema_path) = &manifest.schema { - let schema_path = resolve_path(&opt.manifest, schema_path); - copy_schema(&schema_path, &opt.output_dir)?; - } + let schema_path = resolve_path(&opt.manifest, &manifest.schema); + copy_schema(&schema_path, &opt.output_dir)?; // Copy ABI files for data sources for ds in &manifest.data_sources { @@ -353,17 +347,15 @@ async fn upload_to_ipfs(ipfs_url: &str, output_dir: &Path, manifest: &Manifest) let mut uploaded = UploadedFiles::default(); // Upload schema file - if let Some(schema_path) = &manifest.schema { - let schema_name = Path::new(schema_path) - .file_name() - .and_then(|n| n.to_str()) - .unwrap_or("schema.graphql"); - let schema_file = output_dir.join(schema_name); - let content = fs::read(&schema_file) - .with_context(|| format!("Failed to read schema file: {}", schema_file.display()))?; - let hash = upload_file_to_ipfs(&client, schema_name, content, &mut uploaded).await?; - step(Step::Write, &format!(" {} => {}", schema_name, hash)); - } + let schema_name = Path::new(&manifest.schema) + .file_name() + .and_then(|n| n.to_str()) + .unwrap_or("schema.graphql"); + let schema_file = output_dir.join(schema_name); + let content = fs::read(&schema_file) + .with_context(|| format!("Failed to read schema file: {}", schema_file.display()))?; + let hash = upload_file_to_ipfs(&client, schema_name, content, &mut uploaded).await?; + step(Step::Write, &format!(" {} => {}", schema_name, hash)); // Upload ABI files for data sources for ds in &manifest.data_sources { @@ -489,19 +481,17 @@ fn create_ipfs_manifest( let mut value: serde_yaml::Value = serde_yaml::from_str(&manifest_str)?; // Update schema path to IPFS reference - if let Some(schema_path) = &manifest.schema { - let schema_name = Path::new(schema_path) - .file_name() - .and_then(|n| n.to_str()) - .unwrap_or("schema.graphql"); + let schema_name = Path::new(&manifest.schema) + .file_name() + .and_then(|n| n.to_str()) + .unwrap_or("schema.graphql"); - // Find the hash for this file - if let Some(hash) = uploaded.path_to_ipfs.get(schema_name) - && let Some(schema) = value.get_mut("schema") - && let Some(file) = schema.get_mut("file") - { - *file = create_ipfs_link(hash); - } + // Find the hash for this file + if let Some(hash) = uploaded.path_to_ipfs.get(schema_name) + && let Some(schema) = value.get_mut("schema") + && let Some(file) = schema.get_mut("file") + { + *file = create_ipfs_link(hash); } // Update data source paths @@ -752,9 +742,8 @@ fn write_output_manifest( // Update schema path if let Some(schema) = value.get_mut("schema") && let Some(file) = schema.get_mut("file") - && let Some(schema_path) = manifest.schema.as_ref() { - let schema_name = Path::new(schema_path) + let schema_name = Path::new(&manifest.schema) .file_name() .and_then(|n| n.to_str()) .unwrap_or("schema.graphql"); diff --git a/gnd/src/commands/codegen.rs b/gnd/src/commands/codegen.rs index deb0feb0ca5..f47be4c1a0a 100644 --- a/gnd/src/commands/codegen.rs +++ b/gnd/src/commands/codegen.rs @@ -85,9 +85,7 @@ fn get_files_to_watch(manifest_path: &Path, manifest: &Manifest) -> Vec let mut files = vec![manifest_path.to_path_buf()]; // Add schema file - if let Some(schema_path) = &manifest.schema { - files.push(resolve_path(manifest_path, schema_path)); - } + files.push(resolve_path(manifest_path, &manifest.schema)); // Add ABI files for ds in &manifest.data_sources { @@ -128,10 +126,8 @@ async fn generate_types(opt: &CodegenOpt) -> Result<()> { .with_context(|| format!("Failed to create output directory: {:?}", opt.output_dir))?; // Generate schema types - if let Some(schema_path) = manifest.schema.as_ref() { - let schema_path = resolve_path(&opt.manifest, schema_path); - let _ = generate_schema_types(&schema_path, &opt.output_dir, &manifest.spec_version)?; - } + let schema_path = resolve_path(&opt.manifest, &manifest.schema); + let _ = generate_schema_types(&schema_path, &opt.output_dir, &manifest.spec_version)?; // Generate ABI types for each data source for ds in &manifest.data_sources { diff --git a/gnd/src/commands/dev.rs b/gnd/src/commands/dev.rs index 044cefa877e..9d2c221edf8 100644 --- a/gnd/src/commands/dev.rs +++ b/gnd/src/commands/dev.rs @@ -11,7 +11,6 @@ use graph::{ use graph_core::polling_monitor::ipfs_service; use graph_node::{launcher, opt::Opt}; use tokio::sync::mpsc; -use tokio_util::sync::CancellationToken; use crate::watcher::{deploy_all_subgraphs, parse_manifest_args, watch_subgraphs}; @@ -147,7 +146,6 @@ async fn run_graph_node( opt: Opt, link_resolver: Arc, subgraph_updates_channel: mpsc::Receiver<(DeploymentHash, SubgraphName)>, - cancel_token: CancellationToken, ) -> Result<()> { let env_vars = Arc::new(EnvVars::from_env().context("Failed to load environment variables")?); @@ -173,7 +171,6 @@ async fn run_graph_node( Some(subgraph_updates_channel), prometheus_registry, metrics_registry, - cancel_token, ) .await; Ok(()) @@ -220,11 +217,7 @@ fn get_database_url( } /// Run the dev command -pub async fn run_dev( - dev_opt: DevOpt, - logger: Logger, - cancel_token: CancellationToken, -) -> Result<()> { +pub async fn run_dev(dev_opt: DevOpt, logger: Logger) -> Result<()> { let database_dir = Path::new(&dev_opt.database_dir); info!(logger, "Starting Graph Node Dev"); @@ -245,16 +238,8 @@ pub async fn run_dev( let (tx, rx) = mpsc::channel(1); let logger_clone = logger.clone(); - let cancel_token_clone = cancel_token.clone(); graph::spawn(async move { - let _ = run_graph_node( - &logger_clone, - opt, - file_link_resolver, - rx, - cancel_token_clone, - ) - .await; + let _ = run_graph_node(&logger_clone, opt, file_link_resolver, rx).await; }); let deploy_result: anyhow::Result<()> = diff --git a/gnd/src/commands/test/runner.rs b/gnd/src/commands/test/runner.rs index 19db7347deb..0ac9eb05e70 100644 --- a/gnd/src/commands/test/runner.rs +++ b/gnd/src/commands/test/runner.rs @@ -23,15 +23,12 @@ use super::schema::{TestFile, TestResult}; use super::trigger::build_blocks_with_triggers; use crate::manifest::{Manifest, load_manifest}; use anyhow::{Context, Result, anyhow, ensure}; -use graph::amp::FlightClient; use graph::blockchain::block_stream::BlockWithTriggers; use graph::blockchain::{BlockPtr, BlockchainMap, ChainIdentifier}; use graph::cheap_clone::CheapClone; use graph::components::link_resolver::FileLinkResolver; use graph::components::metrics::MetricsRegistry; -use graph::components::network_provider::{ - AmpChainNames, ChainName, ProviderCheckStrategy, ProviderManager, -}; +use graph::components::network_provider::{ChainName, ProviderCheckStrategy, ProviderManager}; use graph::components::store::DeploymentLocator; use graph::components::subgraph::{Settings, SubgraphInstanceManager as _}; use graph::data::graphql::load_manager::LoadManager; @@ -734,7 +731,6 @@ async fn setup_context( let subgraph_instance_manager = Arc::new(graph_core::subgraph::SubgraphInstanceManager::< SubgraphStore, - FlightClient, >::new( &logger_factory, env_vars.cheap_clone(), @@ -745,24 +741,13 @@ async fn setup_context( link_resolver.cheap_clone(), ipfs_service, arweave_service, - None, static_filters, )); - let mut subgraph_instance_managers = - graph_core::subgraph_provider::SubgraphInstanceManagers::new(); - subgraph_instance_managers.add( - graph_core::subgraph_provider::SubgraphProcessingKind::Trigger, - subgraph_instance_manager.cheap_clone(), - ); - let subgraph_provider = Arc::new(graph_core::subgraph_provider::SubgraphProvider::new( &logger_factory, sg_count.cheap_clone(), - subgraph_store.clone(), - link_resolver.cheap_clone(), - tokio_util::sync::CancellationToken::new(), - subgraph_instance_managers, + subgraph_instance_manager.cheap_clone(), )); let load_manager = LoadManager::new(logger, Vec::new(), Vec::new(), mock_registry.clone()); @@ -782,12 +767,10 @@ async fn setup_context( subgraph_provider.cheap_clone(), subgraph_store.clone(), panicking_subscription_manager, - Option::>::None, blockchain_map.clone(), node_id.clone(), SubgraphVersionSwitchingMode::Instant, Arc::new(Settings::default()), - Arc::new(AmpChainNames::default()), )); SubgraphRegistrar::create_subgraph(subgraph_registrar.as_ref(), subgraph_name.clone()).await?; diff --git a/gnd/src/main.rs b/gnd/src/main.rs index 092674e5da0..e84541d5175 100644 --- a/gnd/src/main.rs +++ b/gnd/src/main.rs @@ -8,7 +8,6 @@ use clap_complete::{Shell, generate}; use git_testament::{git_testament, render_testament}; use graph::log::logger; use lazy_static::lazy_static; -use tokio_util::sync::CancellationToken; use gnd::commands::{ AddOpt, AuthOpt, BuildOpt, CleanOpt, CodegenOpt, CreateOpt, DeployOpt, DevOpt, InitOpt, @@ -123,42 +122,6 @@ pub enum CompletionShell { Zsh, } -fn shutdown_token() -> CancellationToken { - use tokio::signal; - - let cancel_token = CancellationToken::new(); - let cancel_token_clone = cancel_token.clone(); - - async fn shutdown_signal_handler() { - let ctrl_c = async { - signal::ctrl_c().await.unwrap(); - }; - - #[cfg(unix)] - let terminate = async { - signal::unix::signal(signal::unix::SignalKind::terminate()) - .unwrap() - .recv() - .await; - }; - - #[cfg(not(unix))] - let terminate = std::future::pending::<()>(); - - tokio::select! { - _ = ctrl_c => {}, - _ = terminate => {}, - }; - } - - tokio::spawn(async move { - shutdown_signal_handler().await; - cancel_token_clone.cancel(); - }); - - cancel_token -} - fn generate_completions(completions_opt: CompletionsOpt) -> Result<()> { let shell = match completions_opt.shell { CompletionShell::Bash => Shell::Bash, @@ -233,11 +196,10 @@ async fn main() -> Result<()> { let cli = Cli::parse(); let logger = logger(true); - let cancel_token = shutdown_token(); let res = match cli.command { Commands::Dev(dev_opt) => { - run_dev(dev_opt, logger, cancel_token).await?; + run_dev(dev_opt, logger).await?; Ok(()) } Commands::Codegen(codegen_opt) => run_codegen(codegen_opt).await, diff --git a/gnd/src/manifest.rs b/gnd/src/manifest.rs index 0221070edfe..a001ad3b533 100644 --- a/gnd/src/manifest.rs +++ b/gnd/src/manifest.rs @@ -40,7 +40,7 @@ type GraphManifest = UnresolvedSubgraphManifest; #[derive(Debug)] pub struct Manifest { pub spec_version: Version, - pub schema: Option, + pub schema: String, pub features: Vec, pub graft: Option, /// All data sources, including both contract-style sources and subgraph sources. @@ -185,7 +185,7 @@ pub fn load_manifest(path: &Path) -> Result { fn convert_manifest(m: GraphManifest) -> Manifest { let spec_version = m.spec_version; - let schema = m.schema.map(|s| s.file.link); + let schema = m.schema.file.link; let features = m.features.into_iter().map(|f| f.to_string()).collect(); @@ -304,21 +304,6 @@ fn convert_data_source(ds: GraphUnresolvedDS) -> DataSource { call_handlers: vec![], block_handlers: vec![], }, - GraphUnresolvedDS::Amp(amp) => DataSource { - name: amp.name.clone(), - kind: amp.kind.clone(), - network: Some(amp.network.clone()), - mapping_file: None, - api_version: None, - abis: vec![], - source_address: None, - source_abi: None, - start_block: amp.source.start_block.unwrap_or(0), - end_block: amp.source.end_block, - event_handlers: vec![], - call_handlers: vec![], - block_handlers: vec![], - }, } } @@ -521,7 +506,7 @@ templates: let manifest = load_manifest(&manifest_path).unwrap(); assert_eq!(manifest.spec_version, Version::new(0, 0, 4)); - assert_eq!(manifest.schema, Some("./schema.graphql".to_string())); + assert_eq!(manifest.schema, "./schema.graphql"); assert_eq!(manifest.data_sources.len(), 1); assert_eq!(manifest.data_sources[0].name, "Token"); assert_eq!(manifest.data_sources[0].kind, "ethereum/contract"); diff --git a/gnd/src/validation/mod.rs b/gnd/src/validation/mod.rs index 8991df4fba5..18410420ee1 100644 --- a/gnd/src/validation/mod.rs +++ b/gnd/src/validation/mod.rs @@ -362,14 +362,12 @@ fn validate_file_existence( let mut errors = Vec::new(); // Check schema file - if let Some(schema_path) = &manifest.schema { - let full_path = manifest_dir.join(schema_path.as_str()); - if !full_path.exists() { - errors.push(ManifestValidationError::FileNotFound { - path: schema_path.to_string(), - description: "Schema file".to_string(), - }); - } + let full_path = manifest_dir.join(manifest.schema.as_str()); + if !full_path.exists() { + errors.push(ManifestValidationError::FileNotFound { + path: manifest.schema.clone(), + description: "Schema file".to_string(), + }); } // Check data source files @@ -1159,7 +1157,7 @@ type Post @entity { fn create_test_manifest(data_sources: Vec, templates: Vec