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
//! Traits for aggregation
//!
//! This module provides a composable aggregation system with three main layers:
//!
//! ## Field-level aggregation: [`AggregateValue`]
//!
//! Defines how individual field values are merged. For example, [`crate::value::Sum`] sums values,
//! while [`crate::histogram::Histogram`] collects values into distributions. This trait enables
//! compile-time type resolution:
//!
//! ```rust
//! use metrique_aggregation::value::Sum;
//! use metrique_aggregation::traits::AggregateValue;
//! type AggregatedType = <Sum as AggregateValue<u64>>::Aggregated;
//! // ^^^ ^^
//! // Strategy Input type
//! ```
//!
//! ## Entry-level aggregation: [`Merge`] and [`AggregateStrategy`]
//!
//! The [`Merge`] trait defines how complete metric entries are combined. It specifies:
//! - The accumulated type (`Merged`)
//! - How to create new accumulators (`new_merged`)
//! - How to merge entries into accumulators (`merge`)
//!
//! The [`AggregateStrategy`] trait ties together a source type with its merge behavior and
//! key extraction strategy. The `#[aggregate]` macro generates these implementations automatically.
//!
//! ## Key extraction: [`Key`]
//!
//! The [`Key`] trait extracts grouping keys from source entries, enabling keyed aggregation
//! where entries with the same key are merged together. Fields marked with `#[aggregate(key)]`
//! become part of the key.
//!
//! ## The [`crate::aggregator::Aggregate`] wrapper
//!
//! [`crate::aggregator::Aggregate`] is the simplest way to aggregate data, typically used as a field in a larger struct.
//! It wraps an aggregated value and tracks the number of samples merged.
use ;
use Hash;
/// Defines how individual field values are aggregated.
///
/// This trait operates at the field level, not the entry level. Each aggregation
/// strategy (Counter, Histogram, etc.) implements this trait for the types it can aggregate.
///
/// # Type Parameters
///
/// - `T`: The type of value being aggregated
///
/// # Associated Types
///
/// - `Aggregated`: The accumulated type (often same as `T`, but can differ for histograms)
///
/// # Example
///
/// ```rust
/// use metrique_aggregation::traits::AggregateValue;
/// use metrique_core::CloseValue;
///
/// // Average tracks sum and count to compute average
/// pub struct Avg;
///
/// pub struct AvgAccumulator {
/// sum: f64,
/// count: u64,
/// }
///
/// impl CloseValue for AvgAccumulator {
/// type Closed = f64;
///
/// fn close(self) -> f64 {
/// if self.count == 0 {
/// 0.0
/// } else {
/// self.sum / self.count as f64
/// }
/// }
/// }
///
/// impl AggregateValue<f64> for Avg {
/// type Aggregated = AvgAccumulator;
///
/// fn insert(accum: &mut Self::Aggregated, value: f64) {
/// accum.sum += value;
/// accum.count += 1;
/// }
/// }
/// ```
/// Key extraction trait for aggregation strategies.
///
/// Extracts grouping keys from source entries to enable keyed aggregation. Entries with
/// the same key are merged together. The `#[aggregate]` macro generates implementations
/// for fields marked with `#[aggregate(key)]`.
///
/// # Type Parameters
///
/// - `Source`: The type being aggregated
///
/// # Associated Types
///
/// - `Key<'a>`: The key type with lifetime parameter for borrowed data
///
/// # Example
///
/// ```rust
/// use metrique::unit_of_work::metrics;
/// use metrique_aggregation::traits::Key;
/// use std::borrow::Cow;
///
/// struct ApiCall {
/// endpoint: String,
/// latency: u64,
/// }
///
/// #[derive(Clone, Hash, PartialEq, Eq)]
/// #[metrics]
/// struct ApiCallKey<'a> {
/// endpoint: Cow<'a, String>,
/// }
///
/// struct ApiCallByEndpoint;
///
/// impl Key<ApiCall> for ApiCallByEndpoint {
/// type Key<'a> = ApiCallKey<'a>;
///
/// fn from_source(source: &ApiCall) -> Self::Key<'_> {
/// ApiCallKey {
/// endpoint: Cow::Borrowed(&source.endpoint),
/// }
/// }
///
/// fn static_key<'a>(key: &Self::Key<'a>) -> Self::Key<'static> {
/// ApiCallKey {
/// endpoint: Cow::Owned(key.endpoint.clone().into_owned()),
/// }
/// }
///
/// fn static_key_matches<'a>(owned: &Self::Key<'static>, borrowed: &Self::Key<'a>) -> bool {
/// owned.endpoint == borrowed.endpoint
/// }
/// }
/// ```
/// Defines how complete metric entries are merged together.
///
/// This trait operates at the entry level, combining entire structs rather than individual fields.
/// The `#[aggregate]` macro generates implementations that merge each field according to its
/// `#[aggregate(strategy = ...)]` attribute.
///
/// # Type Parameters
///
/// - `Self`: The source type being aggregated
///
/// # Associated Types
///
/// - `Merged`: The accumulated type that holds aggregated values
/// - `MergeConfig`: Configuration needed to create new merged values (often `()`)
///
/// # Example
///
/// ```rust
/// use metrique::unit_of_work::metrics;
/// use metrique_aggregation::traits::Merge;
/// use metrique_aggregation::histogram::Histogram;
/// use std::time::Duration;
///
/// struct ApiCall {
/// latency: Duration,
/// response_size: usize,
/// }
///
/// #[derive(Default)]
/// #[metrics]
/// struct AggregatedApiCall {
/// latency: Histogram<Duration>,
/// response_size: usize,
/// }
///
/// impl Merge for ApiCall {
/// type Merged = AggregatedApiCall;
/// type MergeConfig = ();
///
/// fn new_merged(_conf: &Self::MergeConfig) -> Self::Merged {
/// Self::Merged::default()
/// }
///
/// fn merge(accum: &mut Self::Merged, input: Self) {
/// accum.latency.add_value(&input.latency);
/// accum.response_size += input.response_size;
/// }
/// }
/// ```
/// Borrowed version of [`Merge`] for more efficient aggregation.
///
/// When the source type can be borrowed during merging, it becomes possible
/// to aggregate the same input across multiple sinks (or to send it to multiple sinks.)
/// Ties together source type, merge behavior, and key extraction.
///
/// This trait combines all the pieces needed for aggregation into a single strategy type.
/// The `#[aggregate]` macro generates an implementation automatically.
///
/// # Type Parameters
///
/// None - this is a marker trait that associates types
///
/// # Associated Types
///
/// - `Source`: The type being aggregated (must implement [`Merge`])
/// - `Key`: The key extraction strategy (must implement [`Key<Source>`])
///
/// # Example
///
/// ```rust
/// use metrique::unit_of_work::metrics;
/// use metrique_aggregation::traits::{AggregateStrategy, Key, Merge};
/// use metrique_aggregation::value::NoKey;
///
/// struct ApiCall {
/// latency: u64,
/// }
///
/// #[derive(Default)]
/// #[metrics]
/// struct AggregatedApiCall {
/// latency: u64,
/// }
///
/// impl Merge for ApiCall {
/// type Merged = AggregatedApiCall;
/// type MergeConfig = ();
/// fn new_merged(_: &()) -> Self::Merged { Self::Merged::default() }
/// fn merge(accum: &mut Self::Merged, input: Self) { accum.latency += input.latency; }
/// }
///
/// // Strategy type generated by #[aggregate]
/// struct ApiCallStrategy;
///
/// impl AggregateStrategy for ApiCallStrategy {
/// type Source = ApiCall;
/// type Key = NoKey; // No key fields, aggregate everything together
/// }
/// ```
/// Type alias for the key type of an aggregation strategy.
pub type KeyTy<'a, T> =
Key;
/// Type alias for the aggregated type of an aggregation strategy.
pub type AggregateTy<T> = Merged;
/// Result of keyed aggregation combining key and aggregated value.
///
/// Used by [`crate::aggregator::KeyedAggregator`] to emit aggregated entries
/// with their associated keys.
/// Root sink trait for thread-safe entry points (takes `&self`)
///
/// This is the trait that `WorkerSink` and other thread-safe wrappers implement.
/// Use this for `MergeOnDrop` and `CloseAndMergeOnDrop` targets.
/// Trait for sinks that accept aggregated entries by value (takes `&mut self`)
///
/// This is for single-threaded aggregation contexts where exclusive access is available.
/// Trait for sinks that accept aggregated entries by reference (takes `&mut self`)
///
/// This enables aggregating the same input across multiple sinks without cloning.
/// Requires the source type to implement `MergeRef`.
/// Trait for sinks that can be flushed (takes `&mut self`)