freeswitch-types 1.5.0-rc.6

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
//! [`EslHeaders`] — a flat header store that understands FreeSWITCH's
//! transport encodings.
//!
//! FreeSWITCH's ESL wire format carries headers and channel variables in the
//! same flat key-value namespace, but with two transport quirks that plain
//! RFC-SIP parsers don't account for:
//!
//! - **ARRAY encoding** — repeating SIP headers arrive as
//!   `ARRAY::value1|:value2|:value3` (see [`EslArray`]).
//! - **Bracket wrapping** — some log-sourced headers arrive as `[value]`.
//!
//! Routing those values through the default [`SipHeaderLookup`] methods
//! produces parse errors because the string doesn't match RFC syntax.
//! [`EslHeaders`] wraps an [`IndexMap<String, String>`] and overrides the
//! relevant `SipHeaderLookup` methods to strip both quirks before parsing.
//! The design-rationale doc §"EslHeaders: making the transport boundary
//! visible" explains the layering.

use indexmap::IndexMap;
use sip_header::{HistoryInfo, HistoryInfoError, SipHeaderLookup, UriInfo, UriInfoError};

use crate::lookup::HeaderLookup;
use crate::variables::{EslArray, EslArrayError};

/// A flat header store that decodes FreeSWITCH ARRAY and bracket encoding
/// when answering typed SIP header queries.
///
/// Construct with [`EslHeaders::new`] or [`EslHeaders::from_map`]. Use it
/// anywhere a [`HeaderLookup`] or [`SipHeaderLookup`] implementor is
/// expected:
///
/// ```
/// use freeswitch_types::{EslHeaders, HeaderLookup};
/// use freeswitch_types::sip_header::SipHeaderLookup;
///
/// let mut h = EslHeaders::new();
/// h.insert("Unique-ID", "abc-123");
/// h.insert("Call-Info", "ARRAY::<sip:a@example.com>;purpose=icon|:<sip:b@example.com>");
///
/// assert_eq!(h.header_str("Unique-ID"), Some("abc-123"));
/// let ci = h.call_info().unwrap().unwrap();
/// assert_eq!(ci.entries().len(), 2);
/// ```
///
/// `HeaderLookup` delegates straight to the map; `SipHeaderLookup` methods
/// that parse RFC-structured values (`call_info`, `history_info`, and any
/// future multi-value parsers) first peel the FreeSWITCH encoding and then
/// hand pre-split entries to `sip-header`. Non-parsing lookups
/// (`sip_header_str`, `sip_header`) return the raw stored value untouched —
/// the caller sees exactly what FreeSWITCH put on the wire.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct EslHeaders(IndexMap<String, String>);

impl EslHeaders {
    /// Create an empty store.
    pub fn new() -> Self {
        Self(IndexMap::new())
    }

    /// Wrap an existing map.
    pub fn from_map(map: IndexMap<String, String>) -> Self {
        Self(map)
    }

    /// Access the underlying map.
    pub fn as_map(&self) -> &IndexMap<String, String> {
        &self.0
    }

    /// Consume and return the underlying map.
    pub fn into_map(self) -> IndexMap<String, String> {
        self.0
    }

    /// Insert a header, replacing any existing entry at the same key.
    pub fn insert(&mut self, key: impl Into<String>, value: impl Into<String>) {
        self.0
            .insert(key.into(), value.into());
    }

    /// Remove a header by key.
    pub fn remove(&mut self, key: &str) -> Option<String> {
        self.0
            .shift_remove(key)
    }

    /// Number of entries.
    pub fn len(&self) -> usize {
        self.0
            .len()
    }

    /// `true` if there are no entries.
    pub fn is_empty(&self) -> bool {
        self.0
            .is_empty()
    }
}

impl<K: Into<String>, V: Into<String>> FromIterator<(K, V)> for EslHeaders {
    fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
        let mut headers = Self::new();
        headers.extend(iter);
        headers
    }
}

impl<K: Into<String>, V: Into<String>> Extend<(K, V)> for EslHeaders {
    fn extend<I: IntoIterator<Item = (K, V)>>(&mut self, iter: I) {
        for (key, value) in iter {
            self.insert(key, value);
        }
    }
}

impl From<IndexMap<String, String>> for EslHeaders {
    fn from(map: IndexMap<String, String>) -> Self {
        Self(map)
    }
}

/// Strip a single pair of outer `[...]` brackets from FreeSWITCH log-derived
/// header values. If the value is not bracket-wrapped, returns it unchanged.
fn strip_brackets(s: &str) -> &str {
    if let Some(inner) = s.strip_prefix('[') {
        if let Some(inner) = inner.strip_suffix(']') {
            return inner;
        }
    }
    s
}

impl EslHeaders {
    /// Parse a FreeSWITCH-transported SIP URI-list value into typed [`UriInfo`]
    /// entries, handling both `ARRAY::` encoding and bracket wrapping.
    ///
    /// Use this when you hold a *raw* value — e.g. the `sip_call_info` /
    /// `sip_alert_info` channel variable fetched over ESL — rather than a
    /// populated [`EslHeaders`]. It accepts any of the forms FreeSWITCH emits:
    ///
    /// - **Single RFC entry**: `<sip:a@example.test>;purpose=emergency-CallId`
    /// - **ARRAY encoding**: `ARRAY::<sip:a@example.test>;purpose=icon|:<sip:b@example.test>`
    /// - **Bracket-wrapped**: `[<sip:a@example.test>;purpose=icon]`
    ///
    /// This is the same decoding the [`call_info`](SipHeaderLookup::call_info)
    /// and [`alert_info`](SipHeaderLookup::alert_info) methods apply; iterate
    /// the result via `.entries()`.
    ///
    /// # Errors
    ///
    /// Returns [`UriInfoError`] if the value is malformed or if the `ARRAY::`
    /// structure is invalid. Structural `EslArrayError` cases (e.g.
    /// `TooManyItems`) are surfaced as [`UriInfoError::Malformed`] carrying
    /// the cause.
    ///
    /// # Example
    ///
    /// ```
    /// use freeswitch_types::EslHeaders;
    ///
    /// let value = "ARRAY::<urn:emergency:uid:callid:bcf.test>;purpose=emergency-CallId\
    ///              |:<urn:emergency:uid:incidentid:bcf.test>;purpose=emergency-IncidentId";
    /// let info = EslHeaders::parse_uri_info(value).unwrap();
    /// assert_eq!(info.entries().len(), 2);
    /// ```
    pub fn parse_uri_info(value: &str) -> Result<UriInfo, UriInfoError> {
        let entries =
            Self::split_entries(value).map_err(|e| UriInfoError::Malformed(e.to_string()))?;
        UriInfo::from_entries(
            entries
                .iter()
                .map(String::as_str),
        )
    }

    /// Split one comma-list SIP header value held as an ESL variable into its
    /// entries, applying the same decoding as [`parse_uri_info`](Self::parse_uri_info)
    /// and [`parse_history_info`](Self::parse_history_info): bracket unwrapping,
    /// then `ARRAY::` splitting, falling back to the RFC comma split.
    ///
    /// Only for headers that are lists (`Call-Info`, `Alert-Info`,
    /// `History-Info`, `Diversion`, …). A header whose value legitimately
    /// contains commas without being a list — `Date`, `Subject`, `User-Agent` —
    /// must not go through it.
    ///
    /// # Errors
    ///
    /// A missing `ARRAY::` prefix is the RFC form, not an error. Every other
    /// [`EslArrayError`] is a structural fault in the ESL encoding and is
    /// returned as-is. An empty or whitespace-only value yields no entries,
    /// which the typed parsers turn into their own `Empty` error.
    ///
    /// ```
    /// use freeswitch_types::EslHeaders;
    ///
    /// let entries =
    ///     EslHeaders::split_entries("ARRAY::<sip:a@example.test>|:<sip:b@example.test>").unwrap();
    /// assert_eq!(entries, ["<sip:a@example.test>", "<sip:b@example.test>"]);
    /// ```
    pub fn split_entries(value: &str) -> Result<Vec<String>, EslArrayError> {
        let value = strip_brackets(value);
        match EslArray::parse(value) {
            Ok(array) => Ok(array
                .items()
                .to_vec()),
            Err(EslArrayError::MissingPrefix) => {
                let value = value.trim();
                if value.is_empty() {
                    return Ok(Vec::new());
                }
                Ok(sip_header::split_comma_entries(value)
                    .into_iter()
                    .map(str::to_string)
                    .collect())
            }
            Err(other) => Err(other),
        }
    }

    /// Parse a FreeSWITCH-transported `History-Info` value into a typed
    /// [`HistoryInfo`], handling both `ARRAY::` encoding and bracket wrapping.
    ///
    /// The raw-value counterpart to [`history_info`](SipHeaderLookup::history_info).
    ///
    /// # Errors
    ///
    /// Structural `EslArrayError` cases (e.g. `TooManyItems`) are surfaced as
    /// [`HistoryInfoError::Malformed`] carrying the cause.
    pub fn parse_history_info(value: &str) -> Result<HistoryInfo, HistoryInfoError> {
        let entries =
            Self::split_entries(value).map_err(|e| HistoryInfoError::Malformed(e.to_string()))?;
        HistoryInfo::from_entries(
            entries
                .iter()
                .map(String::as_str),
        )
    }
}

/// Internal: emits the [`SipHeaderLookup`] method overrides that peel
/// FreeSWITCH's ARRAY and bracket encoding before RFC parsing. Invoke inside
/// an `impl SipHeaderLookup for T` block. Not part of the stable API.
#[doc(hidden)]
#[macro_export]
macro_rules! esl_sip_header_overrides {
    () => {
        fn call_info(
            &self,
        ) -> Result<Option<$crate::sip_header::UriInfo>, $crate::sip_header::UriInfoError> {
            match self.sip_header($crate::sip_header::SipHeader::CallInfo) {
                Some(s) => $crate::variables::EslHeaders::parse_uri_info(s).map(Some),
                None => Ok(None),
            }
        }

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

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

impl SipHeaderLookup for EslHeaders {
    fn sip_header_str(&self, name: &str) -> Option<&str> {
        self.0
            .get(name)
            .map(|s| s.as_str())
    }

    crate::esl_sip_header_overrides!();
}

impl HeaderLookup for EslHeaders {
    fn header_str(&self, name: &str) -> Option<&str> {
        self.0
            .get(name)
            .map(|s| s.as_str())
    }

    fn variable_str(&self, name: &str) -> Option<&str> {
        self.0
            .get(&format!("{}{name}", crate::VARIABLE_PREFIX))
            .map(|s| s.as_str())
    }
}

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

    #[test]
    fn header_str_passthrough() {
        let mut h = EslHeaders::new();
        h.insert("Unique-ID", "abc-123");
        assert_eq!(h.header_str("Unique-ID"), Some("abc-123"));
    }

    #[test]
    fn variable_str_prepends_variable_prefix() {
        let mut h = EslHeaders::new();
        h.insert("variable_sip_call_id", "call-1");
        assert_eq!(h.variable_str("sip_call_id"), Some("call-1"));
        assert_eq!(h.variable_str("missing"), None);
    }

    #[test]
    fn call_info_single_value_rfc() {
        let mut h = EslHeaders::new();
        h.insert(
            "Call-Info",
            "<sip:alice@example.com>;purpose=emergency-CallId",
        );
        let ci = h
            .call_info()
            .unwrap()
            .expect("present");
        assert_eq!(
            ci.entries()
                .len(),
            1
        );
        assert_eq!(ci.entries()[0].purpose(), Some("emergency-CallId"));
    }

    #[test]
    fn call_info_array_encoding() {
        let mut h = EslHeaders::new();
        h.insert(
            "Call-Info",
            "ARRAY::<sip:a@example.com>;purpose=icon|:<sip:b@example.com>;purpose=info",
        );
        let ci = h
            .call_info()
            .unwrap()
            .expect("present");
        assert_eq!(
            ci.entries()
                .len(),
            2
        );
        assert_eq!(ci.entries()[0].purpose(), Some("icon"));
        assert_eq!(ci.entries()[1].purpose(), Some("info"));
    }

    #[test]
    fn call_info_bracket_wrapped() {
        let mut h = EslHeaders::new();
        h.insert(
            "Call-Info",
            "[<sip:alice@example.com>;purpose=emergency-CallId]",
        );
        let ci = h
            .call_info()
            .unwrap()
            .expect("present");
        assert_eq!(
            ci.entries()
                .len(),
            1
        );
    }

    #[test]
    fn call_info_absent_is_ok_none() {
        let h = EslHeaders::new();
        assert!(h
            .call_info()
            .unwrap()
            .is_none());
    }

    #[test]
    fn history_info_array_encoding() {
        let mut h = EslHeaders::new();
        h.insert(
            "History-Info",
            "ARRAY::<sip:a@example.com>;index=1|:<sip:b@example.com>;index=1.1",
        );
        let hi = h
            .history_info()
            .unwrap()
            .expect("present");
        assert_eq!(
            hi.entries()
                .len(),
            2
        );
    }

    #[test]
    fn header_lookup_typed_accessors() {
        let mut h = EslHeaders::new();
        h.insert(EventHeader::UniqueId.as_str(), "uuid-1");
        h.insert(EventHeader::ChannelName.as_str(), "sofia/a/b");
        assert_eq!(h.unique_id(), Some("uuid-1"));
        assert_eq!(h.channel_name(), Some("sofia/a/b"));
    }

    #[test]
    fn parse_uri_info_array_form() {
        let value = "ARRAY::<urn:emergency:uid:callid:bcf.example.test>;purpose=emergency-CallId\
                     |:<urn:emergency:uid:incidentid:bcf.example.test>;purpose=emergency-IncidentId\
                     |:<https://eido.example.test/v1/bcf.example.test/abc?test-call=true>;purpose=emergency-eido";
        let info = EslHeaders::parse_uri_info(value).expect("parse ARRAY form");
        let entries = info.entries();
        assert_eq!(entries.len(), 3);
        assert_eq!(entries[0].purpose(), Some("emergency-CallId"));
        assert_eq!(entries[1].purpose(), Some("emergency-IncidentId"));
        assert_eq!(entries[2].purpose(), Some("emergency-eido"));
    }

    #[test]
    fn parse_uri_info_single_entry() {
        let value = "<urn:emergency:uid:callid:test>;purpose=emergency-CallId";
        let info = EslHeaders::parse_uri_info(value).expect("parse single entry");
        assert_eq!(
            info.entries()
                .len(),
            1
        );
        assert_eq!(info.entries()[0].purpose(), Some("emergency-CallId"));
    }

    #[test]
    fn parse_uri_info_empty_value() {
        // Empty string is an error (no angle brackets)
        let result = EslHeaders::parse_uri_info("");
        assert!(result.is_err());
    }

    #[test]
    fn parse_uri_info_malformed_no_panic() {
        // sip-header UriInfo is lenient - this parses without angle brackets
        let info = EslHeaders::parse_uri_info("sip:bare@example.test").expect("lenient parse");
        assert_eq!(
            info.entries()
                .len(),
            1
        );
    }

    #[test]
    fn parse_uri_info_bracket_wrapped() {
        let value = "[<urn:emergency:uid:callid:test>;purpose=emergency-CallId]";
        let info = EslHeaders::parse_uri_info(value).expect("parse bracket-wrapped");
        assert_eq!(
            info.entries()
                .len(),
            1
        );
        assert_eq!(info.entries()[0].purpose(), Some("emergency-CallId"));
    }

    #[test]
    fn parse_uri_info_structural_failure_is_malformed() {
        let value = format!(
            "ARRAY::{}",
            vec!["<sip:a@example.com>"; crate::variables::MAX_ARRAY_ITEMS + 1].join("|:")
        );
        let err = EslHeaders::parse_uri_info(&value).expect_err("over-limit array must fail");
        assert!(matches!(err, UriInfoError::Malformed(_)), "got {err:?}");
    }

    #[test]
    fn parse_history_info_structural_failure_is_malformed() {
        let value = format!(
            "ARRAY::{}",
            vec!["<sip:a@example.com>;index=1"; crate::variables::MAX_ARRAY_ITEMS + 1].join("|:")
        );
        let err = EslHeaders::parse_history_info(&value).expect_err("over-limit array must fail");
        assert!(matches!(err, HistoryInfoError::Malformed(_)), "got {err:?}");
    }

    #[test]
    fn collects_from_key_value_pairs() {
        let h: EslHeaders = [
            ("Unique-ID", "uuid-1"),
            ("Caller-Destination-Number", "911"),
        ]
        .into_iter()
        .collect();
        assert_eq!(h.header_str("Unique-ID"), Some("uuid-1"));
    }

    #[test]
    fn extend_adds_pairs() {
        let mut h = EslHeaders::new();
        h.insert("Unique-ID", "uuid-1");
        h.extend([("Channel-Name", "sofia/a/b")]);
        assert_eq!(h.len(), 2);
    }

    #[test]
    fn split_entries_array_form() {
        let entries =
            EslHeaders::split_entries("ARRAY::<sip:a@example.test>|:<sip:b@example.test>")
                .expect("ARRAY form");
        assert_eq!(entries, ["<sip:a@example.test>", "<sip:b@example.test>"]);
    }

    #[test]
    fn split_entries_rfc_comma_form() {
        let entries = EslHeaders::split_entries(
            "<sip:a@example.test>;text=\"one, two\",<sip:b@example.test>",
        )
        .expect("RFC form");
        assert_eq!(entries.len(), 2);
        assert_eq!(entries[0], "<sip:a@example.test>;text=\"one, two\"");
    }

    #[test]
    fn split_entries_bracket_wrapped() {
        let entries =
            EslHeaders::split_entries("[<sip:a@example.test>;purpose=icon]").expect("bracket form");
        assert_eq!(entries, ["<sip:a@example.test>;purpose=icon"]);
    }

    #[test]
    fn split_entries_blank_value_yields_no_entries() {
        let entries = EslHeaders::split_entries("  ").expect("blank value");
        assert!(entries.is_empty());
    }

    #[test]
    fn parse_history_info_blank_value_is_empty_error() {
        let err = EslHeaders::parse_history_info("  ").expect_err("blank value must fail");
        assert!(matches!(err, HistoryInfoError::Empty), "got {err:?}");
    }

    #[test]
    fn split_entries_too_many_items_is_err() {
        let value = format!(
            "ARRAY::{}",
            vec!["<sip:a@example.test>"; crate::variables::MAX_ARRAY_ITEMS + 1].join("|:")
        );
        let err = EslHeaders::split_entries(&value).expect_err("over-limit array must fail");
        assert!(
            matches!(err, EslArrayError::TooManyItems { .. }),
            "got {err:?}"
        );
    }

    #[test]
    fn parse_history_info_array_form() {
        let value = "ARRAY::<sip:a@example.com>;index=1|:<sip:b@example.com>;index=1.1";
        let info = EslHeaders::parse_history_info(value).expect("parse ARRAY form");
        assert_eq!(
            info.entries()
                .len(),
            2
        );
    }
}