manasight-parser 0.2.0

MTG Arena log file parser — reads Player.log and emits typed game events
Documentation
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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
//! Connection-closure parsers: TCP and WebSocket close events.
//!
//! Parses two paired `[UnityCrossThreadLogger]` entry types that together
//! describe MTG Arena match-connection teardown:
//!
//! | Marker | Event |
//! |--------|-------|
//! | `Client.TcpConnection.Close` | [`GameEvent::TcpConnectionClose`] |
//! | `GREConnection.HandleWebSocketClosed` | [`GameEvent::WebSocketClosed`] |
//!
//! Both payloads are passed through unchanged as [`serde_json::Value`];
//! the parser does not interpret `status` or `closeType` semantics. The
//! desktop connection-health monitor matches on event name +
//! `closeType`/`status` per ADR-011.
//!
//! # Bare-marker TCP close entries
//!
//! `Client.TcpConnection.Close` is emitted as two consecutive lines on
//! both Windows and macOS — a bare marker (no JSON), then the
//! JSON-carrying line. Bare-marker entries return `None`; the paired
//! JSON line emits the event.
//!
//! `GREConnection.HandleWebSocketClosed` is always emitted with a JSON
//! payload (no bare-marker variant observed in the corpus).
//!
//! Satisfies feature spec `connection-health-indicator.md` **AC-DET-2**
//! and **AC-DET-3**.

use crate::events::{EventMetadata, GameEvent, TcpConnectionCloseEvent, WebSocketClosedEvent};
use crate::log::entry::{EntryHeader, LogEntry};
use crate::parsers::api_common;

/// Marker text that identifies a `Client.TcpConnection.Close` entry.
const TCP_CONNECTION_CLOSE_MARKER: &str = "Client.TcpConnection.Close";

/// Marker text that identifies a `GREConnection.HandleWebSocketClosed`
/// entry.
const WEBSOCKET_CLOSED_MARKER: &str = "GREConnection.HandleWebSocketClosed";

/// Attempts to parse a [`LogEntry`] as a TCP or WebSocket connection
/// close event.
///
/// Forks on marker presence in the entry body:
///
/// - `Client.TcpConnection.Close` → [`GameEvent::TcpConnectionClose`]
///   when a JSON payload is present; `None` for bare-marker entries.
/// - `GREConnection.HandleWebSocketClosed` → [`GameEvent::WebSocketClosed`]
///   (always carries JSON in practice).
///
/// Returns `None` for any other body and for non-`UnityCrossThreadLogger`
/// headers.
///
/// The `timestamp` is `None` when the log entry header did not contain a
/// parseable timestamp. It is passed through to [`EventMetadata`] so
/// downstream consumers can distinguish real vs missing timestamps.
pub fn try_parse(
    entry: &LogEntry,
    timestamp: Option<chrono::DateTime<chrono::Utc>>,
) -> Option<GameEvent> {
    if entry.header != EntryHeader::UnityCrossThreadLogger {
        return None;
    }

    if entry.body.contains(TCP_CONNECTION_CLOSE_MARKER) {
        return try_parse_tcp_close(entry, timestamp);
    }

    if entry.body.contains(WEBSOCKET_CLOSED_MARKER) {
        return try_parse_websocket_closed(entry, timestamp);
    }

    None
}

/// Parses a `Client.TcpConnection.Close` entry carrying a JSON payload.
///
/// Returns `None` for bare-marker entries (no JSON on the line) — these
/// are emitted as a preceding duplicate of the JSON-carrying line on
/// both Windows and macOS.
fn try_parse_tcp_close(
    entry: &LogEntry,
    timestamp: Option<chrono::DateTime<chrono::Utc>>,
) -> Option<GameEvent> {
    let json_str = api_common::extract_json_from_body(&entry.body)?;
    let payload: serde_json::Value = match serde_json::from_str(json_str) {
        Ok(v) => v,
        Err(e) => {
            ::log::warn!("Client.TcpConnection.Close: malformed JSON payload: {e}");
            return None;
        }
    };

    let metadata = EventMetadata::new(timestamp, entry.body.as_bytes().to_vec());
    Some(GameEvent::TcpConnectionClose(TcpConnectionCloseEvent::new(
        metadata, payload,
    )))
}

/// Parses a `GREConnection.HandleWebSocketClosed` entry.
///
/// The payload always includes `closeType`, `reason`, and a nested
/// `tcpConn` object. The parser preserves the full parsed JSON.
fn try_parse_websocket_closed(
    entry: &LogEntry,
    timestamp: Option<chrono::DateTime<chrono::Utc>>,
) -> Option<GameEvent> {
    let json_str = api_common::extract_json_from_body(&entry.body)?;
    let payload: serde_json::Value = match serde_json::from_str(json_str) {
        Ok(v) => v,
        Err(e) => {
            ::log::warn!("GREConnection.HandleWebSocketClosed: malformed JSON payload: {e}");
            return None;
        }
    };

    let metadata = EventMetadata::new(timestamp, entry.body.as_bytes().to_vec());
    Some(GameEvent::WebSocketClosed(WebSocketClosedEvent::new(
        metadata, payload,
    )))
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parsers::test_helpers::{
        tcp_connection_close_payload, test_timestamp, unity_entry, websocket_closed_payload,
    };

    /// Build a `[UnityCrossThreadLogger]Client.TcpConnection.Close {...}`
    /// entry body from a raw JSON string.
    fn tcp_close_body(json: &str) -> String {
        format!("[UnityCrossThreadLogger]Client.TcpConnection.Close {json}")
    }

    /// Build a `[UnityCrossThreadLogger]GREConnection.HandleWebSocketClosed {...}`
    /// entry body from a raw JSON string.
    fn websocket_closed_body(json: &str) -> String {
        format!("[UnityCrossThreadLogger]GREConnection.HandleWebSocketClosed {json}")
    }

    // -- Client.TcpConnection.Close: normal closes ---------------------------

    mod tcp_close_normal {
        use super::*;

        #[test]
        fn test_status_7_closed_by_remote_end() {
            let body =
                tcp_close_body(r#"{"status":7,"reason":"Closed by remote end","connectionId":42}"#);
            let entry = unity_entry(&body);
            let result = try_parse(&entry, Some(test_timestamp()));

            assert!(result.is_some());
            let event = result.as_ref().unwrap_or_else(|| unreachable!());
            assert!(
                matches!(event, GameEvent::TcpConnectionClose(_)),
                "expected TcpConnectionClose, got {event:?}"
            );
            let payload = tcp_connection_close_payload(event);
            assert_eq!(payload["status"], 7);
            assert_eq!(payload["reason"], "Closed by remote end");
            assert_eq!(payload["connectionId"], 42);
        }

        #[test]
        fn test_status_2_cleanup_before_reconnecting() {
            let body = tcp_close_body(r#"{"status":2,"reason":"Cleanup before reconnecting"}"#);
            let entry = unity_entry(&body);
            let result = try_parse(&entry, Some(test_timestamp()));

            assert!(result.is_some());
            let event = result.as_ref().unwrap_or_else(|| unreachable!());
            let payload = tcp_connection_close_payload(event);
            assert_eq!(payload["status"], 2);
            assert_eq!(payload["reason"], "Cleanup before reconnecting");
        }

        #[test]
        fn test_status_2_match_manager_reset() {
            let body = tcp_close_body(r#"{"status":2,"reason":"MatchManager.Reset"}"#);
            let entry = unity_entry(&body);
            let result = try_parse(&entry, Some(test_timestamp()));

            assert!(result.is_some());
            let event = result.as_ref().unwrap_or_else(|| unreachable!());
            let payload = tcp_connection_close_payload(event);
            assert_eq!(payload["status"], 2);
            assert_eq!(payload["reason"], "MatchManager.Reset");
        }

        #[test]
        fn test_status_2_on_destroy() {
            let body = tcp_close_body(r#"{"status":2,"reason":"OnDestroy"}"#);
            let entry = unity_entry(&body);
            let result = try_parse(&entry, Some(test_timestamp()));

            assert!(result.is_some());
            let event = result.as_ref().unwrap_or_else(|| unreachable!());
            let payload = tcp_connection_close_payload(event);
            assert_eq!(payload["status"], 2);
            assert_eq!(payload["reason"], "OnDestroy");
        }

        #[test]
        fn test_status_2_match_manager_dispose() {
            let body = tcp_close_body(r#"{"status":2,"reason":"MatchManager.Dispose"}"#);
            let entry = unity_entry(&body);
            let result = try_parse(&entry, Some(test_timestamp()));

            assert!(result.is_some());
            let event = result.as_ref().unwrap_or_else(|| unreachable!());
            let payload = tcp_connection_close_payload(event);
            assert_eq!(payload["status"], 2);
            assert_eq!(payload["reason"], "MatchManager.Dispose");
        }

        #[test]
        fn test_status_5_inactivity_timeout() {
            let body = tcp_close_body(r#"{"status":5,"reason":"Inactivity timeout"}"#);
            let entry = unity_entry(&body);
            let result = try_parse(&entry, Some(test_timestamp()));

            assert!(result.is_some());
            let event = result.as_ref().unwrap_or_else(|| unreachable!());
            let payload = tcp_connection_close_payload(event);
            assert_eq!(payload["status"], 5);
            assert_eq!(payload["reason"], "Inactivity timeout");
        }
    }

    // -- Client.TcpConnection.Close: abnormal closes -------------------------

    mod tcp_close_abnormal {
        use super::*;

        #[test]
        fn test_status_1_with_inner_exception_native_error_code_10054_windows() {
            let body = tcp_close_body(
                r#"{
                    "status":1,
                    "reason":"",
                    "function":"ReadAsync",
                    "description":"An established connection was aborted by the software in your host machine",
                    "exception":{
                        "Message":"Unable to read data from the transport connection",
                        "InnerException":{
                            "Message":"An established connection was aborted",
                            "NativeErrorCode":10054,
                            "SocketErrorCode":"ConnectionAborted"
                        }
                    }
                }"#,
            );
            let entry = unity_entry(&body);
            let result = try_parse(&entry, Some(test_timestamp()));

            assert!(result.is_some());
            let event = result.as_ref().unwrap_or_else(|| unreachable!());
            let payload = tcp_connection_close_payload(event);
            assert_eq!(payload["status"], 1);
            assert_eq!(payload["function"], "ReadAsync");
            assert_eq!(
                payload["exception"]["InnerException"]["NativeErrorCode"],
                10054
            );
            assert_eq!(
                payload["exception"]["InnerException"]["SocketErrorCode"],
                "ConnectionAborted"
            );
        }

        #[test]
        fn test_status_1_with_inner_exception_native_error_code_10060_macos() {
            let body = tcp_close_body(
                r#"{
                    "status":1,
                    "reason":"",
                    "function":"ReadAsync",
                    "description":"Connection timed out",
                    "exception":{
                        "Message":"Unable to read data",
                        "InnerException":{
                            "Message":"Operation timed out",
                            "NativeErrorCode":10060,
                            "SocketErrorCode":"TimedOut"
                        }
                    }
                }"#,
            );
            let entry = unity_entry(&body);
            let result = try_parse(&entry, Some(test_timestamp()));

            assert!(result.is_some());
            let event = result.as_ref().unwrap_or_else(|| unreachable!());
            let payload = tcp_connection_close_payload(event);
            assert_eq!(payload["status"], 1);
            assert_eq!(
                payload["exception"]["InnerException"]["NativeErrorCode"],
                10060
            );
            assert_eq!(
                payload["exception"]["InnerException"]["SocketErrorCode"],
                "TimedOut"
            );
        }

        #[test]
        fn test_status_9_connection_timed_out() {
            let body = tcp_close_body(
                r#"{
                    "status":9,
                    "reason":"Connection timed out",
                    "function":"WriteAsync"
                }"#,
            );
            let entry = unity_entry(&body);
            let result = try_parse(&entry, Some(test_timestamp()));

            assert!(result.is_some());
            let event = result.as_ref().unwrap_or_else(|| unreachable!());
            let payload = tcp_connection_close_payload(event);
            assert_eq!(payload["status"], 9);
            assert_eq!(payload["reason"], "Connection timed out");
            assert_eq!(payload["function"], "WriteAsync");
        }

        #[test]
        fn test_status_9_firewall_permissions_with_embedded_null_bytes() {
            // Real corpus: the reason string for this firewall/permissions
            // error contains embedded `\u0000` characters. JSON string
            // escape `\u0000` decodes to a NUL byte in the resulting Rust
            // String — verify it round-trips through serde_json without
            // truncation or replacement.
            let body = tcp_close_body(
                r#"{
                    "status":9,
                    "reason":"An attempt was made to access a socket in a way forbidden by its access permissions\u0000.\u0000",
                    "function":"ConnectAsync"
                }"#,
            );
            let entry = unity_entry(&body);
            let result = try_parse(&entry, Some(test_timestamp()));

            assert!(result.is_some());
            let event = result.as_ref().unwrap_or_else(|| unreachable!());
            let payload = tcp_connection_close_payload(event);
            assert_eq!(payload["status"], 9);

            let reason = payload["reason"].as_str().unwrap_or("");
            assert!(
                reason.starts_with("An attempt was made to access a socket"),
                "reason prefix preserved, got: {reason:?}"
            );
            // Embedded NUL bytes must survive the round-trip.
            assert!(
                reason.contains('\u{0000}'),
                "reason must preserve embedded NUL bytes, got: {reason:?}"
            );
            assert_eq!(
                reason.matches('\u{0000}').count(),
                2,
                "reason must preserve both embedded NUL bytes, got: {reason:?}"
            );
        }
    }

    // -- Client.TcpConnection.Close: bare marker -----------------------------

    mod tcp_close_bare_marker {
        use super::*;

        #[test]
        fn test_bare_marker_no_json_returns_none() {
            // Observed in corpus on both Windows and macOS: a preceding
            // bare-marker line appears before every JSON-carrying entry.
            let body = "[UnityCrossThreadLogger]Client.TcpConnection.Close";
            let entry = unity_entry(body);
            assert!(try_parse(&entry, Some(test_timestamp())).is_none());
        }

        #[test]
        fn test_bare_marker_with_trailing_whitespace_returns_none() {
            let body = "[UnityCrossThreadLogger]Client.TcpConnection.Close   ";
            let entry = unity_entry(body);
            assert!(try_parse(&entry, Some(test_timestamp())).is_none());
        }

        #[test]
        fn test_bare_marker_followed_by_newline_returns_none() {
            // Just the marker line, no JSON payload anywhere in the body.
            let body = "[UnityCrossThreadLogger]Client.TcpConnection.Close\n";
            let entry = unity_entry(body);
            assert!(try_parse(&entry, Some(test_timestamp())).is_none());
        }
    }

    // -- Client.TcpConnection.Close: numeric types round-trip ----------------

    mod tcp_close_numeric_types {
        use super::*;

        #[test]
        fn test_status_and_native_error_code_stay_numeric() {
            let body = tcp_close_body(
                r#"{"status":1,"exception":{"InnerException":{"NativeErrorCode":10054}}}"#,
            );
            let entry = unity_entry(&body);
            let result = try_parse(&entry, Some(test_timestamp()));

            assert!(result.is_some());
            let event = result.as_ref().unwrap_or_else(|| unreachable!());
            let payload = tcp_connection_close_payload(event);

            // Numeric values must not be coerced to strings.
            assert!(
                payload["status"].is_number(),
                "status must remain numeric, got {:?}",
                payload["status"]
            );
            assert!(
                payload["exception"]["InnerException"]["NativeErrorCode"].is_number(),
                "NativeErrorCode must remain numeric, got {:?}",
                payload["exception"]["InnerException"]["NativeErrorCode"]
            );
        }
    }

    // -- GREConnection.HandleWebSocketClosed ---------------------------------

    mod websocket_closed {
        use super::*;

        /// Build a WebSocket closed JSON payload with the given
        /// `closeType`, `reason`, and a realistic nested `tcpConn` object.
        fn websocket_closed_payload_json(close_type: u32, reason: &str) -> String {
            format!(
                r#"{{
                    "closeType":{close_type},
                    "reason":"{reason}",
                    "tcpConn":{{
                        "host":"mtgarena-prod.example.com",
                        "port":443,
                        "rtTicksRollingAvg":123.45,
                        "rtTicksSamples":[100,110,125,140,130],
                        "lastLocalActivity":637123456789,
                        "lastRemoteActivity":637123456999,
                        "lastRemotePing":637123456800,
                        "inactivityTimeoutMs":30000
                    }}
                }}"#
            )
        }

        #[test]
        fn test_close_type_1_abnormal() {
            let body = websocket_closed_body(&websocket_closed_payload_json(1, "Abnormal closure"));
            let entry = unity_entry(&body);
            let result = try_parse(&entry, Some(test_timestamp()));

            assert!(result.is_some());
            let event = result.as_ref().unwrap_or_else(|| unreachable!());
            assert!(
                matches!(event, GameEvent::WebSocketClosed(_)),
                "expected WebSocketClosed, got {event:?}"
            );
            let payload = websocket_closed_payload(event);
            assert_eq!(payload["closeType"], 1);
            assert_eq!(payload["reason"], "Abnormal closure");
        }

        #[test]
        fn test_close_type_7_closed_by_remote() {
            let body = websocket_closed_body(&websocket_closed_payload_json(7, "Closed by remote"));
            let entry = unity_entry(&body);
            let result = try_parse(&entry, Some(test_timestamp()));

            assert!(result.is_some());
            let event = result.as_ref().unwrap_or_else(|| unreachable!());
            let payload = websocket_closed_payload(event);
            assert_eq!(payload["closeType"], 7);
            assert_eq!(payload["reason"], "Closed by remote");
        }

        #[test]
        fn test_close_type_9_timeout() {
            let body =
                websocket_closed_body(&websocket_closed_payload_json(9, "Connection timed out"));
            let entry = unity_entry(&body);
            let result = try_parse(&entry, Some(test_timestamp()));

            assert!(result.is_some());
            let event = result.as_ref().unwrap_or_else(|| unreachable!());
            let payload = websocket_closed_payload(event);
            assert_eq!(payload["closeType"], 9);
            assert_eq!(payload["reason"], "Connection timed out");
        }

        #[test]
        fn test_payload_preserves_nested_tcp_conn_object() {
            let body = websocket_closed_body(&websocket_closed_payload_json(1, "Abnormal"));
            let entry = unity_entry(&body);
            let result = try_parse(&entry, Some(test_timestamp()));

            assert!(result.is_some());
            let event = result.as_ref().unwrap_or_else(|| unreachable!());
            let payload = websocket_closed_payload(event);

            let tcp = &payload["tcpConn"];
            assert!(tcp.is_object(), "tcpConn must be preserved as object");
            assert_eq!(tcp["host"], "mtgarena-prod.example.com");
            assert_eq!(tcp["port"], 443);
            assert_eq!(tcp["inactivityTimeoutMs"], 30000);
        }

        #[test]
        fn test_tcp_conn_numeric_types_round_trip() {
            let body = websocket_closed_body(&websocket_closed_payload_json(7, "Closed"));
            let entry = unity_entry(&body);
            let result = try_parse(&entry, Some(test_timestamp()));

            assert!(result.is_some());
            let event = result.as_ref().unwrap_or_else(|| unreachable!());
            let payload = websocket_closed_payload(event);

            let tcp = &payload["tcpConn"];

            // Float must remain numeric.
            assert!(
                tcp["rtTicksRollingAvg"].is_number(),
                "rtTicksRollingAvg must be numeric, got {:?}",
                tcp["rtTicksRollingAvg"]
            );
            assert_eq!(tcp["rtTicksRollingAvg"].as_f64(), Some(123.45));

            // Array of numbers — each element must remain numeric.
            assert!(
                tcp["rtTicksSamples"].is_array(),
                "rtTicksSamples must be an array, got {:?}",
                tcp["rtTicksSamples"]
            );
            let samples = tcp["rtTicksSamples"].as_array().unwrap_or_else(|| {
                // Safe: is_array() asserted above.
                unreachable!()
            });
            assert_eq!(samples.len(), 5);
            for sample in samples {
                assert!(
                    sample.is_number(),
                    "each rtTicksSamples entry must be numeric, got {sample:?}"
                );
            }
            assert_eq!(samples[0].as_u64(), Some(100));
            assert_eq!(samples[4].as_u64(), Some(130));
        }
    }

    // -- Non-matching entries -----------------------------------------------

    mod non_matching {
        use super::*;

        #[test]
        fn test_plain_gre_message_returns_none() {
            let body =
                "[UnityCrossThreadLogger]2/25/2026 12:00:00 PM greToClientEvent\n{\"data\":1}";
            let entry = unity_entry(body);
            assert!(try_parse(&entry, Some(test_timestamp())).is_none());
        }

        #[test]
        fn test_front_door_connection_close_returns_none() {
            // Session parser claims this marker; the connection_close parser
            // must NOT also match. Corpus confirms FrontDoorConnection.Close
            // and Client.TcpConnection.Close never appear on the same line.
            let body = "[UnityCrossThreadLogger]FrontDoorConnection.Close";
            let entry = unity_entry(body);
            assert!(try_parse(&entry, Some(test_timestamp())).is_none());
        }

        #[test]
        fn test_similar_but_different_marker_returns_none() {
            let body = "[UnityCrossThreadLogger]Client.TcpConnection.Open {\"status\":0}";
            let entry = unity_entry(body);
            assert!(try_parse(&entry, Some(test_timestamp())).is_none());
        }

        #[test]
        fn test_empty_unity_body_returns_none() {
            let body = "[UnityCrossThreadLogger]";
            let entry = unity_entry(body);
            assert!(try_parse(&entry, Some(test_timestamp())).is_none());
        }

        #[test]
        fn test_non_unity_cross_thread_logger_header_returns_none() {
            // Correct marker text but wrong header — must not parse.
            let entry = LogEntry {
                header: EntryHeader::ClientGre,
                body: "[Client GRE]Client.TcpConnection.Close {\"status\":7,\"reason\":\"Closed by remote end\"}"
                    .to_owned(),
            };
            assert!(try_parse(&entry, Some(test_timestamp())).is_none());
        }

        #[test]
        fn test_metadata_header_returns_none() {
            let entry = LogEntry {
                header: EntryHeader::Metadata,
                body: "Client.TcpConnection.Close {\"status\":7}".to_owned(),
            };
            assert!(try_parse(&entry, Some(test_timestamp())).is_none());
        }

        #[test]
        fn test_connection_manager_header_returns_none() {
            let entry = LogEntry {
                header: EntryHeader::ConnectionManager,
                body: "[ConnectionManager] GREConnection.HandleWebSocketClosed {\"closeType\":1}"
                    .to_owned(),
            };
            assert!(try_parse(&entry, Some(test_timestamp())).is_none());
        }

        #[test]
        fn test_tcp_close_malformed_json_returns_none() {
            let body =
                "[UnityCrossThreadLogger]Client.TcpConnection.Close {\"status\":7,\"reason\":";
            let entry = unity_entry(body);
            assert!(try_parse(&entry, Some(test_timestamp())).is_none());
        }

        #[test]
        fn test_websocket_closed_malformed_json_returns_none() {
            let body =
                "[UnityCrossThreadLogger]GREConnection.HandleWebSocketClosed {\"closeType\":";
            let entry = unity_entry(body);
            assert!(try_parse(&entry, Some(test_timestamp())).is_none());
        }
    }

    // -- Metadata preservation ----------------------------------------------

    mod metadata {
        use super::*;

        #[test]
        fn test_tcp_close_preserves_raw_bytes() {
            let body = tcp_close_body(r#"{"status":7,"reason":"Closed by remote end"}"#);
            let entry = unity_entry(&body);
            let result = try_parse(&entry, Some(test_timestamp()));

            assert!(result.is_some());
            let event = result.as_ref().unwrap_or_else(|| unreachable!());
            assert_eq!(event.metadata().raw_bytes(), body.as_bytes());
        }

        #[test]
        fn test_websocket_closed_preserves_raw_bytes() {
            let body = websocket_closed_body(
                r#"{"closeType":7,"reason":"Closed","tcpConn":{"host":"h"}}"#,
            );
            let entry = unity_entry(&body);
            let result = try_parse(&entry, Some(test_timestamp()));

            assert!(result.is_some());
            let event = result.as_ref().unwrap_or_else(|| unreachable!());
            assert_eq!(event.metadata().raw_bytes(), body.as_bytes());
        }

        #[test]
        fn test_tcp_close_preserves_timestamp() {
            let body = tcp_close_body(r#"{"status":7}"#);
            let entry = unity_entry(&body);
            let ts = Some(test_timestamp());
            let result = try_parse(&entry, ts);

            assert!(result.is_some());
            let event = result.as_ref().unwrap_or_else(|| unreachable!());
            assert_eq!(event.metadata().timestamp(), ts);
        }

        #[test]
        fn test_tcp_close_passes_through_none_timestamp() {
            let body = tcp_close_body(r#"{"status":7}"#);
            let entry = unity_entry(&body);
            let result = try_parse(&entry, None);

            assert!(result.is_some());
            let event = result.as_ref().unwrap_or_else(|| unreachable!());
            assert!(event.metadata().timestamp().is_none());
        }

        #[test]
        fn test_websocket_closed_passes_through_none_timestamp() {
            let body = websocket_closed_body(r#"{"closeType":7,"reason":"Closed","tcpConn":{}}"#);
            let entry = unity_entry(&body);
            let result = try_parse(&entry, None);

            assert!(result.is_some());
            let event = result.as_ref().unwrap_or_else(|| unreachable!());
            assert!(event.metadata().timestamp().is_none());
        }
    }
}