Skip to main content

subc_client_rs/
activity.rs

1//! Activity ledger helpers and refusal classification.
2
3use std::{error::Error, fmt};
4
5pub use subc_control::{
6    ActivityActor, ActivityCursor, ActivityEntry, ActivityOn, ActivityQueryRequest,
7    ActivityQueryResponse, ActivityRecordRequest, ActivityRecordResponse, ActivityRoute,
8    ActivityScope, ActivitySubject, ActivitySubscribeRequest, ActivitySubscribeResponse,
9    ACTIVITY_ACTOR_UNKNOWN, ACTIVITY_CURSOR_INCARNATION_MISMATCH, ACTIVITY_CURSOR_TOO_OLD,
10    ACTIVITY_KIND_FORBIDDEN, ACTIVITY_LEDGER_CAPABILITY, ACTIVITY_MALFORMED, ACTIVITY_RATE_LIMITED,
11    ACTIVITY_READ_FORBIDDEN, ACTIVITY_SUBSCRIBER_LAGGED, ACTIVITY_TOO_LARGE, ACTIVITY_UNAVAILABLE,
12};
13use subc_protocol::{ErrorBody, Frame, FrameType};
14use tokio::{sync::oneshot, time::Instant};
15
16use crate::{consumer::Subscription, CallError, ModuleHandle, CATALOG_UPDATE_TIMEOUT};
17
18/// A daemon activity refusal. Unknown codes remain readable for forward compatibility.
19#[derive(Debug, Clone, PartialEq, Eq)]
20#[non_exhaustive]
21pub enum ActivityRefusal {
22    KindForbidden,
23    ActorUnknown,
24    RateLimited,
25    ReadForbidden,
26    TooLarge,
27    Malformed,
28    Unavailable,
29    CursorIncarnationMismatch,
30    CursorTooOld,
31    SubscriberLagged,
32    Other(String),
33}
34
35impl ActivityRefusal {
36    pub fn from_code(code: &str) -> Self {
37        match code {
38            ACTIVITY_KIND_FORBIDDEN => Self::KindForbidden,
39            ACTIVITY_ACTOR_UNKNOWN => Self::ActorUnknown,
40            ACTIVITY_RATE_LIMITED => Self::RateLimited,
41            ACTIVITY_READ_FORBIDDEN => Self::ReadForbidden,
42            ACTIVITY_TOO_LARGE => Self::TooLarge,
43            ACTIVITY_MALFORMED => Self::Malformed,
44            ACTIVITY_UNAVAILABLE => Self::Unavailable,
45            ACTIVITY_CURSOR_INCARNATION_MISMATCH => Self::CursorIncarnationMismatch,
46            ACTIVITY_CURSOR_TOO_OLD => Self::CursorTooOld,
47            ACTIVITY_SUBSCRIBER_LAGGED => Self::SubscriberLagged,
48            other => Self::Other(other.to_owned()),
49        }
50    }
51
52    pub fn code(&self) -> &str {
53        match self {
54            Self::KindForbidden => ACTIVITY_KIND_FORBIDDEN,
55            Self::ActorUnknown => ACTIVITY_ACTOR_UNKNOWN,
56            Self::RateLimited => ACTIVITY_RATE_LIMITED,
57            Self::ReadForbidden => ACTIVITY_READ_FORBIDDEN,
58            Self::TooLarge => ACTIVITY_TOO_LARGE,
59            Self::Malformed => ACTIVITY_MALFORMED,
60            Self::Unavailable => ACTIVITY_UNAVAILABLE,
61            Self::CursorIncarnationMismatch => ACTIVITY_CURSOR_INCARNATION_MISMATCH,
62            Self::CursorTooOld => ACTIVITY_CURSOR_TOO_OLD,
63            Self::SubscriberLagged => ACTIVITY_SUBSCRIBER_LAGGED,
64            Self::Other(code) => code,
65        }
66    }
67}
68
69/// Recording never retries: a lost reply does not imply that the append failed.
70#[derive(Debug)]
71#[non_exhaustive]
72pub enum ActivityRecordError {
73    /// The HELLO_ACK lacked `activity-ledger/v1`; nothing was sent.
74    NotSupported,
75    Refused {
76        reason: ActivityRefusal,
77        body: Box<ErrorBody>,
78    },
79    /// The daemon may have appended the event before this deadline or connection loss.
80    Timeout,
81    ConnectionClosed,
82    Protocol(String),
83}
84
85impl ActivityRecordError {
86    pub fn code(&self) -> Option<&str> {
87        match self {
88            Self::Refused { body, .. } => Some(&body.code),
89            _ => None,
90        }
91    }
92}
93
94impl fmt::Display for ActivityRecordError {
95    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
96        match self {
97            Self::NotSupported => f.write_str("daemon does not support activity-ledger/v1"),
98            Self::Refused { body, .. } => write!(
99                f,
100                "activity.record refused: {}: {}",
101                body.code, body.message
102            ),
103            Self::Timeout => f.write_str("activity.record timed out; append outcome unknown"),
104            Self::ConnectionClosed => {
105                f.write_str("activity.record connection closed; append outcome unknown")
106            }
107            Self::Protocol(message) => write!(f, "activity.record protocol error: {message}"),
108        }
109    }
110}
111impl Error for ActivityRecordError {}
112
113impl ModuleHandle {
114    /// Append one event through the module connection, after checking the negotiated
115    /// capability. The daemon verifies citations and stamps the actor. Use ids in
116    /// summaries and details, never secret values. A successful reply is durable;
117    /// timeout and connection loss must not be retried blindly.
118    pub async fn record_activity(
119        &self,
120        request: ActivityRecordRequest,
121    ) -> Result<ActivityRecordResponse, ActivityRecordError> {
122        if !self.shared.supports_activity {
123            return Err(ActivityRecordError::NotSupported);
124        }
125        let body = serde_json::to_vec(&request)
126            .map_err(|err| ActivityRecordError::Protocol(err.to_string()))?;
127        let (corr, writer, rx) = {
128            let mut inner = self.shared.lock_inner();
129            if inner.closed {
130                return Err(ActivityRecordError::ConnectionClosed);
131            }
132            let writer = inner
133                .writer
134                .clone()
135                .ok_or(ActivityRecordError::ConnectionClosed)?;
136            let corr = crate::next_module_control_corr(&mut inner)
137                .ok_or(ActivityRecordError::ConnectionClosed)?;
138            let (tx, rx) = oneshot::channel();
139            inner.pending_activity_records.insert(corr, tx);
140            (corr, writer, rx)
141        };
142        // Cancellation removes the waiter even when the caller drops mid-send.
143        let _guard = RecordWaiter {
144            handle: self.clone(),
145            corr,
146        };
147        let frame = Frame::build_with_version(
148            self.shared.negotiated_ver,
149            FrameType::Request,
150            crate::control_flags(),
151            0,
152            0,
153            corr,
154            body,
155        )
156        .map_err(|err| ActivityRecordError::Protocol(err.to_string()))?;
157        let deadline = Instant::now() + CATALOG_UPDATE_TIMEOUT;
158        let reply = tokio::time::timeout_at(deadline, async {
159            writer
160                .send(frame)
161                .await
162                .map_err(|_| ActivityRecordError::ConnectionClosed)?;
163            rx.await.map_err(|_| ActivityRecordError::ConnectionClosed)
164        })
165        .await
166        .map_err(|_| ActivityRecordError::Timeout)??;
167        match reply.header.ty {
168            FrameType::Response => serde_json::from_slice(&reply.body)
169                .map_err(|err| ActivityRecordError::Protocol(err.to_string())),
170            FrameType::Error => {
171                let body: ErrorBody = serde_json::from_slice(&reply.body)
172                    .map_err(|err| ActivityRecordError::Protocol(err.to_string()))?;
173                Err(ActivityRecordError::Refused {
174                    reason: ActivityRefusal::from_code(&body.code),
175                    body: Box::new(body),
176                })
177            }
178            other => Err(ActivityRecordError::Protocol(format!(
179                "unexpected terminal frame: {other:?}"
180            ))),
181        }
182    }
183}
184
185struct RecordWaiter {
186    handle: ModuleHandle,
187    corr: u64,
188}
189impl Drop for RecordWaiter {
190    fn drop(&mut self) {
191        self.handle
192            .shared
193            .lock_inner()
194            .pending_activity_records
195            .remove(&self.corr);
196    }
197}
198
199/// A held activity feed. Entries queued before a terminal error are yielded first.
200/// Drop or unsubscribe to cancel; reconnect by querying and using the returned head.
201pub struct ActivitySubscription {
202    pub(crate) inner: Subscription,
203    pub(crate) finished: bool,
204}
205
206impl ActivitySubscription {
207    /// Read the next durable entry. Cursor refusals and lag carry the daemon's code.
208    /// After a terminal result, every subsequent call returns `Ok(None)`.
209    pub async fn next(&mut self) -> Result<Option<ActivityEntry>, ActivityStreamError> {
210        if self.finished {
211            return Ok(None);
212        }
213        if let Some(body) = self.inner.events().recv().await {
214            return serde_json::from_slice::<ActivitySubscribeResponse>(&body)
215                .map(|response| Some(response.entry))
216                .map_err(|err| {
217                    self.finished = true;
218                    let _ = self.inner.unsubscribe();
219                    ActivityStreamError::Decode(err.to_string())
220                });
221        }
222        let terminal = self.inner.closed().await;
223        self.finished = true;
224        match terminal {
225            Ok(()) => Ok(None),
226            Err(err) => Err(ActivityStreamError::from_call_error(err)),
227        }
228    }
229
230    pub fn unsubscribe(&self) -> Result<(), CallError> {
231        self.inner.unsubscribe()
232    }
233}
234
235/// A terminal daemon refusal, transport failure, or invalid entry in an activity feed.
236#[derive(Debug)]
237#[non_exhaustive]
238pub enum ActivityStreamError {
239    Refused {
240        reason: ActivityRefusal,
241        body: Box<ErrorBody>,
242    },
243    Call(CallError),
244    Decode(String),
245}
246
247impl ActivityStreamError {
248    pub(crate) fn from_call_error(err: CallError) -> Self {
249        match err {
250            CallError::Module(body) => Self::Refused {
251                reason: ActivityRefusal::from_code(&body.code),
252                body: Box::new(body),
253            },
254            other => Self::Call(other),
255        }
256    }
257
258    /// The daemon's original code, including unknown future refusal codes.
259    pub fn code(&self) -> Option<&str> {
260        match self {
261            Self::Refused { body, .. } => Some(&body.code),
262            Self::Call(err) => err.code(),
263            Self::Decode(_) => None,
264        }
265    }
266}
267
268impl fmt::Display for ActivityStreamError {
269    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
270        match self {
271            Self::Refused { body, .. } => write!(
272                f,
273                "activity stream refused: {}: {}",
274                body.code, body.message
275            ),
276            Self::Call(err) => err.fmt(f),
277            Self::Decode(message) => write!(f, "invalid activity stream entry: {message}"),
278        }
279    }
280}
281impl Error for ActivityStreamError {
282    fn source(&self) -> Option<&(dyn Error + 'static)> {
283        match self {
284            Self::Call(err) => Some(err),
285            _ => None,
286        }
287    }
288}
289
290#[cfg(test)]
291#[path = "activity_tests.rs"]
292mod tests;