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
//! The SDK's error type.
//!
//! Every fallible SDK call returns [`Result<T>`], whose error is [`Error`].
//! Errors that came from an HTTP response carry an [`ApiError`] with the status,
//! the server's message and machine-readable code, and a request id for support.

use std::fmt;
use std::time::Duration;

use serde_json::Value;

/// A convenience alias for a `Result` whose error is the SDK's [`Error`].
pub type Result<T> = std::result::Result<T, Error>;

/// A coarse classification of an [`Error`].
///
/// For errors that came from an HTTP response the kind is derived from the
/// status code; client-side failures (misconfiguration, timeouts) set it
/// directly.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ErrorKind {
    /// An error that doesn't map to a more specific kind (includes 5xx).
    Generic,
    /// The client was constructed or used with invalid configuration.
    Configuration,
    /// HTTP 401 — the token is missing or invalid, or the account is inactive.
    Authentication,
    /// HTTP 403 — authenticated, but not permitted.
    Permission,
    /// HTTP 429 — rate limited.
    RateLimit,
    /// HTTP 400 — request validation failed.
    Validation,
    /// HTTP 404 or 402 — resource not found. The API uses both.
    NotFound,
    /// HTTP 409 — conflicting or duplicate state.
    Conflict,
    /// The client-side request timeout elapsed.
    Timeout,
}

impl ErrorKind {
    /// Classifies an HTTP status code.
    ///
    /// Note that **402 maps to [`ErrorKind::NotFound`]** alongside 404: the API
    /// returns 402 for some missing resources. This matches the TypeScript and
    /// Go SDKs.
    pub fn from_status(status: u16) -> Self {
        match status {
            400 => ErrorKind::Validation,
            401 => ErrorKind::Authentication,
            403 => ErrorKind::Permission,
            402 | 404 => ErrorKind::NotFound,
            409 => ErrorKind::Conflict,
            429 => ErrorKind::RateLimit,
            _ => ErrorKind::Generic,
        }
    }
}

/// An error returned by the API as a non-2xx HTTP response.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ApiError {
    /// A human-readable description, normalized from the API's error body.
    pub message: String,
    /// The classification derived from [`ApiError::status`].
    pub kind: ErrorKind,
    /// A machine-readable error code returned by the API, when present.
    pub code: Option<String>,
    /// The HTTP response status code.
    pub status: u16,
    /// A server request id, read from the response headers. Useful for support.
    pub request_id: Option<String>,
    /// The raw parsed error body, for advanced inspection.
    pub details: Option<Value>,
    /// The HTTP method of the failing request.
    pub method: String,
    /// The path of the failing request.
    pub path: String,
    /// The server-requested cooldown parsed from the `Retry-After` header on a
    /// 429 response.
    pub retry_after: Option<Duration>,
}

impl fmt::Display for ApiError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let msg = if self.message.is_empty() {
            "request failed"
        } else {
            &self.message
        };
        if self.method.is_empty() {
            write!(f, "videosdk: {msg} (status {})", self.status)
        } else {
            write!(
                f,
                "videosdk: {msg} ({} {}, status {})",
                self.method, self.path, self.status
            )
        }
    }
}

/// The error type returned by every fallible SDK call.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    /// The API responded with a non-2xx status.
    ///
    /// Boxed so that `Result<T>` stays small on the happy path, which every
    /// call in the crate pays for.
    #[error("{0}")]
    Api(Box<ApiError>),

    /// The client was constructed or used with invalid configuration.
    #[error("videosdk: {0}")]
    Configuration(String),

    /// A token could not be verified (malformed, bad signature, or expired).
    #[error("videosdk: {0}")]
    Authentication(String),

    /// A client-side precondition failed before the request was sent.
    #[error("videosdk: {0}")]
    Validation(String),

    /// The SDK resolved that a resource does not exist without the API saying
    /// so, e.g. asking for a participant in a room that has no live session.
    #[error("videosdk: {0}")]
    NotFound(String),

    /// A multi-step operation the SDK drives to completion failed, e.g. a
    /// batch-call file that the server could not parse.
    ///
    /// Carries a machine-readable [`code`](Error::code) but no HTTP status,
    /// since the failure is a *result* rather than a response.
    #[error("videosdk: {message}")]
    Operation {
        /// How to classify this failure.
        kind: ErrorKind,
        /// A machine-readable code, e.g. `batchcall_parse_failed`.
        code: String,
        /// A human-readable description.
        message: String,
    },

    /// The client-side request timeout elapsed.
    #[error("videosdk: request timed out after {}ms ({method} {path})", .elapsed.as_millis())]
    Timeout {
        /// The HTTP method of the request that timed out.
        method: String,
        /// The path of the request that timed out.
        path: String,
        /// The timeout that elapsed.
        elapsed: Duration,
    },

    /// The request could not be sent, or the response could not be read.
    #[error("videosdk: network request failed ({method} {path}): {source}")]
    Network {
        /// The HTTP method of the failing request.
        method: String,
        /// The path of the failing request.
        path: String,
        /// The underlying transport error.
        #[source]
        source: reqwest::Error,
    },

    /// A response body could not be deserialized into the expected type.
    #[error("videosdk: failed to decode response ({context}): {source}")]
    Decode {
        /// What was being decoded, e.g. `GET /v2/rooms`.
        context: String,
        /// The underlying deserialization error.
        #[source]
        source: serde_json::Error,
    },

    /// A request body could not be serialized.
    #[error("videosdk: failed to encode request body: {source}")]
    Encode {
        /// The underlying serialization error.
        #[source]
        source: serde_json::Error,
    },
}

impl Error {
    /// The coarse classification of this error.
    pub fn kind(&self) -> ErrorKind {
        match self {
            Error::Api(e) => e.kind,
            Error::Configuration(_) => ErrorKind::Configuration,
            Error::Authentication(_) => ErrorKind::Authentication,
            Error::Validation(_) => ErrorKind::Validation,
            Error::NotFound(_) => ErrorKind::NotFound,
            Error::Operation { kind, .. } => *kind,
            Error::Timeout { .. } => ErrorKind::Timeout,
            Error::Network { .. } | Error::Decode { .. } | Error::Encode { .. } => {
                ErrorKind::Generic
            }
        }
    }

    /// The underlying [`ApiError`], if this error came from an HTTP response.
    pub fn as_api(&self) -> Option<&ApiError> {
        match self {
            Error::Api(e) => Some(e.as_ref()),
            _ => None,
        }
    }

    pub(crate) fn api(error: ApiError) -> Self {
        Error::Api(Box::new(error))
    }

    /// The HTTP status code, if this error came from an HTTP response.
    pub fn status(&self) -> Option<u16> {
        self.as_api().map(|e| e.status)
    }

    /// The machine-readable error code, if present.
    pub fn code(&self) -> Option<&str> {
        match self {
            Error::Api(e) => e.code.as_deref(),
            Error::Operation { code, .. } => Some(code),
            _ => None,
        }
    }

    pub(crate) fn operation(
        kind: ErrorKind,
        code: impl Into<String>,
        message: impl Into<String>,
    ) -> Self {
        Error::Operation {
            kind,
            code: code.into(),
            message: message.into(),
        }
    }

    /// The server request id, if the response carried one.
    pub fn request_id(&self) -> Option<&str> {
        self.as_api().and_then(|e| e.request_id.as_deref())
    }

    /// The cooldown the server asked for via `Retry-After` on a 429.
    pub fn retry_after(&self) -> Option<Duration> {
        self.as_api().and_then(|e| e.retry_after)
    }

    /// Whether this is a not-found error (HTTP 404 or 402).
    pub fn is_not_found(&self) -> bool {
        self.kind() == ErrorKind::NotFound
    }

    /// Whether this is an authentication error (HTTP 401, or a bad token).
    pub fn is_authentication(&self) -> bool {
        self.kind() == ErrorKind::Authentication
    }

    /// Whether this is a permission error (HTTP 403).
    pub fn is_permission(&self) -> bool {
        self.kind() == ErrorKind::Permission
    }

    /// Whether this is a validation error (HTTP 400, or a client-side check).
    pub fn is_validation(&self) -> bool {
        self.kind() == ErrorKind::Validation
    }

    /// Whether this is a rate-limit error (HTTP 429).
    pub fn is_rate_limit(&self) -> bool {
        self.kind() == ErrorKind::RateLimit
    }

    /// Whether this is a conflict error (HTTP 409).
    pub fn is_conflict(&self) -> bool {
        self.kind() == ErrorKind::Conflict
    }

    /// Whether this is a client-side timeout.
    pub fn is_timeout(&self) -> bool {
        self.kind() == ErrorKind::Timeout
    }

    pub(crate) fn config(msg: impl Into<String>) -> Self {
        Error::Configuration(msg.into())
    }

    pub(crate) fn auth(msg: impl Into<String>) -> Self {
        Error::Authentication(msg.into())
    }

    pub(crate) fn validation(msg: impl Into<String>) -> Self {
        Error::Validation(msg.into())
    }

    pub(crate) fn not_found(msg: impl Into<String>) -> Self {
        Error::NotFound(msg.into())
    }

    pub(crate) fn decode(context: impl Into<String>, source: serde_json::Error) -> Self {
        Error::Decode {
            context: context.into(),
            source,
        }
    }
}

/// Builds a typed [`ApiError`] from a non-2xx response, pulling a human message
/// and optional code out of the parsed body.
pub(crate) fn normalize_api_error(
    status: u16,
    body: Option<Value>,
    method: &str,
    path: &str,
    request_id: Option<String>,
    retry_after: Option<Duration>,
) -> ApiError {
    let (message, code) = extract_message_and_code(body.as_ref());
    ApiError {
        message: message.unwrap_or_else(|| format!("request failed with status {status}")),
        kind: ErrorKind::from_status(status),
        code,
        status,
        request_id,
        details: body,
        method: method.to_string(),
        path: path.to_string(),
        retry_after,
    }
}

/// Pulls a message and optional code out of an arbitrary parsed error body: a
/// bare string, or an object with `message`/`error`/`msg`/`statusMessage` and
/// `code`/`errorCode` fields.
fn extract_message_and_code(body: Option<&Value>) -> (Option<String>, Option<String>) {
    let Some(body) = body else {
        return (None, None);
    };
    match body {
        Value::Null => (None, None),
        Value::String(s) => (Some(s.clone()), None),
        Value::Object(map) => {
            let pick = |keys: &[&str]| -> Option<String> {
                keys.iter().find_map(|k| {
                    map.get(*k)
                        .and_then(Value::as_str)
                        .filter(|s| !s.is_empty())
                        .map(str::to_string)
                })
            };
            (
                pick(&["message", "error", "msg", "statusMessage"]),
                pick(&["code", "errorCode"]),
            )
        }
        other => (Some(other.to_string()), None),
    }
}

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

    #[test]
    fn status_maps_to_kind() {
        assert_eq!(ErrorKind::from_status(400), ErrorKind::Validation);
        assert_eq!(ErrorKind::from_status(401), ErrorKind::Authentication);
        assert_eq!(ErrorKind::from_status(403), ErrorKind::Permission);
        assert_eq!(ErrorKind::from_status(409), ErrorKind::Conflict);
        assert_eq!(ErrorKind::from_status(429), ErrorKind::RateLimit);
        assert_eq!(ErrorKind::from_status(500), ErrorKind::Generic);
        assert_eq!(ErrorKind::from_status(418), ErrorKind::Generic);
    }

    #[test]
    fn both_402_and_404_are_not_found() {
        // The API overloads 402 to mean "not found" for some resources.
        assert_eq!(ErrorKind::from_status(402), ErrorKind::NotFound);
        assert_eq!(ErrorKind::from_status(404), ErrorKind::NotFound);
    }

    #[test]
    fn extracts_message_and_code_from_object() {
        let body = json!({"message": "nope", "code": "room_gone"});
        let (m, c) = extract_message_and_code(Some(&body));
        assert_eq!(m.as_deref(), Some("nope"));
        assert_eq!(c.as_deref(), Some("room_gone"));
    }

    #[test]
    fn message_falls_back_through_key_aliases() {
        for key in ["message", "error", "msg", "statusMessage"] {
            let body = json!({ key: "boom" });
            let (m, _) = extract_message_and_code(Some(&body));
            assert_eq!(m.as_deref(), Some("boom"), "key {key}");
        }
        let body = json!({"errorCode": "E42"});
        let (_, c) = extract_message_and_code(Some(&body));
        assert_eq!(c.as_deref(), Some("E42"));
    }

    #[test]
    fn empty_string_fields_are_skipped() {
        let body = json!({"message": "", "error": "real"});
        let (m, _) = extract_message_and_code(Some(&body));
        assert_eq!(m.as_deref(), Some("real"));
    }

    #[test]
    fn extracts_message_from_bare_string_body() {
        let body = json!("plain text failure");
        let (m, c) = extract_message_and_code(Some(&body));
        assert_eq!(m.as_deref(), Some("plain text failure"));
        assert!(c.is_none());
    }

    #[test]
    fn falls_back_to_status_message_when_body_has_none() {
        let err = normalize_api_error(500, Some(json!({})), "GET", "/v2/rooms", None, None);
        assert_eq!(err.message, "request failed with status 500");
        assert_eq!(err.kind, ErrorKind::Generic);
    }

    #[test]
    fn display_includes_method_path_and_status() {
        let err = normalize_api_error(404, Some(json!("gone")), "GET", "/v2/rooms/x", None, None);
        assert_eq!(
            Error::api(err).to_string(),
            "videosdk: gone (GET /v2/rooms/x, status 404)"
        );
    }

    #[test]
    fn predicates_match_kind() {
        let err = Error::api(normalize_api_error(404, None, "GET", "/x", None, None));
        assert!(err.is_not_found());
        assert!(!err.is_rate_limit());
        assert_eq!(err.status(), Some(404));

        let err = Error::config("bad");
        assert_eq!(err.kind(), ErrorKind::Configuration);
        assert_eq!(err.status(), None);
    }
}