Skip to main content

relay_event_normalization/eap/
trimming.rs

1use std::cmp::Ordering;
2use std::ops::Bound;
3
4use relay_event_schema::processor::{
5    self, ProcessValue, ProcessingAction, ProcessingResult, ProcessingState, Processor, ValueType,
6};
7use relay_event_schema::protocol::Attributes;
8use relay_protocol::{Array, Empty, Meta, Object};
9
10#[derive(Clone, Debug)]
11struct SizeState {
12    max_depth: Option<usize>,
13    encountered_at_depth: usize,
14    size_remaining: Option<usize>,
15}
16
17/// The action to take when deleting a value.
18#[derive(Debug, Clone, Copy)]
19enum DeleteAction {
20    /// Delete the value without leaving a trace.
21    Hard,
22    /// Delete the value and leave a remark with the given rule ID.
23    WithRemark(&'static str),
24}
25
26impl From<DeleteAction> for ProcessingAction {
27    fn from(action: DeleteAction) -> Self {
28        match action {
29            DeleteAction::Hard => ProcessingAction::DeleteValueHard,
30            DeleteAction::WithRemark(rule_id) => ProcessingAction::DeleteValueWithRemark(rule_id),
31        }
32    }
33}
34
35/// Processor for trimming EAP items (logs, V2 spans).
36///
37/// This primarily differs from the regular [`TrimmingProcessor`](crate::trimming::TrimmingProcessor)
38/// in the handling of [`Attributes`]. This processor handles attributes as follows:
39/// 1. Sort them by combined key and value size, where the key size is just the string length
40///    and the value size is given by [`relay_event_schema::protocol::attribute_size`].
41/// 2. Trim attributes one by one. Key lengths are counted for the attribute's size, but keys
42///    aren't trimmed—if a key is too long, the attribute is simply discarded.
43/// 3. If we run out of space, all subsequent attributes are discarded.
44///
45/// This means that large attributes will be trimmed or discarded before small ones.
46#[derive(Default)]
47pub struct TrimmingProcessor {
48    size_state: Vec<SizeState>,
49    removed_key_byte_budget: usize,
50}
51
52impl TrimmingProcessor {
53    /// Creates a new trimming processor.
54    pub fn new(removed_key_byte_budget: usize) -> Self {
55        Self {
56            size_state: Default::default(),
57            removed_key_byte_budget,
58        }
59    }
60
61    fn should_remove_container<T: Empty>(&self, value: &T, state: &ProcessingState<'_>) -> bool {
62        // Heuristic to avoid trimming a value like `[1, 1, 1, 1, ...]` into `[null, null, null,
63        // null, ...]`, making it take up more space.
64        self.remaining_depth(state) == Some(1) && !value.is_empty()
65    }
66
67    #[inline]
68    fn remaining_size(&self) -> Option<usize> {
69        self.size_state
70            .iter()
71            .filter_map(|x| x.size_remaining)
72            .min()
73    }
74
75    #[inline]
76    fn remaining_depth(&self, state: &ProcessingState<'_>) -> Option<usize> {
77        self.size_state
78            .iter()
79            .filter_map(|size_state| {
80                // The current depth in the entire event payload minus the depth at which we found the
81                // max_depth attribute is the depth where we are at in the property.
82                let current_depth = state.depth() - size_state.encountered_at_depth;
83                size_state
84                    .max_depth
85                    .map(|max_depth| max_depth.saturating_sub(current_depth))
86            })
87            .min()
88    }
89
90    fn consume_size(&mut self, state: Option<&ProcessingState>, default: usize) {
91        let size = state.and_then(|s| s.bytes_size()).unwrap_or(default);
92        for remaining in self
93            .size_state
94            .iter_mut()
95            .filter_map(|state| state.size_remaining.as_mut())
96        {
97            *remaining = remaining.saturating_sub(size);
98        }
99    }
100
101    /// Returns a [`DeleteAction`] for removing the given key.
102    ///
103    /// If there is enough `removed_key_byte_budget` left to accomodate the key,
104    /// this will be [`DeleteAction::WithRemark`] (which causes a remark to be left).
105    /// Otherwise, it will be [`DeleteAction::Hard`] (the key is removed without a trace).
106    fn delete_value(&mut self, key: Option<&str>) -> DeleteAction {
107        let len = key.map_or(0, |key| key.len());
108        if len <= self.removed_key_byte_budget {
109            self.removed_key_byte_budget -= len;
110            DeleteAction::WithRemark("trimmed")
111        } else {
112            DeleteAction::Hard
113        }
114    }
115}
116
117impl Processor for TrimmingProcessor {
118    fn before_process<T: ProcessValue>(
119        &mut self,
120        _: Option<&T>,
121        _: &mut Meta,
122        state: &ProcessingState<'_>,
123    ) -> ProcessingResult {
124        // If we encounter a max_bytes or max_depth attribute it
125        // resets the size and depth that is permitted below it.
126        if state.max_bytes().is_some() || state.attrs().max_depth.is_some() {
127            self.size_state.push(SizeState {
128                size_remaining: state.max_bytes(),
129                encountered_at_depth: state.depth(),
130                max_depth: state.attrs().max_depth,
131            });
132        }
133
134        if state.attrs().trim {
135            let key = state.keys().next();
136            if self.remaining_size() == Some(0) {
137                return Err(self.delete_value(key).into());
138            }
139            if self.remaining_depth(state) == Some(0) {
140                return Err(self.delete_value(key).into());
141            }
142        }
143        Ok(())
144    }
145
146    fn after_process<T: ProcessValue>(
147        &mut self,
148        _value: Option<&T>,
149        _: &mut Meta,
150        state: &ProcessingState<'_>,
151    ) -> ProcessingResult {
152        // If our current depth is the one where we found a bag_size attribute, this means we
153        // are done processing a databag. Pop the bag size state.
154        self.size_state
155            .pop_if(|size_state| state.depth() == size_state.encountered_at_depth);
156
157        // The general `TrimmingProcessor` counts consumed sizes at this point. We can't do this generically
158        // because we want to count sizes using `size::attribute_size` for attribute values. Therefore, the
159        // size accounting needs to happen in the processing functions themselves.
160
161        Ok(())
162    }
163    fn process_u64(
164        &mut self,
165        _value: &mut u64,
166        _meta: &mut Meta,
167        state: &ProcessingState<'_>,
168    ) -> ProcessingResult {
169        self.consume_size(Some(state), 8);
170        Ok(())
171    }
172
173    fn process_i64(
174        &mut self,
175        _value: &mut i64,
176        _meta: &mut Meta,
177        state: &ProcessingState<'_>,
178    ) -> ProcessingResult {
179        self.consume_size(Some(state), 8);
180        Ok(())
181    }
182
183    fn process_f64(
184        &mut self,
185        _value: &mut f64,
186        _meta: &mut Meta,
187        state: &ProcessingState<'_>,
188    ) -> ProcessingResult {
189        self.consume_size(Some(state), 8);
190        Ok(())
191    }
192
193    fn process_bool(
194        &mut self,
195        _value: &mut bool,
196        _meta: &mut Meta,
197        state: &ProcessingState<'_>,
198    ) -> ProcessingResult {
199        self.consume_size(Some(state), 1);
200        Ok(())
201    }
202
203    fn process_string(
204        &mut self,
205        value: &mut String,
206        meta: &mut Meta,
207        state: &ProcessingState<'_>,
208    ) -> ProcessingResult {
209        if let Some(max_chars) = state.max_chars() {
210            crate::trimming::trim_string(value, meta, max_chars, state.attrs().max_chars_allowance);
211        }
212
213        if !state.attrs().trim {
214            self.consume_size(Some(state), value.len());
215            return Ok(());
216        }
217
218        if let Some(size_remaining) = self.remaining_size() {
219            crate::trimming::trim_string(value, meta, size_remaining, 0);
220        }
221
222        self.consume_size(Some(state), value.len());
223
224        Ok(())
225    }
226
227    fn process_array<T>(
228        &mut self,
229        value: &mut Array<T>,
230        meta: &mut Meta,
231        state: &ProcessingState<'_>,
232    ) -> ProcessingResult
233    where
234        T: ProcessValue,
235    {
236        if !state.attrs().trim {
237            return Ok(());
238        }
239
240        // If we need to check the bag size, then we go down a different path
241        if !self.size_state.is_empty() {
242            let original_length = value.len();
243
244            if self.should_remove_container(value, state) {
245                return Err(ProcessingAction::DeleteValueHard);
246            }
247
248            let mut split_index = None;
249            for (index, item) in value.iter_mut().enumerate() {
250                if self.remaining_size() == Some(0) {
251                    split_index = Some(index);
252                    break;
253                }
254
255                let item_state = state.enter_index(index, None, ValueType::for_field(item));
256                processor::process_value(item, self, &item_state)?;
257            }
258
259            if let Some(split_index) = split_index {
260                let mut i = split_index;
261
262                for item in &mut value[split_index..] {
263                    match self.delete_value(None) {
264                        DeleteAction::Hard => break,
265                        DeleteAction::WithRemark(rule_id) => {
266                            processor::delete_with_remark(item, rule_id)
267                        }
268                    }
269
270                    i += 1;
271                }
272
273                let _ = value.split_off(i);
274            }
275
276            if value.len() != original_length {
277                meta.set_original_length(Some(original_length));
278            }
279        } else {
280            value.process_child_values(self, state)?;
281        }
282
283        Ok(())
284    }
285
286    fn process_object<T>(
287        &mut self,
288        value: &mut Object<T>,
289        meta: &mut Meta,
290        state: &ProcessingState<'_>,
291    ) -> ProcessingResult
292    where
293        T: ProcessValue,
294    {
295        if !state.attrs().trim {
296            return Ok(());
297        }
298
299        // If we need to check the bag size, then we go down a different path
300        if !self.size_state.is_empty() {
301            let original_length = value.len();
302
303            if self.should_remove_container(value, state) {
304                return Err(ProcessingAction::DeleteValueHard);
305            }
306
307            let mut split_key = None;
308            for (key, item) in value.iter_mut() {
309                if self.remaining_size() == Some(0) {
310                    split_key = Some(key.to_owned());
311                    break;
312                }
313
314                let item_state = state.enter_borrowed(key, None, ValueType::for_field(item));
315                processor::process_value(item, self, &item_state)?;
316            }
317
318            if let Some(split_key) = split_key {
319                let mut i = split_key.as_str();
320
321                // Morally this is just `range_mut(split_key.as_str()..)`, but that doesn't work for type
322                // inference reasons.
323                for (key, value) in value
324                    .range_mut::<str, _>((Bound::Included(split_key.as_str()), Bound::Unbounded))
325                {
326                    i = key.as_str();
327
328                    match self.delete_value(Some(key.as_ref())) {
329                        DeleteAction::Hard => break,
330                        DeleteAction::WithRemark(rule_id) => {
331                            processor::delete_with_remark(value, rule_id)
332                        }
333                    }
334                }
335
336                let split_key = i.to_owned();
337                let _ = value.split_off(&split_key);
338            }
339
340            if value.len() != original_length {
341                meta.set_original_length(Some(original_length));
342            }
343        } else {
344            value.process_child_values(self, state)?;
345        }
346
347        Ok(())
348    }
349
350    fn process_attributes(
351        &mut self,
352        attributes: &mut Attributes,
353        meta: &mut Meta,
354        state: &ProcessingState,
355    ) -> ProcessingResult {
356        if !state.attrs().trim {
357            return Ok(());
358        }
359
360        // This counts the lengths of all attribute keys regardless of whether
361        // the attribute itself is valid or invalid. Strictly speaking, this is
362        // inconsistent with the trimming logic, which only counts keys of valid
363        // attributes. However, this value is only used to set the `original_value`
364        // on the attributes collection for documentation purposes, we accept this
365        // discrepancy for now. In any case this is fine to change.
366        let original_length = relay_event_schema::protocol::attributes_size(attributes);
367
368        // Sort attributes by key + value size so small attributes are more likely to be preserved.
369        // Attributes with missing values will be sorted at the beginning.
370        let inner = std::mem::take(&mut attributes.0);
371        let mut sorted: Vec<_> = inner.into_iter().collect();
372        sorted.sort_by(
373            |(k1, v1), (k2, v2)| match (v1.value().is_some(), v2.value().is_some()) {
374                (false, false) => k1.len().cmp(&k2.len()),
375                (false, true) => Ordering::Less,
376                (true, false) => Ordering::Greater,
377                (true, true) => (k1.len() + relay_event_schema::protocol::attribute_size(v1))
378                    .cmp(&(k2.len() + relay_event_schema::protocol::attribute_size(v2))),
379            },
380        );
381
382        // Drop keys without values once we run out of
383        // `removed_key_budget`.
384        sorted.retain(|(k, v)| {
385            if v.value().is_some() {
386                return true;
387            }
388
389            match self.delete_value(Some(k)) {
390                DeleteAction::Hard => false,
391                DeleteAction::WithRemark(_) => true,
392            }
393        });
394
395        let mut split_idx = None;
396        for (idx, (key, value)) in sorted.iter_mut().enumerate() {
397            if value.value().is_none() {
398                // Keys without values were already treated in the `retain` above.
399                // In any case, we don't want such keys to be counted against the
400                // trimming size budget.
401                continue;
402            }
403            if let Some(remaining) = self.remaining_size()
404                && remaining < key.len()
405            {
406                split_idx = Some(idx);
407                break;
408            }
409
410            self.consume_size(None, key.len());
411
412            let value_state = state.enter_borrowed(key, None, ValueType::for_field(value));
413            processor::process_value(value, self, &value_state)?;
414        }
415
416        if let Some(split_idx) = split_idx {
417            let mut i = split_idx;
418
419            for (key, value) in &mut sorted[split_idx..] {
420                match self.delete_value(Some(key.as_ref())) {
421                    DeleteAction::Hard => break,
422                    DeleteAction::WithRemark(rule_id) => {
423                        processor::delete_with_remark(value, rule_id)
424                    }
425                }
426
427                i += 1;
428            }
429
430            let _ = sorted.split_off(i);
431        }
432
433        attributes.0 = sorted.into_iter().collect();
434
435        let new_size = relay_event_schema::protocol::attributes_size(attributes);
436        if new_size != original_length {
437            meta.set_original_length(Some(original_length));
438        }
439
440        Ok(())
441    }
442}
443
444#[cfg(test)]
445mod tests {
446    use relay_event_schema::protocol::{AttributeType, AttributeValue};
447    use relay_protocol::{
448        Annotated, FromValue, IntoValue, SerializableAnnotated, Value, assert_annotated_snapshot,
449    };
450
451    use super::*;
452
453    #[derive(Debug, Clone, Empty, IntoValue, FromValue, ProcessValue)]
454    struct TestObject {
455        #[metastructure(max_chars = 10, trim = true)]
456        body: Annotated<String>,
457        // This should neither be trimmed nor factor into size calculations.
458        #[metastructure(trim = false, bytes_size = 0)]
459        number: Annotated<u64>,
460        // This should count as 10B.
461        #[metastructure(trim = false, bytes_size = 10)]
462        other_number: Annotated<u64>,
463        #[metastructure(max_bytes = 40, trim = true)]
464        attributes: Annotated<Attributes>,
465        #[metastructure(trim = true)]
466        footer: Annotated<String>,
467    }
468
469    #[test]
470    fn test_split_on_string() {
471        let mut attributes = Attributes::new();
472
473        attributes.insert("small", 17); // 13B
474        attributes.insert("medium string", "This string should be trimmed"); // 42B
475        attributes.insert("attribute is very large and should be removed", true); // 47B
476
477        let mut value = Annotated::new(TestObject {
478            attributes: Annotated::new(attributes),
479            number: Annotated::empty(),
480            other_number: Annotated::empty(),
481            body: Annotated::new("This is longer than allowed".to_owned()),
482            footer: Annotated::empty(),
483        });
484
485        let mut processor = TrimmingProcessor::new(100);
486
487        let state = ProcessingState::new_root(Default::default(), []);
488        processor::process_value(&mut value, &mut processor, &state).unwrap();
489
490        insta::assert_json_snapshot!(SerializableAnnotated(&value), @r###"
491        {
492          "body": "This is...",
493          "attributes": {
494            "attribute is very large and should be removed": null,
495            "medium string": {
496              "type": "string",
497              "value": "This string..."
498            },
499            "small": {
500              "type": "integer",
501              "value": 17
502            }
503          },
504          "_meta": {
505            "attributes": {
506              "": {
507                "len": 101
508              },
509              "attribute is very large and should be removed": {
510                "": {
511                  "rem": [
512                    [
513                      "trimmed",
514                      "x"
515                    ]
516                  ]
517                }
518              },
519              "medium string": {
520                "value": {
521                  "": {
522                    "rem": [
523                      [
524                        "!limit",
525                        "s",
526                        11,
527                        14
528                      ]
529                    ],
530                    "len": 29
531                  }
532                }
533              }
534            },
535            "body": {
536              "": {
537                "rem": [
538                  [
539                    "!limit",
540                    "s",
541                    7,
542                    10
543                  ]
544                ],
545                "len": 27
546              }
547            }
548          }
549        }
550        "###);
551    }
552
553    #[test]
554    fn test_one_byte_left() {
555        let mut attributes = Attributes::new();
556
557        // First attribute + key of second attribute is 39B, leaving exactly one
558        // byte for the second attribute's value.
559        attributes.insert("small attribute", 17); // 23B
560        attributes.insert("medium attribute", "This string should be trimmed"); // 45B
561
562        let mut value = Annotated::new(TestObject {
563            attributes: Annotated::new(attributes),
564            number: Annotated::empty(),
565            other_number: Annotated::empty(),
566            body: Annotated::new("This is longer than allowed".to_owned()),
567            footer: Annotated::empty(),
568        });
569
570        let mut processor = TrimmingProcessor::new(100);
571
572        let state = ProcessingState::new_root(Default::default(), []);
573        processor::process_value(&mut value, &mut processor, &state).unwrap();
574
575        insta::assert_json_snapshot!(SerializableAnnotated(&value), @r###"
576        {
577          "body": "This is...",
578          "attributes": {
579            "medium attribute": {
580              "type": "string",
581              "value": "..."
582            },
583            "small attribute": {
584              "type": "integer",
585              "value": 17
586            }
587          },
588          "_meta": {
589            "attributes": {
590              "": {
591                "len": 68
592              },
593              "medium attribute": {
594                "value": {
595                  "": {
596                    "rem": [
597                      [
598                        "!limit",
599                        "s",
600                        0,
601                        3
602                      ]
603                    ],
604                    "len": 29
605                  }
606                }
607              }
608            },
609            "body": {
610              "": {
611                "rem": [
612                  [
613                    "!limit",
614                    "s",
615                    7,
616                    10
617                  ]
618                ],
619                "len": 27
620              }
621            }
622          }
623        }
624        "###);
625    }
626
627    #[test]
628    fn test_overaccept_number() {
629        let mut attributes = Attributes::new();
630
631        // The attribute size would get used up by the value of "attribute with long name".
632        // Nevertheless, we accept this attribute, thereby overaccepting 5B.
633        attributes.insert("small", "abcdefgh"); // 5 + 8 = 13B
634        attributes.insert("attribute with long name", 71); // 24 + 8 = 32B
635        attributes.insert("attribute is very large and should be removed", true); // 46 + 1 = 47B
636
637        let mut value = Annotated::new(TestObject {
638            attributes: Annotated::new(attributes),
639            number: Annotated::empty(),
640            other_number: Annotated::empty(),
641            body: Annotated::new("This is longer than allowed".to_owned()),
642            footer: Annotated::empty(),
643        });
644
645        let mut processor = TrimmingProcessor::new(100);
646
647        let state = ProcessingState::new_root(Default::default(), []);
648        processor::process_value(&mut value, &mut processor, &state).unwrap();
649
650        insta::assert_json_snapshot!(SerializableAnnotated(&value), @r###"
651        {
652          "body": "This is...",
653          "attributes": {
654            "attribute is very large and should be removed": null,
655            "attribute with long name": {
656              "type": "integer",
657              "value": 71
658            },
659            "small": {
660              "type": "string",
661              "value": "abcdefgh"
662            }
663          },
664          "_meta": {
665            "attributes": {
666              "": {
667                "len": 91
668              },
669              "attribute is very large and should be removed": {
670                "": {
671                  "rem": [
672                    [
673                      "trimmed",
674                      "x"
675                    ]
676                  ]
677                }
678              }
679            },
680            "body": {
681              "": {
682                "rem": [
683                  [
684                    "!limit",
685                    "s",
686                    7,
687                    10
688                  ]
689                ],
690                "len": 27
691              }
692            }
693          }
694        }
695        "###);
696    }
697
698    #[test]
699    fn test_max_item_size() {
700        let mut attributes = Attributes::new();
701
702        attributes.insert("small", 17); // 13B
703        attributes.insert("medium string", "This string should be trimmed"); // 42B
704        attributes.insert("attribute is very large and should be removed", true); // 47B
705
706        let mut value = Annotated::new(TestObject {
707            attributes: Annotated::new(attributes),
708            number: Annotated::new(0),
709            other_number: Annotated::new(0),
710            body: Annotated::new("Short".to_owned()),
711            footer: Annotated::new("Hello World".to_owned()),
712        });
713
714        let mut processor = TrimmingProcessor::new(100);
715
716        // The `body` takes up 5B, `other_number` 10B, the `"small"` attribute 13B, and the key "medium string" another 13B.
717        // That leaves 9B for the string's value.
718        // Note that the `number` field doesn't take up any size.
719        // The `"footer"` is removed because it comes after the attributes and there's no space left.
720        let state = ProcessingState::root_builder().max_bytes(50).build();
721        processor::process_value(&mut value, &mut processor, &state).unwrap();
722
723        insta::assert_json_snapshot!(SerializableAnnotated(&value), @r###"
724        {
725          "body": "Short",
726          "number": 0,
727          "other_number": 0,
728          "attributes": {
729            "attribute is very large and should be removed": null,
730            "medium string": {
731              "type": "string",
732              "value": "This s..."
733            },
734            "small": {
735              "type": "integer",
736              "value": 17
737            }
738          },
739          "footer": null,
740          "_meta": {
741            "attributes": {
742              "": {
743                "len": 101
744              },
745              "attribute is very large and should be removed": {
746                "": {
747                  "rem": [
748                    [
749                      "trimmed",
750                      "x"
751                    ]
752                  ]
753                }
754              },
755              "medium string": {
756                "value": {
757                  "": {
758                    "rem": [
759                      [
760                        "!limit",
761                        "s",
762                        6,
763                        9
764                      ]
765                    ],
766                    "len": 29
767                  }
768                }
769              }
770            },
771            "footer": {
772              "": {
773                "rem": [
774                  [
775                    "trimmed",
776                    "x"
777                  ]
778                ]
779              }
780            }
781          }
782        }
783        "###);
784    }
785
786    #[test]
787    fn test_array_attribute() {
788        let mut attributes = Attributes::new();
789
790        let array = vec![
791            Annotated::new("first string".into()),
792            Annotated::new("second string".into()),
793            Annotated::new("another string".into()),
794            Annotated::new("last string".into()),
795        ];
796
797        attributes.insert(
798            "array",
799            AttributeValue {
800                ty: Annotated::new(AttributeType::Array),
801                value: Annotated::new(Value::Array(array)),
802            },
803        );
804
805        let mut value = Annotated::new(TestObject {
806            attributes: Annotated::new(attributes),
807            number: Annotated::empty(),
808            other_number: Annotated::empty(),
809            body: Annotated::new("Short".to_owned()),
810            footer: Annotated::empty(),
811        });
812
813        let mut processor = TrimmingProcessor::new(100);
814        let state = ProcessingState::new_root(Default::default(), []);
815        processor::process_value(&mut value, &mut processor, &state).unwrap();
816
817        // The key `"array"` and the first and second array value take up 5 + 12 + 13 = 30B in total,
818        // leaving 10B for the third array value and nothing for the last.
819        insta::assert_json_snapshot!(SerializableAnnotated(&value), @r###"
820        {
821          "body": "Short",
822          "attributes": {
823            "array": {
824              "type": "array",
825              "value": [
826                "first string",
827                "second string",
828                "another...",
829                null
830              ]
831            }
832          },
833          "_meta": {
834            "attributes": {
835              "": {
836                "len": 55
837              },
838              "array": {
839                "value": {
840                  "2": {
841                    "": {
842                      "rem": [
843                        [
844                          "!limit",
845                          "s",
846                          7,
847                          10
848                        ]
849                      ],
850                      "len": 14
851                    }
852                  },
853                  "3": {
854                    "": {
855                      "rem": [
856                        [
857                          "trimmed",
858                          "x"
859                        ]
860                      ]
861                    }
862                  }
863                }
864              }
865            }
866          }
867        }
868        "###);
869    }
870
871    #[test]
872    fn test_oversized_key_does_not_consume_global_limit() {
873        let mut attributes = Attributes::new();
874        attributes.insert("a", 1); // 9B
875        attributes.insert("this_key_is_exactly_35_chars_long!!", true); // 35B key + 1B = 36B
876
877        let mut value = Annotated::new(TestObject {
878            body: Annotated::new("Hi".to_owned()), // 2B
879            number: Annotated::new(0),
880            other_number: Annotated::empty(),
881            attributes: Annotated::new(attributes),
882            footer: Annotated::new("Hello World".to_owned()), // 11B
883        });
884
885        let mut processor = TrimmingProcessor::new(100);
886        let state = ProcessingState::root_builder().max_bytes(30).build();
887        processor::process_value(&mut value, &mut processor, &state).unwrap();
888
889        insta::assert_json_snapshot!(SerializableAnnotated(&value), @r###"
890        {
891          "body": "Hi",
892          "number": 0,
893          "attributes": {
894            "a": {
895              "type": "integer",
896              "value": 1
897            },
898            "this_key_is_exactly_35_chars_long!!": null
899          },
900          "footer": "Hello World",
901          "_meta": {
902            "attributes": {
903              "": {
904                "len": 45
905              },
906              "this_key_is_exactly_35_chars_long!!": {
907                "": {
908                  "rem": [
909                    [
910                      "trimmed",
911                      "x"
912                    ]
913                  ]
914                }
915              }
916            }
917          }
918        }
919        "###);
920    }
921
922    #[test]
923    fn test_invalid_values() {
924        let mut attributes = Attributes::new();
925        attributes.insert("small", 17); // 13B
926        attributes.insert("medium string", "This string should be trimmed"); // 42B
927        attributes.insert("attribute is very large and should be removed", true); // 47B
928        // Manually insert "broken" attributes. We have enough `removed_key_byte_budget`
929        // for the first but not the second.
930        attributes
931            .0
932            .insert("removed attribute".to_owned(), Annotated::empty());
933        attributes
934            .0
935            .insert("another removed attribute".to_owned(), Annotated::empty());
936
937        let mut attributes = Annotated::new(attributes);
938
939        let state = ProcessingState::root_builder().max_bytes(40).build();
940        processor::process_value(&mut attributes, &mut TrimmingProcessor::new(20), &state).unwrap();
941        let attributes_after_trimming = attributes.clone();
942        processor::process_value(&mut attributes, &mut TrimmingProcessor::new(20), &state).unwrap();
943
944        assert_eq!(
945            &attributes, &attributes_after_trimming,
946            "trimming should be idempotent"
947        );
948
949        insta::assert_json_snapshot!(SerializableAnnotated(&attributes), @r###"
950        {
951          "medium string": {
952            "type": "string",
953            "value": "This string..."
954          },
955          "removed attribute": null,
956          "small": {
957            "type": "integer",
958            "value": 17
959          },
960          "_meta": {
961            "": {
962              "len": 143
963            },
964            "medium string": {
965              "value": {
966                "": {
967                  "rem": [
968                    [
969                      "!limit",
970                      "s",
971                      11,
972                      14
973                    ]
974                  ],
975                  "len": 29
976                }
977              }
978            }
979          }
980        }
981        "###);
982    }
983
984    #[test]
985    fn test_tuple_inner_trim_settings() {
986        #[derive(Debug, Clone, Empty, IntoValue, FromValue, ProcessValue)]
987        struct Outer {
988            inner: Annotated<TestTuple>,
989        }
990
991        #[derive(Debug, Clone, Empty, IntoValue, FromValue, ProcessValue)]
992        struct TestTuple(#[metastructure(max_bytes = 10, trim = true)] String);
993
994        let mut value = Annotated::new(Outer {
995            inner: Annotated::new(TestTuple("This is longer than allowed".to_owned())),
996        });
997
998        let mut processor = TrimmingProcessor::new(100);
999        let state = ProcessingState::new_root(Default::default(), []);
1000        processor::process_value(&mut value, &mut processor, &state).unwrap();
1001
1002        assert_annotated_snapshot!(value, @r#"
1003        {
1004          "inner": "This is...",
1005          "_meta": {
1006            "inner": {
1007              "": {
1008                "rem": [
1009                  [
1010                    "!limit",
1011                    "s",
1012                    7,
1013                    10
1014                  ]
1015                ],
1016                "len": 27
1017              }
1018            }
1019          }
1020        }
1021        "#);
1022    }
1023
1024    #[test]
1025    fn test_enum_inner_trim_settings() {
1026        #[derive(Debug, Clone, Empty, IntoValue, FromValue, ProcessValue)]
1027        struct Outer {
1028            inner: Annotated<TestEnum>,
1029        }
1030
1031        #[derive(Debug, Clone, Empty, IntoValue, FromValue, ProcessValue)]
1032        enum TestEnum {
1033            Inner(#[metastructure(max_bytes = 10, trim = true)] TestEnumInner),
1034            #[metastructure(fallback_variant)]
1035            Other(#[metastructure(max_bytes = 10, trim = true)] Object<Value>),
1036        }
1037
1038        #[derive(Debug, Clone, Empty, IntoValue, FromValue, ProcessValue)]
1039        struct TestEnumInner {
1040            value: Annotated<String>,
1041        }
1042
1043        let mut value = Annotated::new(Outer {
1044            inner: Annotated::new(TestEnum::Inner(TestEnumInner {
1045                value: Annotated::new("This is longer than allowed".to_owned()),
1046            })),
1047        });
1048
1049        let mut processor = TrimmingProcessor::new(100);
1050        let state = ProcessingState::new_root(Default::default(), []);
1051        processor::process_value(&mut value, &mut processor, &state).unwrap();
1052
1053        assert_annotated_snapshot!(value, @r#"
1054        {
1055          "inner": {
1056            "value": "This is...",
1057            "type": "inner"
1058          },
1059          "_meta": {
1060            "inner": {
1061              "value": {
1062                "": {
1063                  "rem": [
1064                    [
1065                      "!limit",
1066                      "s",
1067                      7,
1068                      10
1069                    ]
1070                  ],
1071                  "len": 27
1072                }
1073              }
1074            }
1075          }
1076        }
1077        "#);
1078
1079        let mut value = Annotated::new(Outer {
1080            inner: Annotated::new(TestEnum::Other({
1081                let mut other = Object::new();
1082                other.insert(
1083                    "foo".to_owned(),
1084                    Value::String("This is longer than allowed".to_owned()).into(),
1085                );
1086                other
1087            })),
1088        });
1089
1090        let mut processor = TrimmingProcessor::new(100);
1091        let state = ProcessingState::new_root(Default::default(), []);
1092        processor::process_value(&mut value, &mut processor, &state).unwrap();
1093
1094        assert_annotated_snapshot!(value, @r#"
1095        {
1096          "inner": {
1097            "foo": "This is..."
1098          },
1099          "_meta": {
1100            "inner": {
1101              "foo": {
1102                "": {
1103                  "rem": [
1104                    [
1105                      "!limit",
1106                      "s",
1107                      7,
1108                      10
1109                    ]
1110                  ],
1111                  "len": 27
1112                }
1113              }
1114            }
1115          }
1116        }
1117        "#);
1118    }
1119}