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
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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
//! The alert-rules API: metric-threshold alerts over your project's telemetry.

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::{string_enum, MessageResponse};
use crate::error::Result;
use crate::pagination::{auto_page, paginate, ListParams, Page, PageFetcher};
use crate::query::QueryBuilder;
use crate::resources::escape;

const PATH: &str = "/v2/alertRules";

string_enum! {
    /// An alert rule's severity.
    AlertSeverity {
        /// Informational.
        INFO => "info",
        /// A warning.
        WARNING => "warning",
        /// Critical.
        CRITICAL => "critical",
    }
}

string_enum! {
    /// The product domain an alert rule is scoped to.
    ///
    /// The server defaults to [`AlertDomain::RTC`] when omitted — pass
    /// [`AlertDomain::AGENT`] to see agent-domain rules.
    AlertDomain {
        /// Real-time communication.
        RTC => "rtc",
        /// AI agents.
        AGENT => "agent",
    }
}

string_enum! {
    /// Whether an alert rule is active or paused.
    AlertRuleStatus {
        /// The rule is evaluating.
        ACTIVE => "active",
        /// The rule is paused.
        PAUSED => "paused",
    }
}

string_enum! {
    /// The comparison operator in an alert rule condition.
    AlertConditionOperator {
        /// Greater than.
        GREATER_THAN => ">",
        /// Less than.
        LESS_THAN => "<",
        /// Equal to.
        EQUAL => "=",
        /// Not equal to.
        NOT_EQUAL => "!=",
    }
}

string_enum! {
    /// How a condition must be met over the evaluation window.
    AlertMatchType {
        /// Fire if the threshold is crossed at least once. The default.
        AT_LEAST_ONCE => "at_least_once",
        /// Fire only if crossed for the whole window.
        ALL_THE_TIME => "all_the_time",
        /// Fire on the window average.
        ON_AVERAGE => "on_average",
        /// Fire on the window total.
        IN_TOTAL => "in_total",
        /// Fire on the last value.
        LAST => "last",
    }
}

string_enum! {
    /// Collapses each series to a single value before the threshold check.
    AlertReduceTo {
        /// The last value.
        LAST => "last",
        /// The sum.
        SUM => "sum",
        /// The average.
        AVG => "avg",
        /// The minimum.
        MIN => "min",
        /// The maximum.
        MAX => "max",
    }
}

/* -------------------------------- config types -------------------------------- */

/// Alerts when a metric stops reporting data.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AbsentDataAlert {
    /// Whether absent-data alerting is on.
    pub enabled: bool,
    /// Fire after the metric has been absent this long.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub for_seconds: Option<u32>,
}

/// Narrows a metric query. `value` is a string, number, or array of them.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AlertRuleFilter {
    /// The attribute to filter on.
    pub category: String,
    /// The filter operator, e.g. `=`, `in`, `regex`, `exists`.
    pub condition: String,
    /// The value(s) to compare against.
    pub value: Value,
}

/// Groups a metric query by an attribute key.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AlertRuleGroupBy {
    /// The attribute key.
    pub key: String,
    /// The attribute type: `string`, `int64`, `float64`, or `bool`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data_type: Option<String>,
    /// The attribute source: `tag`, `resource`, or `scope`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub key_type: Option<String>,
}

/// Filters on an aggregated column.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AlertRuleHaving {
    /// The aggregated column.
    pub column_name: String,
    /// One of `=`, `!=`, `>`, `>=`, `<`, `<=`.
    pub operator: String,
    /// The value to compare against.
    pub value: f64,
}

/// Selects and aggregates a metric to alert on.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AlertRuleQuery {
    /// The metric name, e.g. `stat_consumer_video_bitrate`. Required.
    pub metric: String,
    /// The metric's category, e.g. `bitrate`, `packet_loss`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metric_category: Option<String>,
    /// Reduces a series over time: `latest`, `sum`, `avg`, `min`, `max`, `count`,
    /// `count_distinct`, `rate`, `increase`, or a percentile `p05`..`p99`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub time_aggregation: Option<String>,
    /// Reduces across series: `sum`, `avg`, `min`, `max`, `count`, or `p50`..`p99`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub space_aggregation: Option<String>,
    /// The metric's value type: `float64`, `int64`, or `string`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data_type: Option<String>,
    /// The query step interval, in seconds.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub step_interval_seconds: Option<u32>,
    /// Filters narrowing the query.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub filter: Vec<AlertRuleFilter>,
    /// Attributes to group by.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub group_by: Vec<AlertRuleGroupBy>,
    /// Post-aggregation filters.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub having: Vec<AlertRuleHaving>,
}

impl AlertRuleQuery {
    /// A query over a single metric, with no aggregation or filters.
    pub fn metric(metric: impl Into<String>) -> Self {
        Self {
            metric: metric.into(),
            ..Default::default()
        }
    }
}

/// Compares the query's aggregated value against a threshold.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AlertRuleCondition {
    /// The comparison operator. Required.
    pub operator: AlertConditionOperator,
    /// The threshold to compare against. Required.
    pub threshold: f64,
    /// Overrides the query's time aggregation for the check.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub time_aggregation: Option<String>,
    /// Overrides the query's space aggregation for the check.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub space_aggregation: Option<String>,
    /// Require at least this many sessions before the rule can fire.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub minimum_session_gate: Option<f64>,
    /// The threshold's unit.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub unit: Option<String>,
    /// How the threshold must be met over the window. Defaults to
    /// [`AlertMatchType::AT_LEAST_ONCE`].
    #[serde(skip_serializing_if = "Option::is_none")]
    pub match_type: Option<AlertMatchType>,
    /// Require a minimum number of data points.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub require_min_points: Option<bool>,
    /// The minimum number of data points required.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub required_num_points: Option<u32>,
    /// How often the condition is evaluated, in seconds. Defaults to 60.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub frequency_seconds: Option<u32>,
}

impl AlertRuleCondition {
    /// A condition comparing the aggregated value against `threshold`.
    pub fn new(operator: AlertConditionOperator, threshold: f64) -> Self {
        Self {
            operator,
            threshold,
            time_aggregation: None,
            space_aggregation: None,
            minimum_session_gate: None,
            unit: None,
            match_type: None,
            require_min_points: None,
            required_num_points: None,
            frequency_seconds: None,
        }
    }
}

/// Controls how often and over what window the rule runs.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AlertRuleEvaluation {
    /// How often the rule is evaluated, in seconds.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub frequency_seconds: Option<u32>,
    /// The evaluation window, in seconds.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub window_seconds: Option<u32>,
}

/// An alert rule's config: a metric `query` and a threshold `condition` (both
/// required), plus optional evaluation, absent-data alerting, and a formula over
/// `additional_queries`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AlertRuleConfig {
    /// The metric to alert on. Required.
    pub query: AlertRuleQuery,
    /// The threshold check. Required.
    pub condition: AlertRuleCondition,
    /// Free-form labels attached to fired incidents.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub labels: HashMap<String, String>,
    /// Evaluation frequency and window.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub evaluation: Option<AlertRuleEvaluation>,
    /// Alert when the metric stops reporting.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub absent_data_alert: Option<AbsentDataAlert>,
    /// Extra named queries (keys `B`..`Z`) referenced by `formula`.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub additional_queries: HashMap<String, AlertRuleQuery>,
    /// A formula combining `query` and `additional_queries`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub formula: Option<String>,
    /// Collapses each series to a single value before the threshold check.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reduce_to: Option<AlertReduceTo>,
}

impl AlertRuleConfig {
    /// A config from a query and a condition, leaving everything else default.
    pub fn new(query: AlertRuleQuery, condition: AlertRuleCondition) -> Self {
        Self {
            query,
            condition,
            labels: HashMap::new(),
            evaluation: None,
            absent_data_alert: None,
            additional_queries: HashMap::new(),
            formula: None,
            reduce_to: None,
        }
    }
}

/* --------------------------------- response ---------------------------------- */

/// A configured alert rule.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AlertRule {
    /// The rule's database id.
    pub id: Option<String>,
    /// The rule id.
    #[serde(default, deserialize_with = "crate::common::null_to_default")]
    pub alert_rule_id: String,
    /// The rule's display name.
    pub name: Option<String>,
    /// The rule's severity.
    pub severity: Option<AlertSeverity>,
    /// The rule's description.
    pub description: Option<String>,
    /// A short summary applied to fired incidents.
    pub summary: Option<String>,
    /// The rule's domain.
    pub domain: Option<AlertDomain>,
    /// The rule's config.
    pub rule_config: Option<AlertRuleConfig>,
    /// The notification channels this rule delivers to.
    #[serde(default, deserialize_with = "crate::common::null_to_default")]
    pub notification_channel_ids: Vec<String>,
    /// Whether the rule is active or paused.
    pub status: Option<AlertRuleStatus>,
    /// The rule's version.
    pub version: Option<i64>,
    /// When the rule last fired.
    pub last_triggered: Option<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>,
}

/* --------------------------------- params ------------------------------------ */

/// The parameters for [`AlertRulesResource::create`].
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateAlertRuleParams {
    /// The rule's display name. Required.
    pub name: String,
    /// The rule's severity. Required.
    pub severity: AlertSeverity,
    /// The rule's config. Required.
    pub rule_config: AlertRuleConfig,
    /// The rule's description.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// A summary applied to the underlying alert. Not stored on the rule record.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub summary: Option<String>,
    /// Whether the alert is active. Surfaces as `status`, not a returned
    /// `enabled` field.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enabled: Option<bool>,
    /// The rule's domain.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub domain: Option<AlertDomain>,
    /// Used when building the alert query. Not persisted on the rule record.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub time_aggregation: Option<String>,
    /// The notification channels to deliver to.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub notification_channel_ids: Vec<String>,
}

impl CreateAlertRuleParams {
    /// The required fields, leaving everything else unset.
    pub fn new(
        name: impl Into<String>,
        severity: AlertSeverity,
        rule_config: AlertRuleConfig,
    ) -> Self {
        Self {
            name: name.into(),
            severity,
            rule_config,
            description: None,
            summary: None,
            enabled: None,
            domain: None,
            time_aggregation: None,
            notification_channel_ids: Vec::new(),
        }
    }
}

/// The parameters for [`AlertRulesResource::update`]. Only the set fields change.
#[derive(Debug, Clone, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct UpdateAlertRuleParams {
    /// A new display name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// A new severity.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub severity: Option<AlertSeverity>,
    /// A new config.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rule_config: Option<AlertRuleConfig>,
    /// A new description.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// A new summary.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub summary: Option<String>,
    /// Activate or pause the rule.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enabled: Option<bool>,
    /// A new domain.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub domain: Option<AlertDomain>,
    /// A new query-time aggregation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub time_aggregation: Option<String>,
    /// New notification channels.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub notification_channel_ids: Vec<String>,
}

/// The query parameters for [`AlertRulesResource::list`].
#[derive(Debug, Clone, Default)]
pub struct ListAlertRulesParams {
    /// 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>,
    /// Filters by region.
    pub region: Option<String>,
    /// Filters by status.
    pub status: Option<AlertRuleStatus>,
    /// Filters by metric category.
    pub metric_category: Option<String>,
    /// Filters by domain. The server defaults to [`AlertDomain::RTC`] when
    /// omitted — pass [`AlertDomain::AGENT`] to see agent-domain rules.
    pub domain: Option<AlertDomain>,
}

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

/* -------------------------------- resource ----------------------------------- */

/// The alert-rules API. Reached via [`Client::alert_rules`].
#[derive(Debug, Clone, Copy)]
pub struct AlertRulesResource<'a> {
    client: &'a Client,
}

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

    /// Creates an alert rule.
    pub async fn create(&self, params: CreateAlertRuleParams) -> Result<AlertRule> {
        self.client
            .wrapped(Method::POST, PATH, "alertRule", CallOptions::json(&params)?)
            .await
    }

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

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

    /// Fetches an alert rule by id.
    pub async fn get(&self, alert_rule_id: &str) -> Result<AlertRule> {
        let path = format!("{PATH}/{}", escape(alert_rule_id));
        self.client
            .wrapped(Method::GET, &path, "alertRule", CallOptions::new())
            .await
    }

    /// Updates an alert rule.
    pub async fn update(
        &self,
        alert_rule_id: &str,
        params: UpdateAlertRuleParams,
    ) -> Result<AlertRule> {
        let path = format!("{PATH}/{}", escape(alert_rule_id));
        self.client
            .wrapped(Method::PUT, &path, "alertRule", CallOptions::json(&params)?)
            .await
    }

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

    fn fetcher(&self, params: &ListAlertRulesParams) -> 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("region", params.region.as_deref())
                    .opt_str(
                        "status",
                        params.status.as_ref().map(AlertRuleStatus::as_str),
                    )
                    .opt_str("metricCategory", params.metric_category.as_deref())
                    .opt_str("domain", params.domain.as_ref().map(AlertDomain::as_str))
                    .into_pairs();
                client
                    .json::<Value>(Method::GET, PATH, CallOptions::new().query(query))
                    .await
            })
        })
    }
}

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

    #[test]
    fn create_serializes_the_typed_config() {
        let params = CreateAlertRuleParams::new(
            "High bitrate",
            AlertSeverity::WARNING,
            AlertRuleConfig::new(
                AlertRuleQuery::metric("stat_consumer_video_bitrate"),
                AlertRuleCondition::new(AlertConditionOperator::GREATER_THAN, 2500.0),
            ),
        );
        assert_eq!(
            serde_json::to_value(&params).unwrap(),
            json!({
                "name": "High bitrate",
                "severity": "warning",
                "ruleConfig": {
                    "query": {"metric": "stat_consumer_video_bitrate"},
                    "condition": {"operator": ">", "threshold": 2500.0},
                },
            })
        );
    }

    #[test]
    fn an_unknown_severity_on_a_response_does_not_fail() {
        // The config + enums ride on the response, so a value this SDK predates
        // must round-trip rather than break the whole rule.
        let rule: AlertRule = serde_json::from_value(json!({
            "alertRuleId": "ar-1",
            "severity": "catastrophic",
            "notificationChannelIds": null,
        }))
        .unwrap();
        assert_eq!(rule.severity.unwrap().as_str(), "catastrophic");
        assert!(rule.notification_channel_ids.is_empty());
    }
}