exercises

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README

metrics.rs (2133B)


      1 //! Business-specific metrics for the Inventory service.
      2 //!
      3 //! Defines counters and histograms that track stock reservation KPIs:
      4 //! attempts, failures, duration, and total reserved quantity.
      5 //! Uses the `OnceLock` singleton pattern so metrics are initialized
      6 //! once and reusable from any handler.
      7 
      8 use opentelemetry::{
      9     global,
     10     metrics::{Counter, Histogram},
     11 };
     12 use std::sync::OnceLock;
     13 
     14 /// Collection of inventory-related metric instruments.
     15 pub struct InventoryMetrics {
     16     /// Total number of stock reservation attempts
     17     pub reservation_attempts: Counter<u64>,
     18     /// Total number of failed reservations, broken down by failure.reason
     19     pub reservation_failures: Counter<u64>,
     20     /// Wall-clock time to complete a stock reservation (seconds)
     21     pub reservation_duration: Histogram<f64>,
     22     /// Cumulative units reserved across all successful reservations
     23     pub reserved_quantity: Counter<u64>,
     24 }
     25 
     26 /// Singleton storage for the metrics instruments.
     27 static METRICS: OnceLock<InventoryMetrics> = OnceLock::new();
     28 
     29 /// Returns a reference to the lazily-initialized inventory metrics.
     30 pub fn metrics() -> &'static InventoryMetrics {
     31     METRICS.get_or_init(|| {
     32         let meter = global::meter("inventory-service");
     33 
     34         InventoryMetrics {
     35             reservation_attempts: meter
     36                 .u64_counter("inventory.reservation.attempts")
     37                 .with_description("Total stock reservation attempts")
     38                 .build(),
     39             reservation_failures: meter
     40                 .u64_counter("inventory.reservation.failures")
     41                 .with_description("Failed stock reservations")
     42                 .build(),
     43             reservation_duration: meter
     44                 .f64_histogram("inventory.reservation.duration")
     45                 .with_description("Time to complete stock reservation")
     46                 .with_unit("s")
     47                 .build(),
     48             reserved_quantity: meter
     49                 .u64_counter("inventory.reserved.quantity")
     50                 .with_description("Total units reserved")
     51                 .with_unit("units")
     52                 .build(),
     53         }
     54     })
     55 }