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
use super::LogEvent;

/// Encapsulates the inductive events merging algorithm.
///
/// In the future, this might be extended by various counters (the number of
/// events that contributed to the current merge event for instance, or the
/// event size) to support circuit breaker logic.
#[derive(Debug)]
pub struct LogEventMergeState {
    /// Intermediate event we merge into.
    intermediate_merged_event: LogEvent,
}

impl LogEventMergeState {
    /// Initialize the algorithm with a first (partial) event.
    pub fn new(first_partial_event: LogEvent) -> Self {
        Self {
            intermediate_merged_event: first_partial_event,
        }
    }

    /// Merge the incoming (partial) event in.
    pub fn merge_in_next_event(&mut self, incoming: LogEvent, fields: &[impl AsRef<str>]) {
        self.intermediate_merged_event.merge(incoming, fields);
    }

    /// Merge the final (non-partial) event in and return the resulting (merged)
    /// event.
    pub fn merge_in_final_event(
        mut self,
        incoming: LogEvent,
        fields: &[impl AsRef<str>],
    ) -> LogEvent {
        self.merge_in_next_event(incoming, fields);
        self.intermediate_merged_event
    }
}

#[cfg(test)]
mod test {
    use super::*;

    fn log_event_with_message(message: &str) -> LogEvent {
        LogEvent::from(message)
    }

    #[test]
    fn log_event_merge_state_example() {
        let fields = vec!["message".to_string()];

        let mut state = LogEventMergeState::new(log_event_with_message("hel"));
        state.merge_in_next_event(log_event_with_message("lo "), &fields);
        let merged_event = state.merge_in_final_event(log_event_with_message("world"), &fields);

        assert_eq!(
            merged_event
                .get("message")
                .unwrap()
                .coerce_to_bytes()
                .as_ref(),
            b"hello world"
        );
    }
}