From 933cc716eb7caf0ffb38e3075dcbc5ace0b9be9c Mon Sep 17 00:00:00 2001 From: Adam Cattermole Date: Fri, 10 May 2024 12:58:41 +0100 Subject: [PATCH] Refactor metrics layer to arc to permit different consume functions --- limitador-server/src/metrics.rs | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/limitador-server/src/metrics.rs b/limitador-server/src/metrics.rs index 97468aae..08d136ae 100644 --- a/limitador-server/src/metrics.rs +++ b/limitador-server/src/metrics.rs @@ -1,5 +1,6 @@ use std::collections::HashMap; use std::ops; +use std::sync::Arc; use std::time::{Duration, Instant}; use tracing::span::{Attributes, Id}; use tracing::Subscriber; @@ -71,39 +72,39 @@ impl SpanState { } } -pub struct MetricsGroup { - consumer: F, +pub struct MetricsGroup { + consumer: Arc, records: Vec, } -impl MetricsGroup { - pub fn new(consumer: F, records: Vec) -> Self { +impl MetricsGroup { + pub fn new(consumer: Arc, records: Vec) -> Self { Self { consumer, records } } } -pub struct MetricsLayer { - groups: HashMap>, +pub struct MetricsLayer { + groups: HashMap, } -impl MetricsLayer { +impl MetricsLayer { pub fn new() -> Self { Self { groups: HashMap::new(), } } - pub fn gather(mut self, aggregate: &str, consumer: F, records: Vec<&str>) -> Self { + pub fn gather(mut self, aggregate: &str, consumer: fn(Timings), records: Vec<&str>) -> Self { // TODO(adam-cattermole): does not handle case where aggregate already exists let rec = records.iter().map(|r| r.to_string()).collect(); self.groups .entry(aggregate.to_string()) - .or_insert(MetricsGroup::new(consumer, rec)); + .or_insert(MetricsGroup::new(Arc::new(consumer), rec)); self } } -impl Layer for MetricsLayer +impl Layer for MetricsLayer where S: Subscriber, S: for<'lookup> LookupSpan<'lookup>, @@ -226,6 +227,7 @@ where #[cfg(test)] mod tests { use super::{MetricsLayer, SpanState, Timings}; + use std::sync::Arc; use std::time::Instant; #[test]