-
Notifications
You must be signed in to change notification settings - Fork 1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add substreams block ingestor #4839
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -7,6 +7,7 @@ members = [ | |
"runtime/*", | ||
"server/*", | ||
"store/*", | ||
"substreams-head-tracker", | ||
"graph", | ||
"tests", | ||
] | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,160 @@ | ||
use std::{sync::Arc, time::Duration}; | ||
|
||
use crate::mapper::Mapper; | ||
use anyhow::{Context, Error}; | ||
use graph::blockchain::{ | ||
client::ChainClient, substreams_block_stream::SubstreamsBlockStream, BlockIngestor, | ||
}; | ||
use graph::prelude::MetricsRegistry; | ||
use graph::slog::trace; | ||
use graph::substreams::Package; | ||
use graph::tokio_stream::StreamExt; | ||
use graph::{ | ||
blockchain::block_stream::BlockStreamEvent, | ||
cheap_clone::CheapClone, | ||
components::store::ChainStore, | ||
prelude::{async_trait, error, info, DeploymentHash, Logger}, | ||
util::backoff::ExponentialBackoff, | ||
}; | ||
use prost::Message; | ||
|
||
const SUBSTREAMS_HEAD_TRACKER_BYTES: &[u8; 89935] = | ||
include_bytes!("../../../substreams-head-tracker/substreams-head-tracker-v1.0.0.spkg"); | ||
|
||
pub struct SubstreamsBlockIngestor { | ||
chain_store: Arc<dyn ChainStore>, | ||
client: Arc<ChainClient<super::Chain>>, | ||
logger: Logger, | ||
chain_name: String, | ||
metrics: Arc<MetricsRegistry>, | ||
} | ||
|
||
impl SubstreamsBlockIngestor { | ||
pub fn new( | ||
chain_store: Arc<dyn ChainStore>, | ||
client: Arc<ChainClient<super::Chain>>, | ||
logger: Logger, | ||
chain_name: String, | ||
metrics: Arc<MetricsRegistry>, | ||
) -> SubstreamsBlockIngestor { | ||
SubstreamsBlockIngestor { | ||
chain_store, | ||
client, | ||
logger, | ||
chain_name, | ||
metrics, | ||
} | ||
} | ||
|
||
async fn fetch_head_cursor(&self) -> String { | ||
let mut backoff = | ||
ExponentialBackoff::new(Duration::from_millis(250), Duration::from_secs(30)); | ||
loop { | ||
match self.chain_store.clone().chain_head_cursor() { | ||
Ok(cursor) => return cursor.unwrap_or_default(), | ||
Err(e) => { | ||
error!(self.logger, "Fetching chain head cursor failed: {:#}", e); | ||
|
||
backoff.sleep_async().await; | ||
} | ||
} | ||
} | ||
} | ||
|
||
/// Consumes the incoming stream of blocks infinitely until it hits an error. In which case | ||
/// the error is logged right away and the latest available cursor is returned | ||
/// upstream for future consumption. | ||
async fn process_blocks( | ||
&self, | ||
cursor: String, | ||
mut stream: SubstreamsBlockStream<super::Chain>, | ||
) -> String { | ||
let mut latest_cursor = cursor; | ||
|
||
while let Some(message) = stream.next().await { | ||
let (block_ptr, cursor) = match message { | ||
Ok(BlockStreamEvent::ProcessBlock(triggers, cursor)) => { | ||
(Arc::new(triggers.block), cursor) | ||
} | ||
Ok(BlockStreamEvent::Revert(_ptr, _cursor)) => { | ||
trace!(self.logger, "Received undo block to ingest, skipping"); | ||
continue; | ||
} | ||
Err(e) => { | ||
info!( | ||
self.logger, | ||
"An error occurred while streaming blocks: {}", e | ||
); | ||
break; | ||
} | ||
}; | ||
|
||
let res = self.process_new_block(block_ptr, cursor.to_string()).await; | ||
if let Err(e) = res { | ||
error!(self.logger, "Process block failed: {:#}", e); | ||
break; | ||
} | ||
|
||
latest_cursor = cursor.to_string() | ||
} | ||
|
||
error!( | ||
self.logger, | ||
"Stream blocks complete unexpectedly, expecting stream to always stream blocks" | ||
); | ||
latest_cursor | ||
} | ||
|
||
async fn process_new_block( | ||
&self, | ||
block_ptr: Arc<super::Block>, | ||
cursor: String, | ||
) -> Result<(), Error> { | ||
trace!(self.logger, "Received new block to ingest {:?}", block_ptr); | ||
|
||
self.chain_store | ||
.clone() | ||
.set_chain_head(block_ptr, cursor) | ||
.await | ||
.context("Updating chain head")?; | ||
|
||
Ok(()) | ||
} | ||
} | ||
|
||
#[async_trait] | ||
impl BlockIngestor for SubstreamsBlockIngestor { | ||
async fn run(self: Box<Self>) { | ||
let mapper = Arc::new(Mapper {}); | ||
let mut latest_cursor = self.fetch_head_cursor().await; | ||
let mut backoff = | ||
ExponentialBackoff::new(Duration::from_millis(250), Duration::from_secs(30)); | ||
let package = Package::decode(SUBSTREAMS_HEAD_TRACKER_BYTES.to_vec().as_ref()).unwrap(); | ||
|
||
loop { | ||
let stream = SubstreamsBlockStream::<super::Chain>::new( | ||
DeploymentHash::default(), | ||
self.client.cheap_clone(), | ||
None, | ||
Some(latest_cursor.clone()), | ||
mapper.cheap_clone(), | ||
package.modules.clone(), | ||
"map_blocks".to_string(), | ||
vec![], | ||
vec![], | ||
self.logger.cheap_clone(), | ||
self.metrics.cheap_clone(), | ||
); | ||
|
||
// Consume the stream of blocks until an error is hit | ||
latest_cursor = self.process_blocks(latest_cursor, stream).await; | ||
|
||
// If we reach this point, we must wait a bit before retrying | ||
backoff.sleep_async().await; | ||
} | ||
} | ||
|
||
fn network_name(&self) -> String { | ||
self.chain_name.clone() | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Looks like
backoff
is never reset, which is not ideal. Maybe should reset if cursor changes.