freeswitch-types 1.4.0

FreeSWITCH ESL protocol types: channel state, events, headers, commands, and variables
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
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
//! ESL event types and structures

mod event_type;
mod format;
mod subscription;

pub use event_type::{EslEventType, ParseEventTypeError};
pub use format::{EventFormat, ParseEventFormatError};
pub use subscription::{EventSubscription, EventSubscriptionError};

use crate::headers::{case_alias_key, normalize_header_key, EventHeader};
use crate::lookup::HeaderLookup;
use crate::lossy_values::LossyValues;
use crate::variables::{EslArray, EslArrayError};
use indexmap::IndexMap;
use percent_encoding::{percent_encode, NON_ALPHANUMERIC};
use std::fmt;

wire_enum! {
    /// Event priority levels matching FreeSWITCH `esl_priority_t`
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
    pub enum EslEventPriority {
        /// Default priority.
        Normal => "NORMAL",
        /// Lower than normal.
        Low => "LOW",
        /// Higher than normal.
        High => "HIGH",
    }
    error ParsePriorityError("priority");
    tests: esl_event_priority_wire_tests;
}

/// ESL Event structure containing headers and optional body
#[derive(Debug, Clone, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct EslEvent {
    headers: IndexMap<String, String>,
    /// Alias map from original wire key to normalized key, populated only
    /// when the original differs from its normalized form (mixed-case
    /// CODEC events, variant-cased log headers). Lets `header_str` resolve
    /// non-canonical casing without allocating on every lookup.
    ///
    /// Derived from `headers`. Marked `#[serde(skip)]` — serde round trips
    /// through `set_header()` during deserialization, which rebuilds this
    /// map from the canonical keys. See the `Deserialize` impl below and
    /// the `original_keys_rebuilt_after_serde_roundtrip` test.
    #[cfg_attr(feature = "serde", serde(skip))]
    original_keys: IndexMap<String, String>,
    body: Option<String>,
    /// Exact wire bytes of a body that was not valid UTF-8; `body` then
    /// holds the U+FFFD-substituted string. `None` in the normal case.
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    raw_body: Option<Vec<u8>>,
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "LossyValues::is_empty")
    )]
    lossy_values: LossyValues,
}

impl EslEvent {
    /// Create a new empty event
    pub fn new() -> Self {
        Self {
            headers: IndexMap::new(),
            original_keys: IndexMap::new(),
            body: None,
            raw_body: None,
            lossy_values: LossyValues::default(),
        }
    }

    /// Create event with the `Event-Name` header set to the given type's
    /// wire name. The event type is derived lazily from this header on
    /// every [`event_type()`](Self::event_type) call — there is no
    /// separate `event_type` field.
    pub fn with_type(event_type: EslEventType) -> Self {
        let mut event = Self::new();
        event.set_header(EventHeader::EventName.as_str(), event_type.as_str());
        event
    }

    /// Parsed event type, derived from the `Event-Name` header.
    ///
    /// Returns `None` if the header is missing or carries a value that
    /// is not a recognized [`EslEventType`] variant. Single source of
    /// truth: the header. Mutating `Event-Name` via `set_header` will
    /// be reflected on the next call.
    pub fn event_type(&self) -> Option<EslEventType> {
        self.header(EventHeader::EventName)
            .and_then(EslEventType::parse_event_type)
    }

    /// Look up a header by its [`EventHeader`] enum variant (case-sensitive).
    ///
    /// For headers not covered by `EventHeader`, use [`header_str()`](Self::header_str).
    pub fn header(&self, name: EventHeader) -> Option<&str> {
        self.headers
            .get(name.as_str())
            .map(|s| s.as_str())
    }

    /// Look up a header by name, trying the canonical key first then falling
    /// back through the alias map for non-canonical lookups.
    ///
    /// Use [`header()`](Self::header) with an [`EventHeader`] variant for known
    /// headers. This method is for headers not (yet) covered by the enum,
    /// such as custom `X-` headers or FreeSWITCH headers added after this
    /// library was published.
    pub fn header_str(&self, name: &str) -> Option<&str> {
        self.headers
            .get(name)
            .or_else(|| {
                self.original_keys
                    .get(name)
                    .and_then(|normalized| {
                        self.headers
                            .get(normalized)
                    })
            })
            .map(|s| s.as_str())
    }

    /// Look up a channel variable by its bare name.
    ///
    /// Equivalent to [`variable()`](Self::variable) but matches the
    /// [`HeaderLookup`] trait signature.
    pub fn variable_str(&self, name: &str) -> Option<&str> {
        let key = format!("variable_{}", name);
        self.header_str(&key)
    }

    /// All headers as a map.
    pub fn headers(&self) -> &IndexMap<String, String> {
        &self.headers
    }

    /// Set or overwrite a header, normalizing the key.
    pub fn set_header(&mut self, name: impl Into<String>, value: impl Into<String>) {
        let original = name.into();
        let normalized = normalize_header_key(&original);
        if case_alias_key(&original).is_some() && original != normalized {
            self.original_keys
                .insert(original, normalized.clone());
        }
        self.headers
            .insert(normalized, value.into());
    }

    /// Remove a header, returning its value if it existed.
    ///
    /// Accepts both canonical and original (non-normalized) key names.
    pub fn remove_header(&mut self, name: impl AsRef<str>) -> Option<String> {
        let name = name.as_ref();
        if let Some(value) = self
            .headers
            .shift_remove(name)
        {
            return Some(value);
        }
        if let Some(normalized) = self
            .original_keys
            .shift_remove(name)
        {
            return self
                .headers
                .shift_remove(&normalized);
        }
        None
    }

    /// Event body (the content after the blank line in plain-text events).
    pub fn body(&self) -> Option<&str> {
        self.body
            .as_deref()
    }

    /// Set the event body.
    pub fn set_body(&mut self, body: impl Into<String>) {
        self.body = Some(body.into());
    }

    /// Exact wire bytes of the event body when it was not valid UTF-8.
    ///
    /// `Some` is the lossy signal: [`body()`](Self::body) then holds the
    /// U+FFFD-substituted string and these are the original payload bytes
    /// (e.g. a Latin-1 SMS body), so the app can re-decode or audit them.
    /// Only populated for plain and log events — the JSON/XML formats
    /// cannot map wire bytes back to the decoded body. `None` in the
    /// normal case.
    pub fn raw_body(&self) -> Option<&[u8]> {
        self.raw_body
            .as_deref()
    }

    /// Set the raw body bytes.
    ///
    /// Used internally by the ESL parser; consumers don't call this directly.
    #[doc(hidden)]
    pub fn set_raw_body(&mut self, bytes: Vec<u8>) {
        self.raw_body = Some(bytes);
    }

    /// Headers whose percent-decoded value contained invalid UTF-8 and was
    /// decoded lossily (U+FFFD substituted).
    ///
    /// Each entry carries the on-wire `raw_value()` (the percent-encoded source
    /// text) so the app can re-decode it (e.g. as Latin-1) or audit it instead
    /// of being stuck with the U+FFFD-substituted string in `headers`. Empty in
    /// the normal case.
    pub fn lossy_values(&self) -> &LossyValues {
        &self.lossy_values
    }

    /// Set the lossy values.
    ///
    /// Used internally by the ESL parser; consumers don't call this directly.
    #[doc(hidden)]
    pub fn set_lossy_values(&mut self, v: LossyValues) {
        self.lossy_values = v;
    }

    /// Sets the `priority` header carried on the event.
    ///
    /// FreeSWITCH stores this as metadata but does **not** use it for dispatch
    /// ordering -- all events are delivered FIFO regardless of priority.
    pub fn set_priority(&mut self, priority: EslEventPriority) {
        self.set_header(EventHeader::Priority.as_str(), priority.to_string());
    }

    /// Append a value to a multi-value header (PUSH semantics).
    ///
    /// If the header doesn't exist, sets it as a plain value.
    /// If it exists as a plain value, converts to `ARRAY::old|:new`.
    /// If it already has an `ARRAY::` prefix, appends the new value.
    ///
    /// Returns [`EslArrayError::TooManyItems`] if the existing header already
    /// contains [`MAX_ARRAY_ITEMS`](crate::MAX_ARRAY_ITEMS) items.
    ///
    /// ```
    /// # use freeswitch_types::EslEvent;
    /// let mut event = EslEvent::new();
    /// event.push_header("X-Test", "first").unwrap();
    /// event.push_header("X-Test", "second").unwrap();
    /// assert_eq!(event.header_str("X-Test"), Some("ARRAY::first|:second"));
    /// ```
    pub fn push_header(&mut self, name: &str, value: &str) -> Result<(), EslArrayError> {
        self.stack_header(name, value, EslArray::push)
    }

    /// Prepend a value to a multi-value header (UNSHIFT semantics).
    ///
    /// Same conversion rules as [`push_header()`](Self::push_header), but
    /// inserts at the front.
    ///
    /// ```
    /// # use freeswitch_types::EslEvent;
    /// let mut event = EslEvent::new();
    /// event.set_header("X-Test", "ARRAY::b|:c");
    /// event.unshift_header("X-Test", "a").unwrap();
    /// assert_eq!(event.header_str("X-Test"), Some("ARRAY::a|:b|:c"));
    /// ```
    pub fn unshift_header(&mut self, name: &str, value: &str) -> Result<(), EslArrayError> {
        self.stack_header(name, value, EslArray::unshift)
    }

    fn stack_header(
        &mut self,
        name: &str,
        value: &str,
        op: fn(&mut EslArray, String),
    ) -> Result<(), EslArrayError> {
        match self
            .headers
            .get(name)
        {
            None => {
                self.set_header(name, value);
            }
            Some(existing) => {
                let arr = match EslArray::parse(existing) {
                    Ok(arr) => arr,
                    Err(EslArrayError::MissingPrefix) => EslArray::new(vec![existing.clone()]),
                    Err(e) => return Err(e),
                };
                if arr.len() >= crate::variables::MAX_ARRAY_ITEMS {
                    return Err(EslArrayError::TooManyItems {
                        count: arr.len(),
                        max: crate::variables::MAX_ARRAY_ITEMS,
                    });
                }
                let mut arr = arr;
                op(&mut arr, value.into());
                self.set_header(name, arr.to_string());
            }
        }
        Ok(())
    }

    /// Check whether this event matches the given type.
    pub fn is_event_type(&self, event_type: EslEventType) -> bool {
        self.event_type() == Some(event_type)
    }

    /// Serialize to ESL plain text wire format with percent-encoded header values.
    ///
    /// This is the inverse of `EslParser::parse_plain_event()`. The output can
    /// be fed back through the parser to reconstruct an equivalent `EslEvent`
    /// (round-trip).
    ///
    /// Headers are emitted in insertion order (which matches wire order when the
    /// event was parsed from the network). `Content-Length` from stored headers
    /// is skipped and recomputed from the body if present.
    pub fn to_plain_format(&self) -> String {
        use fmt::Write;
        let mut result = String::new();

        for (key, value) in &self.headers {
            if key == "Content-Length" {
                continue;
            }
            writeln!(
                result,
                "{}: {}",
                key,
                percent_encode(value.as_bytes(), NON_ALPHANUMERIC)
            )
            .expect("writing to String is infallible");
        }

        if let Some(body) = &self.body {
            writeln!(result, "Content-Length: {}", body.len())
                .expect("writing to String is infallible");
            result.push('\n');
            result.push_str(body);
        } else {
            result.push('\n');
        }

        result
    }
}

impl Default for EslEvent {
    fn default() -> Self {
        Self::new()
    }
}

impl HeaderLookup for EslEvent {
    fn header_str(&self, name: &str) -> Option<&str> {
        EslEvent::header_str(self, name)
    }

    fn variable_str(&self, name: &str) -> Option<&str> {
        let key = format!("variable_{}", name);
        self.header_str(&key)
    }
}

impl sip_header::SipHeaderLookup for EslEvent {
    fn sip_header_str(&self, name: &str) -> Option<&str> {
        EslEvent::header_str(self, name)
    }

    fn call_info(&self) -> Result<Option<sip_header::UriInfo>, sip_header::UriInfoError> {
        match self.sip_header(sip_header::SipHeader::CallInfo) {
            Some(s) => crate::variables::EslHeaders::parse_uri_info(s).map(Some),
            None => Ok(None),
        }
    }

    fn history_info(
        &self,
    ) -> Result<Option<sip_header::HistoryInfo>, sip_header::HistoryInfoError> {
        match self.sip_header(sip_header::SipHeader::HistoryInfo) {
            Some(s) => crate::variables::EslHeaders::parse_history_info(s).map(Some),
            None => Ok(None),
        }
    }

    fn alert_info(&self) -> Result<Option<sip_header::UriInfo>, sip_header::UriInfoError> {
        match self.sip_header(sip_header::SipHeader::AlertInfo) {
            Some(s) => crate::variables::EslHeaders::parse_uri_info(s).map(Some),
            None => Ok(None),
        }
    }
}

impl PartialEq for EslEvent {
    fn eq(&self, other: &Self) -> bool {
        self.headers == other.headers && self.body == other.body
    }
}

impl std::hash::Hash for EslEvent {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        for (k, v) in &self.headers {
            k.hash(state);
            v.hash(state);
        }
        self.body
            .hash(state);
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for EslEvent {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        // Accept (and silently discard) a legacy `event_type` field for
        // backwards compatibility with previously-serialized payloads;
        // the value is now derived from the Event-Name header.
        #[derive(serde::Deserialize)]
        struct Raw {
            #[serde(default)]
            #[allow(dead_code)]
            event_type: Option<EslEventType>,
            headers: IndexMap<String, String>,
            body: Option<String>,
            #[serde(default)]
            raw_body: Option<Vec<u8>>,
            #[serde(default)]
            lossy_values: LossyValues,
        }
        let raw = Raw::deserialize(deserializer)?;
        let mut event = EslEvent::new();
        event.body = raw.body;
        event.raw_body = raw.raw_body;
        event.lossy_values = raw.lossy_values;
        for (k, v) in raw.headers {
            event.set_header(k, v);
        }
        Ok(event)
    }
}

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

    #[test]
    fn headers_preserve_insertion_order() {
        let mut event = EslEvent::new();
        event.set_header("Zebra", "last");
        event.set_header("Alpha", "first");
        event.set_header("Middle", "mid");
        let keys: Vec<&str> = event
            .headers()
            .keys()
            .map(|s| s.as_str())
            .collect();
        assert_eq!(keys, vec!["Zebra", "Alpha", "Middle"]);
    }

    #[test]
    fn test_remove_header() {
        let mut event = EslEvent::new();
        event.set_header("Foo", "bar");
        event.set_header("Baz", "qux");

        let removed = event.remove_header("Foo");
        assert_eq!(removed, Some("bar".to_string()));
        assert!(event
            .header_str("Foo")
            .is_none());
        assert_eq!(event.header_str("Baz"), Some("qux"));

        let removed_again = event.remove_header("Foo");
        assert_eq!(removed_again, None);
    }

    #[test]
    fn test_to_plain_format_basic() {
        let mut event = EslEvent::with_type(EslEventType::Heartbeat);
        event.set_header("Event-Name", "HEARTBEAT");
        event.set_header("Core-UUID", "abc-123");

        let plain = event.to_plain_format();

        assert!(plain.starts_with("Event-Name: "));
        assert!(plain.contains("Core-UUID: "));
        assert!(plain.ends_with("\n\n"));
    }

    #[test]
    fn test_to_plain_format_percent_encoding() {
        let mut event = EslEvent::with_type(EslEventType::Heartbeat);
        event.set_header("Event-Name", "HEARTBEAT");
        event.set_header("Up-Time", "0 years, 0 days");

        let plain = event.to_plain_format();

        assert!(!plain.contains("0 years, 0 days"));
        assert!(plain.contains("Up-Time: "));
        assert!(plain.contains("%20"));
    }

    #[test]
    fn test_to_plain_format_with_body() {
        let mut event = EslEvent::with_type(EslEventType::BackgroundJob);
        event.set_header("Event-Name", "BACKGROUND_JOB");
        event.set_header("Job-UUID", "def-456");
        event.set_body("+OK result\n".to_string());

        let plain = event.to_plain_format();

        assert!(plain.contains("Content-Length: 11\n"));
        assert!(plain.ends_with("\n\n+OK result\n"));
    }

    #[test]
    fn test_to_plain_format_preserves_insertion_order() {
        let mut event = EslEvent::with_type(EslEventType::Heartbeat);
        event.set_header("Event-Name", "HEARTBEAT");
        event.set_header("Core-UUID", "abc-123");
        event.set_header("FreeSWITCH-Hostname", "fs01");
        event.set_header("Up-Time", "0 years, 1 day");

        let plain = event.to_plain_format();
        let lines: Vec<&str> = plain
            .lines()
            .collect();
        assert!(lines[0].starts_with("Event-Name: "));
        assert!(lines[1].starts_with("Core-UUID: "));
        assert!(lines[2].starts_with("FreeSWITCH-Hostname: "));
        assert!(lines[3].starts_with("Up-Time: "));
    }

    #[test]
    fn test_to_plain_format_round_trip() {
        let mut original = EslEvent::with_type(EslEventType::ChannelCreate);
        original.set_header("Event-Name", "CHANNEL_CREATE");
        original.set_header("Core-UUID", "abc-123");
        original.set_header("Channel-Name", "sofia/internal/1000@example.com");
        original.set_header("Caller-Caller-ID-Name", "Jérôme Poulin");
        original.set_body("some body content");

        let plain = original.to_plain_format();

        // Simulate what EslParser::parse_plain_event does
        let (header_section, inner_body) = if let Some(pos) = plain.find("\n\n") {
            (&plain[..pos], Some(&plain[pos + 2..]))
        } else {
            (plain.as_str(), None)
        };

        let mut parsed = EslEvent::new();
        for line in header_section.lines() {
            let line = line.trim();
            if line.is_empty() {
                continue;
            }
            if let Some(colon_pos) = line.find(':') {
                let key = line[..colon_pos].trim();
                if key == "Content-Length" {
                    continue;
                }
                let raw_value = line[colon_pos + 1..].trim();
                let value = percent_encoding::percent_decode_str(raw_value)
                    .decode_utf8()
                    .unwrap()
                    .into_owned();
                parsed.set_header(key, value);
            }
        }
        if let Some(ib) = inner_body {
            if !ib.is_empty() {
                parsed.set_body(ib);
            }
        }

        assert_eq!(original.headers(), parsed.headers());
        assert_eq!(original.body(), parsed.body());
    }

    #[test]
    fn test_set_priority_normal() {
        let mut event = EslEvent::new();
        event.set_priority(EslEventPriority::Normal);
        assert_eq!(
            event
                .priority()
                .unwrap(),
            Some(EslEventPriority::Normal)
        );
        assert_eq!(event.header(EventHeader::Priority), Some("NORMAL"));
    }

    #[test]
    fn test_set_priority_high() {
        let mut event = EslEvent::new();
        event.set_priority(EslEventPriority::High);
        assert_eq!(
            event
                .priority()
                .unwrap(),
            Some(EslEventPriority::High)
        );
        assert_eq!(event.header(EventHeader::Priority), Some("HIGH"));
    }

    #[test]
    fn test_priority_display() {
        assert_eq!(EslEventPriority::Normal.to_string(), "NORMAL");
        assert_eq!(EslEventPriority::Low.to_string(), "LOW");
        assert_eq!(EslEventPriority::High.to_string(), "HIGH");
    }

    #[test]
    fn test_priority_from_str() {
        assert_eq!(
            "NORMAL".parse::<EslEventPriority>(),
            Ok(EslEventPriority::Normal)
        );
        assert_eq!("LOW".parse::<EslEventPriority>(), Ok(EslEventPriority::Low));
        assert_eq!(
            "HIGH".parse::<EslEventPriority>(),
            Ok(EslEventPriority::High)
        );
        assert!("INVALID"
            .parse::<EslEventPriority>()
            .is_err());
    }

    #[test]
    fn test_priority_from_str_rejects_wrong_case() {
        assert!("normal"
            .parse::<EslEventPriority>()
            .is_err());
        assert!("Low"
            .parse::<EslEventPriority>()
            .is_err());
        assert!("hIgH"
            .parse::<EslEventPriority>()
            .is_err());
    }

    #[test]
    fn test_push_header_new() {
        let mut event = EslEvent::new();
        event
            .push_header("X-Test", "first")
            .unwrap();
        assert_eq!(event.header_str("X-Test"), Some("first"));
    }

    #[test]
    fn test_push_header_existing_plain() {
        let mut event = EslEvent::new();
        event.set_header("X-Test", "first");
        event
            .push_header("X-Test", "second")
            .unwrap();
        assert_eq!(event.header_str("X-Test"), Some("ARRAY::first|:second"));
    }

    #[test]
    fn test_push_header_existing_array() {
        let mut event = EslEvent::new();
        event.set_header("X-Test", "ARRAY::a|:b");
        event
            .push_header("X-Test", "c")
            .unwrap();
        assert_eq!(event.header_str("X-Test"), Some("ARRAY::a|:b|:c"));
    }

    #[test]
    fn test_push_header_at_capacity() {
        use crate::variables::MAX_ARRAY_ITEMS;
        let mut event = EslEvent::new();
        let items: Vec<&str> = (0..MAX_ARRAY_ITEMS)
            .map(|_| "x")
            .collect();
        event.set_header("X-Test", format!("ARRAY::{}", items.join("|:")).as_str());
        assert!(matches!(
            event.push_header("X-Test", "overflow"),
            Err(EslArrayError::TooManyItems { .. })
        ));
    }

    #[test]
    fn test_unshift_header_new() {
        let mut event = EslEvent::new();
        event
            .unshift_header("X-Test", "only")
            .unwrap();
        assert_eq!(event.header_str("X-Test"), Some("only"));
    }

    #[test]
    fn test_unshift_header_existing_array() {
        let mut event = EslEvent::new();
        event.set_header("X-Test", "ARRAY::b|:c");
        event
            .unshift_header("X-Test", "a")
            .unwrap();
        assert_eq!(event.header_str("X-Test"), Some("ARRAY::a|:b|:c"));
    }

    #[test]
    fn test_sendevent_with_priority_wire_format() {
        let mut event = EslEvent::with_type(EslEventType::Custom);
        event.set_header("Event-Name", "CUSTOM");
        event.set_header("Event-Subclass", "test::priority");
        event.set_priority(EslEventPriority::High);

        let plain = event.to_plain_format();
        assert!(plain.contains("priority: HIGH\n"));
    }

    #[test]
    fn test_convenience_accessors() {
        let mut event = EslEvent::new();
        event.set_header("Channel-Name", "sofia/internal/1000@example.com");
        event.set_header("Caller-Caller-ID-Number", "1000");
        event.set_header("Caller-Caller-ID-Name", "Alice");
        event.set_header("Hangup-Cause", "NORMAL_CLEARING");
        event.set_header("Event-Subclass", "sofia::register");
        event.set_header("variable_sip_from_display", "Bob");

        assert_eq!(
            event.channel_name(),
            Some("sofia/internal/1000@example.com")
        );
        assert_eq!(event.caller_id_number(), Some("1000"));
        assert_eq!(event.caller_id_name(), Some("Alice"));
        assert_eq!(
            event
                .hangup_cause()
                .unwrap(),
            Some(crate::channel::HangupCause::NormalClearing)
        );
        assert_eq!(event.event_subclass(), Some("sofia::register"));
        assert_eq!(event.variable_str("sip_from_display"), Some("Bob"));
        assert_eq!(event.variable_str("nonexistent"), None);
    }

    // --- EslEvent accessor tests (via HeaderLookup trait) ---

    #[test]
    fn test_event_channel_state_accessor() {
        use crate::channel::ChannelState;
        let mut event = EslEvent::new();
        event.set_header("Channel-State", "CS_EXECUTE");
        assert_eq!(
            event
                .channel_state()
                .unwrap(),
            Some(ChannelState::CsExecute)
        );
    }

    #[test]
    fn test_event_channel_state_number_accessor() {
        use crate::channel::ChannelState;
        let mut event = EslEvent::new();
        event.set_header("Channel-State-Number", "4");
        assert_eq!(
            event
                .channel_state_number()
                .unwrap(),
            Some(ChannelState::CsExecute)
        );
    }

    #[test]
    fn test_event_call_state_accessor() {
        use crate::channel::CallState;
        let mut event = EslEvent::new();
        event.set_header("Channel-Call-State", "ACTIVE");
        assert_eq!(
            event
                .call_state()
                .unwrap(),
            Some(CallState::Active)
        );
    }

    #[test]
    fn test_event_answer_state_accessor() {
        use crate::channel::AnswerState;
        let mut event = EslEvent::new();
        event.set_header("Answer-State", "answered");
        assert_eq!(
            event
                .answer_state()
                .unwrap(),
            Some(AnswerState::Answered)
        );
    }

    #[test]
    fn test_event_call_direction_accessor() {
        use crate::channel::CallDirection;
        let mut event = EslEvent::new();
        event.set_header("Call-Direction", "inbound");
        assert_eq!(
            event
                .call_direction()
                .unwrap(),
            Some(CallDirection::Inbound)
        );
    }

    #[test]
    fn test_event_typed_accessors_missing_headers() {
        let event = EslEvent::new();
        assert_eq!(
            event
                .channel_state()
                .unwrap(),
            None
        );
        assert_eq!(
            event
                .channel_state_number()
                .unwrap(),
            None
        );
        assert_eq!(
            event
                .call_state()
                .unwrap(),
            None
        );
        assert_eq!(
            event
                .answer_state()
                .unwrap(),
            None
        );
        assert_eq!(
            event
                .call_direction()
                .unwrap(),
            None
        );
    }

    // --- Repeating SIP header tests ---

    #[test]
    fn test_sip_p_asserted_identity_comma_separated() {
        let mut event = EslEvent::new();
        // RFC 3325: P-Asserted-Identity can carry two identities (one sip:, one tel:)
        // FreeSWITCH stores the comma-separated value as a single channel variable
        event.set_header(
            "variable_sip_P-Asserted-Identity",
            "<sip:alice@atlanta.example.com>, <tel:+15551234567>",
        );

        assert_eq!(
            event.variable_str("sip_P-Asserted-Identity"),
            Some("<sip:alice@atlanta.example.com>, <tel:+15551234567>")
        );
    }

    #[test]
    fn test_sip_p_asserted_identity_array_format() {
        let mut event = EslEvent::new();
        // When FreeSWITCH stores repeated SIP headers via ARRAY format
        event
            .push_header(
                "variable_sip_P-Asserted-Identity",
                "<sip:alice@atlanta.example.com>",
            )
            .unwrap();
        event
            .push_header("variable_sip_P-Asserted-Identity", "<tel:+15551234567>")
            .unwrap();

        let raw = event
            .header_str("variable_sip_P-Asserted-Identity")
            .unwrap();
        assert_eq!(
            raw,
            "ARRAY::<sip:alice@atlanta.example.com>|:<tel:+15551234567>"
        );

        let arr = crate::variables::EslArray::parse(raw).unwrap();
        assert_eq!(arr.len(), 2);
        assert_eq!(arr.items()[0], "<sip:alice@atlanta.example.com>");
        assert_eq!(arr.items()[1], "<tel:+15551234567>");
    }

    #[test]
    fn test_sip_header_with_colons_in_uri() {
        let mut event = EslEvent::new();
        // SIP URIs contain colons (sip:, sips:) which must not confuse ARRAY parsing
        event
            .push_header(
                "variable_sip_h_Diversion",
                "<sip:+15551234567@gw.example.com;reason=unconditional>",
            )
            .unwrap();
        event
            .push_header(
                "variable_sip_h_Diversion",
                "<sips:+15559876543@secure.example.com;reason=no-answer;counter=3>",
            )
            .unwrap();

        let raw = event
            .header_str("variable_sip_h_Diversion")
            .unwrap();
        let arr = crate::variables::EslArray::parse(raw).unwrap();
        assert_eq!(arr.len(), 2);
        assert_eq!(
            arr.items()[0],
            "<sip:+15551234567@gw.example.com;reason=unconditional>"
        );
        assert_eq!(
            arr.items()[1],
            "<sips:+15559876543@secure.example.com;reason=no-answer;counter=3>"
        );
    }

    #[test]
    fn test_sip_p_asserted_identity_plain_format_round_trip() {
        let mut event = EslEvent::with_type(EslEventType::ChannelCreate);
        event.set_header("Event-Name", "CHANNEL_CREATE");
        event.set_header(
            "variable_sip_P-Asserted-Identity",
            "<sip:alice@atlanta.example.com>, <tel:+15551234567>",
        );

        let plain = event.to_plain_format();
        // The comma-separated value should be percent-encoded on the wire
        assert!(plain.contains("variable_sip_P-Asserted-Identity:"));
        // Angle brackets and comma should be encoded
        assert!(!plain.contains("<sip:alice"));
    }

    // --- Header key normalization on EslEvent ---
    // set_header() normalizes keys so lookups via header(EventHeader::X)
    // and header_str() work regardless of the casing used at insertion.

    #[test]
    fn set_header_normalizes_known_enum_variant() {
        let mut event = EslEvent::new();
        event.set_header("unique-id", "abc-123");
        assert_eq!(event.header(EventHeader::UniqueId), Some("abc-123"));
    }

    #[test]
    fn set_header_normalizes_codec_header() {
        let mut event = EslEvent::new();
        event.set_header("channel-read-codec-bit-rate", "128000");
        assert_eq!(
            event.header(EventHeader::ChannelReadCodecBitRate),
            Some("128000")
        );
    }

    #[test]
    fn header_str_finds_by_original_key() {
        let mut event = EslEvent::new();
        event.set_header("unique-id", "abc-123");
        // Lookup by original non-canonical key should still work
        assert_eq!(event.header_str("unique-id"), Some("abc-123"));
        // Lookup by canonical key also works
        assert_eq!(event.header_str("Unique-ID"), Some("abc-123"));
    }

    #[test]
    fn header_str_finds_unknown_dash_header_by_original() {
        let mut event = EslEvent::new();
        event.set_header("x-custom-header", "val");
        // Stored as Title-Case
        assert_eq!(event.header_str("X-Custom-Header"), Some("val"));
        // Original key also works via alias
        assert_eq!(event.header_str("x-custom-header"), Some("val"));
    }

    #[test]
    fn set_header_underscore_passthrough_preserves_sip_h() {
        let mut event = EslEvent::new();
        event.set_header("variable_sip_h_X-My-CUSTOM-Header", "val");
        assert_eq!(
            event.header_str("variable_sip_h_X-My-CUSTOM-Header"),
            Some("val")
        );
    }

    #[test]
    fn set_header_different_casing_overwrites() {
        let mut event = EslEvent::new();
        event.set_header("Unique-ID", "first");
        event.set_header("unique-id", "second");
        // Both normalize to "Unique-ID", second overwrites first
        assert_eq!(event.header(EventHeader::UniqueId), Some("second"));
    }

    #[test]
    fn remove_header_by_original_key() {
        let mut event = EslEvent::new();
        event.set_header("unique-id", "abc-123");
        let removed = event.remove_header("unique-id");
        assert_eq!(removed, Some("abc-123".to_string()));
        assert_eq!(event.header(EventHeader::UniqueId), None);
    }

    #[test]
    fn remove_header_by_canonical_key() {
        let mut event = EslEvent::new();
        event.set_header("unique-id", "abc-123");
        let removed = event.remove_header("Unique-ID");
        assert_eq!(removed, Some("abc-123".to_string()));
        assert_eq!(event.header_str("unique-id"), None);
    }

    #[test]
    fn serde_round_trip_preserves_canonical_lookups() {
        let mut event = EslEvent::new();
        event.set_header("unique-id", "abc-123");
        event.set_header("channel-read-codec-bit-rate", "128000");
        let json = serde_json::to_string(&event).unwrap();
        let deserialized: EslEvent = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized.header(EventHeader::UniqueId), Some("abc-123"));
        assert_eq!(
            deserialized.header(EventHeader::ChannelReadCodecBitRate),
            Some("128000")
        );
    }

    #[test]
    fn serde_deserialize_normalizes_external_json() {
        let json = r#"{"event_type":null,"headers":{"unique-id":"abc-123","channel-read-codec-bit-rate":"128000"},"body":null}"#;
        let event: EslEvent = serde_json::from_str(json).unwrap();
        assert_eq!(event.header(EventHeader::UniqueId), Some("abc-123"));
        assert_eq!(
            event.header(EventHeader::ChannelReadCodecBitRate),
            Some("128000")
        );
        assert_eq!(event.header_str("unique-id"), Some("abc-123"));
    }

    #[test]
    fn original_keys_rebuilt_after_serde_roundtrip() {
        // Real-world CODEC event quirk: switch_core_codec.c emits
        // `Channel-Write-Codec-Name` (Title-Case) alongside
        // `channel-write-codec-bit-rate` (all lowercase). The wire parser
        // routes every header through `set_header()` which normalizes the
        // key and stores non-canonical originals in the alias map so
        // `header_str("channel-write-codec-bit-rate")` still resolves
        // without an extra hash probe per lookup.
        //
        // The alias map is `#[serde(skip)]`: it's derived state. After
        // deserialization, the map must be rebuilt by routing every
        // incoming key through `set_header` — otherwise external JSON
        // carrying non-canonical keys (which is how FreeSWITCH's own
        // JSON-format events arrive over the wire) would lose non-canonical
        // lookup support.
        //
        // This test simulates that path: external JSON with both a
        // canonical and a non-canonical key present.
        let external_json = r#"{
            "event_type": null,
            "headers": {
                "Channel-Write-Codec-Name": "opus",
                "channel-write-codec-bit-rate": "64000",
                "Custom-X-Header": "preserved"
            },
            "body": null
        }"#;
        let parsed: EslEvent = serde_json::from_str(external_json).unwrap();

        // Canonical lookup via the typed enum — always works because
        // set_header normalizes into the canonical form.
        assert_eq!(
            parsed.header(EventHeader::ChannelWriteCodecName),
            Some("opus")
        );
        assert_eq!(
            parsed.header(EventHeader::ChannelWriteCodecBitRate),
            Some("64000")
        );

        // Non-canonical lookup of the bit-rate key — only works if the
        // alias map was rebuilt during deserialization.
        assert_eq!(
            parsed.header_str("channel-write-codec-bit-rate"),
            Some("64000")
        );
        // And canonical form of the same key still works.
        assert_eq!(
            parsed.header_str("Channel-Write-Codec-Bit-Rate"),
            Some("64000")
        );

        // Headers the library has no enum variant for pass through the
        // title-case fallback path; both forms resolve.
        assert_eq!(parsed.header_str("Custom-X-Header"), Some("preserved"));

        // And a round-trip of our own serialized output preserves the
        // canonical lookups (no aliases needed — we write canonical keys).
        let json = serde_json::to_string(&parsed).unwrap();
        let re_parsed: EslEvent = serde_json::from_str(&json).unwrap();
        assert_eq!(
            re_parsed.header(EventHeader::ChannelWriteCodecBitRate),
            Some("64000")
        );
    }

    #[test]
    fn test_event_typed_accessors_invalid_values() {
        let mut event = EslEvent::new();
        event.set_header("Channel-State", "BOGUS");
        event.set_header("Channel-State-Number", "999");
        event.set_header("Channel-Call-State", "BOGUS");
        event.set_header("Answer-State", "bogus");
        event.set_header("Call-Direction", "bogus");
        assert!(event
            .channel_state()
            .is_err());
        assert!(event
            .channel_state_number()
            .is_err());
        assert!(event
            .call_state()
            .is_err());
        assert!(event
            .answer_state()
            .is_err());
        assert!(event
            .call_direction()
            .is_err());
    }

    // --- Finding 2: EslEvent SipHeaderLookup ARRAY encoding ---

    #[test]
    fn esl_event_call_info_array_encoding() {
        use sip_header::SipHeaderLookup;

        let mut event = EslEvent::new();
        event.set_header(
            "Call-Info".to_string(),
            "ARRAY::<urn:emergency:uid:callid:abc>;purpose=emergency-CallId\
             |:<urn:emergency:uid:incidentid:def>;purpose=emergency-IncidentId"
                .to_string(),
        );
        let ci = event
            .call_info()
            .expect("should parse")
            .expect("should be present");
        assert_eq!(
            ci.entries()
                .len(),
            2,
            "ARRAY:: entries should expand"
        );
    }

    #[test]
    fn esl_event_call_info_plain_value_unchanged() {
        use sip_header::SipHeaderLookup;

        let mut event = EslEvent::new();
        event.set_header(
            "Call-Info".to_string(),
            "<sip:pbx.example.com>;purpose=icon".to_string(),
        );
        let ci = event
            .call_info()
            .expect("plain value should parse")
            .expect("should be present");
        assert_eq!(
            ci.entries()
                .len(),
            1
        );
    }

    #[test]
    fn esl_event_history_info_array_encoding() {
        use sip_header::SipHeaderLookup;

        let mut event = EslEvent::new();
        event.set_header(
            "History-Info".to_string(),
            "ARRAY::<sip:user@pbx.example.com>;index=1\
             |:<sip:forward@pbx.example.com?Reason=unconditional>;index=1.1"
                .to_string(),
        );
        let hi = event
            .history_info()
            .expect("should parse")
            .expect("should be present");
        assert_eq!(
            hi.entries()
                .len(),
            2,
            "ARRAY:: entries should expand"
        );
    }
}