Skip to main content

newton_prover_metrics/
lib.rs

1//! Metrics for the newton prover task manager
2use metrics::{counter, describe_counter, describe_gauge, describe_histogram, gauge, histogram};
3
4pub mod prometheus;
5
6/// Create a new instance of the metrics
7pub fn new() {
8    // ========================================================================
9    // Operator Metrics
10    // ========================================================================
11    describe_counter!(
12        "num_signed_task_responses_accepted_by_aggregator",
13        "The number of signed task responses from this operator accepted by the aggregator"
14    );
15    describe_counter!(
16        "num_tasks_operator_evaluate_success",
17        "The number of tasks successfully evaluated by this operator"
18    );
19    describe_counter!(
20        "num_tasks_operator_evaluate_failure",
21        "The number of tasks that failed evaluation by this operator"
22    );
23    describe_histogram!(
24        "task_evaluation_duration_seconds",
25        "The duration of task evaluation operations in seconds"
26    );
27    describe_counter!(
28        "task_generator_cache_hits",
29        "The number of task generator cache hits (no on-chain call needed)"
30    );
31    describe_counter!(
32        "task_generator_cache_misses",
33        "The number of task generator cache misses (on-chain call required)"
34    );
35
36    // ========================================================================
37    // Aggregator Metrics (task_generator == aggregator in Gateway)
38    // ========================================================================
39    describe_counter!(
40        "num_tasks_aggregator_respond_success",
41        "The number of tasks successfully responded to by the aggregator"
42    );
43    describe_counter!(
44        "num_tasks_aggregator_respond_failure",
45        "The number of tasks that failed aggregator response"
46    );
47    describe_histogram!(
48        "task_aggregation_duration_seconds",
49        "The duration of task aggregation operations in seconds"
50    );
51
52    // ========================================================================
53    // Challenger Metrics
54    // ========================================================================
55    describe_counter!("num_tasks_challenge_success", "The number of successful challenges");
56    describe_counter!("num_tasks_challenge_failure", "The number of failed challenges");
57
58    // ========================================================================
59    // Service Identity Gauges
60    // ========================================================================
61    describe_gauge!("task_generator_address", "task generator signer address (gateway)");
62    describe_gauge!("aggregator_address", "aggregator wallet address");
63    describe_gauge!("operator_address", "operator wallet address");
64    describe_gauge!("operator_id", "operator id derived from bls public key");
65    describe_gauge!("challenger_address", "challenger wallet address");
66
67    // ========================================================================
68    // Gateway High-Level RPC Metrics
69    // ========================================================================
70    describe_histogram!(
71        "gateway_rpc_request_duration_seconds",
72        "Duration of Gateway RPC request by method"
73    );
74    describe_counter!(
75        "gateway_rpc_request_total",
76        "Total Gateway RPC requests by method and status"
77    );
78
79    // ========================================================================
80    // Gateway Stage Metrics (Detailed Breakdown)
81    // ========================================================================
82    describe_histogram!(
83        "gateway_data_provider_duration_seconds",
84        "Duration of policy task data fetch from WASM/cache"
85    );
86    describe_histogram!(
87        "gateway_broadcast_duration_seconds",
88        "Duration of operator broadcast with quorum"
89    );
90    describe_histogram!(
91        "gateway_bls_aggregation_duration_seconds",
92        "Duration of BLS signature aggregation"
93    );
94    describe_histogram!(
95        "gateway_onchain_submit_duration_seconds",
96        "Duration of on-chain task/response submission"
97    );
98    describe_histogram!(
99        "gateway_rpc_parallel_fetch_duration_seconds",
100        "Duration of parallel RPC calls (policy config + block number)"
101    );
102    describe_counter!(
103        "gateway_task_total",
104        "Total gateway tasks by mode (sync/async) and status"
105    );
106    // ========================================================================
107    // Gateway Resilience Metrics
108    // ========================================================================
109    describe_gauge!(
110        "gateway_worker_queue_depth",
111        "Current queue depth for background workers"
112    );
113    describe_gauge!("gateway_task_states_size", "Number of active task states in aggregator");
114    describe_gauge!(
115        "gateway_circuit_breaker_state",
116        "Circuit breaker state by operator (0=closed, 1=open, 2=half-open)"
117    );
118    describe_counter!(
119        "gateway_channel_send_total",
120        "Channel send attempts by channel and status"
121    );
122    describe_counter!("gateway_channel_retry_total", "Channel send retries by channel");
123    describe_counter!(
124        "gateway_failure_notification_total",
125        "Failure notifications sent by type and channel"
126    );
127    describe_counter!("gateway_webhook_delivery_total", "Webhook delivery attempts by status");
128    describe_gauge!("gateway_websocket_connections", "Current WebSocket connection count");
129    describe_gauge!(
130        "gateway_websocket_subscriptions",
131        "Current WebSocket subscription count"
132    );
133    describe_counter!("gateway_quorum_failures_total", "Quorum failures by reason");
134
135    // ========================================================================
136    // Gateway Cleanup Metrics
137    // ========================================================================
138    describe_counter!(
139        "gateway_cleanup_tasks_removed_total",
140        "Total stale tasks removed by periodic cleanup"
141    );
142    describe_histogram!(
143        "gateway_cleanup_duration_seconds",
144        "Duration of periodic cleanup task execution"
145    );
146
147    // ========================================================================
148    // Privacy Layer Metrics
149    // ========================================================================
150    describe_counter!("gateway_privacy_upload_total", "Total encrypted data uploads by status");
151    describe_histogram!(
152        "gateway_privacy_upload_duration_seconds",
153        "Duration of encrypted data upload processing"
154    );
155    describe_counter!("gateway_privacy_task_total", "Total privacy-enabled tasks by status");
156    describe_counter!(
157        "gateway_privacy_auth_validation_total",
158        "Total dual-signature auth validations by result"
159    );
160    describe_histogram!(
161        "gateway_privacy_auth_validation_duration_seconds",
162        "Duration of dual-signature privacy auth validation"
163    );
164    describe_counter!(
165        "operator_privacy_decryption_total",
166        "Total HPKE decryption attempts by status"
167    );
168    describe_histogram!(
169        "operator_privacy_decryption_duration_seconds",
170        "Duration of HPKE envelope decryption"
171    );
172
173    // ========================================================================
174    // Chain Watcher Metrics
175    // ========================================================================
176    describe_counter!(
177        "chain_watcher_events_received_total",
178        "Total events received from WebSocket listener"
179    );
180    describe_counter!(
181        "chain_watcher_events_relayed_total",
182        "Events successfully relayed to gateway"
183    );
184    describe_counter!(
185        "chain_watcher_events_filtered_total",
186        "Tasks filtered out (already seen by gateway)"
187    );
188    describe_counter!("chain_watcher_redis_lookup_total", "Redis SISMEMBER lookup results");
189    describe_histogram!(
190        "chain_watcher_gateway_relay_duration_seconds",
191        "Time to POST event to gateway /watcher endpoint"
192    );
193    describe_counter!(
194        "chain_watcher_gateway_relay_errors_total",
195        "Failed gateway relay attempts (after retries)"
196    );
197    describe_counter!(
198        "chain_watcher_websocket_reconnections_total",
199        "WebSocket reconnection count"
200    );
201    describe_gauge!(
202        "chain_watcher_websocket_connected",
203        "WebSocket connection status (1=connected, 0=disconnected)"
204    );
205
206    // ========================================================================
207    // Gateway Watcher Handler Metrics (gateway-side /watcher endpoint)
208    // ========================================================================
209    describe_counter!(
210        "gateway_watcher_events_received_total",
211        "Events received by gateway /watcher endpoint from chain watchers"
212    );
213    describe_counter!(
214        "gateway_watcher_tasks_processed_total",
215        "Watcher-originated tasks processed (broadcast + aggregation)"
216    );
217    describe_histogram!(
218        "gateway_watcher_task_duration_seconds",
219        "Duration of watcher-originated task processing (broadcast to on-chain submit)"
220    );
221
222    // ========================================================================
223    // Challenger Metrics
224    // ========================================================================
225    describe_counter!(
226        "num_tasks_challenge_detected",
227        "The number of potential challenges detected"
228    );
229    describe_counter!(
230        "num_tasks_challenge_submitted",
231        "The number of challenges submitted on-chain"
232    );
233    describe_histogram!(
234        "challenger_verification_duration_seconds",
235        "Duration of challenge verification"
236    );
237    describe_histogram!(
238        "challenger_zk_proof_generation_duration_seconds",
239        "Duration of ZK proof generation for challenges"
240    );
241
242    // ========================================================================
243    // Two-Phase Protocol Metrics (Latency Breakdown)
244    // ========================================================================
245    describe_histogram!(
246        "gateway_two_phase_total_duration_seconds",
247        "Total duration of Two-Phase Protocol (Prepare + consensus + Evaluate)"
248    );
249    describe_histogram!(
250        "gateway_two_phase_prepare_duration_seconds",
251        "Duration of Prepare phase: fetching unsigned policy data from operators"
252    );
253    describe_histogram!(
254        "gateway_two_phase_consensus_duration_seconds",
255        "Duration of consensus computation (median calculation)"
256    );
257    describe_histogram!(
258        "gateway_two_phase_evaluate_duration_seconds",
259        "Duration of Evaluate phase: collecting BLS signatures from operators"
260    );
261    describe_histogram!(
262        "gateway_two_phase_aggregation_duration_seconds",
263        "Duration of BLS signature aggregation after Evaluate phase"
264    );
265    describe_histogram!(
266        "operator_fetch_policy_data_duration_seconds",
267        "Duration of operator fetching policy data (WASM execution)"
268    );
269    describe_histogram!(
270        "operator_sign_consensus_duration_seconds",
271        "Duration of operator signing consensus digest (BLS signing)"
272    );
273    describe_histogram!(
274        "operator_network_round_trip_seconds",
275        "Network round-trip time to individual operator"
276    );
277    describe_counter!(
278        "gateway_two_phase_early_consensus_total",
279        "Number of tasks that achieved early consensus (all responses identical)"
280    );
281    describe_counter!(
282        "gateway_two_phase_normalization_total",
283        "Number of tasks requiring median normalization"
284    );
285    describe_gauge!(
286        "gateway_two_phase_response_count",
287        "Number of operator responses received per phase"
288    );
289
290    // ========================================================================
291    // Readiness Probe Metrics
292    // ========================================================================
293    describe_gauge!(
294        "gateway_readiness_database",
295        "Database connectivity (1=connected, 0=unavailable)"
296    );
297    describe_gauge!(
298        "gateway_readiness_redis",
299        "Redis connectivity (1=connected, 0=unavailable)"
300    );
301    describe_gauge!(
302        "gateway_readiness_operator_pool_size",
303        "Number of active operators in the pool per chain"
304    );
305    describe_gauge!(
306        "gateway_readiness_worker_queue_depth",
307        "Current worker queue depth per chain"
308    );
309    describe_gauge!(
310        "gateway_readiness_worker_queue_capacity",
311        "Worker queue capacity per chain"
312    );
313    describe_gauge!(
314        "gateway_readiness_aggregator_confirmed_nonce",
315        "Confirmed (latest) nonce for the aggregator signer per chain"
316    );
317    describe_gauge!(
318        "gateway_readiness_aggregator_pending_nonce",
319        "Pending nonce for the aggregator signer per chain"
320    );
321    describe_gauge!(
322        "gateway_readiness_aggregator_in_flight",
323        "In-flight transactions (pending - confirmed) per chain"
324    );
325}
326
327// ============================================================================
328// Operator Metrics Functions
329// ============================================================================
330
331/// Increment the number of tasks accepted by aggregator (operator perspective)
332pub fn inc_num_tasks_accepted_by_aggregator(chain_id: u64) {
333    counter!("num_signed_task_responses_accepted_by_aggregator", "chain_id" => chain_id.to_string()).increment(1);
334}
335
336// ============================================================================
337// Operator Evaluation Metrics
338// ============================================================================
339
340/// Increment the number of successfully evaluated tasks
341pub fn inc_tasks_operator_evaluate_success(chain_id: u64) {
342    counter!("num_tasks_operator_evaluate_success", "chain_id" => chain_id.to_string()).increment(1);
343}
344
345/// Increment the number of failed task evaluations
346pub fn inc_tasks_operator_evaluate_failure(chain_id: u64) {
347    counter!("num_tasks_operator_evaluate_failure", "chain_id" => chain_id.to_string()).increment(1);
348}
349
350/// Record task evaluation duration in seconds
351pub fn record_task_evaluation_duration(chain_id: u64, duration_secs: f64) {
352    histogram!("task_evaluation_duration_seconds", "chain_id" => chain_id.to_string()).record(duration_secs);
353}
354
355// ============================================================================
356// Task Aggregation Metrics
357// ============================================================================
358
359/// Increment the number of successful aggregator responses
360pub fn inc_tasks_aggregator_respond_success() {
361    counter!("num_tasks_aggregator_respond_success").increment(1);
362}
363
364/// Increment the number of failed aggregator responses
365pub fn inc_tasks_aggregator_respond_failure() {
366    counter!("num_tasks_aggregator_respond_failure").increment(1);
367}
368
369/// Record task aggregation duration in seconds
370pub fn record_task_aggregation_duration(duration_secs: f64) {
371    histogram!("task_aggregation_duration_seconds").record(duration_secs);
372}
373
374// ============================================================================
375// Transaction Submission Metrics
376// ============================================================================
377
378/// Increment the number of transaction submission retries with a reason label
379pub fn inc_tx_submission_retry(reason: &str) {
380    counter!("tx_submission_retries_total", "reason" => reason.to_string()).increment(1);
381}
382
383/// Increment the number of transaction submission failures after all retries exhausted
384pub fn inc_tx_submission_exhausted(error_type: &str) {
385    counter!("tx_submission_exhausted_total", "error_type" => error_type.to_string()).increment(1);
386}
387
388/// Increment the number of transaction timeouts
389pub fn inc_tx_submission_timeout() {
390    counter!("tx_submission_timeout_total").increment(1);
391}
392
393/// Record transaction submission attempt count before success or failure
394pub fn record_tx_submission_attempts(attempts: u64) {
395    histogram!("tx_submission_attempts").record(attempts as f64);
396}
397
398// ============================================================================
399// Operator Cache Metrics
400// ============================================================================
401
402/// Increment the number of task generator cache hits
403pub fn inc_task_generator_cache_hits(chain_id: u64) {
404    counter!("task_generator_cache_hits", "chain_id" => chain_id.to_string()).increment(1);
405}
406
407/// Increment the number of task generator cache misses
408pub fn inc_task_generator_cache_misses(chain_id: u64) {
409    counter!("task_generator_cache_misses", "chain_id" => chain_id.to_string()).increment(1);
410}
411
412// ============================================================================
413// Challenger Metrics
414// ============================================================================
415
416/// Increment the number of successful challenges
417pub fn inc_tasks_challenge_success() {
418    counter!("num_tasks_challenge_success").increment(1);
419}
420
421/// Increment the number of failed challenges
422pub fn inc_tasks_challenge_failure() {
423    counter!("num_tasks_challenge_failure").increment(1);
424}
425
426// ============================================================================
427// Service Identity Metrics
428// ============================================================================
429
430/// set task generator address (gateway signer)
431pub fn set_task_generator_address(address: &str) {
432    gauge!("task_generator_address", "address" => address.to_string()).set(1.0);
433}
434
435/// set aggregator address
436pub fn set_aggregator_address(address: &str) {
437    gauge!("aggregator_address", "address" => address.to_string()).set(1.0);
438}
439
440/// set operator address
441pub fn set_operator_address(address: &str) {
442    gauge!("operator_address", "address" => address.to_string()).set(1.0);
443}
444
445/// set operator id
446pub fn set_operator_id(operator_id: &str) {
447    gauge!("operator_id", "id" => operator_id.to_string()).set(1.0);
448}
449
450/// set challenger address
451pub fn set_challenger_address(address: &str) {
452    gauge!("challenger_address", "address" => address.to_string()).set(1.0);
453}
454
455// ============================================================================
456// Gateway High-Level RPC Metrics
457// ============================================================================
458
459/// Record RPC request duration by method
460pub fn record_rpc_request_duration(method: &str, duration_secs: f64) {
461    histogram!("gateway_rpc_request_duration_seconds", "method" => method.to_string()).record(duration_secs);
462}
463
464/// Increment RPC request total by method and status
465pub fn inc_rpc_request_total(method: &str, status: &str) {
466    counter!("gateway_rpc_request_total", "method" => method.to_string(), "status" => status.to_string()).increment(1);
467}
468
469// ============================================================================
470// Gateway Stage Metrics
471// ============================================================================
472
473/// Record data provider duration in seconds
474pub fn record_gateway_data_provider_duration(duration_secs: f64) {
475    histogram!("gateway_data_provider_duration_seconds").record(duration_secs);
476}
477
478/// Record operator broadcast duration in seconds by chain
479pub fn record_gateway_broadcast_duration(chain_id: u64, duration_secs: f64) {
480    histogram!("gateway_broadcast_duration_seconds", "chain_id" => chain_id.to_string()).record(duration_secs);
481}
482
483/// Record BLS aggregation duration in seconds
484pub fn record_gateway_bls_aggregation_duration(duration_secs: f64) {
485    histogram!("gateway_bls_aggregation_duration_seconds").record(duration_secs);
486}
487
488/// Record on-chain submission duration in seconds
489pub fn record_gateway_onchain_submit_duration(duration_secs: f64) {
490    histogram!("gateway_onchain_submit_duration_seconds").record(duration_secs);
491}
492
493/// Record parallel RPC fetch duration in seconds
494pub fn record_gateway_rpc_parallel_fetch_duration(duration_secs: f64) {
495    histogram!("gateway_rpc_parallel_fetch_duration_seconds").record(duration_secs);
496}
497
498/// Increment gateway task total by chain, mode, and status
499pub fn inc_gateway_task_total(chain_id: u64, mode: &str, status: &str) {
500    counter!("gateway_task_total", "chain_id" => chain_id.to_string(), "mode" => mode.to_string(), "status" => status.to_string()).increment(1);
501}
502
503// ============================================================================
504// Gateway Resilience Metrics
505// ============================================================================
506
507/// Set worker queue depth by worker name
508pub fn set_gateway_worker_queue_depth(worker: &str, depth: usize) {
509    gauge!("gateway_worker_queue_depth", "worker" => worker.to_string()).set(depth as f64);
510}
511
512/// Set task states size in aggregator
513pub fn set_gateway_task_states_size(size: usize) {
514    gauge!("gateway_task_states_size").set(size as f64);
515}
516
517/// Set circuit breaker state for an operator (0=closed, 1=open, 2=half-open)
518pub fn set_gateway_circuit_breaker_state(operator_id: &str, state: u8) {
519    gauge!("gateway_circuit_breaker_state", "operator_id" => operator_id.to_string()).set(state as f64);
520}
521
522/// Increment channel send total by channel and status
523pub fn inc_gateway_channel_send_total(channel: &str, status: &str) {
524    counter!("gateway_channel_send_total", "channel" => channel.to_string(), "status" => status.to_string())
525        .increment(1);
526}
527
528/// Increment channel retry total by channel
529pub fn inc_gateway_channel_retry_total(channel: &str) {
530    counter!("gateway_channel_retry_total", "channel" => channel.to_string()).increment(1);
531}
532
533/// Increment failure notification total by type and channel
534pub fn inc_gateway_failure_notification_total(failure_type: &str, channel: &str) {
535    counter!("gateway_failure_notification_total", "failure_type" => failure_type.to_string(), "channel" => channel.to_string()).increment(1);
536}
537
538/// Increment webhook delivery total by status
539pub fn inc_gateway_webhook_delivery_total(status: &str) {
540    counter!("gateway_webhook_delivery_total", "status" => status.to_string()).increment(1);
541}
542
543/// Set WebSocket connection count
544pub fn set_gateway_websocket_connections(count: usize) {
545    gauge!("gateway_websocket_connections").set(count as f64);
546}
547
548/// Set WebSocket subscription count
549pub fn set_gateway_websocket_subscriptions(count: usize) {
550    gauge!("gateway_websocket_subscriptions").set(count as f64);
551}
552
553/// Increment quorum failure total by reason
554pub fn inc_gateway_quorum_failures_total(reason: &str) {
555    counter!("gateway_quorum_failures_total", "reason" => reason.to_string()).increment(1);
556}
557
558// ============================================================================
559// Challenger Metrics
560// ============================================================================
561
562/// Increment the number of challenges detected
563pub fn inc_tasks_challenge_detected(chain_id: u64) {
564    counter!("num_tasks_challenge_detected", "chain_id" => chain_id.to_string()).increment(1);
565}
566
567/// Increment the number of challenges submitted
568pub fn inc_tasks_challenge_submitted(chain_id: u64) {
569    counter!("num_tasks_challenge_submitted", "chain_id" => chain_id.to_string()).increment(1);
570}
571
572/// Record challenger verification duration in seconds
573pub fn record_challenger_verification_duration(chain_id: u64, duration_secs: f64) {
574    histogram!("challenger_verification_duration_seconds", "chain_id" => chain_id.to_string()).record(duration_secs);
575}
576
577/// Record ZK proof generation duration in seconds
578pub fn record_challenger_zk_proof_generation_duration(chain_id: u64, duration_secs: f64) {
579    histogram!("challenger_zk_proof_generation_duration_seconds", "chain_id" => chain_id.to_string())
580        .record(duration_secs);
581}
582
583// ============================================================================
584// Transporter Metrics
585// ============================================================================
586
587/// Increment transporter sync success count
588pub fn inc_transporter_sync_success(source_chain_id: u64, dest_chain_id: u64) {
589    counter!(
590        "transporter_sync_total",
591        "source_chain_id" => source_chain_id.to_string(),
592        "dest_chain_id" => dest_chain_id.to_string(),
593        "status" => "success"
594    )
595    .increment(1);
596}
597
598/// Increment transporter sync failure count
599pub fn inc_transporter_sync_failure(source_chain_id: u64, dest_chain_id: u64) {
600    counter!(
601        "transporter_sync_total",
602        "source_chain_id" => source_chain_id.to_string(),
603        "dest_chain_id" => dest_chain_id.to_string(),
604        "status" => "failure"
605    )
606    .increment(1);
607}
608
609/// Record transporter sync duration in seconds
610pub fn record_transporter_sync_duration(source_chain_id: u64, dest_chain_id: u64, duration_secs: f64) {
611    histogram!(
612        "transporter_sync_duration_seconds",
613        "source_chain_id" => source_chain_id.to_string(),
614        "dest_chain_id" => dest_chain_id.to_string()
615    )
616    .record(duration_secs);
617}
618
619/// Record number of operator tables synced in a transport update
620pub fn record_transporter_operator_tables_synced(source_chain_id: u64, dest_chain_id: u64, count: u64) {
621    gauge!(
622        "transporter_operator_tables_synced",
623        "source_chain_id" => source_chain_id.to_string(),
624        "dest_chain_id" => dest_chain_id.to_string()
625    )
626    .set(count as f64);
627}
628
629/// Increment transporter event-triggered sync count
630pub fn inc_transporter_event_triggered_sync(source_chain_id: u64, dest_chain_id: u64, trigger: &str) {
631    counter!(
632        "transporter_event_triggered_sync_total",
633        "source_chain_id" => source_chain_id.to_string(),
634        "dest_chain_id" => dest_chain_id.to_string(),
635        "trigger" => trigger.to_string()
636    )
637    .increment(1);
638}
639
640// ============================================================================
641// Two-Phase Protocol Metrics
642// ============================================================================
643
644/// Record total Two-Phase Protocol duration in seconds
645pub fn record_two_phase_total_duration(duration_secs: f64) {
646    histogram!("gateway_two_phase_total_duration_seconds").record(duration_secs);
647}
648
649/// Record Prepare phase (fetch policy data) duration in seconds
650pub fn record_two_phase_prepare_duration(duration_secs: f64) {
651    histogram!("gateway_two_phase_prepare_duration_seconds").record(duration_secs);
652}
653
654/// Record consensus computation duration in seconds
655pub fn record_two_phase_consensus_duration(duration_secs: f64) {
656    histogram!("gateway_two_phase_consensus_duration_seconds").record(duration_secs);
657}
658
659/// Record Evaluate phase (sign consensus) duration in seconds
660pub fn record_two_phase_evaluate_duration(duration_secs: f64) {
661    histogram!("gateway_two_phase_evaluate_duration_seconds").record(duration_secs);
662}
663
664/// Record BLS aggregation duration after Evaluate phase in seconds
665pub fn record_two_phase_aggregation_duration(duration_secs: f64) {
666    histogram!("gateway_two_phase_aggregation_duration_seconds").record(duration_secs);
667}
668
669/// Record operator fetch policy data duration in seconds (WASM execution)
670pub fn record_operator_fetch_policy_data_duration(chain_id: u64, operator_id: &str, duration_secs: f64) {
671    histogram!("operator_fetch_policy_data_duration_seconds", "chain_id" => chain_id.to_string(), "operator_id" => operator_id.to_string())
672        .record(duration_secs);
673}
674
675/// Record operator sign consensus duration in seconds (BLS signing)
676pub fn record_operator_sign_consensus_duration(chain_id: u64, operator_id: &str, duration_secs: f64) {
677    histogram!("operator_sign_consensus_duration_seconds", "chain_id" => chain_id.to_string(), "operator_id" => operator_id.to_string())
678        .record(duration_secs);
679}
680
681/// Record network round-trip time to operator in seconds
682pub fn record_operator_network_round_trip(operator_id: &str, duration_secs: f64) {
683    histogram!("operator_network_round_trip_seconds", "operator_id" => operator_id.to_string()).record(duration_secs);
684}
685
686/// Increment early consensus counter (all responses identical)
687pub fn inc_two_phase_early_consensus() {
688    counter!("gateway_two_phase_early_consensus_total").increment(1);
689}
690
691/// Increment normalization counter (median normalization required)
692pub fn inc_two_phase_normalization() {
693    counter!("gateway_two_phase_normalization_total").increment(1);
694}
695
696/// Set response count for a phase
697pub fn set_two_phase_response_count(phase: &str, count: usize) {
698    gauge!("gateway_two_phase_response_count", "phase" => phase.to_string()).set(count as f64);
699}
700
701// ═══════════════════════════════════════════════════════════════════════════
702// Chain Watcher Metrics
703// ═══════════════════════════════════════════════════════════════════════════
704
705/// Increment events received from WebSocket listener
706pub fn inc_chain_watcher_events_received(chain_id: u64, event_type: &str) {
707    counter!("chain_watcher_events_received_total", "chain_id" => chain_id.to_string(), "event_type" => event_type.to_string()).increment(1);
708}
709
710/// Increment events successfully relayed to gateway
711pub fn inc_chain_watcher_events_relayed(chain_id: u64, event_type: &str) {
712    counter!("chain_watcher_events_relayed_total", "chain_id" => chain_id.to_string(), "event_type" => event_type.to_string()).increment(1);
713}
714
715/// Increment tasks filtered out (already seen by gateway)
716pub fn inc_chain_watcher_events_filtered(chain_id: u64) {
717    counter!("chain_watcher_events_filtered_total", "chain_id" => chain_id.to_string()).increment(1);
718}
719
720/// Increment Redis SISMEMBER lookup results
721pub fn inc_chain_watcher_redis_lookup(chain_id: u64, result: &str) {
722    counter!("chain_watcher_redis_lookup_total", "chain_id" => chain_id.to_string(), "result" => result.to_string())
723        .increment(1);
724}
725
726/// Record time to POST event to gateway /watcher endpoint
727pub fn record_chain_watcher_gateway_relay_duration(chain_id: u64, duration_secs: f64) {
728    histogram!("chain_watcher_gateway_relay_duration_seconds", "chain_id" => chain_id.to_string())
729        .record(duration_secs);
730}
731
732/// Increment failed gateway relay attempts (after retries)
733pub fn inc_chain_watcher_gateway_relay_errors(chain_id: u64) {
734    counter!("chain_watcher_gateway_relay_errors_total", "chain_id" => chain_id.to_string()).increment(1);
735}
736
737/// Increment WebSocket reconnection count
738pub fn inc_chain_watcher_websocket_reconnections(chain_id: u64) {
739    counter!("chain_watcher_websocket_reconnections_total", "chain_id" => chain_id.to_string()).increment(1);
740}
741
742/// Set WebSocket connection status (1=connected, 0=disconnected)
743pub fn set_chain_watcher_websocket_connected(chain_id: u64, connected: bool) {
744    gauge!("chain_watcher_websocket_connected", "chain_id" => chain_id.to_string()).set(if connected {
745        1.0
746    } else {
747        0.0
748    });
749}
750
751// ═══════════════════════════════════════════════════════════════════════════
752// Gateway Watcher Handler Metrics (gateway-side /watcher endpoint)
753// ═══════════════════════════════════════════════════════════════════════════
754
755/// Increment events received by gateway /watcher endpoint
756pub fn inc_gateway_watcher_events_received(chain_id: u64, event_type: &str) {
757    counter!("gateway_watcher_events_received_total", "chain_id" => chain_id.to_string(), "event_type" => event_type.to_string())
758        .increment(1);
759}
760
761/// Increment watcher-originated tasks that completed processing
762pub fn inc_gateway_watcher_tasks_processed(chain_id: u64, status: &str) {
763    counter!("gateway_watcher_tasks_processed_total", "chain_id" => chain_id.to_string(), "status" => status.to_string())
764        .increment(1);
765}
766
767/// Record duration of watcher-originated task processing (broadcast to on-chain submit)
768pub fn record_gateway_watcher_task_duration(chain_id: u64, duration_secs: f64) {
769    histogram!("gateway_watcher_task_duration_seconds", "chain_id" => chain_id.to_string()).record(duration_secs);
770}
771
772// ═══════════════════════════════════════════════════════════════════════════
773// Centralized Single-Phase Mode Metrics
774// ═══════════════════════════════════════════════════════════════════════════
775
776/// Record centralized data generation duration in seconds (gateway generates policyTaskData)
777pub fn record_centralized_data_generation_duration(duration_secs: f64) {
778    histogram!("gateway_centralized_data_generation_duration_seconds").record(duration_secs);
779}
780
781/// Record centralized Evaluate phase (evaluate + sign) duration in seconds
782pub fn record_centralized_evaluate_duration(duration_secs: f64) {
783    histogram!("gateway_centralized_evaluate_duration_seconds").record(duration_secs);
784}
785
786/// Record centralized BLS aggregation duration in seconds
787pub fn record_centralized_aggregation_duration(duration_secs: f64) {
788    histogram!("gateway_centralized_aggregation_duration_seconds").record(duration_secs);
789}
790
791/// Record centralized total duration in seconds
792pub fn record_centralized_total_duration(duration_secs: f64) {
793    histogram!("gateway_centralized_total_duration_seconds").record(duration_secs);
794}
795
796/// Set response count for centralized mode
797pub fn set_centralized_response_count(count: usize) {
798    gauge!("gateway_centralized_response_count").set(count as f64);
799}
800
801// ═══════════════════════════════════════════════════════════════════════════
802// Gateway Cleanup Metrics
803// ═══════════════════════════════════════════════════════════════════════════
804
805/// Increment counter for stale tasks removed by cleanup
806pub fn inc_cleanup_tasks_removed(count: u64) {
807    counter!("gateway_cleanup_tasks_removed_total").increment(count);
808}
809
810/// Record cleanup task execution duration in seconds
811pub fn record_cleanup_duration(duration_secs: f64) {
812    histogram!("gateway_cleanup_duration_seconds").record(duration_secs);
813}
814
815// ═══════════════════════════════════════════════════════════════════════════
816// Privacy Layer Metrics
817// ═══════════════════════════════════════════════════════════════════════════
818
819/// Increment encrypted data upload total by status
820pub fn inc_gateway_privacy_upload_total(status: &str) {
821    counter!("gateway_privacy_upload_total", "status" => status.to_string()).increment(1);
822}
823
824/// Record encrypted data upload duration in seconds
825pub fn record_gateway_privacy_upload_duration(duration_secs: f64) {
826    histogram!("gateway_privacy_upload_duration_seconds").record(duration_secs);
827}
828
829/// Increment privacy-enabled task total by status
830pub fn inc_gateway_privacy_task_total(status: &str) {
831    counter!("gateway_privacy_task_total", "status" => status.to_string()).increment(1);
832}
833
834/// Increment dual-signature auth validation total by result
835pub fn inc_gateway_privacy_auth_validation_total(result: &str) {
836    counter!("gateway_privacy_auth_validation_total", "result" => result.to_string()).increment(1);
837}
838
839/// Record dual-signature auth validation duration in seconds
840pub fn record_gateway_privacy_auth_validation_duration(duration_secs: f64) {
841    histogram!("gateway_privacy_auth_validation_duration_seconds").record(duration_secs);
842}
843
844/// Increment operator HPKE decryption total by status
845pub fn inc_operator_privacy_decryption_total(status: &str) {
846    counter!("operator_privacy_decryption_total", "status" => status.to_string()).increment(1);
847}
848
849/// Record operator HPKE decryption duration in seconds
850pub fn record_operator_privacy_decryption_duration(duration_secs: f64) {
851    histogram!("operator_privacy_decryption_duration_seconds").record(duration_secs);
852}
853
854// ═══════════════════════════════════════════════════════════════════════════
855// Readiness Probe Metrics
856// ═══════════════════════════════════════════════════════════════════════════
857
858/// Set database connectivity status (1=connected, 0=unavailable)
859pub fn set_readiness_database(connected: bool) {
860    gauge!("gateway_readiness_database").set(if connected { 1.0 } else { 0.0 });
861}
862
863/// Set Redis connectivity status (1=connected, 0=unavailable)
864pub fn set_readiness_redis(value: f64) {
865    gauge!("gateway_readiness_redis").set(value);
866}
867
868/// Set operator pool size for a chain
869pub fn set_readiness_operator_pool_size(chain_id: u64, size: usize) {
870    gauge!("gateway_readiness_operator_pool_size", "chain_id" => chain_id.to_string()).set(size as f64);
871}
872
873/// Set worker queue depth for a chain
874pub fn set_readiness_worker_queue_depth(chain_id: u64, depth: usize) {
875    gauge!("gateway_readiness_worker_queue_depth", "chain_id" => chain_id.to_string()).set(depth as f64);
876}
877
878/// Set worker queue capacity for a chain
879pub fn set_readiness_worker_queue_capacity(chain_id: u64, capacity: usize) {
880    gauge!("gateway_readiness_worker_queue_capacity", "chain_id" => chain_id.to_string()).set(capacity as f64);
881}
882
883/// Set aggregator confirmed nonce for a chain
884pub fn set_readiness_aggregator_confirmed_nonce(chain_id: u64, nonce: u64) {
885    gauge!("gateway_readiness_aggregator_confirmed_nonce", "chain_id" => chain_id.to_string()).set(nonce as f64);
886}
887
888/// Set aggregator pending nonce for a chain
889pub fn set_readiness_aggregator_pending_nonce(chain_id: u64, nonce: u64) {
890    gauge!("gateway_readiness_aggregator_pending_nonce", "chain_id" => chain_id.to_string()).set(nonce as f64);
891}
892
893/// Set aggregator in-flight transaction count for a chain
894pub fn set_readiness_aggregator_in_flight(chain_id: u64, in_flight: u64) {
895    gauge!("gateway_readiness_aggregator_in_flight", "chain_id" => chain_id.to_string()).set(in_flight as f64);
896}
897
898#[cfg(test)]
899mod tests {
900
901    use super::*;
902    use eigensdk::metrics::prometheus::init_registry;
903    use std::{net::SocketAddr, time::Duration};
904
905    #[tokio::test]
906    #[ignore]
907    async fn test_prometheus_server() {
908        let socket: SocketAddr = "127.0.0.1:9091".parse().unwrap();
909        init_registry(socket);
910
911        // Initialize newton prover metrics
912        new();
913
914        tokio::time::sleep(Duration::from_secs(1)).await;
915
916        async fn get_metrics_body(client: &reqwest::Client, url: &str) -> String {
917            let resp = client.get(url).send().await.unwrap();
918            resp.text().await.unwrap()
919        }
920        let client = reqwest::Client::new();
921
922        inc_num_tasks_accepted_by_aggregator(31337);
923        inc_tasks_operator_evaluate_success(31337);
924
925        let body = get_metrics_body(&client, "http://127.0.0.1:9091/metrics").await;
926        println!("body {body:?}");
927        assert!(body.contains("num_signed_task_responses_accepted_by_aggregator"));
928        assert!(body.contains("num_tasks_operator_evaluate_success"));
929    }
930}