relay_event_schema/protocol/
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
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
use relay_protocol::{Annotated, Empty, Error, FromValue, IntoValue, Meta, Object, Value};

use crate::processor::ProcessValue;
use crate::protocol::JsonLenientString;

/// A log entry message.
///
/// A log message is similar to the `message` attribute on the event itself but
/// can additionally hold optional parameters.
///
/// ```json
/// {
///   "logentry": {
///     "message": "My raw message with interpreted strings like %s",
///     "params": ["this"]
///   }
/// }
/// ```
///
/// ```json
/// {
///   "logentry": {
///     "message": "My raw message with interpreted strings like {foo}",
///     "params": {"foo": "this"}
///   }
/// }
/// ```
#[derive(Clone, Debug, Default, PartialEq, Empty, IntoValue, ProcessValue)]
#[metastructure(process_func = "process_logentry", value_type = "LogEntry")]
pub struct LogEntry {
    /// The log message with parameter placeholders.
    ///
    /// This attribute is primarily used for grouping related events together into issues.
    /// Therefore this really should just be a string template, i.e. `Sending %d requests` instead
    /// of `Sending 9999 requests`. The latter is much better at home in `formatted`.
    ///
    /// It must not exceed 8192 characters. Longer messages will be truncated.
    #[metastructure(max_chars = 8192, max_chars_allowance = 200)]
    pub message: Annotated<Message>,

    /// The formatted message. If `message` and `params` are given, Sentry
    /// will attempt to backfill `formatted` if empty.
    ///
    /// It must not exceed 8192 characters. Longer messages will be truncated.
    #[metastructure(max_chars = 8192, max_chars_allowance = 200, pii = "true")]
    pub formatted: Annotated<Message>,

    /// Parameters to be interpolated into the log message. This can be an array of positional
    /// parameters as well as a mapping of named arguments to their values.
    #[metastructure(max_depth = 5, max_bytes = 2048, pii = "true")]
    pub params: Annotated<Value>,

    /// Additional arbitrary fields for forwards compatibility.
    #[metastructure(additional_properties, pii = "true")]
    pub other: Object<Value>,
}

impl From<String> for LogEntry {
    fn from(formatted_msg: String) -> Self {
        LogEntry {
            formatted: Annotated::new(formatted_msg.into()),
            ..Self::default()
        }
    }
}

#[derive(Clone, Debug, Default, PartialEq, Empty, FromValue, IntoValue, ProcessValue)]
#[metastructure(value_type = "Message", value_type = "String")]
pub struct Message(String);

impl From<String> for Message {
    fn from(msg: String) -> Message {
        Message(msg)
    }
}

impl AsRef<str> for Message {
    fn as_ref(&self) -> &str {
        self.0.as_ref()
    }
}

impl FromValue for LogEntry {
    fn from_value(value: Annotated<Value>) -> Annotated<Self> {
        // raw 'message' is coerced to the Message interface, as its used for pure index of
        // searchable strings. If both a raw 'message' and a Message interface exist, try and
        // add the former as the 'formatted' attribute of the latter.
        // See GH-3248
        match value {
            x @ Annotated(Some(Value::Object(_)), _) => {
                #[derive(Debug, FromValue)]
                struct Helper {
                    message: Annotated<String>,
                    formatted: Annotated<String>,
                    params: Annotated<Value>,
                    #[metastructure(additional_properties)]
                    other: Object<Value>,
                }

                Helper::from_value(x).map_value(|helper| {
                    let params = match helper.params {
                        a @ Annotated(Some(Value::Object(_)), _) => a,
                        a @ Annotated(Some(Value::Array(_)), _) => a,
                        a @ Annotated(None, _) => a,
                        Annotated(Some(value), _) => Annotated::from_error(
                            Error::expected("message parameters"),
                            Some(value),
                        ),
                    };

                    LogEntry {
                        message: helper.message.map_value(Message),
                        formatted: helper.formatted.map_value(Message),
                        params,
                        other: helper.other,
                    }
                })
            }
            Annotated(None, meta) => Annotated(None, meta),
            // The next two cases handle the legacy top-level `message` attribute, which was sent as
            // literal string, false (which should be ignored) or even as deep JSON object. Sentry
            // historically JSONified this field.
            Annotated(Some(Value::Bool(false)), _) => Annotated(None, Meta::default()),
            x => Annotated::new(LogEntry {
                formatted: JsonLenientString::from_value(x)
                    .map_value(JsonLenientString::into_inner)
                    .map_value(Message),
                ..Default::default()
            }),
        }
    }
}

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

    use super::*;

    #[test]
    fn test_logentry_roundtrip() {
        let json = r#"{
  "message": "Hello, %s %s!",
  "params": [
    "World",
    1
  ],
  "other": "value"
}"#;

        let entry = Annotated::new(LogEntry {
            message: Annotated::new("Hello, %s %s!".to_string().into()),
            formatted: Annotated::empty(),
            params: Annotated::new(Value::Array(vec![
                Annotated::new(Value::String("World".to_string())),
                Annotated::new(Value::I64(1)),
            ])),
            other: {
                let mut map = Object::new();
                map.insert(
                    "other".to_string(),
                    Annotated::new(Value::String("value".to_string())),
                );
                map
            },
        });

        assert_eq!(entry, Annotated::from_json(json).unwrap());
        assert_eq!(json, entry.to_json_pretty().unwrap());
    }

    #[test]
    fn test_logentry_from_message() {
        let input = r#""hi""#;
        let output = r#"{
  "formatted": "hi"
}"#;

        let entry = Annotated::new(LogEntry {
            formatted: Annotated::new("hi".to_string().into()),
            ..Default::default()
        });

        assert_eq!(entry, Annotated::from_json(input).unwrap());
        assert_eq!(output, entry.to_json_pretty().unwrap());
    }

    #[test]
    fn test_logentry_empty_params() {
        let input = r#"{"params":[]}"#;
        let entry = Annotated::new(LogEntry {
            params: Annotated::new(Value::Array(vec![])),
            ..Default::default()
        });

        assert_eq!(entry, Annotated::from_json(input).unwrap());
        assert_eq!(input, entry.to_json().unwrap());
    }

    #[test]
    fn test_logentry_named_params() {
        let json = r#"{
  "message": "Hello, %s!",
  "params": {
    "name": "World"
  }
}"#;

        let entry = Annotated::new(LogEntry {
            message: Annotated::new("Hello, %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()
        });

        assert_eq!(entry, Annotated::from_json(json).unwrap());
        assert_eq!(json, entry.to_json_pretty().unwrap());
    }

    #[test]
    fn test_logentry_invalid_params() {
        let json = r#"{
  "message": "Hello, %s!",
  "params": 42
}"#;

        let entry = Annotated::new(LogEntry {
            message: Annotated::new("Hello, %s!".to_string().into()),
            params: Annotated::from_error(
                Error::expected("message parameters"),
                Some(Value::I64(42)),
            ),
            ..LogEntry::default()
        });

        assert_eq!(entry, Annotated::from_json(json).unwrap());
    }
}