1use std::collections::{BTreeSet, VecDeque};
4use std::future::Future;
5use std::path::{Path, PathBuf};
6use std::sync::{Arc, Mutex, OnceLock};
7use std::time::Duration;
8
9use subc_client_rs::{AgentCommandFinished, AgentCommandRoot, AgentCommandsError};
10use tokio::sync::Notify;
11use tokio_util::sync::CancellationToken;
12
13#[derive(Clone, Debug, Default)]
14pub struct Batch {
15 pub started: Vec<AgentCommandRoot>,
16 pub finished: Vec<AgentCommandFinished>,
17 pub known: Option<Vec<AgentCommandRoot>>,
18 through: u64,
19}
20
21enum Event {
22 Started(AgentCommandRoot),
23 Finished(AgentCommandFinished),
24 Restored,
25}
26
27#[derive(Default)]
28struct State {
29 live: BTreeSet<AgentCommandRoot>,
30 adopted: BTreeSet<AgentCommandRoot>,
31 events: VecDeque<(u64, Event)>,
32 sequence: u64,
33 connection: u64,
34 cancel: Option<CancellationToken>,
35 storage: Option<PathBuf>,
36 unsupported: bool,
37}
38
39#[derive(Default)]
40struct Declarations {
41 state: Mutex<State>,
42 changed: Notify,
43 persisting: tokio::sync::Mutex<()>,
44}
45
46impl State {
47 fn push(&mut self, event: Event) {
48 self.sequence += 1;
49 if !self.unsupported {
50 self.events.push_back((self.sequence, event));
51 }
52 }
53}
54
55impl Declarations {
56 fn load(&self, storage: &Path) {
57 let path = storage.join("agent-command-roots.json");
58 let roots = std::fs::read(&path)
59 .ok()
60 .and_then(|bytes| serde_json::from_slice::<Vec<AgentCommandRoot>>(&bytes).ok())
61 .unwrap_or_default();
62 self.state.lock().unwrap_or_else(|e| e.into_inner()).storage = Some(path);
63 for root in roots {
64 if subc_os::process_start_time_ms(root.pid) == Some(root.start_time_ms) {
65 self.restored(root);
66 }
67 }
68 }
69
70 fn started(&self, root: AgentCommandRoot) {
71 let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
72 state.live.insert(root);
73 state.adopted.remove(&root);
74 state.push(Event::Started(root));
75 drop(state);
76 self.changed.notify_one();
77 }
78
79 fn restored(&self, root: AgentCommandRoot) {
80 let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
81 if !state.live.insert(root) {
82 return;
83 }
84 state.adopted.insert(root);
85 state.push(Event::Restored);
86 drop(state);
87 self.changed.notify_one();
88 }
89
90 fn finished(&self, root: AgentCommandRoot, cpu_ms: Option<u64>) {
91 let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
92 if !state.live.remove(&root) {
93 return;
94 }
95 state.adopted.remove(&root);
96 state.push(Event::Finished(AgentCommandFinished {
97 pid: root.pid,
98 start_time_ms: root.start_time_ms,
99 cpu_ms,
100 }));
101 drop(state);
102 self.changed.notify_one();
103 }
104
105 fn batch(&self, initial: bool) -> Batch {
106 let state = self.state.lock().unwrap_or_else(|e| e.into_inner());
107 let mut batch = Batch {
108 through: state.sequence,
109 ..Batch::default()
110 };
111 let mut known = initial;
112 for (_, event) in &state.events {
113 match event {
114 Event::Started(root) => batch.started.push(*root),
115 Event::Finished(root) => batch.finished.push(*root),
116 Event::Restored => known = true,
117 }
118 }
119 if known {
120 batch.known = Some(state.live.iter().copied().collect());
121 }
122 batch
123 }
124
125 fn connect<F, Fut>(self: &Arc<Self>, send: F) -> Connection
126 where
127 F: Fn(Batch) -> Fut + Send + 'static,
128 Fut: Future<Output = Result<(), AgentCommandsError>> + Send,
129 {
130 let cancel = CancellationToken::new();
131 let generation = {
132 let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
133 if let Some(old) = state.cancel.replace(cancel.clone()) {
134 old.cancel();
135 }
136 state.connection += 1;
137 state.unsupported = false;
138 state.connection
139 };
140 let declarations = self.clone();
141 let stopped = cancel.clone();
142 let task = tokio::spawn(async move {
143 declarations.drive(generation, stopped, send).await;
144 });
145 Connection {
146 cancel,
147 task: Some(task),
148 }
149 }
150
151 async fn drive<F, Fut>(&self, generation: u64, cancel: CancellationToken, send: F)
152 where
153 F: Fn(Batch) -> Fut,
154 Fut: Future<Output = Result<(), AgentCommandsError>>,
155 {
156 let mut initial = true;
157 loop {
158 self.prune_exited();
159 let changed = self.changed.notified();
160 let batch = self.batch(initial);
161 if !initial
162 && batch.started.is_empty()
163 && batch.finished.is_empty()
164 && batch.known.is_none()
165 {
166 tokio::select! {
167 _ = cancel.cancelled() => return,
168 _ = changed => continue,
169 _ = tokio::time::sleep(Duration::from_secs(1)) => continue,
170 }
171 }
172 self.persist().await;
173 let mut backoff = Duration::from_millis(50);
174 loop {
175 let result = tokio::select! {
176 biased;
177 _ = cancel.cancelled() => return,
178 result = send(batch.clone()) => result,
179 };
180 match result {
181 Ok(()) => break,
182 Err(AgentCommandsError::Unsupported) => {
183 static LOGGED: OnceLock<()> = OnceLock::new();
184 LOGGED.get_or_init(|| {
185 crate::slog_debug!("daemon does not support agent command declarations")
186 });
187 let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
188 state.unsupported = true;
189 state.events.clear();
190 return;
191 }
192 Err(error) if error.is_retryable() => {
193 tokio::select! {
194 _ = cancel.cancelled() => return,
195 _ = tokio::time::sleep(backoff) => {}
196 }
197 backoff = (backoff * 2).min(Duration::from_secs(2));
198 }
199 Err(error) => {
200 crate::slog_warn!("agent command declaration refused: {error}");
201 break;
202 }
203 }
204 }
205 let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
206 if state.connection != generation {
207 return;
208 }
209 state
210 .events
211 .retain(|(sequence, _)| *sequence > batch.through);
212 initial = false;
213 }
214 }
215
216 fn prune_exited(&self) {
217 let roots: Vec<_> = self
220 .state
221 .lock()
222 .unwrap_or_else(|e| e.into_inner())
223 .adopted
224 .iter()
225 .copied()
226 .collect();
227 for root in roots {
228 if subc_os::process_start_time_ms(root.pid) != Some(root.start_time_ms) {
229 self.finished(root, None);
230 }
231 }
232 }
233
234 async fn persist(&self) {
235 let _order = self.persisting.lock().await;
238 let (path, roots) = {
239 let state = self.state.lock().unwrap_or_else(|e| e.into_inner());
240 (
241 state.storage.clone(),
242 state.live.iter().copied().collect::<Vec<_>>(),
243 )
244 };
245 if let Some(path) = path {
246 let result = tokio::task::spawn_blocking(move || -> std::io::Result<()> {
247 if let Some(parent) = path.parent() {
248 std::fs::create_dir_all(parent)?;
249 }
250 let bytes = serde_json::to_vec(&roots)?;
251 crate::durability::atomic_write(
252 &path,
253 &bytes,
254 crate::durability::AtomicWriteDurability::FileAndDirectory,
255 )
256 })
257 .await;
258 if !matches!(result, Ok(Ok(()))) {
259 crate::slog_warn!("failed to retain live agent command identities: {result:?}");
260 }
261 }
262 }
263}
264
265fn declarations() -> &'static Arc<Declarations> {
266 static DECLARATIONS: OnceLock<Arc<Declarations>> = OnceLock::new();
267 DECLARATIONS.get_or_init(|| Arc::new(Declarations::default()))
268}
269
270pub struct Connection {
272 cancel: CancellationToken,
273 task: Option<tokio::task::JoinHandle<()>>,
274}
275
276impl Connection {
277 pub async fn stop(mut self) {
278 self.cancel.cancel();
279 if let Some(task) = self.task.take() {
280 let _ = task.await;
281 }
282 }
283}
284
285impl Drop for Connection {
286 fn drop(&mut self) {
287 self.cancel.cancel();
288 }
289}
290
291pub fn connect<F, Fut>(send: F) -> Connection
292where
293 F: Fn(Batch) -> Fut + Send + 'static,
294 Fut: Future<Output = Result<(), AgentCommandsError>> + Send,
295{
296 declarations().connect(send)
297}
298
299pub fn enable(storage: &Path) {
300 declarations().load(storage);
301}
302
303pub fn started(pid: u32) -> Option<AgentCommandRoot> {
304 if declarations()
305 .state
306 .lock()
307 .unwrap_or_else(|e| e.into_inner())
308 .storage
309 .is_none()
310 {
311 return None;
312 }
313 let root = AgentCommandRoot {
314 pid,
315 start_time_ms: subc_os::process_start_time_ms(pid)?,
316 };
317 declarations().started(root);
318 Some(root)
319}
320
321pub(crate) fn finished(root: Option<AgentCommandRoot>, cpu_ms: Option<u64>) {
322 if let Some(root) = root {
323 declarations().finished(root, cpu_ms);
324 }
325}
326
327#[cfg(unix)]
328pub(crate) fn wait4(
329 pid: u32,
330 flags: libc::c_int,
331 root: Option<AgentCommandRoot>,
332) -> std::io::Result<Option<std::process::ExitStatus>> {
333 use std::os::unix::process::ExitStatusExt;
334 loop {
335 let mut status = 0;
336 let mut usage = std::mem::MaybeUninit::<libc::rusage>::zeroed();
337 let result =
339 unsafe { libc::wait4(pid as libc::pid_t, &mut status, flags, usage.as_mut_ptr()) };
340 if result > 0 {
341 let usage = unsafe { usage.assume_init() };
342 let micros = |time: libc::timeval| {
343 (time.tv_sec as u64)
344 .saturating_mul(1_000_000)
345 .saturating_add(time.tv_usec as u64)
346 };
347 let cpu_ms = micros(usage.ru_utime).saturating_add(micros(usage.ru_stime)) / 1_000;
348 finished(root, Some(cpu_ms));
349 return Ok(Some(std::process::ExitStatus::from_raw(status)));
350 }
351 if result == 0 {
352 return Ok(None);
353 }
354 let error = std::io::Error::last_os_error();
355 if error.kind() != std::io::ErrorKind::Interrupted {
356 return Err(error);
357 }
358 }
359}
360
361#[cfg(windows)]
362pub(crate) fn windows_cpu_ms(handle: std::os::windows::io::RawHandle) -> Option<u64> {
363 use windows_sys::Win32::Foundation::FILETIME;
364 use windows_sys::Win32::System::Threading::GetProcessTimes;
365 let mut created = FILETIME::default();
366 let mut exited = FILETIME::default();
367 let mut kernel = FILETIME::default();
368 let mut user = FILETIME::default();
369 if unsafe { GetProcessTimes(handle, &mut created, &mut exited, &mut kernel, &mut user) } == 0 {
371 return None;
372 }
373 let ticks =
374 |time: FILETIME| (u64::from(time.dwHighDateTime) << 32) | u64::from(time.dwLowDateTime);
375 Some(ticks(kernel).saturating_add(ticks(user)) / 10_000)
376}
377
378#[cfg(windows)]
379#[derive(Debug)]
380pub struct WindowsChild {
381 child: std::process::Child,
382 root: Option<AgentCommandRoot>,
383}
384
385#[cfg(windows)]
386impl From<std::process::Child> for WindowsChild {
387 fn from(child: std::process::Child) -> Self {
388 Self { child, root: None }
389 }
390}
391
392#[cfg(windows)]
393impl std::ops::Deref for WindowsChild {
394 type Target = std::process::Child;
395 fn deref(&self) -> &Self::Target {
396 &self.child
397 }
398}
399
400#[cfg(windows)]
401impl std::ops::DerefMut for WindowsChild {
402 fn deref_mut(&mut self) -> &mut Self::Target {
403 &mut self.child
404 }
405}
406
407#[cfg(windows)]
408impl WindowsChild {
409 pub fn declare_agent(&mut self) {
410 self.root = started(self.child.id());
411 }
412 #[allow(dead_code)]
414 pub(crate) fn try_wait(&mut self) -> std::io::Result<Option<std::process::ExitStatus>> {
415 let status = self.child.try_wait()?;
416 if status.is_some() {
417 self.finished();
418 }
419 Ok(status)
420 }
421 #[allow(dead_code)]
422 pub(crate) fn wait(&mut self) -> std::io::Result<std::process::ExitStatus> {
423 let status = self.child.wait()?;
424 self.finished();
425 Ok(status)
426 }
427 #[allow(dead_code)]
428 fn finished(&self) {
429 use std::os::windows::io::AsRawHandle;
430 finished(self.root, windows_cpu_ms(self.child.as_raw_handle()));
431 }
432}
433
434pub fn wait_pty(
435 child: &mut dyn portable_pty::Child,
436 root: Option<AgentCommandRoot>,
437) -> std::io::Result<portable_pty::ExitStatus> {
438 #[cfg(unix)]
439 if let Some(pid) = child.process_id() {
440 return wait4(pid, 0, root)?
441 .map(Into::into)
442 .ok_or_else(|| std::io::Error::other("wait4 returned no status"));
443 }
444 let status = child.wait()?;
445 if root.is_some() {
446 #[cfg(windows)]
447 let cpu = child.as_raw_handle().and_then(windows_cpu_ms);
448 #[cfg(not(windows))]
449 let cpu = None;
450 finished(root, cpu);
451 }
452 Ok(status)
453}
454
455pub fn try_wait_pty(
456 child: &mut dyn portable_pty::Child,
457 root: Option<AgentCommandRoot>,
458) -> std::io::Result<Option<portable_pty::ExitStatus>> {
459 #[cfg(unix)]
460 if let Some(pid) = child.process_id() {
461 return wait4(pid, libc::WNOHANG, root).map(|status| status.map(Into::into));
462 }
463 let status = child.try_wait()?;
464 if status.is_some() {
465 if root.is_some() {
466 #[cfg(windows)]
467 let cpu = child.as_raw_handle().and_then(windows_cpu_ms);
468 #[cfg(not(windows))]
469 let cpu = None;
470 finished(root, cpu);
471 }
472 }
473 Ok(status)
474}
475
476#[cfg(test)]
477mod tests {
478 use super::*;
479 use tokio::sync::{mpsc, oneshot};
480
481 type Reply = oneshot::Sender<Result<(), AgentCommandsError>>;
482
483 fn sender(hub: &Arc<Declarations>) -> (Connection, mpsc::UnboundedReceiver<(Batch, Reply)>) {
484 let (tx, rx) = mpsc::unbounded_channel();
485 let connection = hub.connect(move |batch| {
486 let (reply, result) = oneshot::channel();
487 tx.send((batch, reply)).unwrap();
488 async {
489 result
490 .await
491 .unwrap_or(Err(AgentCommandsError::ConnectionClosed))
492 }
493 });
494 (connection, rx)
495 }
496
497 async fn receive(rx: &mut mpsc::UnboundedReceiver<(Batch, Reply)>) -> (Batch, Reply) {
498 tokio::time::timeout(Duration::from_secs(2), rx.recv())
499 .await
500 .unwrap()
501 .unwrap()
502 }
503
504 fn root(pid: u32) -> AgentCommandRoot {
505 AgentCommandRoot {
506 pid,
507 start_time_ms: 1_700_000_000_000 + u64::from(pid),
508 }
509 }
510
511 #[test]
512 fn agent_commands_reused_pid_finishes_only_the_original_kernel_identity() {
513 let hub = Declarations::default();
514 let old = root(42);
515 let new = AgentCommandRoot {
516 start_time_ms: old.start_time_ms + 1,
517 ..old
518 };
519 hub.started(old);
520 hub.started(new);
521 hub.finished(old, Some(250));
522 let batch = hub.batch(true);
523 assert_eq!(batch.known, Some(vec![new]));
524 assert_eq!(
525 batch.finished,
526 [AgentCommandFinished {
527 pid: old.pid,
528 start_time_ms: old.start_time_ms,
529 cpu_ms: Some(250)
530 }]
531 );
532 hub.finished(old, Some(250));
533 assert_eq!(
534 hub.batch(true).finished.len(),
535 1,
536 "cached waits must not finish twice or settle the reused PID"
537 );
538 }
539
540 #[tokio::test]
541 async fn agent_commands_start_finish_cpu_and_known_after_reconnect() {
542 let hub = Arc::new(Declarations::default());
543 let live = root(42);
544 let ended = root(43);
545 hub.started(live);
546 hub.started(ended);
547 hub.finished(ended, Some(250));
548 let (connection, mut rx) = sender(&hub);
549 let (batch, reply) = receive(&mut rx).await;
550 assert_eq!(batch.started, [live, ended]);
551 assert_eq!(
552 batch.finished,
553 [AgentCommandFinished {
554 pid: ended.pid,
555 start_time_ms: ended.start_time_ms,
556 cpu_ms: Some(250)
557 }]
558 );
559 assert_eq!(batch.known, Some(vec![live]));
560 reply.send(Ok(())).unwrap();
561 tokio::task::yield_now().await;
562 drop(connection);
563 let (_connection, mut reconnected) = sender(&hub);
564 let (batch, reply) = receive(&mut reconnected).await;
565 assert!(batch.started.is_empty());
566 assert!(batch.finished.is_empty());
567 assert_eq!(batch.known, Some(vec![live]));
568 reply.send(Ok(())).unwrap();
569 hub.finished(live, None);
570 let (batch, reply) = receive(&mut reconnected).await;
571 assert_eq!(batch.finished[0].cpu_ms, None);
572 let wire = serde_json::to_value(batch.finished[0]).unwrap();
573 assert!(wire.get("cpu_ms").is_none());
574 reply.send(Ok(())).unwrap();
575 }
576
577 #[tokio::test]
578 async fn agent_commands_busy_retries_the_same_roots_before_later_finishes() {
579 let hub = Arc::new(Declarations::default());
580 let live = root(42);
581 hub.started(live);
582 let (_connection, mut rx) = sender(&hub);
583 let (first, reply) = receive(&mut rx).await;
584 reply
585 .send(Err(AgentCommandsError::Refused(Box::new(
586 subc_protocol::ErrorBody::new("busy", "try again"),
587 ))))
588 .unwrap();
589 hub.finished(live, Some(19));
590 let (retry, reply) = receive(&mut rx).await;
591 assert_eq!(retry.started, first.started);
592 assert_eq!(retry.finished, first.finished);
593 assert_eq!(retry.known, first.known);
594 reply.send(Ok(())).unwrap();
595 let (next, reply) = receive(&mut rx).await;
596 assert!(next.started.is_empty());
597 assert_eq!(next.finished[0].cpu_ms, Some(19));
598 assert!(next.known.is_none());
599 reply.send(Ok(())).unwrap();
600 }
601
602 #[tokio::test]
603 async fn agent_commands_unsupported_is_quiet_and_stops_retrying() {
604 let hub = Arc::new(Declarations::default());
605 let (_connection, mut rx) = sender(&hub);
606 let (_, reply) = receive(&mut rx).await;
607 reply.send(Err(AgentCommandsError::Unsupported)).unwrap();
608 tokio::task::yield_now().await;
609 hub.started(root(42));
610 assert!(rx.recv().await.is_none());
611 assert!(hub.state.lock().unwrap().events.is_empty());
612 }
613
614 #[tokio::test]
615 async fn agent_commands_reconnect_cancels_the_stale_connection_and_keeps_unacked_roots() {
616 let hub = Arc::new(Declarations::default());
617 hub.started(root(42));
618 let (_old, mut first) = sender(&hub);
619 let (_, old_reply) = receive(&mut first).await;
620 let (_current, mut current) = sender(&hub);
621 let (batch, reply) = receive(&mut current).await;
622 assert_eq!(batch.started, [root(42)]);
623 assert_eq!(batch.known, Some(vec![root(42)]));
624 tokio::task::yield_now().await;
625 assert!(old_reply.is_closed());
626 reply.send(Ok(())).unwrap();
627 }
628
629 #[cfg(unix)]
630 #[tokio::test]
631 async fn agent_commands_persists_before_send_and_recovers_without_a_project_bind() {
632 let storage = tempfile::tempdir().unwrap();
633 let mut child = std::process::Command::new("sleep")
634 .arg("30")
635 .spawn()
636 .unwrap();
637 let root = AgentCommandRoot {
638 pid: child.id(),
639 start_time_ms: subc_os::process_start_time_ms(child.id()).unwrap(),
640 };
641 let first = Arc::new(Declarations::default());
642 first.load(storage.path());
643 first.started(root);
644 let (connection, mut rx) = sender(&first);
645 let (_, reply) = receive(&mut rx).await;
646 let saved: Vec<AgentCommandRoot> = serde_json::from_slice(
647 &std::fs::read(storage.path().join("agent-command-roots.json")).unwrap(),
648 )
649 .unwrap();
650 assert_eq!(saved, [root]);
651 reply.send(Ok(())).unwrap();
652 connection.stop().await;
653
654 let recovered = Arc::new(Declarations::default());
655 recovered.load(storage.path());
656 let (connection, mut rx) = sender(&recovered);
657 let (batch, reply) = receive(&mut rx).await;
658 assert_eq!(batch.known, Some(vec![root]));
659 assert!(batch.started.is_empty());
660 reply.send(Ok(())).unwrap();
661 connection.stop().await;
662 child.kill().unwrap();
663 child.wait().unwrap();
664 }
665
666 #[cfg(unix)]
667 #[tokio::test]
668 async fn agent_commands_restored_roots_use_kernel_identity_and_prune_when_gone() {
669 let mut child = std::process::Command::new("/bin/sh")
670 .args(["-c", "sleep 30"])
671 .spawn()
672 .unwrap();
673 let root = AgentCommandRoot {
674 pid: child.id(),
675 start_time_ms: subc_os::process_start_time_ms(child.id()).unwrap(),
676 };
677 let hub = Arc::new(Declarations::default());
678 hub.restored(root);
679 let (_connection, mut rx) = sender(&hub);
680 let (batch, reply) = receive(&mut rx).await;
681 assert_eq!(batch.known, Some(vec![root]));
682 assert!(
683 batch.started.is_empty(),
684 "known must not introduce a new start after restart"
685 );
686 reply.send(Ok(())).unwrap();
687 child.kill().unwrap();
688 child.wait().unwrap();
689 hub.prune_exited();
690 let (batch, reply) = receive(&mut rx).await;
691 assert_eq!(
692 batch.finished,
693 [AgentCommandFinished {
694 pid: root.pid,
695 start_time_ms: root.start_time_ms,
696 cpu_ms: None
697 }]
698 );
699 reply.send(Ok(())).unwrap();
700 }
701}