1use crate::{AgentCommandFinished, AgentCommandRoot, ModuleHandle};
4use subc_protocol::{session::ModuleControlRequestFromModule, ErrorBody, Frame, FrameType};
5use tokio::sync::oneshot;
6
7#[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 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 pub async fn agent_commands(
61 &self,
62 started: Vec<AgentCommandRoot>,
63 finished: Vec<AgentCommandFinished>,
64 known: Option<Vec<AgentCommandRoot>>,
65 ) -> Result<(), AgentCommandsError> {
66 if !self.shared.supports_agent_commands {
67 return Err(AgentCommandsError::Unsupported);
68 }
69 let body = serde_json::to_vec(&ModuleControlRequestFromModule::AgentCommands {
70 started,
71 finished,
72 known,
73 })
74 .map_err(|err| AgentCommandsError::Protocol(err.to_string()))?;
75 let (corr, writer, rx) = {
76 let mut inner = self.shared.lock_inner();
77 if inner.closed {
78 return Err(AgentCommandsError::ConnectionClosed);
79 }
80 let writer = inner
81 .writer
82 .clone()
83 .ok_or(AgentCommandsError::ConnectionClosed)?;
84 let corr = crate::next_module_control_corr(&mut inner)
85 .ok_or(AgentCommandsError::ConnectionClosed)?;
86 let (tx, rx) = oneshot::channel();
87 inner.pending_agent_commands.insert(corr, tx);
88 (corr, writer, rx)
89 };
90 let _guard = Waiter {
91 handle: self.clone(),
92 corr,
93 };
94 let frame = Frame::build_with_version(
95 self.shared.negotiated_ver,
96 FrameType::Request,
97 crate::control_flags(),
98 0,
99 0,
100 corr,
101 body,
102 )
103 .map_err(|err| AgentCommandsError::Protocol(err.to_string()))?;
104 let reply = tokio::time::timeout(crate::CATALOG_UPDATE_TIMEOUT, async {
105 writer
106 .send(frame)
107 .await
108 .map_err(|_| AgentCommandsError::ConnectionClosed)?;
109 rx.await.map_err(|_| AgentCommandsError::ConnectionClosed)
110 })
111 .await
112 .map_err(|_| AgentCommandsError::Timeout)??;
113 match reply.header.ty {
114 FrameType::Response => {
115 let value: serde_json::Value = serde_json::from_slice(&reply.body)
116 .map_err(|err| AgentCommandsError::Protocol(err.to_string()))?;
117 if value.is_object() {
118 Ok(())
119 } else {
120 Err(AgentCommandsError::Protocol("expected an object".into()))
121 }
122 }
123 FrameType::Error => {
124 let body: ErrorBody = serde_json::from_slice(&reply.body)
125 .map_err(|err| AgentCommandsError::Protocol(err.to_string()))?;
126 Err(match body.code.as_str() {
127 "unsupported_control_frame" | "unknown_control_op" => {
128 AgentCommandsError::Unsupported
129 }
130 "not_supervised" | "not_registered" => AgentCommandsError::NotSupervised,
131 _ => AgentCommandsError::Refused(Box::new(body)),
132 })
133 }
134 other => Err(AgentCommandsError::Protocol(format!(
135 "unexpected terminal frame: {other:?}"
136 ))),
137 }
138 }
139}
140
141struct Waiter {
142 handle: ModuleHandle,
143 corr: u64,
144}
145impl Drop for Waiter {
146 fn drop(&mut self) {
147 self.handle
148 .shared
149 .lock_inner()
150 .pending_agent_commands
151 .remove(&self.corr);
152 }
153}
154
155#[cfg(test)]
156mod tests {
157 use super::*;
158
159 #[test]
160 fn declaration_retry_mapping_uses_the_shared_protocol_classes() {
161 for (code, retry) in [
162 ("agent_roots_full", true),
163 ("busy", true),
164 ("duplicate_correlation", true),
165 ("declaration_closed", true),
166 ("invalid_request", false),
167 ("future_code", false),
168 ] {
169 let error = AgentCommandsError::Refused(Box::new(ErrorBody::new(code, "refused")));
170 assert_eq!(error.is_retryable(), retry, "{code}");
171 }
172 assert!(!AgentCommandsError::NotSupervised.is_retryable());
173 assert!(!AgentCommandsError::Unsupported.is_retryable());
174 assert!(AgentCommandsError::Timeout.is_retryable());
175 assert!(AgentCommandsError::ConnectionClosed.is_retryable());
176 }
177 use subc_protocol::{ModuleHelloAckBody, PROTOCOL_VERSION};
178 use tokio::sync::mpsc;
179 use tokio_util::sync::CancellationToken;
180
181 fn handle(supported: bool) -> (ModuleHandle, mpsc::Receiver<Frame>) {
182 let (writer, receiver) = mpsc::channel(4);
183 let ack = ModuleHelloAckBody {
184 negotiated_ver: PROTOCOL_VERSION,
185 subc_ops: if supported {
186 vec!["supervisor.agent_commands".into()]
187 } else {
188 Vec::new()
189 },
190 subc_capabilities: Vec::new(),
191 storage: None,
192 machine_id: None,
193 };
194 (
195 ModuleHandle::new(
196 &ack,
197 writer,
198 1,
199 CancellationToken::new(),
200 tokio::runtime::Handle::current(),
201 ),
202 receiver,
203 )
204 }
205
206 #[tokio::test]
207 async fn agent_commands_unsupported_and_ack_keep_connection_open() {
208 let (old, mut wire) = handle(false);
209 assert!(matches!(
210 old.agent_commands(Vec::new(), Vec::new(), None).await,
211 Err(AgentCommandsError::Unsupported)
212 ));
213 assert!(wire.try_recv().is_err());
214 assert!(!old.is_closed());
215 let (handle, mut wire) = handle(true);
216 for code in [
217 Some("unsupported_control_frame"),
218 Some("unknown_control_op"),
219 Some("not_supervised"),
220 Some("agent_roots_full"),
221 Some("declaration_closed"),
222 Some("duplicate_correlation"),
223 Some("busy"),
224 None,
225 ] {
226 let caller = handle.clone();
227 let root = AgentCommandRoot {
228 pid: 42,
229 start_time_ms: 1_700_000_000_000,
230 };
231 let call = tokio::spawn(async move {
232 caller
233 .agent_commands(vec![root], Vec::new(), Some(vec![root]))
234 .await
235 });
236 let request = wire.recv().await.unwrap();
237 assert_eq!(request.header.channel, 0);
238 let body: serde_json::Value = serde_json::from_slice(&request.body).unwrap();
239 assert_eq!(body["op"], "supervisor.agent_commands");
240 assert_eq!(body["started"][0]["start_time_ms"], root.start_time_ms);
241 assert_eq!(body["known"][0]["pid"], root.pid);
242 let (ty, body) = match code {
243 Some(code) => (
244 FrameType::Error,
245 serde_json::json!({"code":code,"message":"refused"}),
246 ),
247 None => (FrameType::Response, serde_json::json!({})),
248 };
249 let reply = Frame::build(
250 ty,
251 crate::control_flags(),
252 0,
253 0,
254 request.header.corr,
255 serde_json::to_vec(&body).unwrap(),
256 )
257 .unwrap();
258 assert!(handle.handle_control_reply(reply));
259 let result = call.await.unwrap();
260 match code {
261 Some("not_supervised") => {
262 assert!(matches!(result, Err(AgentCommandsError::NotSupervised)))
263 }
264 Some(
265 "agent_roots_full" | "declaration_closed" | "duplicate_correlation" | "busy",
266 ) => {
267 assert!(result.unwrap_err().is_retryable());
268 }
269 Some(_) => assert!(matches!(result, Err(AgentCommandsError::Unsupported))),
270 None => assert!(result.is_ok()),
271 }
272 assert!(
273 !handle.is_closed(),
274 "a refused declaration must not tear down the serving connection"
275 );
276 assert!(handle.shared.lock_inner().pending_agent_commands.is_empty());
277 }
278 }
279}