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
//! Composition settings and handles shared by every egress: recordings, HLS and
//! RTMP.

use serde::Serialize;
use serde_json::Value;

use crate::common::{
    CompositionConfig, CompositionQuality, LayoutConfig, LayoutPriority, LayoutType, Orientation,
    Theme,
};

/// A composition layout: one of the named layouts, or a custom template.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CompositionLayout {
    /// An even grid of participants.
    Grid,
    /// Highlights the active participant.
    Spotlight,
    /// A main stage with a sidebar of participants.
    Sidebar,
    /// Renders a custom template, given its URL, instead of a named layout.
    Custom(String),
}

impl CompositionLayout {
    /// A custom-template layout.
    pub fn custom(template_url: impl Into<String>) -> Self {
        CompositionLayout::Custom(template_url.into())
    }

    /// The wire layout type of a named layout, or `None` for a custom template.
    fn layout_type(&self) -> Option<LayoutType> {
        match self {
            CompositionLayout::Grid => Some(LayoutType::Grid),
            CompositionLayout::Spotlight => Some(LayoutType::Spotlight),
            CompositionLayout::Sidebar => Some(LayoutType::Sidebar),
            CompositionLayout::Custom(_) => None,
        }
    }
}

/// The composition options shared by every egress: layout, priority, grid size,
/// orientation, theme and quality.
///
/// If `layout` is omitted while `quality`, `theme` or `orientation` are set, the
/// layout defaults to [`CompositionLayout::Grid`] — the API requires a layout
/// whenever any other composition option is present.
#[derive(Debug, Clone, Default)]
pub struct Composition {
    /// A named layout, or a custom template.
    pub layout: Option<CompositionLayout>,
    /// The speaker priority. HLS and RTMP require it when a layout is present,
    /// so the SDK defaults it to [`LayoutPriority::Speaker`] for those.
    pub priority: Option<LayoutPriority>,
    /// The number of tiles in a grid layout: 0-25, defaulting to 25.
    pub grid_size: Option<u32>,
    /// The composition's orientation.
    pub orientation: Option<Orientation>,
    /// The composition's theme.
    pub theme: Option<Theme>,
    /// The recorder quality tier.
    pub quality: Option<CompositionQuality>,
}

/// The request-body composition settings produced by [`composition_to_config`].
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) struct MappedComposition {
    pub(crate) config: Option<CompositionConfig>,
    pub(crate) template_url: Option<String>,
}

/// Converts a [`Composition`] into the request-body composition settings.
///
/// `default_priority` is applied to a named layout that has no explicit
/// priority; HLS and RTMP require a priority whenever a layout is present.
pub(crate) fn composition_to_config(
    composition: Option<&Composition>,
    default_priority: Option<LayoutPriority>,
) -> MappedComposition {
    let Some(composition) = composition else {
        return MappedComposition::default();
    };

    let priority = || composition.priority.or(default_priority);
    let mut config = CompositionConfig::default();
    let mut template_url = None;

    match &composition.layout {
        Some(CompositionLayout::Custom(url)) => template_url = Some(url.clone()),
        Some(named) => {
            config.layout = Some(LayoutConfig {
                kind: named.layout_type(),
                priority: priority(),
                grid_size: composition.grid_size,
            })
        }
        None => {}
    }

    config.orientation = composition.orientation;
    config.theme = composition.theme;
    config.quality = composition.quality;

    // The API rejects (HTTP 406) any non-empty `config` that has no `layout` —
    // even alongside a `templateUrl`. If the caller set quality, theme or
    // orientation without a named layout, default the layout to GRID so the
    // composition starts. With a custom template, the top-level `templateUrl`
    // remains the more specific layout directive downstream.
    if !config.is_empty() && config.layout.is_none() {
        config.layout = Some(LayoutConfig {
            kind: Some(LayoutType::Grid),
            priority: priority(),
            grid_size: None,
        });
    }

    MappedComposition {
        config: (!config.is_empty()).then_some(config),
        template_url,
    }
}

/* -------------------------------- egress handles ------------------------------- */

/// The kind of egress an [`EgressHandle`] refers to.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EgressType {
    /// A room (composed) recording.
    Recording,
    /// A server-side composed recording.
    Composite,
    /// An HLS stream.
    Hls,
    /// An RTMP-out livestream.
    Livestream,
}

/// A handle to a running egress.
///
/// `start` returns one; pass it — or a bare room id — to `stop`.
///
/// Recordings, HLS and RTMP stop by `room_id`, where `id` is only an optional
/// disambiguator. **Composite** recordings stop by `id` (their `recordingId`),
/// which their start response provides.
#[derive(Debug, Clone)]
pub struct EgressHandle {
    /// Which egress this handle refers to.
    pub kind: EgressType,
    /// The room the egress runs in — the primary stop key.
    pub room_id: String,
    /// The server id, when the start response provides one.
    pub id: Option<String>,
    /// The session correlation id, when the start response provides one.
    pub session_id: Option<String>,
    /// The raw start response: a confirmation string, or an object.
    pub raw: Option<Value>,
}

/// Builds a handle from a start response, which is sometimes a bare confirmation
/// string and sometimes an id-bearing object.
pub(crate) fn to_egress_handle(kind: EgressType, room_id: &str, raw: Value) -> EgressHandle {
    let mut handle = EgressHandle {
        kind,
        room_id: room_id.to_string(),
        id: None,
        session_id: None,
        raw: None,
    };

    if let Some(object) = raw.as_object() {
        let string = |key: &str| object.get(key).and_then(Value::as_str).map(str::to_string);
        handle.id = string("recordingId")
            .or_else(|| string("id"))
            .or_else(|| string("_id"));
        handle.session_id = string("sessionId");
        if let Some(room_id) = string("roomId") {
            handle.room_id = room_id;
        }
    }

    handle.raw = Some(raw);
    handle
}

/// What to stop: an [`EgressHandle`], or a bare room id.
///
/// ```no_run
/// # async fn f(client: &videosdk::Client, handle: videosdk::EgressHandle) -> Result<(), videosdk::Error> {
/// client.hls().stop(&handle).await?;
/// client.hls().stop("abcd-efgh-ijkl").await?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct StopTarget {
    /// The room the egress runs in.
    pub room_id: String,
    /// The specific egress to stop, when known.
    pub id: Option<String>,
}

impl From<&str> for StopTarget {
    fn from(room_id: &str) -> Self {
        Self {
            room_id: room_id.to_string(),
            id: None,
        }
    }
}

impl From<String> for StopTarget {
    fn from(room_id: String) -> Self {
        Self { room_id, id: None }
    }
}

impl From<EgressHandle> for StopTarget {
    fn from(handle: EgressHandle) -> Self {
        Self {
            room_id: handle.room_id,
            id: handle.id,
        }
    }
}

impl From<&EgressHandle> for StopTarget {
    fn from(handle: &EgressHandle) -> Self {
        Self {
            room_id: handle.room_id.clone(),
            id: handle.id.clone(),
        }
    }
}

/// The body of a `stop` request: `{roomId, id?}`.
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct StopWire<'a> {
    room_id: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    id: Option<&'a str>,
}

impl<'a> From<&'a StopTarget> for StopWire<'a> {
    fn from(target: &'a StopTarget) -> Self {
        Self {
            room_id: &target.room_id,
            id: target.id.as_deref().filter(|id| !id.is_empty()),
        }
    }
}

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

    fn config_of(composition: Composition, default: Option<LayoutPriority>) -> Value {
        let mapped = composition_to_config(Some(&composition), default);
        json!({
            "config": mapped.config.map(|c| serde_json::to_value(c).unwrap()),
            "templateUrl": mapped.template_url,
        })
    }

    #[test]
    fn no_composition_maps_to_nothing() {
        assert_eq!(
            composition_to_config(None, None),
            MappedComposition::default()
        );
    }

    #[test]
    fn an_empty_composition_maps_to_nothing() {
        let mapped = composition_to_config(Some(&Composition::default()), None);
        assert_eq!(mapped, MappedComposition::default());
    }

    #[test]
    fn a_named_layout_is_uppercased() {
        let mapped = config_of(
            Composition {
                layout: Some(CompositionLayout::Spotlight),
                ..Default::default()
            },
            None,
        );
        assert_eq!(mapped["config"], json!({"layout": {"type": "SPOTLIGHT"}}));
        assert_eq!(mapped["templateUrl"], json!(null));
    }

    #[test]
    fn a_custom_layout_becomes_a_sibling_template_url_not_a_config_layout() {
        let mapped = config_of(
            Composition {
                layout: Some(CompositionLayout::custom("https://example.com/t.html")),
                ..Default::default()
            },
            None,
        );
        assert_eq!(mapped["config"], json!(null));
        assert_eq!(mapped["templateUrl"], json!("https://example.com/t.html"));
    }

    #[test]
    fn a_default_priority_applies_only_when_none_is_given() {
        let mapped = config_of(
            Composition {
                layout: Some(CompositionLayout::Grid),
                ..Default::default()
            },
            Some(LayoutPriority::Speaker),
        );
        assert_eq!(mapped["config"]["layout"]["priority"], json!("SPEAKER"));

        let mapped = config_of(
            Composition {
                layout: Some(CompositionLayout::Grid),
                priority: Some(LayoutPriority::Pin),
                ..Default::default()
            },
            Some(LayoutPriority::Speaker),
        );
        assert_eq!(mapped["config"]["layout"]["priority"], json!("PIN"));
    }

    #[test]
    fn recordings_send_no_priority_by_default() {
        let mapped = config_of(
            Composition {
                layout: Some(CompositionLayout::Grid),
                ..Default::default()
            },
            None,
        );
        assert_eq!(mapped["config"], json!({"layout": {"type": "GRID"}}));
    }

    #[test]
    fn grid_size_rides_along_with_a_named_layout() {
        let mapped = config_of(
            Composition {
                layout: Some(CompositionLayout::Grid),
                grid_size: Some(9),
                ..Default::default()
            },
            None,
        );
        assert_eq!(
            mapped["config"]["layout"],
            json!({"type": "GRID", "gridSize": 9})
        );
    }

    /// The backend answers 406 to a non-empty `config` with no `layout`.
    #[test]
    fn a_layoutless_config_gets_grid_injected() {
        let mapped = config_of(
            Composition {
                quality: Some(CompositionQuality::High),
                theme: Some(Theme::Dark),
                ..Default::default()
            },
            None,
        );
        assert_eq!(
            mapped["config"],
            json!({"layout": {"type": "GRID"}, "theme": "DARK", "quality": "high"})
        );
    }

    #[test]
    fn grid_injection_carries_the_resolved_priority_but_not_grid_size() {
        let mapped = config_of(
            Composition {
                orientation: Some(Orientation::Portrait),
                grid_size: Some(4),
                ..Default::default()
            },
            Some(LayoutPriority::Speaker),
        );
        assert_eq!(
            mapped["config"]["layout"],
            json!({"type": "GRID", "priority": "SPEAKER"})
        );
    }

    #[test]
    fn a_custom_template_with_other_options_still_gets_grid_injected() {
        let mapped = config_of(
            Composition {
                layout: Some(CompositionLayout::custom("https://example.com/t.html")),
                quality: Some(CompositionQuality::Low),
                ..Default::default()
            },
            None,
        );
        assert_eq!(
            mapped["config"],
            json!({"layout": {"type": "GRID"}, "quality": "low"})
        );
        assert_eq!(mapped["templateUrl"], json!("https://example.com/t.html"));
    }

    /* ------------------------------- handles ------------------------------- */

    #[test]
    fn a_string_start_response_yields_a_room_keyed_handle() {
        let handle = to_egress_handle(EgressType::Hls, "r-1", json!("HLS started"));
        assert_eq!(handle.room_id, "r-1");
        assert!(handle.id.is_none());
        assert_eq!(handle.raw, Some(json!("HLS started")));
    }

    #[test]
    fn an_object_start_response_yields_ids_in_priority_order() {
        let handle = to_egress_handle(
            EgressType::Composite,
            "r-1",
            json!({"recordingId": "rec-1", "id": "other", "_id": "another", "sessionId": "s-1"}),
        );
        assert_eq!(handle.id.as_deref(), Some("rec-1"));
        assert_eq!(handle.session_id.as_deref(), Some("s-1"));

        let handle = to_egress_handle(EgressType::Hls, "r-1", json!({"id": "h-1"}));
        assert_eq!(handle.id.as_deref(), Some("h-1"));

        let handle = to_egress_handle(EgressType::Hls, "r-1", json!({"_id": "h-2"}));
        assert_eq!(handle.id.as_deref(), Some("h-2"));
    }

    #[test]
    fn a_start_response_room_id_overrides_the_requested_one() {
        let handle = to_egress_handle(
            EgressType::Recording,
            "requested",
            json!({"roomId": "real"}),
        );
        assert_eq!(handle.room_id, "real");
    }

    #[test]
    fn stop_targets_accept_handles_and_bare_room_ids() {
        let handle = to_egress_handle(EgressType::Recording, "r-1", json!({"id": "e-1"}));
        let target: StopTarget = (&handle).into();
        assert_eq!(target.room_id, "r-1");
        assert_eq!(target.id.as_deref(), Some("e-1"));

        let target: StopTarget = "r-2".into();
        assert_eq!(target.room_id, "r-2");
        assert!(target.id.is_none());
    }

    #[test]
    fn stop_wire_omits_an_absent_or_empty_id() {
        let target = StopTarget {
            room_id: "r-1".into(),
            id: None,
        };
        assert_eq!(
            serde_json::to_value(StopWire::from(&target)).unwrap(),
            json!({"roomId": "r-1"})
        );

        let target = StopTarget {
            room_id: "r-1".into(),
            id: Some(String::new()),
        };
        assert_eq!(
            serde_json::to_value(StopWire::from(&target)).unwrap(),
            json!({"roomId": "r-1"})
        );

        let target = StopTarget {
            room_id: "r-1".into(),
            id: Some("e-1".into()),
        };
        assert_eq!(
            serde_json::to_value(StopWire::from(&target)).unwrap(),
            json!({"roomId": "r-1", "id": "e-1"})
        );
    }
}