Skip to main content

subc_control/
scope_watch.rs

1//! Scope lifecycle subscriptions, separate from the exhaustive control enums.
2
3use serde::{Deserialize, Serialize};
4use subc_protocol::Principal;
5
6/// An owner-qualified scope reference, without selecting an epoch.
7#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
8#[serde(deny_unknown_fields)]
9pub struct ScopeRef {
10    pub owner: Principal,
11    #[serde(rename = "ref")]
12    pub scope_ref: String,
13}
14
15/// One epoch whose lifetime the caller wants to observe.
16#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
17#[serde(deny_unknown_fields)]
18pub struct ScopeWatchSelector {
19    pub scope_ref: ScopeRef,
20    pub epoch: u64,
21}
22
23/// Open an immutable set of at most 256 scope epochs on channel zero.
24#[non_exhaustive]
25#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
26pub struct ScopeWatchRequest {
27    op: ScopeWatchOp,
28    pub scopes: Vec<ScopeWatchSelector>,
29}
30
31impl ScopeWatchRequest {
32    pub const OP: &'static str = crate::ops::SCOPE_WATCH;
33
34    pub fn new(scopes: Vec<ScopeWatchSelector>) -> Self {
35        Self {
36            op: ScopeWatchOp::Watch,
37            scopes,
38        }
39    }
40}
41
42open_string_enum! {
43    /// Current state of a requested epoch; unknown never establishes liveness.
44    ScopeWatchStatus {
45        Live => "live",
46        Ended => "ended",
47        Superseded => "superseded",
48        UnknownScope => "unknown",
49    }
50}
51
52/// One entry in the initial snapshot, in request order.
53#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
54pub struct ScopeWatchState {
55    pub scope_ref: ScopeRef,
56    pub epoch: u64,
57    pub status: ScopeWatchStatus,
58    #[serde(default, skip_serializing_if = "Option::is_none")]
59    pub by_epoch: Option<u64>,
60}
61
62/// Initial nonterminal RESPONSE, followed by lifecycle STREAM_DATA pushes.
63#[non_exhaustive]
64#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
65pub struct ScopeWatchResponse {
66    op: ScopeWatchOp,
67    pub scopes: Vec<ScopeWatchState>,
68}
69
70impl ScopeWatchResponse {
71    pub fn new(scopes: Vec<ScopeWatchState>) -> Self {
72        Self {
73            op: ScopeWatchOp::Watch,
74            scopes,
75        }
76    }
77}
78
79open_string_enum! {
80    /// Terminal lifecycle transition for the watched epoch.
81    ScopeWatchEvent {
82        Ended => "ended",
83        Superseded => "superseded",
84    }
85}
86
87/// A terminal event delivered at most once per selector within one watch.
88#[non_exhaustive]
89#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
90pub struct ScopeWatchPush {
91    op: ScopeWatchOp,
92    pub event: ScopeWatchEvent,
93    pub scope_ref: ScopeRef,
94    pub epoch: u64,
95    #[serde(default, skip_serializing_if = "Option::is_none")]
96    pub by_epoch: Option<u64>,
97}
98
99impl ScopeWatchPush {
100    pub fn new(
101        event: ScopeWatchEvent,
102        scope_ref: ScopeRef,
103        epoch: u64,
104        by_epoch: Option<u64>,
105    ) -> Self {
106        Self {
107            op: ScopeWatchOp::Watch,
108            event,
109            scope_ref,
110            epoch,
111            by_epoch,
112        }
113    }
114}
115
116#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
117enum ScopeWatchOp {
118    #[serde(rename = "scope.watch")]
119    Watch,
120}
121
122#[cfg(test)]
123mod tests {
124    use super::*;
125    use serde_json::json;
126
127    #[test]
128    fn scope_watch_wire_shapes_require_op_and_accept_future_fields() {
129        let selector: ScopeWatchSelector = serde_json::from_value(json!({
130            "scope_ref":{"owner":{"kind":"reserved","module_id":"owner"},"ref":"session"},
131            "epoch":7
132        }))
133        .unwrap();
134        let request = ScopeWatchRequest::new(vec![selector.clone()]);
135        assert_eq!(
136            serde_json::to_value(&request).unwrap(),
137            json!({
138                "op":"scope.watch", "scopes":[selector]
139            })
140        );
141        let snapshot = json!({"op":"scope.watch","scopes":[{
142            "scope_ref":selector.scope_ref,"epoch":7,"status":"superseded","by_epoch":8
143        }]});
144        let reply: ScopeWatchResponse = serde_json::from_value(snapshot.clone()).unwrap();
145        assert_eq!(reply.scopes[0].status, ScopeWatchStatus::Superseded);
146        assert_eq!(serde_json::to_value(reply).unwrap(), snapshot);
147        for (event, by_epoch) in [
148            (ScopeWatchEvent::Ended, None),
149            (ScopeWatchEvent::Superseded, Some(8)),
150        ] {
151            let push = ScopeWatchPush::new(event, selector.scope_ref.clone(), 7, by_epoch);
152            let mut value = serde_json::to_value(&push).unwrap();
153            assert_eq!(value.get("by_epoch").is_some(), by_epoch.is_some());
154            value["future"] = json!(true);
155            assert_eq!(
156                serde_json::from_value::<ScopeWatchPush>(value.clone()).unwrap(),
157                push
158            );
159            value["op"] = json!("scope.describe");
160            assert!(serde_json::from_value::<ScopeWatchPush>(value).is_err());
161        }
162        assert_eq!(
163            serde_json::from_value::<ScopeWatchEvent>(json!("future")).unwrap(),
164            ScopeWatchEvent::Unknown("future".into())
165        );
166        assert!(serde_json::from_value::<ScopeWatchStatus>(json!(false)).is_err());
167    }
168}