relay_cardinality/
limiter.rs

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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
//! Relay Cardinality Limiter

use std::cmp::Reverse;
use std::collections::BTreeMap;

use hashbrown::{HashMap, HashSet};
use relay_base_schema::metrics::{MetricName, MetricNamespace, MetricType};
use relay_base_schema::organization::OrganizationId;
use relay_base_schema::project::ProjectId;
use relay_common::time::UnixTimestamp;
use relay_statsd::metric;

use crate::statsd::CardinalityLimiterTimers;
use crate::{CardinalityLimit, Error, Result};

/// Data scoping information.
///
/// This structure holds information of all scopes required for attributing entries to limits.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct Scoping {
    /// The organization id.
    pub organization_id: OrganizationId,
    /// The project id.
    pub project_id: ProjectId,
}

/// Cardinality report for a specific limit.
///
/// Contains scoping information for the enforced limit and the current cardinality.
/// If all of the scoping information is `None`, the limit is a global cardinality limit.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct CardinalityReport {
    /// Time for which the cardinality limit was enforced.
    pub timestamp: UnixTimestamp,

    /// Organization id for which the cardinality limit was applied.
    ///
    /// Only available if the the limit was at least scoped to
    /// [`CardinalityScope::Organization`](crate::CardinalityScope::Organization).
    pub organization_id: Option<OrganizationId>,
    /// Project id for which the cardinality limit was applied.
    ///
    /// Only available if the the limit was at least scoped to
    /// [`CardinalityScope::Project`](crate::CardinalityScope::Project).
    pub project_id: Option<ProjectId>,
    /// Metric type for which the cardinality limit was applied.
    ///
    /// Only available if the the limit was scoped to
    /// [`CardinalityScope::Type`](crate::CardinalityScope::Type).
    pub metric_type: Option<MetricType>,
    /// Metric name for which the cardinality limit was applied.
    ///
    /// Only available if the the limit was scoped to
    /// [`CardinalityScope::Name`](crate::CardinalityScope::Name).
    pub metric_name: Option<MetricName>,

    /// The current cardinality.
    pub cardinality: u32,
}

/// Accumulator of all cardinality limiter decisions.
pub trait Reporter<'a> {
    /// Called for ever [`Entry`] which was rejected from the [`Limiter`].
    fn reject(&mut self, limit: &'a CardinalityLimit, entry_id: EntryId);

    /// Called for every individual limit applied.
    ///
    /// The callback can be called multiple times with different reports
    /// for the same `limit` or not at all if there was no change in cardinality.
    ///
    /// For example, with a name scoped limit can be called once for every
    /// metric name matching the limit.
    fn report_cardinality(&mut self, limit: &'a CardinalityLimit, report: CardinalityReport);
}

/// Limiter responsible to enforce limits.
pub trait Limiter {
    /// Verifies cardinality limits.
    ///
    /// Returns an iterator containing only accepted entries.
    fn check_cardinality_limits<'a, 'b, E, R>(
        &self,
        scoping: Scoping,
        limits: &'a [CardinalityLimit],
        entries: E,
        reporter: &mut R,
    ) -> Result<()>
    where
        E: IntoIterator<Item = Entry<'b>>,
        R: Reporter<'a>;
}

/// Unit of operation for the cardinality limiter.
pub trait CardinalityItem {
    /// Transforms this item into a consistent hash.
    fn to_hash(&self) -> u32;

    /// Metric namespace of the item.
    ///
    /// If this method returns `None` the item is automatically rejected.
    fn namespace(&self) -> Option<MetricNamespace>;

    /// Name of the item.
    fn name(&self) -> &MetricName;
}

/// A single entry to check cardinality for.
#[derive(Clone, Copy, Debug)]
pub struct Entry<'a> {
    /// Opaque entry Id, used to keep track of indices and buckets.
    pub id: EntryId,

    /// Metric namespace to which the cardinality limit can be scoped.
    pub namespace: MetricNamespace,
    /// Name to which the cardinality limit can be scoped.
    pub name: &'a MetricName,
    /// Hash of the metric name and tags.
    pub hash: u32,
}

/// Represents a unique Id for a bucket within one invocation
/// of the cardinality limiter.
///
/// Opaque data structure used by [`CardinalityLimiter`] to track
/// which buckets have been accepted and rejected.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
pub struct EntryId(pub usize);

impl<'a> Entry<'a> {
    /// Creates a new entry.
    pub fn new(id: EntryId, namespace: MetricNamespace, name: &'a MetricName, hash: u32) -> Self {
        Self {
            id,
            namespace,
            name,
            hash,
        }
    }
}

/// Cardinality Limiter enforcing cardinality limits on buckets.
///
/// Delegates enforcement to a [`Limiter`].
pub struct CardinalityLimiter<T: Limiter> {
    limiter: T,
}

impl<T: Limiter> CardinalityLimiter<T> {
    /// Creates a new cardinality limiter.
    pub fn new(limiter: T) -> Self {
        Self { limiter }
    }

    /// Checks cardinality limits of a list of buckets.
    ///
    /// Returns an iterator of all buckets that have been accepted.
    pub fn check_cardinality_limits<'a, I: CardinalityItem>(
        &self,
        scoping: Scoping,
        limits: &'a [CardinalityLimit],
        items: Vec<I>,
    ) -> Result<CardinalityLimits<'a, I>, (Vec<I>, Error)> {
        if limits.is_empty() {
            return Ok(CardinalityLimits::new(items, Default::default()));
        }

        metric!(timer(CardinalityLimiterTimers::CardinalityLimiter), {
            let entries = items.iter().enumerate().filter_map(|(id, item)| {
                Some(Entry::new(
                    EntryId(id),
                    item.namespace()?,
                    item.name(),
                    item.to_hash(),
                ))
            });

            let mut rejections = DefaultReporter::default();
            if let Err(err) =
                self.limiter
                    .check_cardinality_limits(scoping, limits, entries, &mut rejections)
            {
                return Err((items, err));
            }

            if !rejections.entries.is_empty() {
                relay_log::debug!(
                    scoping = ?scoping,
                    "rejected {} metrics due to cardinality limit",
                    rejections.entries.len(),
                );
            }

            Ok(CardinalityLimits::new(items, rejections))
        })
    }
}

/// Internal outcome accumulator tracking the raw value from an [`EntryId`].
///
/// The result can be used directly by [`CardinalityLimits`].
#[derive(Debug, Default)]
struct DefaultReporter<'a> {
    /// All limits that have been exceeded.
    exceeded_limits: HashSet<&'a CardinalityLimit>,
    /// A map from entries that have been rejected to the most
    /// specific non-passive limit that they exceeded.
    ///
    /// "Specificity" is determined by scope and limit, in that order.
    entries: HashMap<usize, &'a CardinalityLimit>,
    reports: BTreeMap<&'a CardinalityLimit, Vec<CardinalityReport>>,
}

impl<'a> Reporter<'a> for DefaultReporter<'a> {
    #[inline(always)]
    fn reject(&mut self, limit: &'a CardinalityLimit, entry_id: EntryId) {
        self.exceeded_limits.insert(limit);
        if !limit.passive {
            // Write `limit` into the entry if it's more specific than the existing limit
            // (or if there isn't one)
            self.entries
                .entry(entry_id.0)
                .and_modify(|existing_limit| {
                    // Scopes are ordered by reverse specificity (org is the smallest), so we use `Reverse` here
                    if (Reverse(limit.scope), limit.limit)
                        < (Reverse(existing_limit.scope), existing_limit.limit)
                    {
                        *existing_limit = limit;
                    }
                })
                .or_insert(limit);
        }
    }

    #[inline(always)]
    fn report_cardinality(&mut self, limit: &'a CardinalityLimit, report: CardinalityReport) {
        if !limit.report {
            return;
        }
        self.reports.entry(limit).or_default().push(report);
    }
}

/// Split of the original source containing accepted and rejected source elements.
#[derive(Debug)]
pub struct CardinalityLimitsSplit<'a, T> {
    /// The list of accepted elements of the source.
    pub accepted: Vec<T>,
    /// The list of rejected elements of the source, together
    /// with the most specific limit they exceeded.
    pub rejected: Vec<(T, &'a CardinalityLimit)>,
}

impl<T> CardinalityLimitsSplit<'_, T> {
    /// Creates a new cardinality limits split with a given capacity for `accepted` and `rejected`
    /// elements.
    fn with_capacity(accepted_capacity: usize, rejected_capacity: usize) -> Self {
        CardinalityLimitsSplit {
            accepted: Vec::with_capacity(accepted_capacity),
            rejected: Vec::with_capacity(rejected_capacity),
        }
    }
}

/// Result of [`CardinalityLimiter::check_cardinality_limits`].
#[derive(Debug)]
pub struct CardinalityLimits<'a, T> {
    /// The source.
    source: Vec<T>,
    /// List of rejected item indices pointing into `source`.
    rejections: HashMap<usize, &'a CardinalityLimit>,
    /// All non-passive exceeded limits.
    exceeded_limits: HashSet<&'a CardinalityLimit>,
    /// Generated cardinality reports.
    reports: BTreeMap<&'a CardinalityLimit, Vec<CardinalityReport>>,
}

impl<'a, T> CardinalityLimits<'a, T> {
    fn new(source: Vec<T>, reporter: DefaultReporter<'a>) -> Self {
        Self {
            source,
            rejections: reporter.entries,
            exceeded_limits: reporter.exceeded_limits,
            reports: reporter.reports,
        }
    }

    /// Returns `true` if any items have been rejected.
    pub fn has_rejections(&self) -> bool {
        !self.rejections.is_empty()
    }

    /// Returns all id's of cardinality limits which were exceeded.
    ///
    /// This includes passive limits.
    pub fn exceeded_limits(&self) -> &HashSet<&'a CardinalityLimit> {
        &self.exceeded_limits
    }

    /// Returns all cardinality reports grouped by the cardinality limit.
    ///
    /// Cardinality reports are generated for all cardinality limits with reporting enabled
    /// and the current cardinality changed.
    pub fn cardinality_reports(&self) -> &BTreeMap<&'a CardinalityLimit, Vec<CardinalityReport>> {
        &self.reports
    }

    /// Recovers the original list of items passed to the cardinality limiter.
    pub fn into_source(self) -> Vec<T> {
        self.source
    }

    /// Returns an iterator yielding only rejected items.
    pub fn rejected(&self) -> impl Iterator<Item = &T> {
        self.rejections.keys().filter_map(|&i| self.source.get(i))
    }

    /// Consumes the result and returns [`CardinalityLimitsSplit`] containing all accepted and rejected items.
    pub fn into_split(mut self) -> CardinalityLimitsSplit<'a, T> {
        if self.rejections.is_empty() {
            return CardinalityLimitsSplit {
                accepted: self.source,
                rejected: Vec::new(),
            };
        }
        // TODO: we might want to optimize this method later, by reusing one of the arrays and
        // swap removing elements from it.
        let source_len = self.source.len();
        let rejections_len = self.rejections.len();
        self.source.into_iter().enumerate().fold(
            CardinalityLimitsSplit::with_capacity(source_len - rejections_len, rejections_len),
            |mut split, (i, item)| {
                if let Some(exceeded) = self.rejections.remove(&i) {
                    split.rejected.push((item, exceeded));
                } else {
                    split.accepted.push(item);
                };

                split
            },
        )
    }
}

#[cfg(test)]
mod tests {
    use crate::{CardinalityScope, SlidingWindow};

    use super::*;

    #[derive(Debug, Clone, Hash, PartialEq, Eq)]
    struct Item {
        hash: u32,
        namespace: Option<MetricNamespace>,
        name: MetricName,
    }

    impl Item {
        fn new(hash: u32, namespace: impl Into<Option<MetricNamespace>>) -> Self {
            Self {
                hash,
                namespace: namespace.into(),
                name: MetricName::from("foobar"),
            }
        }
    }

    impl CardinalityItem for Item {
        fn to_hash(&self) -> u32 {
            self.hash
        }

        fn namespace(&self) -> Option<MetricNamespace> {
            self.namespace
        }

        fn name(&self) -> &MetricName {
            &self.name
        }
    }

    fn build_limits() -> [CardinalityLimit; 1] {
        [CardinalityLimit {
            id: "limit".to_owned(),
            passive: false,
            report: false,
            window: SlidingWindow {
                window_seconds: 3600,
                granularity_seconds: 360,
            },
            limit: 10_000,
            scope: CardinalityScope::Organization,
            namespace: None,
        }]
    }

    fn build_scoping() -> Scoping {
        Scoping {
            organization_id: OrganizationId::new(1),
            project_id: ProjectId::new(1),
        }
    }

    #[test]
    fn test_accepted() {
        // HACK: we need to make Windows happy.
        fn assert_eq(value: Vec<char>, expected_value: Vec<char>) {
            assert_eq!(value, expected_value)
        }

        let limit = CardinalityLimit {
            id: "dummy_limit".to_owned(),
            passive: false,
            report: false,
            window: SlidingWindow {
                window_seconds: 0,
                granularity_seconds: 0,
            },
            limit: 0,
            scope: CardinalityScope::Organization,
            namespace: None,
        };

        let limits = CardinalityLimits {
            source: vec!['a', 'b', 'c', 'd', 'e'],
            rejections: HashMap::from([(0, &limit), (1, &limit), (3, &limit)]),
            exceeded_limits: HashSet::new(),
            reports: BTreeMap::new(),
        };
        assert!(limits.has_rejections());
        let split = limits.into_split();
        assert_eq!(
            split.rejected,
            vec![('a', &limit), ('b', &limit), ('d', &limit)]
        );
        assert_eq!(split.accepted, vec!['c', 'e']);

        let limits = CardinalityLimits {
            source: vec!['a', 'b', 'c', 'd', 'e'],
            rejections: HashMap::from([]),
            exceeded_limits: HashSet::new(),
            reports: BTreeMap::new(),
        };
        assert!(!limits.has_rejections());
        let split = limits.into_split();
        assert!(split.rejected.is_empty());
        assert_eq!(split.accepted, vec!['a', 'b', 'c', 'd', 'e']);

        let limits = CardinalityLimits {
            source: vec!['a', 'b', 'c', 'd', 'e'],
            rejections: HashMap::from([
                (0, &limit),
                (1, &limit),
                (2, &limit),
                (3, &limit),
                (4, &limit),
            ]),
            exceeded_limits: HashSet::new(),
            reports: BTreeMap::new(),
        };
        assert!(limits.has_rejections());
        let split = limits.into_split();
        assert_eq!(
            split.rejected,
            vec![
                ('a', &limit),
                ('b', &limit),
                ('c', &limit),
                ('d', &limit),
                ('e', &limit)
            ]
        );
        assert_eq(split.accepted, vec![]);
    }

    #[test]
    fn test_limiter_reject_all() {
        struct RejectAllLimiter;

        impl Limiter for RejectAllLimiter {
            fn check_cardinality_limits<'a, 'b, I, T>(
                &self,
                _scoping: Scoping,
                limits: &'a [CardinalityLimit],
                entries: I,
                rejections: &mut T,
            ) -> Result<()>
            where
                I: IntoIterator<Item = Entry<'b>>,
                T: Reporter<'a>,
            {
                for entry in entries {
                    rejections.reject(&limits[0], entry.id);
                }

                Ok(())
            }
        }

        let limiter = CardinalityLimiter::new(RejectAllLimiter);

        let items = vec![
            Item::new(0, MetricNamespace::Transactions),
            Item::new(1, MetricNamespace::Transactions),
        ];
        let limits = build_limits();
        let result = limiter
            .check_cardinality_limits(build_scoping(), &limits, items.clone())
            .unwrap();

        let expected_items = items
            .into_iter()
            .zip(std::iter::repeat(&limits[0]))
            .collect::<Vec<_>>();

        assert_eq!(result.exceeded_limits(), &HashSet::from([&limits[0]]));
        let split = result.into_split();
        assert_eq!(split.rejected, expected_items);
        assert!(split.accepted.is_empty());
    }

    #[test]
    fn test_limiter_accept_all() {
        struct AcceptAllLimiter;

        impl Limiter for AcceptAllLimiter {
            fn check_cardinality_limits<'a, 'b, I, T>(
                &self,
                _scoping: Scoping,
                _limits: &'a [CardinalityLimit],
                _entries: I,
                _reporter: &mut T,
            ) -> Result<()>
            where
                I: IntoIterator<Item = Entry<'b>>,
                T: Reporter<'a>,
            {
                Ok(())
            }
        }

        let limiter = CardinalityLimiter::new(AcceptAllLimiter);

        let items = vec![
            Item::new(0, MetricNamespace::Transactions),
            Item::new(1, MetricNamespace::Spans),
        ];
        let limits = build_limits();
        let result = limiter
            .check_cardinality_limits(build_scoping(), &limits, items.clone())
            .unwrap();

        let split = result.into_split();
        assert!(split.rejected.is_empty());
        assert_eq!(split.accepted, items);
    }

    #[test]
    fn test_limiter_accept_odd_reject_even() {
        struct RejectEvenLimiter;

        impl Limiter for RejectEvenLimiter {
            fn check_cardinality_limits<'a, 'b, I, T>(
                &self,
                scoping: Scoping,
                limits: &'a [CardinalityLimit],
                entries: I,
                reporter: &mut T,
            ) -> Result<()>
            where
                I: IntoIterator<Item = Entry<'b>>,
                T: Reporter<'a>,
            {
                assert_eq!(scoping, build_scoping());
                assert_eq!(limits, &build_limits());

                for entry in entries {
                    if entry.id.0 % 2 == 0 {
                        reporter.reject(&limits[0], entry.id);
                    }
                }

                Ok(())
            }
        }

        let limiter = CardinalityLimiter::new(RejectEvenLimiter);

        let items = vec![
            Item::new(0, MetricNamespace::Sessions),
            Item::new(1, MetricNamespace::Transactions),
            Item::new(2, MetricNamespace::Spans),
            Item::new(3, MetricNamespace::Custom),
            Item::new(4, MetricNamespace::Custom),
            Item::new(5, MetricNamespace::Transactions),
            Item::new(6, MetricNamespace::Spans),
        ];
        let limits = build_limits();
        let split = limiter
            .check_cardinality_limits(build_scoping(), &limits, items)
            .unwrap()
            .into_split();

        assert_eq!(
            split.rejected,
            vec![
                (Item::new(0, MetricNamespace::Sessions), &limits[0]),
                (Item::new(2, MetricNamespace::Spans), &limits[0]),
                (Item::new(4, MetricNamespace::Custom), &limits[0]),
                (Item::new(6, MetricNamespace::Spans), &limits[0]),
            ]
        );
        assert_eq!(
            split.accepted,
            vec![
                Item::new(1, MetricNamespace::Transactions),
                Item::new(3, MetricNamespace::Custom),
                Item::new(5, MetricNamespace::Transactions),
            ]
        );
    }

    #[test]
    fn test_limiter_passive() {
        struct RejectLimits;

        impl Limiter for RejectLimits {
            fn check_cardinality_limits<'a, 'b, I, T>(
                &self,
                _scoping: Scoping,
                limits: &'a [CardinalityLimit],
                entries: I,
                reporter: &mut T,
            ) -> Result<()>
            where
                I: IntoIterator<Item = Entry<'b>>,
                T: Reporter<'a>,
            {
                for entry in entries {
                    reporter.reject(&limits[entry.id.0 % limits.len()], entry.id);
                }
                Ok(())
            }
        }

        let limiter = CardinalityLimiter::new(RejectLimits);
        let limits = &[
            CardinalityLimit {
                id: "limit_passive".to_owned(),
                passive: false,
                report: false,
                window: SlidingWindow {
                    window_seconds: 3600,
                    granularity_seconds: 360,
                },
                limit: 10_000,
                scope: CardinalityScope::Organization,
                namespace: None,
            },
            CardinalityLimit {
                id: "limit_enforced".to_owned(),
                passive: true,
                report: false,
                window: SlidingWindow {
                    window_seconds: 3600,
                    granularity_seconds: 360,
                },
                limit: 10_000,
                scope: CardinalityScope::Organization,
                namespace: None,
            },
        ];

        let items = vec![
            Item::new(0, MetricNamespace::Custom),
            Item::new(1, MetricNamespace::Custom),
            Item::new(2, MetricNamespace::Custom),
            Item::new(3, MetricNamespace::Custom),
            Item::new(4, MetricNamespace::Custom),
            Item::new(5, MetricNamespace::Custom),
        ];
        let limited = limiter
            .check_cardinality_limits(build_scoping(), limits, items)
            .unwrap();

        assert!(limited.has_rejections());
        assert_eq!(limited.exceeded_limits(), &limits.iter().collect());

        let split = limited.into_split();
        assert_eq!(
            split.rejected,
            vec![
                (Item::new(0, MetricNamespace::Custom), &limits[0]),
                (Item::new(2, MetricNamespace::Custom), &limits[0]),
                (Item::new(4, MetricNamespace::Custom), &limits[0]),
            ]
        );
        assert_eq!(
            split.accepted,
            vec![
                Item::new(1, MetricNamespace::Custom),
                Item::new(3, MetricNamespace::Custom),
                Item::new(5, MetricNamespace::Custom),
            ]
        );
    }

    #[test]
    fn test_cardinality_report() {
        struct CreateReports;

        impl Limiter for CreateReports {
            fn check_cardinality_limits<'a, 'b, I, T>(
                &self,
                scoping: Scoping,
                limits: &'a [CardinalityLimit],
                _entries: I,
                reporter: &mut T,
            ) -> Result<()>
            where
                I: IntoIterator<Item = Entry<'b>>,
                T: Reporter<'a>,
            {
                reporter.report_cardinality(
                    &limits[0],
                    CardinalityReport {
                        timestamp: UnixTimestamp::from_secs(5000),
                        organization_id: Some(scoping.organization_id),
                        project_id: Some(scoping.project_id),
                        metric_type: None,
                        metric_name: Some(MetricName::from("foo")),
                        cardinality: 1,
                    },
                );

                reporter.report_cardinality(
                    &limits[0],
                    CardinalityReport {
                        timestamp: UnixTimestamp::from_secs(5001),
                        organization_id: Some(scoping.organization_id),
                        project_id: Some(scoping.project_id),
                        metric_type: None,
                        metric_name: Some(MetricName::from("bar")),
                        cardinality: 2,
                    },
                );

                reporter.report_cardinality(
                    &limits[2],
                    CardinalityReport {
                        timestamp: UnixTimestamp::from_secs(5002),
                        organization_id: Some(scoping.organization_id),
                        project_id: Some(scoping.project_id),
                        metric_type: None,
                        metric_name: None,
                        cardinality: 3,
                    },
                );

                Ok(())
            }
        }

        let window = SlidingWindow {
            window_seconds: 3600,
            granularity_seconds: 360,
        };

        let limits = &[
            CardinalityLimit {
                id: "report".to_owned(),
                passive: false,
                report: true,
                window,
                limit: 10_000,
                scope: CardinalityScope::Organization,
                namespace: None,
            },
            CardinalityLimit {
                id: "no_report".to_owned(),
                passive: false,
                report: false,
                window,
                limit: 10_000,
                scope: CardinalityScope::Organization,
                namespace: None,
            },
            CardinalityLimit {
                id: "report_again".to_owned(),
                passive: true,
                report: true,
                window,
                limit: 10_000,
                scope: CardinalityScope::Organization,
                namespace: None,
            },
        ];
        let scoping = build_scoping();
        let items = vec![Item::new(0, MetricNamespace::Custom)];

        let limiter = CardinalityLimiter::new(CreateReports);
        let limited = limiter
            .check_cardinality_limits(scoping, limits, items)
            .unwrap();

        let reports = limited.cardinality_reports();
        assert_eq!(reports.len(), 2);
        assert_eq!(
            reports.get(&limits[0]).unwrap(),
            &[
                CardinalityReport {
                    timestamp: UnixTimestamp::from_secs(5000),
                    organization_id: Some(scoping.organization_id),
                    project_id: Some(scoping.project_id),
                    metric_type: None,
                    metric_name: Some(MetricName::from("foo")),
                    cardinality: 1
                },
                CardinalityReport {
                    timestamp: UnixTimestamp::from_secs(5001),
                    organization_id: Some(scoping.organization_id),
                    project_id: Some(scoping.project_id),
                    metric_type: None,
                    metric_name: Some(MetricName::from("bar")),
                    cardinality: 2
                }
            ]
        );
        assert_eq!(
            reports.get(&limits[2]).unwrap(),
            &[CardinalityReport {
                timestamp: UnixTimestamp::from_secs(5002),
                organization_id: Some(scoping.organization_id),
                project_id: Some(scoping.project_id),
                metric_type: None,
                metric_name: None,
                cardinality: 3
            }]
        );
    }
}