tsdb_reader/chunkenc/
decode_limits.rs1use crate::error::{Error, Result};
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub struct DecodeLimits {
25 pub max_buckets: usize,
27 pub max_spans: usize,
29 pub max_custom_values: usize,
31 pub max_samples: u64,
33}
34
35impl Default for DecodeLimits {
36 fn default() -> Self {
37 Self {
38 max_buckets: 1 << 20,
39 max_spans: 1 << 16,
40 max_custom_values: 1 << 16,
41 max_samples: 1 << 20,
42 }
43 }
44}
45
46impl DecodeLimits {
47 pub const UNLIMITED: Self = Self {
50 max_buckets: usize::MAX,
51 max_spans: usize::MAX,
52 max_custom_values: usize::MAX,
53 max_samples: u64::MAX,
54 };
55
56 pub fn check_buckets(&self, buckets: usize) -> Result<()> {
58 if buckets > self.max_buckets {
59 return Err(Error::decode(format!(
60 "histogram declares {buckets} buckets, limit is {}",
61 self.max_buckets
62 )));
63 }
64 Ok(())
65 }
66
67 pub fn check_spans(&self, spans: u64) -> Result<()> {
69 if spans > self.max_spans as u64 {
70 return Err(Error::decode(format!(
71 "histogram declares {spans} spans, limit is {}",
72 self.max_spans
73 )));
74 }
75 Ok(())
76 }
77
78 pub fn check_custom_values(&self, values: u64) -> Result<()> {
80 if values > self.max_custom_values as u64 {
81 return Err(Error::decode(format!(
82 "histogram declares {values} custom bounds, limit is {}",
83 self.max_custom_values
84 )));
85 }
86 Ok(())
87 }
88
89 pub fn check_samples(&self, samples: u64) -> Result<()> {
91 if samples > self.max_samples {
92 return Err(Error::decode(format!(
93 "chunk declares {samples} samples, limit is {}",
94 self.max_samples
95 )));
96 }
97 Ok(())
98 }
99}
100
101#[cfg(test)]
102mod tests {
103 use super::*;
104
105 #[test]
106 fn defaults_accept_normal_payloads() {
107 let limits = DecodeLimits::default();
108 limits.check_samples(120).unwrap();
109 limits.check_buckets(2000).unwrap();
110 limits.check_spans(64).unwrap();
111 limits.check_custom_values(100).unwrap();
112 }
113
114 #[test]
115 fn declared_counts_above_the_limit_are_rejected() {
116 let limits = DecodeLimits {
117 max_buckets: 4,
118 max_spans: 2,
119 max_custom_values: 3,
120 max_samples: 10,
121 };
122 assert!(limits.check_buckets(5).unwrap_err().is_corruption());
123 assert!(limits.check_spans(3).is_err());
124 assert!(limits.check_custom_values(4).is_err());
125 assert!(limits.check_samples(11).is_err());
126 limits.check_buckets(4).unwrap();
127 limits.check_samples(10).unwrap();
128 }
129
130 #[test]
131 fn unlimited_accepts_everything() {
132 DecodeLimits::UNLIMITED.check_buckets(usize::MAX).unwrap();
133 DecodeLimits::UNLIMITED.check_samples(u64::MAX).unwrap();
134 }
135}