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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
use std::fmt;

use relay_protocol::{
    Annotated, Empty, Error, ErrorKind, FromValue, IntoValue, Object, SkipSerialization, Value,
};
use serde::{Deserialize, Serialize, Serializer};

use crate::processor::ProcessValue;
use crate::protocol::{RawStacktrace, Stacktrace};

/// Represents a thread id.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Ord, PartialOrd, Hash)]
#[serde(untagged)]
pub enum ThreadId {
    /// Integer representation of the thread id.
    Int(u64),
    /// String representation of the thread id.
    String(String),
}

impl FromValue for ThreadId {
    fn from_value(value: Annotated<Value>) -> Annotated<Self> {
        match value {
            Annotated(Some(Value::String(value)), meta) => {
                Annotated(Some(ThreadId::String(value)), meta)
            }
            Annotated(Some(Value::U64(value)), meta) => Annotated(Some(ThreadId::Int(value)), meta),
            Annotated(Some(Value::I64(value)), meta) => {
                Annotated(Some(ThreadId::Int(value as u64)), meta)
            }
            Annotated(None, meta) => Annotated(None, meta),
            Annotated(Some(value), mut meta) => {
                meta.add_error(Error::expected("a thread id"));
                meta.set_original_value(Some(value));
                Annotated(None, meta)
            }
        }
    }
}

impl IntoValue for ThreadId {
    fn into_value(self) -> Value {
        match self {
            ThreadId::String(value) => Value::String(value),
            ThreadId::Int(value) => Value::U64(value),
        }
    }

    fn serialize_payload<S>(&self, s: S, _behavior: SkipSerialization) -> Result<S::Ok, S::Error>
    where
        Self: Sized,
        S: Serializer,
    {
        match *self {
            ThreadId::String(ref value) => Serialize::serialize(value, s),
            ThreadId::Int(value) => Serialize::serialize(&value, s),
        }
    }
}

impl ProcessValue for ThreadId {}

impl Empty for ThreadId {
    #[inline]
    fn is_empty(&self) -> bool {
        match self {
            ThreadId::Int(_) => false,
            ThreadId::String(string) => string.is_empty(),
        }
    }
}

impl fmt::Display for ThreadId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ThreadId::Int(id) => write!(f, "{}", id),
            ThreadId::String(id) => write!(f, "{}", id),
        }
    }
}

/// Possible lock types responsible for a thread's blocked state
#[derive(Debug, Copy, Clone, Eq, PartialEq, ProcessValue, Empty)]
pub enum LockReasonType {
    /// Thread is Runnable but holding a lock object (generic case).
    Locked = 1,
    /// Thread TimedWaiting in Object.wait() with a timeout.
    Waiting = 2,
    /// Thread TimedWaiting in Thread.sleep().
    Sleeping = 4,
    /// Thread Blocked on a monitor/shared lock.
    Blocked = 8,
    // This enum does not have a `fallback_variant` because we consider it unlikely to be extended. If it is,
    // The error added to `Meta` will tell us to update this enum.
}

impl LockReasonType {
    fn from_android_lock_reason_type(value: u64) -> Option<LockReasonType> {
        Some(match value {
            1 => LockReasonType::Locked,
            2 => LockReasonType::Waiting,
            4 => LockReasonType::Sleeping,
            8 => LockReasonType::Blocked,
            _ => return None,
        })
    }
}

impl FromValue for LockReasonType {
    fn from_value(value: Annotated<Value>) -> Annotated<Self> {
        match value {
            Annotated(Some(Value::U64(val)), mut meta) => {
                match LockReasonType::from_android_lock_reason_type(val) {
                    Some(value) => Annotated(Some(value), meta),
                    None => {
                        meta.add_error(ErrorKind::InvalidData);
                        meta.set_original_value(Some(val));
                        Annotated(None, meta)
                    }
                }
            }
            Annotated(Some(Value::I64(val)), mut meta) => {
                match LockReasonType::from_android_lock_reason_type(val as u64) {
                    Some(value) => Annotated(Some(value), meta),
                    None => {
                        meta.add_error(ErrorKind::InvalidData);
                        meta.set_original_value(Some(val));
                        Annotated(None, meta)
                    }
                }
            }
            Annotated(None, meta) => Annotated(None, meta),
            Annotated(Some(value), mut meta) => {
                meta.add_error(Error::expected("lock reason type"));
                meta.set_original_value(Some(value));
                Annotated(None, meta)
            }
        }
    }
}

impl IntoValue for LockReasonType {
    fn into_value(self) -> Value {
        Value::U64(self as u64)
    }

    fn serialize_payload<S>(&self, s: S, _behavior: SkipSerialization) -> Result<S::Ok, S::Error>
    where
        Self: Sized,
        S: Serializer,
    {
        Serialize::serialize(&(*self as u64), s)
    }
}

/// Represents an instance of a held lock (java monitor object) in a thread.
#[derive(Clone, Debug, PartialEq, Empty, FromValue, IntoValue, ProcessValue)]
pub struct LockReason {
    /// Type of lock on the thread with available options being blocked, waiting, sleeping and locked.
    #[metastructure(field = "type", required = "true")]
    pub ty: Annotated<LockReasonType>,

    /// Address of the java monitor object.
    #[metastructure(skip_serialization = "empty")]
    pub address: Annotated<String>,

    /// Package name of the java monitor object.
    #[metastructure(skip_serialization = "empty")]
    pub package_name: Annotated<String>,

    /// Class name of the java monitor object.
    #[metastructure(skip_serialization = "empty")]
    pub class_name: Annotated<String>,

    /// Thread ID that's holding the lock.
    #[metastructure(skip_serialization = "empty")]
    pub thread_id: Annotated<ThreadId>,

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

/// A process thread of an event.
///
/// The Threads Interface specifies threads that were running at the time an event happened. These threads can also contain stack traces.
///
/// An event may contain one or more threads in an attribute named `threads`.
///
/// The following example illustrates the threads part of the event payload and omits other attributes for simplicity.
///
/// ```json
/// {
///   "threads": {
///     "values": [
///       {
///         "id": "0",
///         "name": "main",
///         "crashed": true,
///         "stacktrace": {}
///       }
///     ]
///   }
/// }
/// ```
#[derive(Clone, Debug, Default, PartialEq, Empty, FromValue, IntoValue, ProcessValue)]
#[metastructure(process_func = "process_thread", value_type = "Thread")]
pub struct Thread {
    /// The ID of the thread. Typically a number or numeric string.
    ///
    /// Needs to be unique among the threads. An exception can set the `thread_id` attribute to cross-reference this thread.
    #[metastructure(max_chars = 256, max_chars_allowance = 20)]
    pub id: Annotated<ThreadId>,

    /// Display name of this thread.
    #[metastructure(max_chars = 1024, max_chars_allowance = 100)]
    pub name: Annotated<String>,

    /// Stack trace containing frames of this exception.
    ///
    /// The thread that crashed with an exception should not have a stack trace, but instead, the `thread_id` attribute should be set on the exception and Sentry will connect the two.
    #[metastructure(skip_serialization = "empty")]
    pub stacktrace: Annotated<Stacktrace>,

    /// Optional unprocessed stack trace.
    #[metastructure(skip_serialization = "empty", omit_from_schema)]
    pub raw_stacktrace: Annotated<RawStacktrace>,

    /// A flag indicating whether the thread crashed. Defaults to `false`.
    pub crashed: Annotated<bool>,

    /// A flag indicating whether the thread was in the foreground. Defaults to `false`.
    pub current: Annotated<bool>,

    /// A flag indicating whether the thread was responsible for rendering the user interface.
    pub main: Annotated<bool>,

    /// Thread state at the time of the crash.
    #[metastructure(skip_serialization = "empty")]
    pub state: Annotated<String>,

    /// Represents a collection of locks (java monitor objects) held by a thread.
    ///
    /// A map of lock object addresses and their respective lock reason/details.
    pub held_locks: Annotated<Object<LockReason>>,

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

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

    use super::*;

    #[test]
    fn test_thread_id() {
        assert_eq!(
            ThreadId::String("testing".into()),
            Annotated::<ThreadId>::from_json("\"testing\"")
                .unwrap()
                .0
                .unwrap()
        );
        assert_eq!(
            ThreadId::String("42".into()),
            Annotated::<ThreadId>::from_json("\"42\"")
                .unwrap()
                .0
                .unwrap()
        );
        assert_eq!(
            ThreadId::Int(42),
            Annotated::<ThreadId>::from_json("42").unwrap().0.unwrap()
        );
    }

    #[test]
    fn test_thread_roundtrip() {
        // stack traces are tested separately
        let json = r#"{
  "id": 42,
  "name": "myname",
  "crashed": true,
  "current": true,
  "main": true,
  "state": "RUNNABLE",
  "other": "value"
}"#;
        let thread = Annotated::new(Thread {
            id: Annotated::new(ThreadId::Int(42)),
            name: Annotated::new("myname".to_string()),
            stacktrace: Annotated::empty(),
            raw_stacktrace: Annotated::empty(),
            crashed: Annotated::new(true),
            current: Annotated::new(true),
            main: Annotated::new(true),
            state: Annotated::new("RUNNABLE".to_string()),
            held_locks: Annotated::empty(),
            other: {
                let mut map = Map::new();
                map.insert(
                    "other".to_string(),
                    Annotated::new(Value::String("value".to_string())),
                );
                map
            },
        });

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

    #[test]
    fn test_thread_default_values() {
        let json = "{}";
        let thread = Annotated::new(Thread::default());

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

    #[test]
    fn test_thread_lock_reason_roundtrip() {
        // stack traces are tested separately
        let input = r#"{
  "id": 42,
  "name": "myname",
  "crashed": true,
  "current": true,
  "main": true,
  "state": "BLOCKED",
  "held_locks": {
    "0x07d7437b": {
      "type": 2,
      "package_name": "io.sentry.samples",
      "class_name": "MainActivity",
      "thread_id": 7
    },
    "0x0d3a2f0a": {
      "type": 1,
      "package_name": "android.database.sqlite",
      "class_name": "SQLiteConnection",
      "thread_id": 2
    }
  },
  "other": "value"
}"#;
        let thread = Annotated::new(Thread {
            id: Annotated::new(ThreadId::Int(42)),
            name: Annotated::new("myname".to_string()),
            stacktrace: Annotated::empty(),
            raw_stacktrace: Annotated::empty(),
            crashed: Annotated::new(true),
            current: Annotated::new(true),
            main: Annotated::new(true),
            state: Annotated::new("BLOCKED".to_string()),
            held_locks: {
                let mut locks = Object::new();
                locks.insert(
                    "0x07d7437b".to_string(),
                    Annotated::new(LockReason {
                        ty: Annotated::new(LockReasonType::Waiting),
                        address: Annotated::empty(),
                        package_name: Annotated::new("io.sentry.samples".to_string()),
                        class_name: Annotated::new("MainActivity".to_string()),
                        thread_id: Annotated::new(ThreadId::Int(7)),
                        other: Default::default(),
                    }),
                );
                locks.insert(
                    "0x0d3a2f0a".to_string(),
                    Annotated::new(LockReason {
                        ty: Annotated::new(LockReasonType::Locked),
                        address: Annotated::empty(),
                        package_name: Annotated::new("android.database.sqlite".to_string()),
                        class_name: Annotated::new("SQLiteConnection".to_string()),
                        thread_id: Annotated::new(ThreadId::Int(2)),
                        other: Default::default(),
                    }),
                );
                Annotated::new(locks)
            },
            other: {
                let mut map = Map::new();
                map.insert(
                    "other".to_string(),
                    Annotated::new(Value::String("value".to_string())),
                );
                map
            },
        });

        assert_eq!(thread, Annotated::from_json(input).unwrap());

        assert_eq!(input, thread.to_json_pretty().unwrap());
    }
}