Skip to content

Commit

Permalink
Refactor metrics layer to arc<fn> to permit different consume functions
Browse files Browse the repository at this point in the history
  • Loading branch information
adam-cattermole committed May 10, 2024
1 parent eacd256 commit 933cc71
Showing 1 changed file with 12 additions and 10 deletions.
22 changes: 12 additions & 10 deletions limitador-server/src/metrics.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -71,39 +72,39 @@ impl SpanState {
}
}

pub struct MetricsGroup<F: Fn(Timings)> {
consumer: F,
pub struct MetricsGroup {
consumer: Arc<fn(Timings)>,
records: Vec<String>,
}

impl<F: Fn(Timings)> MetricsGroup<F> {
pub fn new(consumer: F, records: Vec<String>) -> Self {
impl MetricsGroup {
pub fn new(consumer: Arc<fn(Timings)>, records: Vec<String>) -> Self {
Self { consumer, records }
}
}

pub struct MetricsLayer<F: Fn(Timings)> {
groups: HashMap<String, MetricsGroup<F>>,
pub struct MetricsLayer {
groups: HashMap<String, MetricsGroup>,
}

impl<F: Fn(Timings)> MetricsLayer<F> {
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<S, F: Fn(Timings) + 'static> Layer<S> for MetricsLayer<F>
impl<S> Layer<S> for MetricsLayer
where
S: Subscriber,
S: for<'lookup> LookupSpan<'lookup>,
Expand Down Expand Up @@ -226,6 +227,7 @@ where
#[cfg(test)]
mod tests {
use super::{MetricsLayer, SpanState, Timings};
use std::sync::Arc;

Check failure on line 230 in limitador-server/src/metrics.rs

View workflow job for this annotation

GitHub Actions / Clippy

unused import: `std::sync::Arc`

Check failure on line 230 in limitador-server/src/metrics.rs

View workflow job for this annotation

GitHub Actions / Bench

unused import: `std::sync::Arc`

Check failure on line 230 in limitador-server/src/metrics.rs

View workflow job for this annotation

GitHub Actions / Test Suite

unused import: `std::sync::Arc`
use std::time::Instant;

#[test]
Expand Down

0 comments on commit 933cc71

Please sign in to comment.