relay_event_normalization/
logentry.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
#![cfg_attr(test, allow(unused_must_use))]

use std::borrow::Cow;

use dynfmt::{Argument, Format, FormatArgs, PythonFormat, SimpleCurlyFormat};
use relay_event_schema::processor::{ProcessingAction, ProcessingResult};
use relay_event_schema::protocol::LogEntry;
use relay_protocol::{Annotated, Empty, Error, Meta, Value};

struct ValueRef<'a>(&'a Value);

impl FormatArgs for ValueRef<'_> {
    fn get_index(&self, index: usize) -> Result<Option<Argument<'_>>, ()> {
        match self.0 {
            Value::Array(array) => Ok(array
                .get(index)
                .and_then(Annotated::value)
                .map(|v| v as Argument<'_>)),
            _ => Err(()),
        }
    }

    fn get_key(&self, key: &str) -> Result<Option<Argument<'_>>, ()> {
        match self.0 {
            Value::Object(object) => Ok(object
                .get(key)
                .and_then(Annotated::value)
                .map(|v| v as Argument<'_>)),
            _ => Err(()),
        }
    }
}

fn format_message(format: &str, params: &Value) -> Option<String> {
    // NB: This currently resembles the historic logic for formatting strings. It could be much more
    // lenient however, and try multiple formats one after another without exiting early.
    if format.contains('%') {
        PythonFormat
            .format(format, ValueRef(params))
            .ok()
            .map(Cow::into_owned)
    } else if format.contains('{') {
        SimpleCurlyFormat
            .format(format, ValueRef(params))
            .ok()
            .map(Cow::into_owned)
    } else {
        None
    }
}

pub fn normalize_logentry(logentry: &mut LogEntry, meta: &mut Meta) -> ProcessingResult {
    // An empty logentry should just be skipped during serialization. No need for an error.
    if logentry.is_empty() {
        return Ok(());
    }

    if logentry.formatted.value().is_none() && logentry.message.value().is_none() {
        meta.add_error(Error::invalid("no message present"));
        return Err(ProcessingAction::DeleteValueSoft);
    }

    if let Some(params) = logentry.params.value() {
        if logentry.formatted.value().is_none() {
            if let Some(message) = logentry.message.value() {
                if let Some(formatted) = format_message(message.as_ref(), params) {
                    logentry.formatted = Annotated::new(formatted.into());
                }
            }
        }
    }

    // Move `message` to `formatted` if they are equal or only message is given. This also
    // overwrites the meta data on formatted. However, do not move if both of them are None to
    // retain potential meta data on `formatted`.
    if logentry.formatted.value().is_none()
        || logentry.message.value() == logentry.formatted.value()
    {
        logentry.formatted = std::mem::take(&mut logentry.message);
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use relay_protocol::Object;
    use similar_asserts::assert_eq;

    use super::*;

    #[test]
    fn test_format_python() {
        let mut logentry = LogEntry {
            message: Annotated::new("hello, %s!".to_string().into()),
            params: Annotated::new(Value::Array(vec![Annotated::new(Value::String(
                "world".to_string(),
            ))])),
            ..LogEntry::default()
        };

        normalize_logentry(&mut logentry, &mut Meta::default());
        assert_eq!(logentry.formatted.as_str(), Some("hello, world!"));
    }

    #[test]
    fn test_format_python_named() {
        let mut logentry = LogEntry {
            message: Annotated::new("hello, %(name)s!".to_string().into()),
            params: Annotated::new(Value::Object({
                let mut object = Object::new();
                object.insert(
                    "name".to_string(),
                    Annotated::new(Value::String("world".to_string())),
                );
                object
            })),
            ..LogEntry::default()
        };

        normalize_logentry(&mut logentry, &mut Meta::default());
        assert_eq!(logentry.formatted.as_str(), Some("hello, world!"));
    }

    #[test]
    fn test_format_java() {
        let mut logentry = LogEntry {
            message: Annotated::new("hello, {}!".to_string().into()),
            params: Annotated::new(Value::Array(vec![Annotated::new(Value::String(
                "world".to_string(),
            ))])),
            ..LogEntry::default()
        };

        normalize_logentry(&mut logentry, &mut Meta::default());
        assert_eq!(logentry.formatted.as_str(), Some("hello, world!"));
    }

    #[test]
    fn test_format_dotnet() {
        let mut logentry = LogEntry {
            message: Annotated::new("hello, {0}!".to_string().into()),
            params: Annotated::new(Value::Array(vec![Annotated::new(Value::String(
                "world".to_string(),
            ))])),
            ..LogEntry::default()
        };

        normalize_logentry(&mut logentry, &mut Meta::default());
        assert_eq!(logentry.formatted.as_str(), Some("hello, world!"));
    }

    #[test]
    fn test_format_no_params() {
        let mut logentry = LogEntry {
            message: Annotated::new("hello, %s!".to_string().into()),
            ..LogEntry::default()
        };

        normalize_logentry(&mut logentry, &mut Meta::default());
        assert_eq!(logentry.formatted.as_str(), Some("hello, %s!"));
    }

    #[test]
    fn test_only_message() {
        let mut logentry = LogEntry {
            message: Annotated::new("hello, world!".to_string().into()),
            ..LogEntry::default()
        };

        normalize_logentry(&mut logentry, &mut Meta::default());
        assert_eq!(logentry.message.value(), None);
        assert_eq!(logentry.formatted.as_str(), Some("hello, world!"));
    }

    #[test]
    fn test_message_formatted_equal() {
        let mut logentry = LogEntry {
            message: Annotated::new("hello, world!".to_string().into()),
            formatted: Annotated::new("hello, world!".to_string().into()),
            ..LogEntry::default()
        };

        normalize_logentry(&mut logentry, &mut Meta::default());
        assert_eq!(logentry.message.value(), None);
        assert_eq!(logentry.formatted.as_str(), Some("hello, world!"));
    }

    #[test]
    fn test_empty_missing_message() {
        let mut logentry = LogEntry {
            params: Value::U64(0).into(), // Ensure the logentry is not empty
            ..LogEntry::default()
        };
        let mut meta = Meta::default();

        assert_eq!(
            normalize_logentry(&mut logentry, &mut meta),
            Err(ProcessingAction::DeleteValueSoft)
        );
        assert!(meta.has_errors());
    }

    #[test]
    fn test_empty_logentry() {
        let mut logentry = LogEntry::default();
        let mut meta = Meta::default();

        assert_eq!(normalize_logentry(&mut logentry, &mut meta), Ok(()));
        assert!(!meta.has_errors());
    }
}