freeswitch-types 1.1.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
//! [`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, SipHeader, 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 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 via [`UriInfoError::MissingAngleBrackets`]
    /// carrying the cause so operators see the actual reason in logs.
    ///
    /// # 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 value = strip_brackets(value);
        match EslArray::parse(value) {
            Ok(array) => UriInfo::from_entries(
                array
                    .items()
                    .iter()
                    .map(String::as_str),
            ),
            Err(EslArrayError::MissingPrefix) => UriInfo::parse(value),
            // Upstream UriInfoError lacks a generic "structural array
            // failure" variant; carry the cause in MissingAngleBrackets so
            // operators see the actual reason in logs.
            Err(other) => Err(UriInfoError::MissingAngleBrackets(format!(
                "ARRAY:: parse failed: {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::Empty`] rather than silently falling back — upstream
    /// lacks a richer variant for non-entry array failures.
    pub fn parse_history_info(value: &str) -> Result<HistoryInfo, HistoryInfoError> {
        let value = strip_brackets(value);
        match EslArray::parse(value) {
            Ok(array) => HistoryInfo::from_entries(
                array
                    .items()
                    .iter()
                    .map(String::as_str),
            ),
            Err(EslArrayError::MissingPrefix) => HistoryInfo::parse(value),
            Err(_) => Err(HistoryInfoError::Empty),
        }
    }
}

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

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

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

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

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!("variable_{name}"))
            .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_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
        );
    }
}