Skip to main content

subc_daemon/control/
activity.rs

1use super::*;
2
3/// Observe test request cancellation relative to the connection's cleanup.
4#[cfg(test)]
5pub(super) struct ActivityRequestPause {
6    pub(super) connection: ConnectionId,
7    pub(super) started: tokio::sync::Notify,
8    pub(super) cancelled: tokio::sync::Notify,
9    pub(super) cleanup_started: std::sync::atomic::AtomicBool,
10    pub(super) cancelled_after_cleanup: std::sync::atomic::AtomicBool,
11}
12
13#[cfg(test)]
14struct ActivityRequestCancellation(Arc<ActivityRequestPause>);
15
16#[cfg(test)]
17impl Drop for ActivityRequestCancellation {
18    fn drop(&mut self) {
19        self.0.cancelled_after_cleanup.store(
20            self.0
21                .cleanup_started
22                .load(std::sync::atomic::Ordering::Acquire),
23            std::sync::atomic::Ordering::Release,
24        );
25        self.0.cancelled.notify_one();
26    }
27}
28
29impl ControlHandler {
30    /// Open the ledger on its own writer thread; an unavailable sink does not
31    /// prevent the daemon from serving routing or supervisor requests.
32    pub fn with_activity_ledger(mut self, run_dir: &Path, incarnation: String) -> Self {
33        self.activity = Some(crate::activity::ActivityLedger::open(
34            run_dir.join("activity.jsonl"),
35            incarnation,
36        ));
37        self.supervisor.set_activity(self.activity.clone());
38        self
39    }
40}
41
42impl ControlHandler {
43    pub(crate) fn with_activity_ledger_config(
44        mut self,
45        run_dir: &Path,
46        incarnation: String,
47        config: crate::activity::ActivityConfig,
48    ) -> Self {
49        self.activity = Some(crate::activity::ActivityLedger::open_config(
50            run_dir.join("activity.jsonl"),
51            incarnation,
52            config,
53        ));
54        self.supervisor.set_activity(self.activity.clone());
55        self
56    }
57
58    pub(crate) async fn configure_activity(
59        &self,
60        config: crate::activity::ActivityConfig,
61    ) -> Result<(), &'static str> {
62        match &self.activity {
63            Some(ledger) => ledger.configure(config).await,
64            None => Ok(()),
65        }
66    }
67
68    pub(super) fn cancel_activity_subscription(
69        &self,
70        ctx: &RouteCtx,
71        frame: &Frame,
72    ) -> Result<bool, RouterError> {
73        let key = (ctx.connection_id, frame.header.corr);
74        let mut streams = self
75            .activity_streams
76            .lock()
77            .unwrap_or_else(|p| p.into_inner());
78        // A subscription still being set up is cancelled through the
79        // reservation the reader made, under the same stream lock.
80        match streams.remove(&key) {
81            Some(task) => task.abort(),
82            None if self.activity_reservations.cancel(key) => {}
83            None => return Ok(false),
84        }
85        drop(streams);
86        let end = Frame::build_with_version(
87            response_version(frame),
88            FrameType::StreamEnd,
89            control_flags(),
90            0,
91            0,
92            frame.header.corr,
93            Vec::new(),
94        )
95        .map_err(|error| RouterError::backend(0, frame.header.corr, error.to_string()))?;
96        let sink = ctx.egress.clone();
97        tokio::spawn(async move {
98            let _ = sink.send(end).await;
99        });
100        Ok(true)
101    }
102
103    pub(super) async fn handle_activity_read(
104        &self,
105        ctx: &RouteCtx,
106        frame: Frame,
107    ) -> Result<Vec<Frame>, RouterError> {
108        #[cfg(test)]
109        {
110            let pause = self
111                .activity_request_pause
112                .lock()
113                .unwrap()
114                .clone()
115                .filter(|pause| pause.connection == ctx.connection_id);
116            if let Some(pause) = pause {
117                let _cancelled = ActivityRequestCancellation(pause.clone());
118                pause.started.notify_one();
119                std::future::pending::<()>().await;
120            }
121        }
122        use subc_control::{
123            ActivityQueryRequest, ActivitySubscribeRequest, ActivitySubscribeResponse,
124            ACTIVITY_MALFORMED, ACTIVITY_READ_FORBIDDEN, ACTIVITY_UNAVAILABLE,
125        };
126        #[derive(Deserialize)]
127        struct Identity {
128            #[serde(default)]
129            consumer_identity: Option<ConsumerIdentity>,
130        }
131        // A registration channel or claim-bound connection carries its module in
132        // its binding, so no request field can name another principal, and its
133        // subscription ends when the bound spawn's authority does.
134        let mut bound_spawn = None;
135        let legacy = match self.activity_reader(ctx.connection_id) {
136            channel_operations::ActivityReader::Module { module_id, spawn } => {
137                bound_spawn = Some(spawn);
138                Some(Ok(Principal::Reserved { module_id }))
139            }
140            // Refused outright: falling back to `direct` would admit it.
141            channel_operations::ActivityReader::Refused => {
142                return Ok(vec![control_error_frame(
143                    &frame,
144                    ACTIVITY_READ_FORBIDDEN,
145                    "helper, relay and retired connections cannot read activity",
146                )?]);
147            }
148            channel_operations::ActivityReader::Legacy => None,
149        };
150        // A registered module connection already identifies its caller. Ignore
151        // consumer_identity there so a module cannot borrow a mirror's identity.
152        // Only separate consumer connections use the Direct/nonce trust boundary.
153        let principal = match legacy {
154            Some(principal) => principal,
155            None => match self
156                .forwarding
157                .module_id_for_connection(ctx.connection_id)
158                .map_err(RouterError::Forwarding)?
159            {
160                Some(module_id) => Ok(Principal::Reserved { module_id }),
161                None => {
162                    let identity: Identity = match serde_json::from_slice(&frame.body) {
163                        Ok(identity) => identity,
164                        Err(_) => {
165                            return Ok(vec![control_error_frame(
166                                &frame,
167                                ACTIVITY_MALFORMED,
168                                "malformed activity read",
169                            )?])
170                        }
171                    };
172                    self.route_open_principal(
173                        ctx.connection_id,
174                        &frame,
175                        identity.consumer_identity,
176                    )?
177                }
178            },
179        };
180        let admitted = matches!(principal, Ok(Principal::Direct))
181            || matches!(&principal, Ok(Principal::Reserved { module_id }) if module_id == "callosum" || module_id == "ckbus");
182        if !admitted {
183            return Ok(vec![control_error_frame(
184                &frame,
185                ACTIVITY_READ_FORBIDDEN,
186                "activity reads require an operator or trusted mirror principal",
187            )?]);
188        }
189        let Some(ledger) = &self.activity else {
190            return Ok(vec![control_error_frame(
191                &frame,
192                ACTIVITY_UNAVAILABLE,
193                "activity ledger unavailable",
194            )?]);
195        };
196        if serde_json::from_slice::<ControlOpProbe>(&frame.body)
197            .is_ok_and(|probe| probe.op == ops::ACTIVITY_QUERY)
198        {
199            let result = match serde_json::from_slice::<ActivityQueryRequest>(&frame.body) {
200                Ok(request) => ledger.query(request).await,
201                Err(_) => Err(ACTIVITY_MALFORMED),
202            };
203            return match result {
204                Ok(reply) => Ok(vec![control_response_body_frame(
205                    &frame,
206                    &reply,
207                    ops::ACTIVITY_QUERY,
208                )?]),
209                Err(code) => Ok(vec![control_error_frame(
210                    &frame,
211                    code,
212                    "activity query refused",
213                )?]),
214            };
215        }
216        let request: ActivitySubscribeRequest = match serde_json::from_slice(&frame.body) {
217            Ok(request) => request,
218            Err(_) => {
219                return Ok(vec![control_error_frame(
220                    &frame,
221                    ACTIVITY_MALFORMED,
222                    "malformed activity subscription",
223                )?])
224            }
225        };
226        let mut subscription = match ledger.subscribe(request.since).await {
227            Ok(subscription) => subscription,
228            Err(code) => {
229                return Ok(vec![control_error_frame(
230                    &frame,
231                    code,
232                    "activity subscription refused",
233                )?])
234            }
235        };
236        let key = (ctx.connection_id, frame.header.corr);
237        let sink = ctx.egress.clone();
238        let mut streams = self
239            .activity_streams
240            .lock()
241            .unwrap_or_else(|p| p.into_inner());
242        streams.retain(|_, task| !task.is_finished());
243        if self.activity_reservations.cancelled(key) {
244            return Ok(Vec::new()); // Its CANCEL already sent STREAM_END.
245        }
246        if streams.get(&key).is_some_and(|task| !task.is_finished()) {
247            return Ok(vec![control_error_frame(
248                &frame,
249                "duplicate_subscription",
250                "activity subscription correlation id already in use",
251            )?]);
252        }
253        let stream = async move {
254            loop {
255                let entry = if let Some(entry) = subscription.replay.pop_front() {
256                    Some(entry)
257                } else {
258                    subscription.receiver.recv().await
259                };
260                let Some(entry) = entry else {
261                    break;
262                };
263                let Ok(body) = serde_json::to_vec(&ActivitySubscribeResponse { entry }) else {
264                    return;
265                };
266                let Ok(next) = Frame::build_with_version(
267                    response_version(&frame),
268                    FrameType::StreamData,
269                    control_flags(),
270                    0,
271                    0,
272                    frame.header.corr,
273                    body,
274                ) else {
275                    return;
276                };
277                if sink.send(next).await.is_err() {
278                    return;
279                }
280            }
281            // Dropping a full subscriber's sender drains its accepted entries
282            // before the terminal error, preserving their order on the wire.
283            if let Some(code) = subscription.terminal_code() {
284                if let Ok(end) =
285                    control_error_frame(&frame, code, "activity subscriber fell behind")
286                {
287                    let _ = sink.send(end).await;
288                }
289            }
290        };
291        // The spawn's retirement revokes this connection's authority. End the
292        // subscription then, rather than when the connection's close is
293        // eventually processed or the next entry fails to send.
294        let task = tokio::spawn(async move {
295            match bound_spawn {
296                Some(spawn) => {
297                    tokio::select! {
298                        () = stream => {}
299                        () = spawn.wait_closed() => {}
300                    }
301                }
302                None => stream.await,
303            }
304        });
305        streams.insert(key, task.abort_handle());
306        Ok(Vec::new())
307    }
308
309    pub(super) async fn handle_activity_record(
310        &self,
311        ctx: &RouteCtx,
312        frame: Frame,
313    ) -> Result<Vec<Frame>, RouterError> {
314        use subc_control::{
315            ActivityRecordRequest, ActivityRecordResponse, ACTIVITY_ACTOR_UNKNOWN,
316            ACTIVITY_MALFORMED, ACTIVITY_UNAVAILABLE,
317        };
318        let result = async {
319            let module = self
320                .forwarding
321                .module_id_for_connection(ctx.connection_id)
322                .ok()
323                .flatten()
324                .ok_or(ACTIVITY_ACTOR_UNKNOWN)?;
325            let request: ActivityRecordRequest =
326                serde_json::from_slice(&frame.body).map_err(|_| ACTIVITY_MALFORMED)?;
327            crate::activity::validate(&module, &request)?;
328            let actor = self.activity_actor(ctx.connection_id, &module, request.on.as_ref())?;
329            let ledger = self.activity.as_ref().ok_or(ACTIVITY_UNAVAILABLE)?;
330            let at_ms = std::time::SystemTime::now()
331                .duration_since(std::time::UNIX_EPOCH)
332                .unwrap_or_default()
333                .as_millis() as u64;
334            ledger.record(module, request, actor, at_ms).await
335        }
336        .await;
337        match result {
338            Ok(entry) => Ok(vec![control_response_body_frame(
339                &frame,
340                &ActivityRecordResponse { seq: entry.seq },
341                "activity.record",
342            )?]),
343            Err(code) => Ok(vec![control_error_frame(
344                &frame,
345                code,
346                "activity recording refused",
347            )?]),
348        }
349    }
350
351    fn activity_actor(
352        &self,
353        connection: ConnectionId,
354        module: &str,
355        on: Option<&subc_control::ActivityOn>,
356    ) -> Result<subc_control::ActivityActor, &'static str> {
357        use crate::forwarding::{DataRoute, DataRouteState};
358        use subc_control::{ActivityActor, ActivityOn, ACTIVITY_ACTOR_UNKNOWN};
359        let principal = |id: &str| Principal::Reserved {
360            module_id: id.to_owned(),
361        };
362        let mut actor = ActivityActor {
363            principal: principal(module),
364            scope_owner: None,
365            agent_id: None,
366            run_id: None,
367            flow_id: None,
368            project_root: None,
369            workdir: None,
370            project_id: None,
371        };
372        let scope = match on {
373            None => return Ok(actor),
374            Some(ActivityOn::Scope(scope)) => {
375                let selector = subc_protocol::scope::ScopeSelector::new(
376                    principal(module),
377                    scope.scope_ref.clone(),
378                    Some(scope.epoch),
379                );
380                self.scopes
381                    .read()
382                    .map_err(|_| ACTIVITY_ACTOR_UNKNOWN)?
383                    .attribute(&principal(module), module, &selector, true)
384                    .map_err(|_| ACTIVITY_ACTOR_UNKNOWN)?
385            }
386            Some(ActivityOn::Route(route)) => {
387                let DataRoute::Module(DataRouteState::Bound(binding)) = self
388                    .forwarding
389                    .lookup_data_route(connection, route.channel, route.epoch)
390                    .map_err(|_| ACTIVITY_ACTOR_UNKNOWN)?
391                else {
392                    return Err(ACTIVITY_ACTOR_UNKNOWN);
393                };
394                if binding.module_id != module {
395                    return Err(ACTIVITY_ACTOR_UNKNOWN);
396                }
397                actor.principal = binding.principal.clone();
398                actor.project_root = binding
399                    .project_root
400                    .as_ref()
401                    .map(|root| root.as_path().to_path_buf());
402                let Some(bound) = &binding.scope else {
403                    return Ok(actor);
404                };
405                let owner = principal(&bound.owner);
406                let selector = subc_protocol::scope::ScopeSelector::new(
407                    owner.clone(),
408                    bound.scope_ref.clone(),
409                    Some(bound.tag.scope_epoch),
410                );
411                let admitted = self
412                    .scopes
413                    .read()
414                    .map_err(|_| ACTIVITY_ACTOR_UNKNOWN)?
415                    .attribute(&owner, module, &selector, true)
416                    .map_err(|_| ACTIVITY_ACTOR_UNKNOWN)?;
417                if admitted.tag != bound.tag {
418                    return Err(ACTIVITY_ACTOR_UNKNOWN);
419                }
420                admitted
421            }
422        };
423        actor.scope_owner = Some(scope.stamp.owner);
424        actor.agent_id = scope.stamp.attributes.agent_id;
425        actor.run_id = scope.stamp.attributes.run_id;
426        actor.flow_id = scope.stamp.attributes.flow_id;
427        actor.workdir = scope.stamp.workdir.map(std::path::PathBuf::from);
428        actor.project_id = scope.stamp.project_id;
429        Ok(actor)
430    }
431}