Skip to main content

subc_client_rs/
agent_commands.rs

1//! Module declarations of agent-requested command roots.
2
3use crate::{AgentCommandFinished, AgentCommandRoot, ModuleHandle};
4use subc_protocol::{session::ModuleControlRequestFromModule, ErrorBody, Frame, FrameType};
5use tokio::sync::oneshot;
6
7/// A refused or incomplete agent-command declaration never closes the module's connection.
8#[derive(Debug)]
9#[non_exhaustive]
10pub enum AgentCommandsError {
11    Unsupported,
12    NotSupervised,
13    Refused(Box<ErrorBody>),
14    ConnectionClosed,
15    Timeout,
16    Protocol(String),
17}
18
19impl AgentCommandsError {
20    /// Retryable refusals need a fresh correlation; a closed declaration queue
21    /// additionally needs a current supervised connection. This does not retry automatically.
22    pub fn is_retryable(&self) -> bool {
23        match self {
24            Self::Refused(body) => {
25                subc_protocol::error_codes::is_retryable_agent_commands(&body.code)
26            }
27            Self::Timeout | Self::ConnectionClosed => true,
28            Self::Unsupported | Self::NotSupervised | Self::Protocol(_) => false,
29        }
30    }
31}
32
33impl std::fmt::Display for AgentCommandsError {
34    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
35        match self {
36            Self::Unsupported => f.write_str("daemon does not support agent command declarations"),
37            Self::NotSupervised => {
38                f.write_str("agent commands require this module's supervised connection")
39            }
40            Self::Refused(body) => write!(
41                f,
42                "agent command declaration refused: {} ({})",
43                body.message, body.code
44            ),
45            Self::ConnectionClosed => {
46                f.write_str("connection closed before agent command acknowledgement")
47            }
48            Self::Timeout => f.write_str("agent command acknowledgement timed out"),
49            Self::Protocol(message) => write!(f, "invalid agent command reply: {message}"),
50        }
51    }
52}
53impl std::error::Error for AgentCommandsError {}
54
55impl ModuleHandle {
56    /// Attribute commands to agents rather than to this module. Start times must
57    /// come from `subc_os::process_start_time_ms`. `known` replaces the whole live
58    /// set; omitting it only applies starts and finishes. An older daemon returns
59    /// [`AgentCommandsError::Unsupported`], which callers may safely ignore.
60    pub async fn agent_commands(
61        &self,
62        started: Vec<AgentCommandRoot>,
63        finished: Vec<AgentCommandFinished>,
64        known: Option<Vec<AgentCommandRoot>>,
65    ) -> Result<(), AgentCommandsError> {
66        let shared = self.shared();
67        shared.check_upgrade_fence().map_err(|err| match err {
68            crate::CatalogUpdateError::Rejected(body) => {
69                AgentCommandsError::Refused(Box::new(body))
70            }
71            _ => AgentCommandsError::ConnectionClosed,
72        })?;
73        if !shared.supports_agent_commands {
74            return Err(AgentCommandsError::Unsupported);
75        }
76        let body = serde_json::to_vec(&ModuleControlRequestFromModule::AgentCommands {
77            started,
78            finished,
79            known,
80        })
81        .map_err(|err| AgentCommandsError::Protocol(err.to_string()))?;
82        let (corr, writer, rx) = {
83            let mut inner = shared.lock_inner();
84            if inner.closed {
85                return Err(AgentCommandsError::ConnectionClosed);
86            }
87            let writer = inner
88                .writer
89                .clone()
90                .ok_or(AgentCommandsError::ConnectionClosed)?;
91            let corr = crate::next_module_control_corr(&mut inner)
92                .ok_or(AgentCommandsError::ConnectionClosed)?;
93            let (tx, rx) = oneshot::channel();
94            inner.pending_agent_commands.insert(corr, tx);
95            (corr, writer, rx)
96        };
97        let _guard = Waiter {
98            shared: shared.clone(),
99            corr,
100        };
101        let frame = Frame::build_with_version(
102            shared.negotiated_ver,
103            FrameType::Request,
104            crate::control_flags(),
105            0,
106            0,
107            corr,
108            body,
109        )
110        .map_err(|err| AgentCommandsError::Protocol(err.to_string()))?;
111        let reply = tokio::time::timeout(crate::CATALOG_UPDATE_TIMEOUT, async {
112            shared
113                .queue_request(&writer, frame)
114                .await
115                .map_err(|err| match err {
116                    crate::CatalogUpdateError::Rejected(body) => {
117                        AgentCommandsError::Refused(Box::new(body))
118                    }
119                    _ => AgentCommandsError::ConnectionClosed,
120                })?;
121            rx.await.map_err(|_| AgentCommandsError::ConnectionClosed)
122        })
123        .await
124        .map_err(|_| AgentCommandsError::Timeout)??;
125        match reply.header.ty {
126            FrameType::Response => {
127                let value: serde_json::Value = serde_json::from_slice(&reply.body)
128                    .map_err(|err| AgentCommandsError::Protocol(err.to_string()))?;
129                if value.is_object() {
130                    Ok(())
131                } else {
132                    Err(AgentCommandsError::Protocol("expected an object".into()))
133                }
134            }
135            FrameType::Error => {
136                let body: ErrorBody = serde_json::from_slice(&reply.body)
137                    .map_err(|err| AgentCommandsError::Protocol(err.to_string()))?;
138                Err(match body.code.as_str() {
139                    "unsupported_control_frame" | "unknown_control_op" => {
140                        AgentCommandsError::Unsupported
141                    }
142                    "not_supervised" | "not_registered" => AgentCommandsError::NotSupervised,
143                    _ => AgentCommandsError::Refused(Box::new(body)),
144                })
145            }
146            other => Err(AgentCommandsError::Protocol(format!(
147                "unexpected terminal frame: {other:?}"
148            ))),
149        }
150    }
151}
152
153struct Waiter {
154    shared: std::sync::Arc<crate::ModuleHandleShared>,
155    corr: u64,
156}
157impl Drop for Waiter {
158    fn drop(&mut self) {
159        self.shared
160            .lock_inner()
161            .pending_agent_commands
162            .remove(&self.corr);
163    }
164}
165
166#[cfg(test)]
167mod tests {
168    use super::*;
169
170    #[test]
171    fn declaration_retry_mapping_uses_the_shared_protocol_classes() {
172        for (code, retry) in [
173            ("agent_roots_full", true),
174            ("busy", true),
175            ("duplicate_correlation", true),
176            ("declaration_closed", true),
177            ("invalid_request", false),
178            ("future_code", false),
179        ] {
180            let error = AgentCommandsError::Refused(Box::new(ErrorBody::new(code, "refused")));
181            assert_eq!(error.is_retryable(), retry, "{code}");
182        }
183        assert!(!AgentCommandsError::NotSupervised.is_retryable());
184        assert!(!AgentCommandsError::Unsupported.is_retryable());
185        assert!(AgentCommandsError::Timeout.is_retryable());
186        assert!(AgentCommandsError::ConnectionClosed.is_retryable());
187    }
188    use subc_protocol::{ModuleHelloAckBody, PROTOCOL_VERSION};
189    use tokio::sync::mpsc;
190    use tokio_util::sync::CancellationToken;
191
192    fn handle(supported: bool) -> (ModuleHandle, mpsc::Receiver<Frame>) {
193        let (writer, receiver) = mpsc::channel(4);
194        let ack = ModuleHelloAckBody {
195            resume_token: None,
196            negotiated_ver: PROTOCOL_VERSION,
197            subc_ops: if supported {
198                vec!["supervisor.agent_commands".into()]
199            } else {
200                Vec::new()
201            },
202            subc_capabilities: Vec::new(),
203            storage: None,
204            machine_id: None,
205        };
206        (
207            ModuleHandle::new(
208                &ack,
209                writer,
210                1,
211                CancellationToken::new(),
212                tokio::runtime::Handle::current(),
213            ),
214            receiver,
215        )
216    }
217
218    #[tokio::test]
219    async fn agent_commands_unsupported_and_ack_keep_connection_open() {
220        let (old, mut wire) = handle(false);
221        assert!(matches!(
222            old.agent_commands(Vec::new(), Vec::new(), None).await,
223            Err(AgentCommandsError::Unsupported)
224        ));
225        assert!(wire.try_recv().is_err());
226        assert!(!old.is_closed());
227        let (handle, mut wire) = handle(true);
228        for code in [
229            Some("unsupported_control_frame"),
230            Some("unknown_control_op"),
231            Some("not_supervised"),
232            Some("agent_roots_full"),
233            Some("declaration_closed"),
234            Some("duplicate_correlation"),
235            Some("busy"),
236            None,
237        ] {
238            let caller = handle.clone();
239            let root = AgentCommandRoot {
240                pid: 42,
241                start_time_ms: 1_700_000_000_000,
242            };
243            let call = tokio::spawn(async move {
244                caller
245                    .agent_commands(vec![root], Vec::new(), Some(vec![root]))
246                    .await
247            });
248            let request = wire.recv().await.unwrap();
249            assert_eq!(request.header.channel, 0);
250            let body: serde_json::Value = serde_json::from_slice(&request.body).unwrap();
251            assert_eq!(body["op"], "supervisor.agent_commands");
252            assert_eq!(body["started"][0]["start_time_ms"], root.start_time_ms);
253            assert_eq!(body["known"][0]["pid"], root.pid);
254            let (ty, body) = match code {
255                Some(code) => (
256                    FrameType::Error,
257                    serde_json::json!({"code":code,"message":"refused"}),
258                ),
259                None => (FrameType::Response, serde_json::json!({})),
260            };
261            let reply = Frame::build(
262                ty,
263                crate::control_flags(),
264                0,
265                0,
266                request.header.corr,
267                serde_json::to_vec(&body).unwrap(),
268            )
269            .unwrap();
270            assert!(handle.handle_control_reply(reply));
271            let result = call.await.unwrap();
272            match code {
273                Some("not_supervised") => {
274                    assert!(matches!(result, Err(AgentCommandsError::NotSupervised)))
275                }
276                Some(
277                    "agent_roots_full" | "declaration_closed" | "duplicate_correlation" | "busy",
278                ) => {
279                    assert!(result.unwrap_err().is_retryable());
280                }
281                Some(_) => assert!(matches!(result, Err(AgentCommandsError::Unsupported))),
282                None => assert!(result.is_ok()),
283            }
284            assert!(
285                !handle.is_closed(),
286                "a refused declaration must not tear down the serving connection"
287            );
288            assert!(handle
289                .shared()
290                .lock_inner()
291                .pending_agent_commands
292                .is_empty());
293        }
294    }
295}