-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathconfig.rs
More file actions
2221 lines (1986 loc) · 69.2 KB
/
config.rs
File metadata and controls
2221 lines (1986 loc) · 69.2 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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use graph::{
anyhow::Error,
blockchain::BlockchainKind,
components::{
network_provider::{AmpChainNames, ChainName},
store::BLOCK_CACHE_SIZE,
},
env::ENV_VARS,
firehose::{SubgraphLimit, SUBGRAPHS_PER_CONN},
itertools::Itertools,
prelude::{
anyhow::{anyhow, bail, Context, Result},
info,
regex::Regex,
serde::{
de::{self, value, SeqAccess, Visitor},
Deserialize, Deserializer,
},
serde_json, serde_regex, toml, Logger, NodeId, StoreError, BLOCK_NUMBER_MAX,
},
};
use graph_chain_ethereum as ethereum;
use graph_chain_ethereum::{Compression, NodeCapabilities};
use graph_store_postgres::{DeploymentPlacer, Shard as ShardName, PRIMARY_SHARD};
use graph::http::{HeaderMap, Uri};
use serde::Serialize;
use std::{
collections::{BTreeMap, BTreeSet, HashMap},
fmt,
};
use std::{fs::read_to_string, time::Duration};
use url::Url;
const ANY_NAME: &str = ".*";
/// A regular expression that matches nothing
const NO_NAME: &str = ".^";
pub struct Opt {
pub postgres_url: Option<String>,
pub config: Option<String>,
// This is only used when we cosntruct a config purely from command
// line options. When using a configuration file, pool sizes must be
// set in the configuration file alone
pub store_connection_pool_size: u32,
pub postgres_secondary_hosts: Vec<String>,
pub postgres_host_weights: Vec<usize>,
pub disable_block_ingestor: bool,
pub node_id: String,
pub ethereum_rpc: Vec<String>,
pub ethereum_ws: Vec<String>,
pub ethereum_ipc: Vec<String>,
pub unsafe_config: bool,
}
impl Default for Opt {
fn default() -> Self {
Opt {
postgres_url: None,
config: None,
store_connection_pool_size: 10,
postgres_secondary_hosts: vec![],
postgres_host_weights: vec![],
disable_block_ingestor: true,
node_id: "default".to_string(),
ethereum_rpc: vec![],
ethereum_ws: vec![],
ethereum_ipc: vec![],
unsafe_config: false,
}
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Config {
#[serde(skip, default = "default_node_id")]
pub node: NodeId,
#[serde(skip)]
pub disable_block_ingestor: bool,
pub general: Option<GeneralSection>,
#[serde(rename = "store")]
pub stores: BTreeMap<String, Shard>,
pub chains: ChainSection,
pub deployment: Deployment,
}
fn validate_name(s: &str) -> Result<()> {
if s.is_empty() {
return Err(anyhow!("names must not be empty"));
}
if s.len() > 30 {
return Err(anyhow!(
"names can be at most 30 characters, but `{}` has {} characters",
s,
s.len()
));
}
if !s
.chars()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
{
return Err(anyhow!(
"name `{}` is invalid: names can only contain lowercase alphanumeric characters or '-'",
s
));
}
Ok(())
}
impl Config {
/// Returns `true` if this node should run block ingestion.
///
/// Block ingestion runs when the `--disable-block-ingestor` kill switch
/// is **not** set and this node's id matches the `ingestor` value from
/// the `[chains]` config section.
pub fn is_block_ingestor(&self) -> bool {
!self.disable_block_ingestor && self.chains.ingestor == self.node.to_string()
}
pub fn chain_ids(&self) -> Vec<ChainName> {
self.chains
.chains
.keys()
.map(|k| k.as_str().into())
.collect()
}
/// Build an `AmpChainNames` mapping from the config. Chains with an
/// explicit `amp` name map that name to the chain name; chains without
/// use identity mapping.
pub fn amp_chain_names(&self) -> AmpChainNames {
let mapping: HashMap<ChainName, ChainName> = self
.chains
.chains
.iter()
.map(|(chain_name, chain)| {
let amp_name: ChainName =
chain.amp.as_deref().unwrap_or(chain_name.as_str()).into();
let internal_name: ChainName = chain_name.as_str().into();
(amp_name, internal_name)
})
.collect();
AmpChainNames::new(mapping)
}
/// Check that the config is valid.
fn validate(&mut self) -> Result<()> {
if !self.stores.contains_key(PRIMARY_SHARD.as_str()) {
return Err(anyhow!("missing a primary store"));
}
if self.stores.len() > 1 && ethereum::ENV_VARS.cleanup_blocks {
// See 8b6ad0c64e244023ac20ced7897fe666
return Err(anyhow!(
"GRAPH_ETHEREUM_CLEANUP_BLOCKS can not be used with a sharded store"
));
}
for (key, shard) in self.stores.iter_mut() {
shard.validate(key, &self.node)?;
}
self.deployment.validate()?;
// Check that deployment rules only reference existing stores and chains
for (i, rule) in self.deployment.rules.iter().enumerate() {
for shard in &rule.shards {
if !self.stores.contains_key(shard) {
return Err(anyhow!("unknown shard {} in deployment rule {}", shard, i));
}
}
if let Some(networks) = &rule.pred.network {
for network in networks.to_vec() {
if !self.chains.chains.contains_key(&network) {
return Err(anyhow!(
"unknown network {} in deployment rule {}",
network,
i
));
}
}
}
}
// Check that chains only reference existing stores
for (name, chain) in &self.chains.chains {
if !self.stores.contains_key(&chain.shard) {
return Err(anyhow!("unknown shard {} in chain {}", chain.shard, name));
}
}
self.chains.validate()?;
Ok(())
}
/// Load a configuration file if `opt.config` is set. If not, generate
/// a config from the command line arguments in `opt`
pub fn load(logger: &Logger, opt: &Opt) -> Result<Config> {
if let Some(config) = &opt.config {
Self::from_file(logger, config, opt)
} else {
info!(
logger,
"Generating configuration from command line arguments"
);
Self::from_opt(opt)
}
}
pub fn from_file(logger: &Logger, path: &str, opt: &Opt) -> Result<Config> {
info!(logger, "Reading configuration file `{}`", path);
Self::from_str(&read_to_string(path)?, opt)
}
pub fn from_str(config: &str, opt: &Opt) -> Result<Config> {
let mut config: Config = toml::from_str(config)?;
config.node =
NodeId::new(&opt.node_id).map_err(|node| anyhow!("invalid node id {}", node))?;
config.disable_block_ingestor = opt.disable_block_ingestor;
config.validate()?;
Ok(config)
}
fn from_opt(opt: &Opt) -> Result<Config> {
let deployment = Deployment::from_opt(opt);
let mut stores = BTreeMap::new();
let chains = ChainSection::from_opt(opt)?;
let node = NodeId::new(opt.node_id.to_string())
.map_err(|node| anyhow!("invalid node id {}", node))?;
stores.insert(PRIMARY_SHARD.to_string(), Shard::from_opt(true, opt)?);
Ok(Config {
node,
disable_block_ingestor: opt.disable_block_ingestor,
general: None,
stores,
chains,
deployment,
})
}
/// Generate a JSON representation of the config.
pub fn to_json(&self) -> Result<String> {
// It would be nice to produce a TOML representation, but that runs
// into this error: https://github.com/alexcrichton/toml-rs/issues/142
// and fixing it as described in the issue didn't fix it. Since serializing
// this data isn't crucial and only needed for debugging, we'll
// just stick with JSON
Ok(serde_json::to_string_pretty(&self)?)
}
pub fn primary_store(&self) -> &Shard {
self.stores
.get(PRIMARY_SHARD.as_str())
.expect("a validated config has a primary store")
}
pub fn query_only(&self, node: &NodeId) -> bool {
self.general
.as_ref()
.map(|g| match g.query.find(node.as_str()) {
None => false,
Some(m) => m.as_str() == node.as_str(),
})
.unwrap_or(false)
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct GeneralSection {
#[serde(with = "serde_regex", default = "no_name")]
query: Regex,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Shard {
pub connection: String,
#[serde(default = "one")]
pub weight: usize,
#[serde(default)]
pub pool_size: PoolSize,
#[serde(default = "PoolSize::five")]
pub fdw_pool_size: PoolSize,
#[serde(default)]
pub replicas: BTreeMap<String, Replica>,
}
impl Shard {
fn validate(&mut self, name: &str, node: &NodeId) -> Result<()> {
ShardName::new(name.to_string()).map_err(|e| anyhow!(e))?;
self.expand_connection(node)?;
if matches!(self.pool_size, PoolSize::None) {
return Err(anyhow!("missing pool size definition for shard `{}`", name));
}
self.pool_size
.validate(name == PRIMARY_SHARD.as_str(), &self.connection)?;
for (name, replica) in self.replicas.iter_mut() {
validate_name(name).context("illegal replica name")?;
replica.validate(name == PRIMARY_SHARD.as_str(), &self.pool_size)?;
}
let no_weight =
self.weight == 0 && self.replicas.values().all(|replica| replica.weight == 0);
if no_weight {
return Err(anyhow!(
"all weights for shard `{}` are 0; \
remove explicit weights or set at least one of them to a value bigger than 0",
name
));
}
Ok(())
}
fn from_opt(is_primary: bool, opt: &Opt) -> Result<Self> {
let postgres_url = opt
.postgres_url
.as_ref()
.expect("validation checked that postgres_url is set");
let pool_size = PoolSize::Fixed(opt.store_connection_pool_size);
pool_size.validate(is_primary, postgres_url)?;
let mut replicas = BTreeMap::new();
for (i, host) in opt.postgres_secondary_hosts.iter().enumerate() {
let replica = Replica {
connection: replace_host(postgres_url, host),
weight: opt.postgres_host_weights.get(i + 1).cloned().unwrap_or(1),
pool_size: pool_size.clone(),
};
replicas.insert(format!("replica{}", i + 1), replica);
}
Ok(Self {
connection: postgres_url.clone(),
weight: opt.postgres_host_weights.first().cloned().unwrap_or(1),
pool_size,
fdw_pool_size: PoolSize::five(),
replicas,
})
}
// Put the PGAPPNAME into the URL since tokio-postgres ignores this
// environment variable. If PGAPPNAME is not set, use `node`.
fn expand_connection(&mut self, node: &NodeId) -> Result<()> {
let app_name = std::env::var("PGAPPNAME").unwrap_or(node.to_string());
let mut url = Url::parse(shellexpand::env(&self.connection)?.as_ref())?;
let query = match url.query() {
Some(query) => {
format!("{query}&application_name={app_name}")
}
None => {
format!("application_name={app_name}")
}
};
url.set_query(Some(&query));
self.connection = url.to_string();
Ok(())
}
}
#[derive(Clone, Debug, Deserialize, Serialize, Default)]
#[serde(untagged)]
pub enum PoolSize {
#[default]
None,
Fixed(u32),
Rule(Vec<PoolSizeRule>),
}
impl PoolSize {
fn five() -> Self {
Self::Fixed(5)
}
fn validate(&self, is_primary: bool, connection: &str) -> Result<()> {
use PoolSize::*;
let pool_size = match self {
None => bail!("missing pool size for {}", connection),
Fixed(s) => *s,
Rule(rules) => rules.iter().map(|rule| rule.size).min().unwrap_or(0u32),
};
match pool_size {
0 if is_primary => Err(anyhow!(
"the pool size for the primary shard must be at least 2"
)),
0 => Ok(()),
1 => Err(anyhow!(
"connection pool size must be at least 2, but is {} for {}",
pool_size,
connection
)),
_ => Ok(()),
}
}
pub fn size_for(&self, node: &NodeId, name: &str) -> Result<u32> {
use PoolSize::*;
match self {
None => unreachable!("validation ensures we have a pool size"),
Fixed(s) => Ok(*s),
Rule(rules) => rules
.iter()
.find(|rule| rule.matches(node.as_str()))
.map(|rule| rule.size)
.ok_or_else(|| {
anyhow!(
"no rule matches node id `{}` for the pool of shard {}",
node.as_str(),
name
)
}),
}
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct PoolSizeRule {
#[serde(with = "serde_regex", default = "any_name")]
node: Regex,
size: u32,
}
impl PoolSizeRule {
fn matches(&self, name: &str) -> bool {
match self.node.find(name) {
None => false,
Some(m) => m.as_str() == name,
}
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Replica {
pub connection: String,
#[serde(default = "one")]
pub weight: usize,
#[serde(default)]
pub pool_size: PoolSize,
}
impl Replica {
fn validate(&mut self, is_primary: bool, pool_size: &PoolSize) -> Result<()> {
self.connection = shellexpand::env(&self.connection)?.into_owned();
if matches!(self.pool_size, PoolSize::None) {
self.pool_size = pool_size.clone();
}
self.pool_size.validate(is_primary, &self.connection)?;
Ok(())
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct ChainSection {
pub ingestor: String,
#[serde(flatten)]
pub chains: BTreeMap<String, Chain>,
/// The default for chains that don't set this explicitly. When running
/// without a config file, we use `BLOCK_NUMBER_MAX` to turn off pruning
/// the block cache
#[serde(default = "default_cache_size")]
pub cache_size: i32,
}
impl ChainSection {
fn validate(&mut self) -> Result<()> {
NodeId::new(&self.ingestor)
.map_err(|node| anyhow!("invalid node id for ingestor {}", node))?;
let reorg_threshold = ENV_VARS.reorg_threshold();
if self.cache_size <= reorg_threshold {
return Err(anyhow!(
"default chains.cache_size ({}) must be greater than reorg_threshold ({})",
self.cache_size,
reorg_threshold
));
}
// Apply section-level cache_size as default for chains that
// don't set their own.
for chain in self.chains.values_mut() {
if chain.cache_size == 0 {
chain.cache_size = self.cache_size;
}
}
for (name, chain) in self.chains.iter_mut() {
chain.validate()?;
if chain.cache_size <= reorg_threshold {
return Err(anyhow!(
"chain '{}': cache_size ({}) must be greater than reorg_threshold ({})",
name,
chain.cache_size,
reorg_threshold
));
}
}
// Validate that effective AMP names are unique and don't collide
// with other chain names.
let mut amp_names: BTreeMap<String, String> = BTreeMap::new();
for (chain_name, chain) in &self.chains {
let effective = chain.amp.as_deref().unwrap_or(chain_name.as_str());
if let Some(prev_chain) = amp_names.get(effective) {
return Err(anyhow!(
"duplicate AMP name `{}`: used by chains `{}` and `{}`",
effective,
prev_chain,
chain_name
));
}
// Check that an explicit amp alias doesn't collide with
// another chain's own name (which would be ambiguous).
if chain.amp.is_some() {
if let Some(other) = self.chains.get(effective) {
// Only a collision if the other chain doesn't also
// set the same amp alias (which is covered by the
// duplicate check above).
if other.amp.as_deref() != Some(effective) {
return Err(anyhow!(
"AMP alias `{}` on chain `{}` collides with chain `{}`",
effective,
chain_name,
effective,
));
}
}
}
amp_names.insert(effective.to_string(), chain_name.clone());
}
Ok(())
}
fn from_opt(opt: &Opt) -> Result<Self> {
let ingestor = opt.node_id.clone();
let mut chains = BTreeMap::new();
Self::parse_networks(&mut chains, Transport::Rpc, &opt.ethereum_rpc)?;
Self::parse_networks(&mut chains, Transport::Ws, &opt.ethereum_ws)?;
Self::parse_networks(&mut chains, Transport::Ipc, &opt.ethereum_ipc)?;
Ok(Self {
ingestor,
chains,
// When running without a config file, we do not prune the block cache
cache_size: BLOCK_NUMBER_MAX,
})
}
pub fn providers(&self) -> Vec<String> {
self.chains
.values()
.flat_map(|chain| {
chain
.providers
.iter()
.map(|p| p.label.clone())
.collect::<Vec<String>>()
})
.collect()
}
fn parse_networks(
chains: &mut BTreeMap<String, Chain>,
transport: Transport,
args: &[String],
) -> Result<()> {
for (nr, arg) in args.iter().enumerate() {
if arg.starts_with("wss://")
|| arg.starts_with("http://")
|| arg.starts_with("https://")
{
return Err(anyhow!(
"Is your Ethereum node string missing a network name? \
Try 'mainnet:' + the Ethereum node URL."
));
} else {
// Parse string (format is "NETWORK_NAME:NETWORK_CAPABILITIES:URL" OR
// "NETWORK_NAME::URL" which will default to NETWORK_CAPABILITIES="archive,traces")
let colon = arg.find(':').ok_or_else(|| {
anyhow!(
"A network name must be provided alongside the \
Ethereum node location. Try e.g. 'mainnet:URL'."
)
})?;
let (name, rest_with_delim) = arg.split_at(colon);
let rest = &rest_with_delim[1..];
if name.is_empty() {
return Err(anyhow!("Ethereum network name cannot be an empty string"));
}
if rest.is_empty() {
return Err(anyhow!("Ethereum node URL cannot be an empty string"));
}
let colon = rest.find(':').ok_or_else(|| {
anyhow!(
"A network name must be provided alongside the \
Ethereum node location. Try e.g. 'mainnet:URL'."
)
})?;
let (features, url_str) = rest.split_at(colon);
let (url, features) = if ["http", "https", "ws", "wss"].contains(&features) {
(rest, DEFAULT_PROVIDER_FEATURES.to_vec())
} else {
(&url_str[1..], features.split(',').collect())
};
let features = features.into_iter().map(|s| s.to_string()).collect();
let provider = Provider {
label: format!("{}-{}-{}", name, transport, nr),
details: ProviderDetails::Web3(Web3Provider {
transport,
url: url.to_string(),
features,
headers: Default::default(),
rules: vec![],
}),
};
let entry = chains.entry(name.to_string()).or_insert_with(|| Chain {
shard: PRIMARY_SHARD.to_string(),
protocol: BlockchainKind::Ethereum,
polling_interval: default_polling_interval(),
providers: vec![],
amp: None,
cache_size: 0,
});
entry.providers.push(provider);
}
}
Ok(())
}
}
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
pub struct Chain {
pub shard: String,
#[serde(default = "default_blockchain_kind")]
pub protocol: BlockchainKind,
#[serde(
default = "default_polling_interval",
deserialize_with = "deserialize_duration_millis"
)]
pub polling_interval: Duration,
#[serde(rename = "provider")]
pub providers: Vec<Provider>,
/// AMP network name alias. When set, AMP manifests using this name will
/// resolve to this chain. Defaults to the chain name.
#[serde(default)]
pub amp: Option<String>,
/// Number of blocks from chain head for which to keep block data
/// cached. When `GRAPH_STORE_IGNORE_BLOCK_CACHE` is set, blocks
/// older than this are treated as if they have no data.
#[serde(default)]
pub cache_size: i32,
}
fn default_cache_size() -> i32 {
BLOCK_CACHE_SIZE
}
fn default_blockchain_kind() -> BlockchainKind {
BlockchainKind::Ethereum
}
impl Chain {
fn validate(&mut self) -> Result<()> {
let mut labels = self.providers.iter().map(|p| &p.label).collect_vec();
labels.sort();
labels.dedup();
if labels.len() != self.providers.len() {
return Err(anyhow!("Provider labels must be unique"));
}
// `Config` validates that `self.shard` references a configured shard
for provider in self.providers.iter_mut() {
provider.validate()?
}
Ok(())
}
}
fn deserialize_http_headers<'de, D>(deserializer: D) -> Result<HeaderMap, D::Error>
where
D: serde::Deserializer<'de>,
{
let kvs: BTreeMap<String, String> = Deserialize::deserialize(deserializer)?;
Ok(btree_map_to_http_headers(kvs))
}
fn btree_map_to_http_headers(kvs: BTreeMap<String, String>) -> HeaderMap {
let mut headers = HeaderMap::new();
for (k, v) in kvs.into_iter() {
headers.insert(
k.parse::<graph::http::header::HeaderName>()
.unwrap_or_else(|_| panic!("invalid HTTP header name: {}", k)),
v.parse::<graph::http::header::HeaderValue>()
.unwrap_or_else(|_| panic!("invalid HTTP header value: {}: {}", k, v)),
);
}
headers
}
#[derive(Clone, Debug, Serialize, PartialEq)]
pub struct Provider {
pub label: String,
pub details: ProviderDetails,
}
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum ProviderDetails {
Firehose(FirehoseProvider),
Web3(Web3Provider),
Web3Call(Web3Provider),
}
const FIREHOSE_FILTER_FEATURE: &str = "filters";
const FIREHOSE_COMPRESSION_FEATURE: &str = "compression";
const FIREHOSE_PROVIDER_FEATURES: [&str; 2] =
[FIREHOSE_FILTER_FEATURE, FIREHOSE_COMPRESSION_FEATURE];
fn twenty() -> u16 {
20
}
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub struct FirehoseProvider {
pub url: String,
pub token: Option<String>,
pub key: Option<String>,
#[serde(default = "twenty")]
pub conn_pool_size: u16,
#[serde(default)]
pub features: BTreeSet<String>,
#[serde(default, rename = "match")]
rules: Vec<Web3Rule>,
}
impl FirehoseProvider {
pub fn limit_for(&self, node: &NodeId) -> SubgraphLimit {
self.rules.limit_for(node)
}
pub fn filters_enabled(&self) -> bool {
self.features.contains(FIREHOSE_FILTER_FEATURE)
}
pub fn compression_enabled(&self) -> bool {
self.features.contains(FIREHOSE_COMPRESSION_FEATURE)
}
}
pub trait Web3Rules {
fn limit_for(&self, node: &NodeId) -> SubgraphLimit;
}
impl Web3Rules for Vec<Web3Rule> {
fn limit_for(&self, node: &NodeId) -> SubgraphLimit {
self.iter()
.map(|rule| rule.limit_for(node))
.max()
.unwrap_or(SubgraphLimit::Unlimited)
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
struct Web3Rule {
#[serde(with = "serde_regex")]
name: Regex,
limit: usize,
}
impl PartialEq for Web3Rule {
fn eq(&self, other: &Self) -> bool {
self.name.to_string() == other.name.to_string() && self.limit == other.limit
}
}
impl Web3Rule {
fn limit_for(&self, node: &NodeId) -> SubgraphLimit {
match self.name.find(node.as_str()) {
Some(m) if m.as_str() == node.as_str() => {
if self.limit == 0 {
SubgraphLimit::Disabled
} else {
SubgraphLimit::Limit(self.limit)
}
}
_ => SubgraphLimit::Disabled,
}
}
}
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub struct Web3Provider {
#[serde(default)]
pub transport: Transport,
pub url: String,
pub features: BTreeSet<String>,
// TODO: This should be serialized.
#[serde(
skip_serializing,
default,
deserialize_with = "deserialize_http_headers"
)]
pub headers: HeaderMap,
#[serde(default, rename = "match")]
rules: Vec<Web3Rule>,
}
impl Web3Provider {
pub fn node_capabilities(&self) -> NodeCapabilities {
NodeCapabilities {
archive: self.features.contains("archive"),
traces: self.features.contains("traces"),
}
}
pub fn compression(&self) -> Compression {
if self.features.contains("compression/gzip") {
Compression::Gzip
} else if self.features.contains("compression/brotli") {
Compression::Brotli
} else if self.features.contains("compression/deflate") {
Compression::Deflate
} else {
Compression::None
}
}
pub fn limit_for(&self, node: &NodeId) -> SubgraphLimit {
self.rules.limit_for(node)
}
}
/// Supported provider features:
/// - `traces`: Provider supports debug_traceBlockByNumber for call tracing
/// - `archive`: Provider is an archive node with full historical state
/// - `no_eip1898`: Provider doesn't support EIP-1898 (block parameter by hash/number object)
/// - `no_eip2718`: Provider doesn't return the `type` field in transaction receipts.
/// When set, receipts are patched to add `"type": "0x0"` for legacy transaction compatibility.
const PROVIDER_FEATURES: [&str; 7] = [
"traces",
"archive",
"no_eip1898",
"no_eip2718",
"compression/gzip",
"compression/brotli",
"compression/deflate",
];
const DEFAULT_PROVIDER_FEATURES: [&str; 2] = ["traces", "archive"];
impl Provider {
fn validate(&mut self) -> Result<()> {
validate_name(&self.label).context("illegal provider name")?;
match self.details {
ProviderDetails::Firehose(ref mut firehose) => {
firehose.url = shellexpand::env(&firehose.url)?.into_owned();
// A Firehose url must be a valid Uri since gRPC library we use (Tonic)
// works with Uri.
let label = &self.label;
firehose.url.parse::<Uri>().map_err(|e| {
anyhow!(
"the url `{}` for firehose provider {} is not a legal URI: {}",
firehose.url,
label,
e
)
})?;
if let Some(token) = &firehose.token {
firehose.token = Some(shellexpand::env(token)?.into_owned());
}
if let Some(key) = &firehose.key {
firehose.key = Some(shellexpand::env(key)?.into_owned());
}
if firehose
.features
.iter()
.any(|feature| !FIREHOSE_PROVIDER_FEATURES.contains(&feature.as_str()))
{
return Err(anyhow!(
"supported firehose endpoint filters are: {:?}",
FIREHOSE_PROVIDER_FEATURES
));
}
if firehose.rules.iter().any(|r| r.limit > SUBGRAPHS_PER_CONN) {
bail!(
"per node subgraph limit for firehose/substreams has to be in the range 0-{}",
SUBGRAPHS_PER_CONN
);
}
}
ProviderDetails::Web3Call(ref mut web3) | ProviderDetails::Web3(ref mut web3) => {
for feature in &web3.features {
if !PROVIDER_FEATURES.contains(&feature.as_str()) {
return Err(anyhow!(
"illegal feature `{}` for provider {}. Features must be one of {}",
feature,
self.label,
PROVIDER_FEATURES.join(", ")
));
}
}
let compression_count = web3
.features
.iter()
.filter(|f| f.starts_with("compression/"))
.count();
if compression_count > 1 {
return Err(anyhow!(
"at most one compression method allowed for provider {}",
self.label
));
}
web3.url = shellexpand::env(&web3.url)?.into_owned();
let label = &self.label;
Url::parse(&web3.url).map_err(|e| {
anyhow!(
"the url `{}` for provider {} is not a legal URL: {}",
web3.url,
label,
e
)
})?;
}
}
Ok(())
}
}
impl<'de> Deserialize<'de> for Provider {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
struct ProviderVisitor;
impl<'de> serde::de::Visitor<'de> for ProviderVisitor {
type Value = Provider;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("struct Provider")
}
fn visit_map<V>(self, mut map: V) -> Result<Provider, V::Error>
where
V: serde::de::MapAccess<'de>,
{
let mut label = None;
let mut details = None;
let mut url = None;
let mut transport = None;
let mut features = None;
let mut headers = None;
let mut nodes = Vec::new();
while let Some(key) = map.next_key()? {
match key {
ProviderField::Label => {
if label.is_some() {
return Err(serde::de::Error::duplicate_field("label"));
}
label = Some(map.next_value()?);
}
ProviderField::Details => {
if details.is_some() {
return Err(serde::de::Error::duplicate_field("details"));
}
details = Some(map.next_value()?);
}
ProviderField::Url => {
if url.is_some() {
return Err(serde::de::Error::duplicate_field("url"));
}
url = Some(map.next_value()?);
}
ProviderField::Transport => {
if transport.is_some() {
return Err(serde::de::Error::duplicate_field("transport"));
}
transport = Some(map.next_value()?);
}
ProviderField::Features => {
if features.is_some() {