videosdk-server-sdk 0.1.0

Rust server SDK for the VideoSDK v2 REST APIs
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
//! SIP routing rules, which bind provisioned numbers to a dispatch target.

use std::collections::HashMap;
use std::sync::Arc;

use futures_util::Stream;
use reqwest::Method;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};

use crate::client::{CallOptions, Client};
use crate::common::MessageResponse;
use crate::error::Result;
use crate::pagination::{auto_page, paginate, ListParams, Page, PageFetcher};
use crate::query::QueryBuilder;
use crate::resources::escape;
use crate::resources::sip::{SipDirection, SipIncludeHeaders, SipRoomPrefix, SipRoomType};

const PATH: &str = "/v2/sip/routing-rule";

/// The destination-room configuration of a routing rule, as it appears on the wire.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SipRoomConfig {
    /// How the room is allocated.
    #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
    pub kind: Option<SipRoomType>,
    /// How a per-call room id is generated, for dynamic rooms.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub prefix: Option<SipRoomPrefix>,
    /// The fixed room id, for static rooms.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    /// An optional room PIN.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pin: Option<String>,
}

/// Where a routing rule sends the caller.
///
/// This is friendly sugar over [`SipRoomConfig`]. Pass it as
/// [`CreateRoutingRuleParams::rule`]; set [`CreateRoutingRuleParams::room`]
/// instead to configure the wire shape directly.
#[derive(Debug, Clone)]
pub enum RoutingRuleTarget {
    /// Places every matching call into one fixed room.
    Direct {
        /// The fixed room id.
        room_id: String,
        /// An optional room PIN.
        pin: Option<String>,
    },
    /// Creates a fresh room for each matching call.
    Individual {
        /// How the per-call room id is generated. Defaults to
        /// [`SipRoomPrefix::BLANK`]. A strategy, not a literal prefix.
        room_prefix: Option<SipRoomPrefix>,
        /// An optional room PIN.
        pin: Option<String>,
    },
}

impl From<RoutingRuleTarget> for SipRoomConfig {
    fn from(target: RoutingRuleTarget) -> Self {
        match target {
            RoutingRuleTarget::Direct { room_id, pin } => SipRoomConfig {
                kind: Some(SipRoomType::STATIC),
                prefix: None,
                id: Some(room_id),
                pin,
            },
            RoutingRuleTarget::Individual { room_prefix, pin } => SipRoomConfig {
                kind: Some(SipRoomType::DYNAMIC),
                prefix: Some(room_prefix.unwrap_or(SipRoomPrefix::BLANK)),
                id: None,
                pin,
            },
        }
    }
}

/// A routing rule, binding provisioned phone numbers to a dispatch target.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SipRoutingRule {
    /// The rule id.
    pub id: String,
    /// The rule's display name.
    pub name: Option<String>,
    /// The rule's direction.
    #[serde(rename = "type")]
    pub direction: Option<SipDirection>,
    /// The phone numbers bound to this rule.
    #[serde(default, deserialize_with = "crate::common::null_to_default")]
    pub numbers: Vec<String>,
    /// The destination room configuration.
    pub room: Option<SipRoomConfig>,
    /// The agent dispatched for matching calls.
    pub agent_id: Option<String>,
    /// Metadata handed to the dispatched agent.
    pub agent_metadata: Option<Map<String, Value>>,
    /// Whether the caller's number is hidden from the room.
    pub hide_phone_number: Option<bool>,
    /// Free-form tags.
    #[serde(default, deserialize_with = "crate::common::null_to_default")]
    pub tags: Vec<String>,
    /// The API key that owns this rule.
    pub api_key: Option<String>,
    /// Whether matching calls are recorded.
    pub recording: Option<bool>,
    /// Whether DTMF is enabled.
    pub dtmf: Option<bool>,
    /// Whether noise cancellation is applied.
    pub noise_cancellation: Option<bool>,
    /// The allowed caller-number patterns.
    #[serde(default, deserialize_with = "crate::common::null_to_default")]
    pub allowed_numbers: Vec<String>,
    /// The allowed source IP addresses.
    #[serde(
        rename = "allowedIpAddresses",
        default,
        deserialize_with = "crate::common::null_to_default"
    )]
    pub allowed_ip_addresses: Vec<String>,
    /// Which SIP headers are forwarded.
    pub include_headers: Option<SipIncludeHeaders>,
    /// Headers added to outbound calls.
    #[serde(default, deserialize_with = "crate::common::null_to_default")]
    pub headers: HashMap<String, String>,
    /// Inbound headers mapped onto participant attributes.
    #[serde(default, deserialize_with = "crate::common::null_to_default")]
    pub headers_to_attributes: HashMap<String, String>,
    /// When the rule was created.
    pub created_at: Option<String>,
    /// When the rule was last updated.
    pub updated_at: Option<String>,
    /// Any fields the server returned that this SDK does not model yet.
    #[serde(flatten)]
    pub extra: Map<String, Value>,
}

/// The parameters for [`SipRoutingRulesResource::create`].
#[derive(Debug, Clone, Default)]
pub struct CreateRoutingRuleParams {
    /// The display name. Required.
    pub name: String,
    /// The direction. Required.
    pub direction: Option<SipDirection>,
    /// The provisioned phone numbers to bind.
    pub phone_numbers: Vec<String>,
    /// Where to route matching calls. Friendly sugar over `room`.
    pub rule: Option<RoutingRuleTarget>,
    /// An explicit room configuration. Used only when `rule` is omitted.
    pub room: Option<SipRoomConfig>,
    /// The agent to dispatch for matching calls.
    pub agent_id: Option<String>,
    /// Metadata handed to the dispatched agent. Applied on create only when
    /// `agent_id` is also set.
    pub agent_metadata: Option<Map<String, Value>>,
    /// Which SIP headers to forward.
    pub include_headers: Option<SipIncludeHeaders>,
    /// Headers to add. **Outbound rules only** — the server rejects this on an
    /// inbound rule.
    pub headers: HashMap<String, String>,
    /// Inbound headers to map onto participant attributes. **Inbound rules
    /// only** — the server rejects this on an outbound rule.
    pub headers_to_attributes: HashMap<String, String>,
    /// The allowed caller-number patterns.
    pub allowed_numbers: Vec<String>,
    /// The allowed source IP addresses.
    pub allowed_ip_addresses: Vec<String>,
    /// Free-form tags.
    pub tags: Vec<String>,
    /// Whether to record matching calls.
    pub recording: Option<bool>,
    /// Whether to enable DTMF.
    pub dtmf: Option<bool>,
    /// Whether to apply noise cancellation.
    pub noise_cancellation: Option<bool>,
    /// Whether to hide the caller's number from the room.
    pub hide_phone_number: Option<bool>,
    /// The API key that should own this rule.
    pub api_key: Option<String>,
}

/// The parameters for [`SipRoutingRulesResource::update`]. A rule's direction is
/// fixed at creation and cannot be changed.
#[derive(Debug, Clone, Default)]
pub struct UpdateRoutingRuleParams {
    /// The display name.
    pub name: Option<String>,
    /// The provisioned phone numbers to bind.
    pub phone_numbers: Vec<String>,
    /// Where to route matching calls. Friendly sugar over `room`.
    pub rule: Option<RoutingRuleTarget>,
    /// An explicit room configuration. Used only when `rule` is omitted.
    pub room: Option<SipRoomConfig>,
    /// The agent to dispatch for matching calls.
    pub agent_id: Option<String>,
    /// Metadata handed to the dispatched agent.
    pub agent_metadata: Option<Map<String, Value>>,
    /// Which SIP headers to forward.
    pub include_headers: Option<SipIncludeHeaders>,
    /// Headers to add. Outbound rules only.
    pub headers: HashMap<String, String>,
    /// Inbound headers to map onto participant attributes. Inbound rules only.
    pub headers_to_attributes: HashMap<String, String>,
    /// The allowed caller-number patterns.
    pub allowed_numbers: Vec<String>,
    /// The allowed source IP addresses.
    pub allowed_ip_addresses: Vec<String>,
    /// Free-form tags.
    pub tags: Vec<String>,
    /// Whether to record matching calls.
    pub recording: Option<bool>,
    /// Whether to enable DTMF.
    pub dtmf: Option<bool>,
    /// Whether to apply noise cancellation.
    pub noise_cancellation: Option<bool>,
    /// Whether to hide the caller's number from the room.
    pub hide_phone_number: Option<bool>,
    /// The API key that should own this rule.
    pub api_key: Option<String>,
}

/// The shared wire body. `direction` is sent on create and omitted on update.
#[derive(Debug, Default, Serialize)]
#[serde(rename_all = "camelCase")]
struct RoutingRuleWire {
    #[serde(skip_serializing_if = "Option::is_none")]
    name: Option<String>,
    #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
    direction: Option<SipDirection>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    phone_numbers: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    room: Option<SipRoomConfig>,
    #[serde(skip_serializing_if = "Option::is_none")]
    agent_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    agent_metadata: Option<Map<String, Value>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    include_headers: Option<SipIncludeHeaders>,
    #[serde(skip_serializing_if = "HashMap::is_empty")]
    headers: HashMap<String, String>,
    #[serde(skip_serializing_if = "HashMap::is_empty")]
    headers_to_attributes: HashMap<String, String>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    allowed_numbers: Vec<String>,
    #[serde(rename = "allowedIpAddresses", skip_serializing_if = "Vec::is_empty")]
    allowed_ip_addresses: Vec<String>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    tags: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    recording: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    dtmf: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    noise_cancellation: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    hide_phone_number: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    api_key: Option<String>,
}

/// An explicit `room` wins over the `rule` sugar.
fn resolve_room(
    room: Option<SipRoomConfig>,
    rule: Option<RoutingRuleTarget>,
) -> Option<SipRoomConfig> {
    room.or_else(|| rule.map(SipRoomConfig::from))
}

impl From<CreateRoutingRuleParams> for RoutingRuleWire {
    fn from(params: CreateRoutingRuleParams) -> Self {
        Self {
            name: Some(params.name).filter(|name| !name.is_empty()),
            direction: params.direction,
            phone_numbers: params.phone_numbers,
            room: resolve_room(params.room, params.rule),
            agent_id: params.agent_id,
            agent_metadata: params.agent_metadata,
            include_headers: params.include_headers,
            headers: params.headers,
            headers_to_attributes: params.headers_to_attributes,
            allowed_numbers: params.allowed_numbers,
            allowed_ip_addresses: params.allowed_ip_addresses,
            tags: params.tags,
            recording: params.recording,
            dtmf: params.dtmf,
            noise_cancellation: params.noise_cancellation,
            hide_phone_number: params.hide_phone_number,
            api_key: params.api_key,
        }
    }
}

impl From<UpdateRoutingRuleParams> for RoutingRuleWire {
    fn from(params: UpdateRoutingRuleParams) -> Self {
        Self {
            name: params.name,
            // A rule's direction is fixed at creation.
            direction: None,
            phone_numbers: params.phone_numbers,
            room: resolve_room(params.room, params.rule),
            agent_id: params.agent_id,
            agent_metadata: params.agent_metadata,
            include_headers: params.include_headers,
            headers: params.headers,
            headers_to_attributes: params.headers_to_attributes,
            allowed_numbers: params.allowed_numbers,
            allowed_ip_addresses: params.allowed_ip_addresses,
            tags: params.tags,
            recording: params.recording,
            dtmf: params.dtmf,
            noise_cancellation: params.noise_cancellation,
            hide_phone_number: params.hide_phone_number,
            api_key: params.api_key,
        }
    }
}

/// The query parameters for [`SipRoutingRulesResource::list`].
#[derive(Debug, Clone, Default)]
pub struct SipRoutingRuleListParams {
    /// The 1-based page number.
    pub page: Option<u32>,
    /// Items per page.
    pub per_page: Option<u32>,
    /// An opaque cursor from a previous page.
    pub cursor: Option<String>,
    /// Matches on name or numbers.
    pub search: Option<String>,
    /// Filters by direction.
    pub direction: Option<SipDirection>,
    /// Filters to specific rule ids.
    pub rule_ids: Vec<String>,
    /// Filters by destination room type.
    pub room_type: Vec<SipRoomType>,
}

impl SipRoutingRuleListParams {
    fn pagination(&self) -> ListParams {
        ListParams {
            page: self.page,
            per_page: self.per_page,
            cursor: self.cursor.clone(),
        }
    }
}

/// SIP routing rules. Reached via [`SipResource::routing_rules`](crate::SipResource::routing_rules).
#[derive(Debug, Clone, Copy)]
pub struct SipRoutingRulesResource<'a> {
    client: &'a Client,
}

impl<'a> SipRoutingRulesResource<'a> {
    pub(crate) fn new(client: &'a Client) -> Self {
        Self { client }
    }

    /// Creates a routing rule.
    pub async fn create(&self, params: CreateRoutingRuleParams) -> Result<SipRoutingRule> {
        let body = RoutingRuleWire::from(params);
        self.client
            .json(Method::POST, PATH, CallOptions::json(&body)?)
            .await
    }

    /// Lists routing rules, one page at a time.
    pub async fn list(&self, params: SipRoutingRuleListParams) -> Result<Page<SipRoutingRule>> {
        paginate(self.fetcher(&params), &params.pagination(), "data", None).await
    }

    /// Lists routing rules, transparently fetching every page.
    pub fn list_stream(
        &self,
        params: SipRoutingRuleListParams,
    ) -> impl Stream<Item = Result<SipRoutingRule>> + Send {
        auto_page(self.fetcher(&params), params.pagination(), "data", None)
    }

    /// Fetches a routing rule by id.
    pub async fn get(&self, rule_id: &str) -> Result<SipRoutingRule> {
        let path = format!("{PATH}/{}", escape(rule_id));
        self.client
            .json(Method::GET, &path, CallOptions::new())
            .await
    }

    /// Partially updates a routing rule. Its direction cannot be changed.
    pub async fn update(
        &self,
        rule_id: &str,
        params: UpdateRoutingRuleParams,
    ) -> Result<SipRoutingRule> {
        let body = RoutingRuleWire::from(params);
        let path = format!("{PATH}/{}", escape(rule_id));
        self.client
            .json(Method::PATCH, &path, CallOptions::json(&body)?)
            .await
    }

    /// Deletes a routing rule.
    pub async fn delete(&self, rule_id: &str) -> Result<MessageResponse> {
        let path = format!("{PATH}/{}", escape(rule_id));
        self.client
            .json(Method::DELETE, &path, CallOptions::new())
            .await
    }

    fn fetcher(&self, params: &SipRoutingRuleListParams) -> PageFetcher {
        let client = self.client.clone();
        let params = params.clone();
        Arc::new(move |page, per_page| {
            let client = client.clone();
            let params = params.clone();
            Box::pin(async move {
                let query = QueryBuilder::new()
                    .opt("page", page)
                    .opt("perPage", per_page)
                    .opt_str("search", params.search.as_deref())
                    .opt_str("type", params.direction.as_ref().map(SipDirection::as_str))
                    .csv("ruleIds", &params.rule_ids)
                    .csv("roomType", &params.room_type)
                    .into_pairs();
                client
                    .json::<Value>(Method::GET, PATH, CallOptions::new().query(query))
                    .await
            })
        })
    }
}

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

    fn wire(params: CreateRoutingRuleParams) -> Value {
        serde_json::to_value(RoutingRuleWire::from(params)).unwrap()
    }

    #[test]
    fn a_direct_target_becomes_a_static_room() {
        let body = wire(CreateRoutingRuleParams {
            name: "rule".into(),
            direction: Some(SipDirection::INBOUND),
            rule: Some(RoutingRuleTarget::Direct {
                room_id: "abcd-efgh".into(),
                pin: Some("1234".into()),
            }),
            ..Default::default()
        });
        assert_eq!(
            body,
            json!({
                "name": "rule",
                "type": "inbound",
                "room": {"type": "static", "id": "abcd-efgh", "pin": "1234"},
            })
        );
    }

    #[test]
    fn an_individual_target_becomes_a_dynamic_room_defaulting_to_blank() {
        let body = wire(CreateRoutingRuleParams {
            name: "rule".into(),
            rule: Some(RoutingRuleTarget::Individual {
                room_prefix: None,
                pin: None,
            }),
            ..Default::default()
        });
        assert_eq!(body["room"], json!({"type": "dynamic", "prefix": "blank"}));

        let body = wire(CreateRoutingRuleParams {
            name: "rule".into(),
            rule: Some(RoutingRuleTarget::Individual {
                room_prefix: Some(SipRoomPrefix::SIP_NUMBER),
                pin: None,
            }),
            ..Default::default()
        });
        assert_eq!(
            body["room"],
            json!({"type": "dynamic", "prefix": "sipNumber"})
        );
    }

    #[test]
    fn an_explicit_room_wins_over_the_rule_sugar() {
        let body = wire(CreateRoutingRuleParams {
            name: "rule".into(),
            room: Some(SipRoomConfig {
                kind: Some(SipRoomType::STATIC),
                id: Some("explicit".into()),
                ..Default::default()
            }),
            rule: Some(RoutingRuleTarget::Direct {
                room_id: "sugar".into(),
                pin: None,
            }),
            ..Default::default()
        });
        assert_eq!(body["room"]["id"], json!("explicit"));
    }

    #[test]
    fn an_update_never_sends_the_direction() {
        let body = serde_json::to_value(RoutingRuleWire::from(UpdateRoutingRuleParams {
            name: Some("renamed".into()),
            ..Default::default()
        }))
        .unwrap();
        assert_eq!(body, json!({"name": "renamed"}));
        assert!(body.get("type").is_none(), "direction is fixed at creation");
    }

    #[test]
    fn empty_collections_are_omitted() {
        let body = wire(CreateRoutingRuleParams {
            name: "rule".into(),
            ..Default::default()
        });
        assert_eq!(body, json!({"name": "rule"}));
    }

    #[test]
    fn allowed_ip_addresses_keeps_its_lowercase_p() {
        let body = wire(CreateRoutingRuleParams {
            name: "rule".into(),
            allowed_ip_addresses: vec!["1.2.3.4".into()],
            ..Default::default()
        });
        assert_eq!(body["allowedIpAddresses"], json!(["1.2.3.4"]));
    }
}