-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathconfig.rs
More file actions
319 lines (292 loc) · 9.66 KB
/
config.rs
File metadata and controls
319 lines (292 loc) · 9.66 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
use std::{
collections::{BTreeMap, HashSet},
path::{Path, PathBuf},
};
use anyhow::Context;
use ipnetwork::IpNetwork;
use ordered_float::NotNan;
use semver::Version;
use serde::{Deserialize, Serialize};
use serde_with::{DisplayFromStr, serde_as};
use thegraph_core::{
DeploymentId,
alloy::primitives::{Address, B256, BlockNumber, U256},
};
use url::Url;
use crate::{auth::ApiKey, network::subgraph_client::TrustedIndexer};
/// The Graph Gateway configuration.
#[serde_as]
#[derive(Deserialize)]
pub struct Config {
pub api_keys: ApiKeys,
pub attestations: AttestationConfig,
/// Blocklist applying to indexers.
#[serde(default)]
pub blocklist: Vec<BlocklistEntry>,
/// Chain aliases
#[serde(default)]
pub chain_aliases: BTreeMap<String, String>,
/// Ethereum RPC provider, or fixed exchange rate for testing
pub exchange_rate_provider: ExchangeRateProvider,
/// Graph network environment identifier, inserted into Kafka messages
pub graph_env_id: String,
/// Optional environment qualifier appended to Kafka topic names (e.g. "staging" results in
/// topics like "gateway_queries_staging"). When absent, default topic names are used.
#[serde(default)]
pub kafka_topic_environment: Option<String>,
/// File path of CSV containing rows of `IpNetwork,Country`
pub ip_blocker_db: Option<PathBuf>,
/// See https://github.com/confluentinc/librdkafka/blob/master/CONFIGURATION.md
#[serde(default)]
pub kafka: KafkaConfig,
/// Format log output as JSON
pub log_json: bool,
/// Minimum graph-node version that will receive queries
#[serde_as(as = "DisplayFromStr")]
pub min_graph_node_version: Version,
/// Minimum indexer-service version that will receive queries
#[serde_as(as = "DisplayFromStr")]
pub min_indexer_version: Version,
/// Trusted indexers that can serve the network subgraph for free
pub trusted_indexers: Vec<TrustedIndexer>,
/// Maximum acceptable lag (in seconds) for network subgraph responses (default: 120)
#[serde(default = "default_network_subgraph_max_lag_seconds")]
pub network_subgraph_max_lag_seconds: u64,
/// Check payment state of client (disable for testnets)
pub payment_required: bool,
/// public API port
pub port_api: u16,
/// private metrics port
pub port_metrics: u16,
/// Target for indexer fees paid per request
#[serde(deserialize_with = "deserialize_not_nan_f64")]
pub query_fees_target: NotNan<f64>,
pub receipts: Receipts,
/// Address for the Subgraph Service
pub subgraph_service: Address,
/// x402 payment support configuration
pub x402: Option<X402Config>,
}
/// API keys configuration.
///
/// See [`Config`]'s [`api_keys`](struct.Config.html#structfield.api_keys).
#[serde_as]
#[derive(Deserialize)]
#[serde(untagged)]
pub enum ApiKeys {
Endpoint {
/// URL where the API key info is served
#[serde_as(as = "DisplayFromStr")]
url: Url,
/// Bearer auth token
auth: String,
/// API keys that won't be blocked for non-payment
#[serde(default)]
special: Vec<String>,
},
KakfaTopic {
topic: String,
#[serde_as(as = "DisplayFromStr")]
bootstrap_url: Url,
bootstrap_auth: String,
/// API keys that won't be blocked for non-payment
#[serde(default)]
special: Vec<String>,
},
/// Fixed set of API keys
Fixed(Vec<ApiKey>),
}
#[derive(Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum BlocklistEntry {
Poi {
deployment: DeploymentId,
public_poi: B256,
block: BlockNumber,
},
Other {
deployment: DeploymentId,
indexer: Address,
},
}
/// Attestation configuration.
///
/// See [`Config`]'s [`attestations`](struct.Config.html#structfield.attestations).
#[derive(Deserialize)]
pub struct AttestationConfig {
pub chain_id: String,
pub dispute_manager: Address,
}
/// The exchange rate provider.
///
/// See [`Config`]'s [`exchange_rate_provider`](struct.Config.html#structfield.exchange_rate_provider).
#[serde_as]
#[derive(Deserialize)]
#[serde(untagged)]
pub enum ExchangeRateProvider {
/// Ethereum RPC provider
Rpc(#[serde_as(as = "DisplayFromStr")] Url),
/// Fixed conversion rate of GRT/USD
Fixed(#[serde(deserialize_with = "deserialize_not_nan_f64")] NotNan<f64>),
}
/// Kafka configuration.
///
/// See [`Config`]'s [`kafka`](struct.Config.html#structfield.kafka).
#[derive(Clone, Deserialize)]
pub struct KafkaConfig(BTreeMap<String, String>);
impl Default for KafkaConfig {
fn default() -> Self {
let settings = [
("bootstrap.servers", ""),
("message.timeout.ms", "3000"),
("queue.buffering.max.ms", "1000"),
("queue.buffering.max.messages", "100000"),
];
Self(
settings
.into_iter()
.map(|(k, v)| (k.to_owned(), v.to_owned()))
.collect(),
)
}
}
impl From<KafkaConfig> for rdkafka::config::ClientConfig {
fn from(mut from: KafkaConfig) -> Self {
let mut settings = KafkaConfig::default().0;
settings.append(&mut from.0);
let mut config = rdkafka::config::ClientConfig::new();
for (k, v) in settings {
config.set(&k, &v);
}
config
}
}
#[derive(Deserialize)]
pub struct Receipts {
/// TAP verifier contract chain
pub chain_id: U256,
/// TAP payer address
pub payer: Address,
/// TAP signer key
pub signer: B256,
/// TAP verifier contract address
pub verifier: Address,
}
/// x402 payment support configuration.
#[serde_as]
#[derive(Clone, Deserialize)]
pub struct X402Config {
/// x402 facilitator URL (e.g., "https://x402.org/facilitator")
#[serde_as(as = "DisplayFromStr")]
pub facilitator_url: Url,
/// Wallet address to receive USDC payments
pub receiver_address: Address,
/// Chain for USDC payments (base, base_sepolia)
#[serde(default = "default_x402_chain")]
pub chain: X402Chain,
/// Price per query in USD (e.g., 0.002 for $0.002 per query)
#[serde(deserialize_with = "deserialize_not_nan_f64")]
pub price: NotNan<f64>,
/// Optional headers to send with requests to the facilitator (e.g., for authentication)
#[serde(default)]
pub facilitator_headers: BTreeMap<String, String>,
}
/// Supported chains for x402 USDC payments.
#[derive(Clone, Copy, Debug, Default, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum X402Chain {
#[default]
Base,
BaseSepolia,
}
// -----------------------------------------------------------------------------
// Helper functions
// -----------------------------------------------------------------------------
/// Default network subgraph max lag threshold (120 seconds)
fn default_network_subgraph_max_lag_seconds() -> u64 {
120
}
/// Deserialize a `NotNan<f64>` from a `f64` and return an error if the value is NaN.
fn deserialize_not_nan_f64<'de, D>(deserializer: D) -> Result<NotNan<f64>, D::Error>
where
D: serde::Deserializer<'de>,
{
let value = f64::deserialize(deserializer)?;
NotNan::new(value).map_err(serde::de::Error::custom)
}
fn default_x402_chain() -> X402Chain {
X402Chain::Base
}
/// Returns `base` with `_{env}` appended when `env` is `Some` and non-empty, or `base` unchanged
/// otherwise.
pub fn topic_name(env: Option<&str>, base: &str) -> String {
match env.map(str::trim).filter(|s| !s.is_empty()) {
Some(env) => format!("{base}_{env}"),
None => base.to_string(),
}
}
/// Load the configuration from a JSON file.
pub fn load_from_file(path: &Path) -> anyhow::Result<Config> {
let config_content = std::fs::read_to_string(path)?;
let config = serde_json::from_str(&config_content)?;
Ok(config)
}
/// Load the IP blocklist from a CSV file.
///
/// The CSV file should contain rows of `IpNetwork,Country`.
pub fn load_ip_blocklist_from_file(path: &Path) -> anyhow::Result<HashSet<IpNetwork>> {
let db = std::fs::read_to_string(path).context("IP blocklist DB")?;
Ok(db
.lines()
.filter_map(|line| line.split_once(',')?.0.parse().ok())
.collect())
}
#[cfg(test)]
mod tests {
use super::topic_name;
#[test]
fn topic_name_no_env() {
assert_eq!(topic_name(None, "gateway_queries"), "gateway_queries");
assert_eq!(
topic_name(None, "gateway_attestations"),
"gateway_attestations"
);
assert_eq!(topic_name(None, "gateway_blocklist"), "gateway_blocklist");
}
#[test]
fn topic_name_with_env() {
assert_eq!(
topic_name(Some("staging"), "gateway_queries"),
"gateway_queries_staging",
);
assert_eq!(
topic_name(Some("staging"), "gateway_attestations"),
"gateway_attestations_staging",
);
assert_eq!(
topic_name(Some("staging"), "gateway_blocklist"),
"gateway_blocklist_staging",
);
}
#[test]
fn topic_name_env_applies_to_any_base() {
assert_eq!(topic_name(Some("mainnet"), "foo"), "foo_mainnet");
assert_eq!(topic_name(Some("testnet"), "bar"), "bar_testnet");
}
#[test]
fn topic_name_empty_env_treated_as_none() {
assert_eq!(topic_name(Some(""), "gateway_queries"), "gateway_queries");
assert_eq!(topic_name(Some(" "), "gateway_queries"), "gateway_queries");
assert_eq!(
topic_name(Some("\t\n"), "gateway_queries"),
"gateway_queries"
);
}
#[test]
fn topic_name_env_is_trimmed() {
assert_eq!(
topic_name(Some(" staging "), "gateway_queries"),
"gateway_queries_staging"
);
}
}