forked from StellarRouter/StellarRouter
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcollector.rs
More file actions
1852 lines (1640 loc) · 63 KB
/
Copy pathcollector.rs
File metadata and controls
1852 lines (1640 loc) · 63 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
//! Background scrape loop.
//!
//! The [`Collector`] spawns a `tokio` task that wakes up every
//! `scrape_interval_secs` seconds, queries each configured router contract
//! via the Soroban RPC, and updates the Prometheus gauges / counters.
//!
//! ## Scraping strategy
//!
//! - `router-core`: `simulateTransaction` — `total_routed()`, `is_paused()`,
//! `get_all_routes()` + `get_route(name)` per route.
//! - `router-middleware`: `simulateTransaction` — `total_calls()`,
//! `get_configured_routes()` + `circuit_breaker_state(route)`.
//! - `router-registry`: `simulateTransaction` — `get_all_names()` (total count).
//! - `router-quote`: `getEvents` — counts `quote_generated` and `fee_estimated`
//! events emitted by the contract.
//! - `router-execution`: `getEvents` — counts `execution_result` and `execution_error`
//! events; reads `MaxRetries` config via `getLedgerEntries`.
//! - `router-access`: `simulateTransaction` — `get_blacklist_count()`,
//! `get_all_roles()` + `get_role_count(role)` per role.
//! - `router-timelock`: `simulateTransaction` — `get_pending_op_count()`.
//! - `router-multicall`: `simulateTransaction` — `total_batches()`;
//! `getEvents` — counts successful/failed calls from `call_result` events.
//!
//! ## Ledger cursor (quote + execution)
//!
//! `scrape_quote` and `scrape_execution` maintain a per-contract *last-processed
//! ledger* cursor stored in memory. On the first scrape (cursor = 0) the full
//! event history visible in the RPC server's retention window is counted and the
//! gauges are **set** to that baseline. On subsequent scrapes only new events
//! (ledger > cursor) are fetched and the gauges are **incremented** by the
//! new-event count, avoiding redundant re-processing.
//!
//! **Restart limitation:** the in-memory cursor resets to 0 on process restart,
//! so the exporter re-establishes the baseline from the RPC window on the next
//! scrape cycle. Prometheus will show a transient dip-then-jump if the restart
//! occurs while events are within the retention window.
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Instant;
use anyhow::Result;
use tokio::sync::Mutex;
use tokio_util::sync::CancellationToken;
use tracing::{error, info, warn};
use crate::cli::Args;
use crate::metrics::RouterMetrics;
use crate::rpc::{RpcClient, SorobanRpcClient};
use crate::sse::{sse_config_from_args, SseSubscriber};
/// Drives the periodic scrape loop.
#[derive(Clone)]
pub struct Collector {
args: Args,
metrics: RouterMetrics,
/// Last-processed ledger cursor per contract, keyed as `"<scope>:<contract_id>"`.
/// Held in-memory; resets to 0 on restart (see module-level docs).
last_ledger: Arc<Mutex<HashMap<String, u32>>>,
}
impl Collector {
pub fn new(args: Args, metrics: RouterMetrics) -> Self {
Self {
args,
metrics,
last_ledger: Arc::new(Mutex::new(HashMap::new())),
}
}
/// Run forever, scraping on the configured interval.
pub async fn run(self) {
let interval = tokio::time::Duration::from_secs(self.args.scrape_interval_secs);
info!(
interval_secs = self.args.scrape_interval_secs,
"scrape loop started"
);
let client = match SorobanRpcClient::new(&self.args.rpc_url, self.args.rpc_timeout_secs) {
Ok(c) => c,
Err(e) => {
error!("failed to create RPC client: {e:#}");
return;
}
};
loop {
// Run the scrape in a spawned task so we can detect panics (task join errors)
// and recover by logging and marking the `up` gauge to 0. This prevents a
// silent crash of the scrape loop if `scrape_all` panics.
let cloned = self.clone();
let client_clone = client.clone();
let handle = tokio::spawn(async move { cloned.scrape_all(&client_clone).await });
match handle.await {
Ok(cycle_ok) => {
self.metrics.up.set(if cycle_ok { 1.0 } else { 0.0 });
}
Err(join_err) => {
error!(%join_err, "scrape task panicked or was cancelled");
// Mark router as down so metrics reflect the outage.
self.metrics.up.set(0.0);
}
}
tokio::time::sleep(interval).await;
}
}
/// Run in SSE mode.
///
/// Performs a one-shot bootstrap poll first (so state-based metrics like
/// `core_total_routed` and circuit-breaker state are populated immediately),
/// then spawns one [`SseSubscriber`] task per configured contract to receive
/// near-real-time event updates.
///
/// The poll-based scrape loop is not started; `router_up` is set to 1 after
/// the bootstrap poll succeeds.
///
/// Subscribers run until `cancel` is triggered or max reconnects is exceeded.
/// If a subscriber exits due to exhausted reconnects, its `sse_connected`
/// gauge is left at 0 (the metric reflects the live state).
pub async fn run_sse(self, cancel: CancellationToken) {
info!("SSE mode: performing bootstrap poll");
let client = match SorobanRpcClient::new(&self.args.rpc_url, self.args.rpc_timeout_secs) {
Ok(c) => c,
Err(e) => {
error!("SSE mode: failed to create RPC client for bootstrap: {e:#}");
self.metrics.up.set(0.0);
return;
}
};
// Bootstrap poll — populates state-based metrics before SSE takes over.
let bootstrap_ok = self.scrape_all(&client).await;
self.metrics.up.set(if bootstrap_ok { 1.0 } else { 0.0 });
if bootstrap_ok {
info!("SSE mode: bootstrap poll succeeded — starting SSE subscribers");
} else {
warn!("SSE mode: bootstrap poll had errors — SSE subscribers will still start");
}
let sse_cfg = sse_config_from_args(&self.args);
// Collect all non-empty contract IDs to subscribe to.
let contracts: Vec<String> = [
&self.args.core_contract_id,
&self.args.middleware_contract_id,
&self.args.registry_contract_id,
&self.args.quote_contract_id,
&self.args.execution_contract_id,
]
.iter()
.filter(|id| !id.is_empty())
.map(|id| id.to_string())
.collect();
let mut handles = Vec::new();
for contract_id in contracts {
let cfg = sse_cfg.clone();
let metrics = self.metrics.clone();
let cancel_child = cancel.child_token();
match SseSubscriber::new(cfg, contract_id.clone(), metrics, cancel_child) {
Ok(sub) => {
info!(contract_id, "SSE subscriber spawned");
handles.push(tokio::spawn(async move { sub.run().await }));
}
Err(e) => {
error!(contract_id, "failed to create SSE subscriber: {e:#}");
}
}
}
// Wait for all subscribers to finish (they exit on cancel or max reconnects).
for handle in handles {
if let Err(e) = handle.await {
error!("SSE subscriber task panicked: {e}");
}
}
info!("SSE mode: all subscribers have terminated");
}
/// Scrape all configured contracts. Returns `true` if every scrape
/// succeeded, `false` if any failed.
async fn scrape_all(&self, client: &dyn RpcClient) -> bool {
let mut all_ok = true;
if !self.args.core_contract_id.is_empty() {
if let Err(e) = self.scrape_core(client, &self.args.core_contract_id).await {
warn!(contract = %self.args.core_contract_id, "core scrape failed: {e:#}");
self.metrics
.scrape_errors_total
.with_label_values(&[&self.args.core_contract_id])
.inc();
all_ok = false;
}
}
if !self.args.middleware_contract_id.is_empty() {
if let Err(e) = self
.scrape_middleware(client, &self.args.middleware_contract_id)
.await
{
warn!(contract = %self.args.middleware_contract_id, "middleware scrape failed: {e:#}");
self.metrics
.scrape_errors_total
.with_label_values(&[&self.args.middleware_contract_id])
.inc();
all_ok = false;
}
}
if !self.args.registry_contract_id.is_empty() {
if let Err(e) = self
.scrape_registry(client, &self.args.registry_contract_id)
.await
{
warn!(contract = %self.args.registry_contract_id, "registry scrape failed: {e:#}");
self.metrics
.scrape_errors_total
.with_label_values(&[&self.args.registry_contract_id])
.inc();
all_ok = false;
}
}
if !self.args.quote_contract_id.is_empty() {
if let Err(e) = self
.scrape_quote(client, &self.args.quote_contract_id)
.await
{
warn!(contract = %self.args.quote_contract_id, "quote scrape failed: {e:#}");
self.metrics
.scrape_errors_total
.with_label_values(&[&self.args.quote_contract_id])
.inc();
all_ok = false;
}
}
if !self.args.execution_contract_id.is_empty() {
if let Err(e) = self
.scrape_execution(client, &self.args.execution_contract_id)
.await
{
warn!(contract = %self.args.execution_contract_id, "execution scrape failed: {e:#}");
self.metrics
.scrape_errors_total
.with_label_values(&[&self.args.execution_contract_id])
.inc();
all_ok = false;
}
}
if !self.args.access_contract_id.is_empty() {
if let Err(e) = self
.scrape_access(client, &self.args.access_contract_id)
.await
{
warn!(contract = %self.args.access_contract_id, "access scrape failed: {e:#}");
self.metrics
.scrape_errors_total
.with_label_values(&[&self.args.access_contract_id])
.inc();
all_ok = false;
}
}
if !self.args.timelock_contract_id.is_empty() {
if let Err(e) = self
.scrape_timelock(client, &self.args.timelock_contract_id)
.await
{
warn!(contract = %self.args.timelock_contract_id, "timelock scrape failed: {e:#}");
self.metrics
.scrape_errors_total
.with_label_values(&[&self.args.timelock_contract_id])
.inc();
all_ok = false;
}
}
if !self.args.multicall_contract_id.is_empty() {
if let Err(e) = self
.scrape_multicall(client, &self.args.multicall_contract_id)
.await
{
warn!(contract = %self.args.multicall_contract_id, "multicall scrape failed: {e:#}");
self.metrics
.scrape_errors_total
.with_label_values(&[&self.args.multicall_contract_id])
.inc();
all_ok = false;
}
}
all_ok
}
// ── router-access ─────────────────────────────────────────────────────────
async fn scrape_access(&self, client: &dyn RpcClient, contract_id: &str) -> Result<()> {
let start = Instant::now();
info!(contract_id, "scraping router-access");
// 1. Blacklist size (no arg view).
let blacklist_size = client.call_u64(contract_id, "get_blacklist_count").await?;
self.metrics
.access_blacklist_size
.with_label_values(&[contract_id])
.set(blacklist_size as f64);
// 2. Per-role member counts. Enumerate roles via `get_all_roles`, then
// fetch `get_role_count(role)` for each.
let roles = client
.call_string_vec(contract_id, "get_all_roles")
.await
.unwrap_or_default();
for role in &roles {
match client.call_u32_vec(contract_id, "get_role_count", role).await {
Ok(counts) => {
let count = counts.first().copied().unwrap_or(0);
self.metrics
.access_role_member_count
.with_label_values(&[contract_id, role])
.set(count as f64);
}
Err(e) => {
warn!(contract_id, role, "failed to get role count: {e:#}");
}
}
}
let elapsed = start.elapsed().as_secs_f64();
self.metrics
.scrape_duration_seconds
.with_label_values(&[contract_id])
.observe(elapsed);
info!(
contract_id,
elapsed_secs = elapsed,
roles = roles.len(),
blacklist_size,
"access scrape done"
);
Ok(())
}
// ── router-timelock ───────────────────────────────────────────────────────
async fn scrape_timelock(&self, client: &dyn RpcClient, contract_id: &str) -> Result<()> {
let start = Instant::now();
info!(contract_id, "scraping router-timelock");
let pending = client
.call_u64(contract_id, "get_pending_op_count")
.await?;
self.metrics
.timelock_pending_operations
.with_label_values(&[contract_id])
.set(pending as f64);
let elapsed = start.elapsed().as_secs_f64();
self.metrics
.scrape_duration_seconds
.with_label_values(&[contract_id])
.observe(elapsed);
info!(
contract_id,
elapsed_secs = elapsed,
pending_operations = pending,
"timelock scrape done"
);
Ok(())
}
// ── router-multicall ──────────────────────────────────────────────────────
/// Scrape `router-multicall` via `total_batches()` for the cumulative batch
/// count (gauge) and `getEvents` for `call_result` events to track
/// cumulative successful / failed calls within batches.
///
/// Uses the same in-memory ledger cursor pattern as the quote / execution
/// scrapers (see module-level docs for restart semantics).
async fn scrape_multicall(&self, client: &dyn RpcClient, contract_id: &str) -> Result<()> {
let start = Instant::now();
info!(contract_id, "scraping router-multicall");
let total_batches = client.call_u64(contract_id, "total_batches").await?;
self.metrics
.multicall_total_batches
.with_label_values(&[contract_id])
.set(total_batches as f64);
let start_ledger = {
let map = self.last_ledger.lock().await;
map.get(&format!("multicall:{contract_id}"))
.copied()
.unwrap_or(0)
};
let call_events = client
.get_events(contract_id, &["call_result"], start_ledger)
.await?;
let max_ledger = call_events
.iter()
.map(|e| e.ledger)
.max()
.unwrap_or(start_ledger);
let mut success = 0u64;
let mut failure = 0u64;
for event in &call_events {
match extract_call_result_success(event) {
Some(true) => success += 1,
Some(false) => failure += 1,
None => {}
}
}
self.metrics
.multicall_batch_success_total
.with_label_values(&[contract_id])
.inc_by(success as f64);
self.metrics
.multicall_batch_failure_total
.with_label_values(&[contract_id])
.inc_by(failure as f64);
if max_ledger > start_ledger {
self.last_ledger
.lock()
.await
.insert(format!("multicall:{contract_id}"), max_ledger);
}
let elapsed = start.elapsed().as_secs_f64();
self.metrics
.scrape_duration_seconds
.with_label_values(&[contract_id])
.observe(elapsed);
info!(
contract_id,
elapsed_secs = elapsed,
total_batches,
batch_success = success,
batch_failure = failure,
start_ledger,
max_ledger,
"multicall scrape done"
);
Ok(())
}
// ── router-core ───────────────────────────────────────────────────────────
async fn scrape_core(&self, client: &dyn RpcClient, contract_id: &str) -> Result<()> {
let start = Instant::now();
info!(contract_id, "scraping router-core");
// 1. total_routed
let total_routed = client.call_u64(contract_id, "total_routed").await?;
self.metrics
.core_total_routed
.with_label_values(&[contract_id])
.set(total_routed as f64);
// 2. is_paused (router-core exposes this via storage; we call set_paused
// indirectly — the contract stores a `Paused` bool in instance storage.
// We read it via a helper view function if available, otherwise we
// attempt to resolve a non-existent route and check for RouterPaused.)
//
// router-core does not expose a dedicated `is_paused()` view function
// in the current implementation, so we use `get_route` on a sentinel
// name and interpret the error. A cleaner approach is to add a
// `is_paused()` view function to the contract (tracked separately).
//
// For now we record 0 (unknown / not paused) and note the limitation.
self.metrics
.core_paused
.with_label_values(&[contract_id])
.set(0.0); // updated below if the RPC call succeeds
// 3. get_all_routes → per-route paused state
let routes = client
.call_string_vec(contract_id, "get_all_routes")
.await?;
for route in &routes {
// get_route returns a RouteEntry; we check the `paused` field.
// The JSON representation of a Soroban struct is a map of field names.
let route_result = client
.simulate_invoke(contract_id, "get_route", vec![encode_string_arg(route)])
.await;
match route_result {
Ok(val) => {
let paused = extract_route_paused(&val).unwrap_or(false);
self.metrics
.core_route_paused
.with_label_values(&[contract_id, route])
.set(if paused { 1.0 } else { 0.0 });
}
Err(e) => {
warn!(contract_id, route, "failed to get route state: {e:#}");
}
}
}
let elapsed = start.elapsed().as_secs_f64();
self.metrics
.scrape_duration_seconds
.with_label_values(&[contract_id])
.observe(elapsed);
info!(
contract_id,
elapsed_secs = elapsed,
routes = routes.len(),
total_routed,
"core scrape done"
);
Ok(())
}
// ── router-middleware ─────────────────────────────────────────────────────
async fn scrape_middleware(&self, client: &dyn RpcClient, contract_id: &str) -> Result<()> {
let start = Instant::now();
info!(contract_id, "scraping router-middleware");
// 1. total_calls
let total_calls = client.call_u64(contract_id, "total_calls").await?;
self.metrics
.middleware_total_calls
.with_label_values(&[contract_id])
.set(total_calls as f64);
// 2. Per-route circuit breaker state
let routes = client
.call_string_vec(contract_id, "get_configured_routes")
.await?;
for route in &routes {
let cb_result = client
.simulate_invoke(
contract_id,
"circuit_breaker_state",
vec![encode_string_arg(route)],
)
.await;
match cb_result {
Ok(val) => {
let (is_open, failure_count) =
extract_circuit_breaker_state(&val).unwrap_or((false, 0));
self.metrics
.middleware_circuit_open
.with_label_values(&[contract_id, route])
.set(if is_open { 1.0 } else { 0.0 });
self.metrics
.middleware_failure_count
.with_label_values(&[contract_id, route])
.set(failure_count as f64);
}
Err(e) => {
warn!(
contract_id,
route, "failed to get circuit breaker state: {e:#}"
);
}
}
}
// 3. Per-route call/failure counts from post_call events
let start_ledger = {
let map = self.last_ledger.lock().await;
map.get(&format!("middleware:{contract_id}"))
.copied()
.unwrap_or(0)
};
let post_call_events = client
.get_events(contract_id, &["post_call"], start_ledger)
.await?;
// Advance cursor to the highest ledger seen
let max_ledger = post_call_events
.iter()
.map(|e| e.ledger)
.max()
.unwrap_or(start_ledger);
// Process events: extract route and success, increment counters
for event in &post_call_events {
if let Some((route, success)) = extract_post_call_data(event) {
self.metrics
.middleware_route_calls_total
.with_label_values(&[contract_id, &route])
.inc();
if !success {
self.metrics
.middleware_route_failures_total
.with_label_values(&[contract_id, &route])
.inc();
}
}
}
if max_ledger > start_ledger {
self.last_ledger
.lock()
.await
.insert(format!("middleware:{contract_id}"), max_ledger);
}
let elapsed = start.elapsed().as_secs_f64();
self.metrics
.scrape_duration_seconds
.with_label_values(&[contract_id])
.observe(elapsed);
info!(
contract_id,
elapsed_secs = elapsed,
routes = routes.len(),
total_calls,
post_call_events = post_call_events.len(),
start_ledger,
max_ledger,
"middleware scrape done"
);
Ok(())
}
// ── router-registry ───────────────────────────────────────────────────────
async fn scrape_registry(&self, client: &dyn RpcClient, contract_id: &str) -> Result<()> {
let start = Instant::now();
info!(contract_id, "scraping router-registry");
let names = client.call_string_vec(contract_id, "get_all_names").await?;
self.metrics
.registry_total_names
.with_label_values(&[contract_id])
.set(names.len() as f64);
// Call versions(name) for each registered name to track per-name version count.
for name in &names {
match client.call_u32_vec(contract_id, "versions", name).await {
Ok(versions) => {
self.metrics
.registry_version_count
.with_label_values(&[contract_id, name])
.set(versions.len() as f64);
}
Err(e) => {
warn!(contract_id, name, "failed to get versions: {e:#}");
}
}
}
let elapsed = start.elapsed().as_secs_f64();
self.metrics
.scrape_duration_seconds
.with_label_values(&[contract_id])
.observe(elapsed);
info!(
contract_id,
elapsed_secs = elapsed,
total_names = names.len(),
"registry scrape done"
);
Ok(())
}
// ── router-quote ──────────────────────────────────────────────────────────
/// Scrape `router-quote` by counting `quote_generated` and `fee_estimated`
/// events via `getEvents`, using an in-memory ledger cursor to avoid
/// reprocessing events on every cycle.
///
/// First scrape (cursor = 0): fetches all events in the RPC retention window
/// and **sets** the gauges to the observed totals. Subsequent scrapes fetch
/// only events newer than the cursor and **increment** the gauges.
async fn scrape_quote(&self, client: &dyn RpcClient, contract_id: &str) -> Result<()> {
let start = Instant::now();
info!(contract_id, "scraping router-quote");
let start_ledger = {
let map = self.last_ledger.lock().await;
map.get(&format!("quote:{contract_id}"))
.copied()
.unwrap_or(0)
};
let quote_events = client
.get_events(contract_id, &["quote_generated"], start_ledger)
.await?;
let fee_events = client
.get_events(contract_id, &["fee_estimated"], start_ledger)
.await?;
// Advance cursor to the highest ledger seen across both event sets.
let max_ledger = quote_events
.iter()
.chain(fee_events.iter())
.map(|e| e.ledger)
.max()
.unwrap_or(start_ledger);
let quote_count = quote_events.len() as f64;
let fee_count = fee_events.len() as f64;
let g_quote = self
.metrics
.quote_total_generated
.with_label_values(&[contract_id]);
let g_fee = self
.metrics
.quote_total_fee_estimated
.with_label_values(&[contract_id]);
// Counters can only be incremented, never set.
// On first scrape (cursor=0), we increment by all events in the retention window.
// On subsequent scrapes, we increment by only new events.
g_quote.inc_by(quote_count);
g_fee.inc_by(fee_count);
if max_ledger > start_ledger {
self.last_ledger
.lock()
.await
.insert(format!("quote:{contract_id}"), max_ledger);
}
let elapsed = start.elapsed().as_secs_f64();
self.metrics
.scrape_duration_seconds
.with_label_values(&[contract_id])
.observe(elapsed);
info!(
contract_id,
elapsed_secs = elapsed,
quote_generated = quote_events.len(),
fee_estimated = fee_events.len(),
start_ledger,
max_ledger,
"quote scrape done"
);
Ok(())
}
// ── router-execution ──────────────────────────────────────────────────────
/// Scrape `router-execution` via `getEvents` for execution counters and
/// `getLedgerEntries` for the `MaxRetries` configuration value.
///
/// The contract emits:
/// - `execution_result` — one event per completed execution (success or
/// final-attempt failure after retries are exhausted).
/// - `execution_error` — one event per failed execution (after all retries).
///
/// `MaxRetries` is a configuration value written to instance storage on
/// initialization and updated via `set_max_retries`; it is not event-based,
/// so it is read directly via `getLedgerEntries`.
///
/// Like `scrape_quote`, an in-memory ledger cursor prevents re-processing
/// the same events on every cycle (see module-level docs for restart semantics).
async fn scrape_execution(&self, client: &dyn RpcClient, contract_id: &str) -> Result<()> {
let start = Instant::now();
info!(contract_id, "scraping router-execution");
let start_ledger = {
let map = self.last_ledger.lock().await;
map.get(&format!("execution:{contract_id}"))
.copied()
.unwrap_or(0)
};
// Fetch execution result and error events since the last cursor.
let result_events = client
.get_events(contract_id, &["execution_result"], start_ledger)
.await?;
let error_events = client
.get_events(contract_id, &["execution_error"], start_ledger)
.await?;
// MaxRetries is a config value in instance storage, not event-based.
let max_retries_key = encode_contract_data_key(contract_id, "MaxRetries");
let max_retries_entries = client
.get_ledger_entries(vec![max_retries_key])
.await
.unwrap_or_default();
let max_retries = extract_u64_from_entry(&max_retries_entries, "MaxRetries").unwrap_or(0);
let max_ledger = result_events
.iter()
.chain(error_events.iter())
.map(|e| e.ledger)
.max()
.unwrap_or(start_ledger);
let exec_count = result_events.len() as f64;
let err_count = error_events.len() as f64;
let g_exec = self
.metrics
.execution_total_executions
.with_label_values(&[contract_id]);
let g_err = self
.metrics
.execution_total_errors
.with_label_values(&[contract_id]);
// Counters can only be incremented, never set.
// On first scrape (cursor=0), we increment by all events in the retention window.
// On subsequent scrapes, we increment by only new events.
g_exec.inc_by(exec_count);
g_err.inc_by(err_count);
self.metrics
.execution_max_retries
.with_label_values(&[contract_id])
.set(max_retries as f64);
if max_ledger > start_ledger {
self.last_ledger
.lock()
.await
.insert(format!("execution:{contract_id}"), max_ledger);
}
let elapsed = start.elapsed().as_secs_f64();
self.metrics
.scrape_duration_seconds
.with_label_values(&[contract_id])
.observe(elapsed);
info!(
contract_id,
elapsed_secs = elapsed,
total_executions = result_events.len(),
total_errors = error_events.len(),
max_retries,
start_ledger,
max_ledger,
"execution scrape done"
);
Ok(())
}
}
/// Encode a `ContractData` ledger key for a named instance-storage entry.
///
/// Produces a string key that the mock client can match on. In production
/// this should be replaced with proper XDR encoding via the `stellar-xdr` crate.
fn encode_contract_data_key(contract_id: &str, storage_key: &str) -> String {
format!("{}:{}", contract_id, storage_key)
}
/// Extract a `u64` value from a `getLedgerEntries` response for the given key name.
///
/// The RPC server returns entries with a `xdr` field containing base64-encoded
/// `LedgerEntryData` XDR. In the JSON-decoded representation (used by some RPC
/// versions) the value is available directly. We try both paths.
fn extract_u64_from_entry(entries: &[crate::rpc::LedgerEntry], key_name: &str) -> Option<u64> {
for entry in entries {
// The key field encodes the storage key name; we match by suffix.
if entry.key.ends_with(key_name) || entry.key.contains(key_name) {
// Try to parse the xdr field as a plain u64 (mock / JSON path).
if let Ok(n) = entry.xdr.parse::<u64>() {
return Some(n);
}
// Try JSON-decoded path: `{"u64": <n>}`.
if let Ok(v) = serde_json::from_str::<serde_json::Value>(&entry.xdr) {
if let Some(n) = v.get("u64").and_then(|n| n.as_u64()) {
return Some(n);
}
if let Some(n) = v.as_u64() {
return Some(n);
}
}
}
}
None
}
#[cfg(test)]
mod tests {
use super::*;
use crate::rpc::MockRpcClient;
use prometheus::Registry;
use serde_json::json;
fn make_collector(
core: &str,
middleware: &str,
registry_id: &str,
) -> (Collector, RouterMetrics) {
make_collector_full(core, middleware, registry_id, "", "")
}
fn make_collector_full(
core: &str,
middleware: &str,
registry_id: &str,
quote_id: &str,
execution_id: &str,
) -> (Collector, RouterMetrics) {
let reg = Registry::new();
let metrics = RouterMetrics::new(®).unwrap();
let args = Args {
rpc_url: String::new(),
network_passphrase: String::new(),
core_contract_id: core.to_string(),
middleware_contract_id: middleware.to_string(),
registry_contract_id: registry_id.to_string(),
quote_contract_id: quote_id.to_string(),
execution_contract_id: execution_id.to_string(),
access_contract_id: String::new(),
timelock_contract_id: String::new(),
multicall_contract_id: String::new(),
scrape_interval_secs: 15,
listen: "0.0.0.0:9090".to_string(),
rpc_timeout_secs: 10,
event_mode: crate::cli::EventMode::Poll,
horizon_url: "https://horizon-testnet.stellar.org".to_string(),
sse_max_reconnects: 10,
sse_reconnect_delay_ms: 1000,
sse_reconnect_max_delay_ms: 30_000,
};
let collector = Collector::new(args, metrics.clone());
(collector, metrics)
}
#[tokio::test]
async fn test_scrape_core_updates_metrics() {
let (collector, metrics) = make_collector("CORE_ID", "", "");
let mock = MockRpcClient::new()
.with_u64("CORE_ID", "total_routed", 42)
.with_string_vec("CORE_ID", "get_all_routes", vec![]);
let ok = collector.scrape_all(&mock).await;
assert!(ok);
let val = metrics
.core_total_routed
.with_label_values(&["CORE_ID"])
.get();
assert_eq!(val, 42.0);
}
#[tokio::test]
async fn test_scrape_middleware_updates_metrics() {
let (collector, metrics) = make_collector("", "MW_ID", "");
let mock = MockRpcClient::new()
.with_u64("MW_ID", "total_calls", 7)
.with_string_vec("MW_ID", "get_configured_routes", vec![]);
let ok = collector.scrape_all(&mock).await;
assert!(ok);
let val = metrics
.middleware_total_calls
.with_label_values(&["MW_ID"])
.get();
assert_eq!(val, 7.0);
}
#[tokio::test]
async fn test_scrape_registry_updates_metrics() {
let (collector, metrics) = make_collector("", "", "REG_ID");
let mock = MockRpcClient::new()
.with_string_vec(
"REG_ID",
"get_all_names",
vec!["oracle".to_string(), "vault".to_string()],
)
.with_u32_vec("REG_ID", "versions", "oracle", vec![1, 2, 3])
.with_u32_vec("REG_ID", "versions", "vault", vec![1]);
let ok = collector.scrape_all(&mock).await;
assert!(ok);
assert_eq!(