-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathconfig.rs
More file actions
491 lines (410 loc) · 14.4 KB
/
config.rs
File metadata and controls
491 lines (410 loc) · 14.4 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
mod watcher;
pub use watcher::{ConfigWatcher, NewChainEvent, SharedHttpConfig};
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::path::Path;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config {
/// HTTP API settings
#[serde(default)]
pub http: HttpConfig,
/// Prometheus metrics settings
#[serde(default)]
pub prometheus: PrometheusConfig,
/// Chains to index
pub chains: Vec<ChainConfig>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HttpConfig {
/// Enable HTTP API (default: true)
#[serde(default = "default_true")]
pub enabled: bool,
/// HTTP API port (default: 8080)
#[serde(default = "default_http_port")]
pub port: u16,
/// Bind address (default: 0.0.0.0)
#[serde(default = "default_bind")]
pub bind: String,
/// Trusted CIDRs for admin operations (e.g., `100.64.0.0/10` for Tailscale)
#[serde(default)]
pub trusted_cidrs: Vec<String>,
}
impl Default for HttpConfig {
fn default() -> Self {
Self {
enabled: true,
port: 8080,
bind: "0.0.0.0".to_string(),
trusted_cidrs: Vec::new(),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PrometheusConfig {
/// Enable Prometheus metrics (default: true)
#[serde(default = "default_true")]
pub enabled: bool,
/// Metrics port (default: 9090)
#[serde(default = "default_metrics_port")]
pub port: u16,
}
impl Default for PrometheusConfig {
fn default() -> Self {
Self {
enabled: true,
port: 9090,
}
}
}
fn default_true() -> bool {
true
}
fn default_http_port() -> u16 {
8080
}
fn default_bind() -> String {
"0.0.0.0".to_string()
}
fn default_metrics_port() -> u16 {
9090
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChainConfig {
/// Chain name (for display/logging)
pub name: String,
/// Chain ID
pub chain_id: u64,
/// RPC URL
pub rpc_url: String,
/// Database connection URL for this chain.
/// If `pg_password_env` is set, the password in this URL will be replaced
/// with the value from that environment variable.
pub pg_url: String,
/// Environment variable name containing the PostgreSQL password.
/// When set, the password portion of `pg_url` is replaced with this value.
#[serde(default)]
pub pg_password_env: Option<String>,
/// Starting block number for indexing (default: 0 = genesis).
/// When set, backfill will stop at this block instead of going to genesis.
#[serde(default)]
pub start_block: u64,
/// Enable backfill to genesis (default: true)
#[serde(default = "default_backfill")]
pub backfill: bool,
/// Batch size for RPC requests (default: 100)
#[serde(default = "default_batch_size")]
pub batch_size: u64,
/// Number of concurrent gap-fill workers (default: 4)
#[serde(default = "default_concurrency")]
pub concurrency: usize,
/// Complete backfill before starting realtime sync (default: false)
/// When true, syncs all gaps to genesis before following chain head.
/// When false (default), runs realtime and backfill concurrently.
#[serde(default)]
pub backfill_first: bool,
/// Trust RPC data without validating parent hashes (default: false)
/// When true, skips reorg detection for faster sync on trusted RPCs.
/// Use for chains with frequent shallow reorgs where RPC is authoritative.
#[serde(default)]
pub trust_rpc: bool,
/// Separate PostgreSQL URL for the HTTP API (e.g., a CNPG `-r` read replica).
/// When set, the API connection pool connects to this URL instead of `pg_url`.
/// If `api_pg_password_env` is also set, the password is injected into this URL.
#[serde(default)]
pub api_pg_url: Option<String>,
/// Environment variable name containing the API PostgreSQL password.
/// When set, replaces the password in `api_pg_url` with the env var value.
/// Has no effect without `api_pg_url`.
#[serde(default)]
pub api_pg_password_env: Option<String>,
/// ClickHouse OLAP settings (for analytical queries)
#[serde(default)]
pub clickhouse: Option<ClickHouseConfig>,
}
/// Configuration for ClickHouse OLAP engine
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClickHouseConfig {
/// Enable ClickHouse OLAP queries (default: false)
#[serde(default)]
pub enabled: bool,
/// Primary ClickHouse HTTP URL (default: http://clickhouse:8123)
#[serde(default = "default_clickhouse_url")]
pub url: String,
/// Additional ClickHouse instance URLs for failover.
/// Queries go to the primary `url`; failover instances are tried
/// in order if the primary is unavailable.
#[serde(default)]
pub failover_urls: Vec<String>,
/// Database name override (default: tidx_{chain_id})
#[serde(default)]
pub database: Option<String>,
/// ClickHouse username for HTTP basic auth.
#[serde(default)]
pub user: Option<String>,
/// Environment variable name containing the ClickHouse password.
/// When set, the password is read from this env var at startup.
#[serde(default)]
pub password_env: Option<String>,
}
impl ClickHouseConfig {
/// Returns all URLs: primary first, then failover instances.
pub fn all_urls(&self) -> Vec<&str> {
let mut urls = vec![self.url.as_str()];
urls.extend(self.failover_urls.iter().map(|u| u.as_str()));
urls
}
/// Resolve the ClickHouse password from the environment variable specified by `password_env`.
pub fn resolved_password(&self) -> Result<Option<String>> {
match &self.password_env {
Some(env_var) => {
let password = std::env::var(env_var).with_context(|| {
format!(
"clickhouse password_env '{env_var}' is set but environment variable not found"
)
})?;
Ok(Some(password))
}
None => Ok(None),
}
}
}
impl Default for ClickHouseConfig {
fn default() -> Self {
Self {
enabled: false,
url: "http://clickhouse:8123".to_string(),
failover_urls: Vec::new(),
database: None,
user: None,
password_env: None,
}
}
}
fn default_clickhouse_url() -> String {
"http://clickhouse:8123".to_string()
}
fn default_backfill() -> bool {
true
}
impl ChainConfig {
/// Returns the PostgreSQL connection URL with password resolved from environment if configured.
/// If `pg_password_env` is set, replaces the password in `pg_url` with the env var value.
pub fn resolved_pg_url(&self) -> Result<String> {
match &self.pg_password_env {
Some(env_var) => {
let password = std::env::var(env_var).with_context(|| {
format!("pg_password_env '{env_var}' is set but environment variable not found")
})?;
let mut url = url::Url::parse(&self.pg_url)
.with_context(|| format!("Invalid pg_url: {}", self.pg_url))?;
url.set_password(Some(&password))
.map_err(|()| anyhow::anyhow!("Failed to set password in pg_url"))?;
Ok(url.to_string())
}
None => Ok(self.pg_url.clone()),
}
}
/// Returns a separate API database URL for read-only queries.
/// Returns `None` if `api_pg_url` is not set (API uses the main pool).
pub fn resolved_api_pg_url(&self) -> Result<Option<String>> {
let api_url = match &self.api_pg_url {
Some(url) => url,
None => return Ok(None),
};
match &self.api_pg_password_env {
Some(pass_env) => {
let password = std::env::var(pass_env).with_context(|| {
format!(
"api_pg_password_env '{pass_env}' is set but environment variable not found"
)
})?;
let mut url = url::Url::parse(api_url)
.with_context(|| format!("Invalid api_pg_url: {api_url}"))?;
url.set_password(Some(&password))
.map_err(|()| anyhow::anyhow!("Failed to set password in api_pg_url"))?;
Ok(Some(url.to_string()))
}
None => Ok(Some(api_url.clone())),
}
}
}
fn default_batch_size() -> u64 {
100
}
fn default_concurrency() -> usize {
4
}
impl Config {
pub fn load(path: &Path) -> Result<Self> {
let content = std::fs::read_to_string(path)
.with_context(|| format!("Failed to read config file: {}", path.display()))?;
let config: Config = toml::from_str(&content)
.with_context(|| format!("Failed to parse config file: {}", path.display()))?;
if config.chains.is_empty() {
anyhow::bail!("No chains configured. Add at least one [[chains]] section.");
}
Ok(config)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_chain_config_defaults() {
let toml_str = r#"
name = "test"
chain_id = 1
rpc_url = "http://localhost:8545"
pg_url = "postgres://localhost/test"
"#;
let config: ChainConfig = toml::from_str(toml_str).unwrap();
assert!(config.backfill);
assert_eq!(config.batch_size, 100);
assert_eq!(config.concurrency, 4);
assert_eq!(config.start_block, 0);
}
#[test]
fn test_chain_config_with_start_block() {
let toml_str = r#"
name = "test"
chain_id = 1
rpc_url = "http://localhost:8545"
pg_url = "postgres://localhost/test"
start_block = 1000
"#;
let config: ChainConfig = toml::from_str(toml_str).unwrap();
assert_eq!(config.start_block, 1000);
}
#[test]
fn test_full_config_with_multiple_chains() {
let toml_str = r#"
[http]
enabled = true
port = 8080
[prometheus]
enabled = true
port = 9090
[[chains]]
name = "chain1"
chain_id = 1
rpc_url = "http://localhost:8545"
pg_url = "postgres://localhost/chain1"
[[chains]]
name = "chain2"
chain_id = 2
rpc_url = "http://localhost:8546"
pg_url = "postgres://localhost/chain2"
"#;
let config: Config = toml::from_str(toml_str).unwrap();
assert_eq!(config.chains.len(), 2);
}
#[test]
fn test_clickhouse_config_with_failover() {
let toml_str = r#"
name = "test"
chain_id = 1
rpc_url = "http://localhost:8545"
pg_url = "postgres://localhost/test"
[clickhouse]
enabled = true
url = "http://clickhouse-1:8123"
failover_urls = ["http://clickhouse-2:8123", "http://clickhouse-3:8123"]
"#;
let config: ChainConfig = toml::from_str(toml_str).unwrap();
let ch = config.clickhouse.unwrap();
assert!(ch.enabled);
assert_eq!(ch.url, "http://clickhouse-1:8123");
assert_eq!(ch.failover_urls.len(), 2);
assert_eq!(
ch.all_urls(),
vec![
"http://clickhouse-1:8123",
"http://clickhouse-2:8123",
"http://clickhouse-3:8123",
]
);
}
#[test]
fn test_clickhouse_config_without_failover() {
let toml_str = r#"
name = "test"
chain_id = 1
rpc_url = "http://localhost:8545"
pg_url = "postgres://localhost/test"
[clickhouse]
enabled = true
url = "http://clickhouse:8123"
"#;
let config: ChainConfig = toml::from_str(toml_str).unwrap();
let ch = config.clickhouse.unwrap();
assert!(ch.failover_urls.is_empty());
assert_eq!(ch.all_urls(), vec!["http://clickhouse:8123"]);
}
#[test]
fn test_resolved_pg_url_without_env() {
let config = ChainConfig {
name: "test".to_string(),
chain_id: 1,
rpc_url: "http://localhost:8545".to_string(),
pg_url: "postgres://user:pass@localhost/db".to_string(),
pg_password_env: None,
start_block: 0,
backfill: true,
batch_size: 100,
concurrency: 4,
backfill_first: false,
trust_rpc: false,
api_pg_url: None,
api_pg_password_env: None,
clickhouse: None,
};
assert_eq!(
config.resolved_pg_url().unwrap(),
"postgres://user:pass@localhost/db"
);
}
#[test]
fn test_resolved_pg_url_with_env() {
// PATH is always set, use it to test env var substitution
let config = ChainConfig {
name: "test".to_string(),
chain_id: 1,
rpc_url: "http://localhost:8545".to_string(),
pg_url: "postgres://user:placeholder@localhost/db".to_string(),
pg_password_env: Some("PATH".to_string()),
start_block: 0,
backfill: true,
batch_size: 100,
concurrency: 4,
backfill_first: false,
trust_rpc: false,
api_pg_url: None,
api_pg_password_env: None,
clickhouse: None,
};
let resolved = config.resolved_pg_url().unwrap();
assert!(resolved.starts_with("postgres://user:"));
assert!(resolved.ends_with("@localhost/db"));
assert!(!resolved.contains("placeholder"));
}
#[test]
fn test_resolved_pg_url_missing_env() {
let config = ChainConfig {
name: "test".to_string(),
chain_id: 1,
rpc_url: "http://localhost:8545".to_string(),
pg_url: "postgres://user:placeholder@localhost/db".to_string(),
pg_password_env: Some("NONEXISTENT_VAR_XYZ_999".to_string()),
start_block: 0,
backfill: true,
batch_size: 100,
concurrency: 4,
backfill_first: false,
trust_rpc: false,
api_pg_url: None,
api_pg_password_env: None,
clickhouse: None,
};
assert!(config.resolved_pg_url().is_err());
}
}