-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathmod.rs
More file actions
257 lines (227 loc) · 8.29 KB
/
mod.rs
File metadata and controls
257 lines (227 loc) · 8.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
mod instance;
use crate::polling_monitor::{
spawn_monitor, ArweaveService, IpfsRequest, IpfsService, PollingMonitor, PollingMonitorMetrics,
};
use anyhow::{self, Error};
use bytes::Bytes;
use graph::{
blockchain::Blockchain,
components::{store::DeploymentId, subgraph::HostMetrics},
data::subgraph::SubgraphManifest,
data_source::{
causality_region::CausalityRegionSeq,
offchain::{self, Base64},
CausalityRegion, DataSource, DataSourceTemplate,
},
derive::CheapClone,
ipfs::IpfsContext,
prelude::{
BlockNumber, CancelGuard, CheapClone, DeploymentHash, MetricsRegistry, RuntimeHostBuilder,
SubgraphCountMetric, TriggerProcessor,
},
slog::Logger,
};
use std::collections::HashMap;
use std::sync::Arc;
use graph::parking_lot::RwLock;
use tokio::sync::mpsc;
use self::instance::SubgraphInstance;
use super::Decoder;
#[derive(Clone, CheapClone, Debug)]
pub struct SubgraphKeepAlive {
alive_map: Arc<RwLock<HashMap<DeploymentId, CancelGuard>>>,
sg_metrics: Arc<SubgraphCountMetric>,
}
impl SubgraphKeepAlive {
pub fn new(sg_metrics: Arc<SubgraphCountMetric>) -> Self {
Self {
sg_metrics,
alive_map: Arc::new(RwLock::new(HashMap::default())),
}
}
pub fn remove(&self, deployment_id: &DeploymentId) {
self.alive_map.write().remove(deployment_id);
self.sg_metrics.running_count.dec();
}
pub fn insert(&self, deployment_id: DeploymentId, guard: CancelGuard) {
let old = self.alive_map.write().insert(deployment_id, guard);
if old.is_none() {
self.sg_metrics.running_count.inc();
}
}
pub fn contains(&self, deployment_id: &DeploymentId) -> bool {
self.alive_map.read().contains_key(deployment_id)
}
}
// The context keeps track of mutable in-memory state that is retained across blocks.
//
// Currently most of the changes are applied in `runner.rs`, but ideally more of that would be
// refactored into the context so it wouldn't need `pub` fields. The entity cache should probably
// also be moved here.
pub struct IndexingContext<C, T>
where
T: RuntimeHostBuilder<C>,
C: Blockchain,
{
pub(crate) instance: SubgraphInstance<C, T>,
pub instances: SubgraphKeepAlive,
pub offchain_monitor: OffchainMonitor,
pub(crate) trigger_processor: Box<dyn TriggerProcessor<C, T>>,
pub(crate) decoder: Box<Decoder<C, T>>,
}
impl<C: Blockchain, T: RuntimeHostBuilder<C>> IndexingContext<C, T> {
pub fn new(
manifest: SubgraphManifest<C>,
host_builder: T,
host_metrics: Arc<HostMetrics>,
causality_region_seq: CausalityRegionSeq,
instances: SubgraphKeepAlive,
offchain_monitor: OffchainMonitor,
trigger_processor: Box<dyn TriggerProcessor<C, T>>,
decoder: Box<Decoder<C, T>>,
) -> Self {
let instance = SubgraphInstance::new(
manifest,
host_builder,
host_metrics.clone(),
causality_region_seq,
);
Self {
instance,
instances,
offchain_monitor,
trigger_processor,
decoder,
}
}
/// Removes data sources hosts with a creation block greater or equal to `reverted_block`, so
/// that they are no longer candidates for `process_trigger`.
///
/// This does not currently affect the `offchain_monitor` or the `filter`, so they will continue
/// to include data sources that have been reverted. This is not ideal for performance, but it
/// does not affect correctness since triggers that have no matching host will be ignored by
/// `process_trigger`.
///
/// File data sources that have been marked not done during this process will get re-queued
pub fn revert_data_sources(&mut self, reverted_block: BlockNumber) {
let removed = self.instance.revert_data_sources(reverted_block);
removed
.into_iter()
.for_each(|source| self.offchain_monitor.add_source(source))
}
pub fn add_dynamic_data_source(
&mut self,
logger: &Logger,
data_source: DataSource<C>,
) -> Result<Option<Arc<T::Host>>, Error> {
let offchain_fields = data_source
.as_offchain()
.map(|ds| (ds.source.clone(), ds.is_processed()));
let host = self.instance.add_dynamic_data_source(logger, data_source)?;
if host.is_some() {
if let Some((source, is_processed)) = offchain_fields {
// monitor data source only if it has not yet been processed.
if !is_processed {
self.offchain_monitor.add_source(source);
}
}
}
Ok(host)
}
pub fn causality_region_next_value(&mut self) -> CausalityRegion {
self.instance.causality_region_next_value()
}
pub fn hosts_len(&self) -> usize {
self.instance.hosts_len()
}
pub fn onchain_data_sources(&self) -> impl Iterator<Item = &C::DataSource> + Clone {
self.instance.onchain_data_sources()
}
pub fn static_data_sources(&self) -> &[DataSource<C>] {
&self.instance.static_data_sources
}
pub fn templates(&self) -> &[DataSourceTemplate<C>] {
&self.instance.templates
}
}
pub struct OffchainMonitor {
ipfs_monitor: PollingMonitor<IpfsRequest>,
ipfs_monitor_rx: mpsc::UnboundedReceiver<(IpfsRequest, Bytes)>,
arweave_monitor: PollingMonitor<Base64>,
arweave_monitor_rx: mpsc::UnboundedReceiver<(Base64, Bytes)>,
deployment_hash: DeploymentHash,
logger: Logger,
}
impl OffchainMonitor {
pub fn new(
logger: Logger,
registry: Arc<MetricsRegistry>,
subgraph_hash: &DeploymentHash,
ipfs_service: IpfsService,
arweave_service: ArweaveService,
) -> Self {
let metrics = Arc::new(PollingMonitorMetrics::new(registry, subgraph_hash));
// The channel is unbounded, as it is expected that `fn ready_offchain_events` is called
// frequently, or at least with the same frequency that requests are sent.
let (ipfs_monitor_tx, ipfs_monitor_rx) = mpsc::unbounded_channel();
let (arweave_monitor_tx, arweave_monitor_rx) = mpsc::unbounded_channel();
let ipfs_monitor = spawn_monitor(
ipfs_service,
ipfs_monitor_tx,
logger.cheap_clone(),
metrics.cheap_clone(),
);
let arweave_monitor = spawn_monitor(
arweave_service,
arweave_monitor_tx,
logger.cheap_clone(),
metrics,
);
Self {
ipfs_monitor,
ipfs_monitor_rx,
arweave_monitor,
arweave_monitor_rx,
deployment_hash: subgraph_hash.to_owned(),
logger,
}
}
fn add_source(&mut self, source: offchain::Source) {
match source {
offchain::Source::Ipfs(path) => self.ipfs_monitor.monitor(IpfsRequest {
ctx: IpfsContext::new(&self.deployment_hash, &self.logger),
path,
}),
offchain::Source::Arweave(base64) => self.arweave_monitor.monitor(base64),
};
}
pub fn ready_offchain_events(&mut self) -> Result<Vec<offchain::TriggerData>, Error> {
use tokio::sync::mpsc::error::TryRecvError;
let mut triggers = vec![];
loop {
match self.ipfs_monitor_rx.try_recv() {
Ok((req, data)) => triggers.push(offchain::TriggerData {
source: offchain::Source::Ipfs(req.path),
data: Arc::new(data),
}),
Err(TryRecvError::Disconnected) => {
anyhow::bail!("ipfs monitor unexpectedly terminated")
}
Err(TryRecvError::Empty) => break,
}
}
loop {
match self.arweave_monitor_rx.try_recv() {
Ok((base64, data)) => triggers.push(offchain::TriggerData {
source: offchain::Source::Arweave(base64),
data: Arc::new(data),
}),
Err(TryRecvError::Disconnected) => {
anyhow::bail!("arweave monitor unexpectedly terminated")
}
Err(TryRecvError::Empty) => break,
}
}
Ok(triggers)
}
}