1use std::fs::{File, OpenOptions};
5use std::io::Read;
6use std::path::{Path, PathBuf};
7use std::process::{Command, Stdio};
8use std::sync::atomic::{AtomicBool, Ordering};
9use std::sync::{Arc, Mutex};
10use std::time::{Duration, Instant};
11
12use anyhow::{Context, Result, bail};
13use serde::{Deserialize, Serialize};
14
15use crate::proc::Quiet as _;
16use crate::talk::{self, Talks};
17
18pub const DEFAULT_TIMEOUT: u64 = 900;
20pub const MAX_TIMEOUT: u64 = 3600;
22pub const MAX_CONCURRENT: usize = 4;
24pub const OUTPUT_CAP: usize = 8192;
26
27#[derive(Debug, Serialize, Deserialize)]
28struct Job {
29 id: String,
30 talk: String,
31 cwd: PathBuf,
32 command: Vec<String>,
33 timeout: u64,
34 supervisor: Option<(u32, String)>,
35 child: Option<(u32, String)>,
36 result: Option<String>,
37 tail: String,
38 delivered: bool,
39}
40
41fn root(home: &Path) -> PathBuf {
42 home.join("chat-watches")
43}
44
45struct Lock(File);
46
47impl Drop for Lock {
48 fn drop(&mut self) {
49 unlock_file(&self.0);
50 }
51}
52
53fn open_lock(path: &Path) -> Result<File> {
54 Ok(OpenOptions::new()
55 .create(true)
56 .truncate(false)
57 .read(true)
58 .write(true)
59 .open(path)?)
60}
61
62fn lock(path: &Path) -> Result<Lock> {
63 let file = open_lock(path)?;
64 lock_file(&file, false)?;
65 Ok(Lock(file))
66}
67
68fn try_lock(path: &Path) -> Result<Option<Lock>> {
69 let file = open_lock(path)?;
70 if lock_file(&file, true)? {
71 Ok(Some(Lock(file)))
72 } else {
73 Ok(None)
74 }
75}
76
77#[cfg(unix)]
78fn lock_file(file: &File, immediate: bool) -> std::io::Result<bool> {
79 use std::os::fd::AsRawFd;
80 loop {
81 if unsafe {
82 libc::flock(
83 file.as_raw_fd(),
84 libc::LOCK_EX | if immediate { libc::LOCK_NB } else { 0 },
85 )
86 } == 0
87 {
88 return Ok(true);
89 }
90 let error = std::io::Error::last_os_error();
91 match error.kind() {
92 std::io::ErrorKind::Interrupted => continue,
93 std::io::ErrorKind::WouldBlock if immediate => return Ok(false),
94 _ => return Err(error),
95 }
96 }
97}
98
99#[cfg(unix)]
100fn unlock_file(file: &File) {
101 use std::os::fd::AsRawFd;
102 unsafe {
103 libc::flock(file.as_raw_fd(), libc::LOCK_UN);
104 }
105}
106
107#[cfg(windows)]
108fn lock_file(file: &File, immediate: bool) -> std::io::Result<bool> {
109 use std::os::windows::io::AsRawHandle;
110 windows::lock_file(file.as_raw_handle(), immediate)
111}
112
113#[cfg(windows)]
114fn unlock_file(file: &File) {
115 use std::os::windows::io::AsRawHandle;
116 windows::unlock_file(file.as_raw_handle());
117}
118
119fn load(dir: &Path) -> Result<Job> {
120 Ok(serde_json::from_slice(&std::fs::read(
121 dir.join("job.json"),
122 )?)?)
123}
124
125fn save(dir: &Path, job: &Job) -> Result<()> {
126 let tmp = dir.join("job.tmp");
127 std::fs::write(&tmp, serde_json::to_vec(job)?)?;
128 std::fs::rename(tmp, dir.join("job.json"))?;
129 Ok(())
130}
131
132fn directories(home: &Path) -> Result<Vec<PathBuf>> {
133 Ok(std::fs::read_dir(root(home))?
134 .filter_map(Result::ok)
135 .map(|e| e.path())
136 .filter(|p| {
137 p.is_dir()
138 && !p
139 .file_name()
140 .is_some_and(|n| n.to_string_lossy().starts_with('.'))
141 })
142 .collect())
143}
144
145pub(crate) fn registered_ids(
147 home: &Path,
148 talk: &str,
149) -> Result<std::collections::BTreeSet<String>> {
150 let entries = match std::fs::read_dir(root(home)) {
151 Ok(entries) => entries,
152 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Default::default()),
153 Err(e) => return Err(e.into()),
154 };
155 let mut ids = std::collections::BTreeSet::new();
156 for entry in entries {
157 let entry = entry?;
158 if !entry.file_type()?.is_dir() || entry.file_name().to_string_lossy().starts_with('.') {
159 continue;
160 }
161 let dir = entry.path();
162 let job = load(&dir)?;
163 if job.talk == talk
164 && job.supervisor.is_some()
165 && (job.child.is_some() || job.result.is_some())
166 {
167 ids.insert(job.id);
168 }
169 }
170 Ok(ids)
171}
172
173pub fn authorize(talks: &Talks, run: &str, node: &str) -> Result<String> {
175 if node != crate::queue::CHAT_NODE || run.trim().is_empty() {
176 bail!("talk watch requires MAGI_NODE=chat and MAGI_RUN from a standing chat");
177 }
178 let t = talks.get(run)?;
179 if t.id != run || !t.status.open() {
180 bail!("talk watch requires the exact id of an open conversation");
181 }
182 Ok(t.id)
183}
184
185pub fn start(
188 home: &Path,
189 talks: &Talks,
190 run: &str,
191 node: &str,
192 command: Vec<String>,
193 timeout: u64,
194) -> Result<String> {
195 let talk = authorize(talks, run, node)?;
196 if command.is_empty() || !(1..=MAX_TIMEOUT).contains(&timeout) {
197 bail!("watch needs a command and a timeout between 1 and {MAX_TIMEOUT} seconds");
198 }
199 std::fs::create_dir_all(root(home))?;
200 let _store = lock(&root(home).join("store.lock"))?;
201 let active = directories(home)?
202 .iter()
203 .try_fold(0, |n, dir| -> Result<usize> {
204 Ok(n + usize::from(load(dir)?.result.is_none()))
205 })?;
206 if active >= MAX_CONCURRENT {
207 bail!("at most {MAX_CONCURRENT} chat watches may run concurrently");
208 }
209 let id = crate::rng::SplitMix64::new(crate::rng::entropy()).uuid_v4();
210 let dir = root(home).join(&id);
211 let staging = root(home).join(format!(".new-{id}"));
212 std::fs::create_dir(&staging)?;
213 let mut job = Job {
214 id: id.clone(),
215 talk,
216 cwd: std::env::current_dir()?,
217 command,
218 timeout,
219 supervisor: None,
220 child: None,
221 result: None,
222 tail: String::new(),
223 delivered: false,
224 };
225 save(&staging, &job)?;
226 std::fs::rename(&staging, &dir)?;
227 let mut cmd = Command::new(crate::updater::current_exe()?);
228 cmd.arg("talk")
229 .arg("watch-run")
230 .arg(home)
231 .arg(&id)
232 .env_remove("MAGI_RUN")
233 .env_remove("MAGI_NODE")
234 .stdin(Stdio::null())
235 .stdout(Stdio::null())
236 .stderr(Stdio::null());
237 crate::chat_control::bridge::clear_std_environment(&mut cmd);
238 #[cfg(unix)]
239 {
240 use std::os::unix::process::CommandExt;
241 unsafe {
243 cmd.pre_exec(|| {
244 if libc::setsid() < 0 {
245 return Err(std::io::Error::last_os_error());
246 }
247 Ok(())
248 });
249 }
250 }
251 #[cfg(windows)]
252 {
253 use std::os::windows::process::CommandExt;
254 cmd.creation_flags(0x0000_0008 | 0x0000_0200);
257 }
258 let mut supervisor = match cmd.spawn() {
259 Ok(child) => child,
260 Err(e) => {
261 job.result = Some(format!("supervisor startup failed: {e}"));
262 save(&dir, &job)?;
263 return Err(e.into());
264 }
265 };
266 let deadline = Instant::now() + Duration::from_secs(10);
267 loop {
268 let fresh = load(&dir)?;
269 if fresh.supervisor.is_some() && (fresh.child.is_some() || fresh.result.is_some()) {
270 std::thread::spawn(move || {
273 let _ = supervisor.wait();
274 });
275 return Ok(id);
276 }
277 if supervisor.try_wait()?.is_some() || Instant::now() >= deadline {
278 let _ = supervisor.kill();
279 let _ = supervisor.wait();
280 bail!(
281 "watch supervisor did not acknowledge startup; its durable reservation will be reconciled"
282 );
283 }
284 std::thread::sleep(Duration::from_millis(20));
285 }
286}
287
288fn identity(pid: u32) -> Result<(u32, String)> {
289 Ok((
290 pid,
291 crate::proc::process_started_at(pid).context("cannot identify watch process")?,
292 ))
293}
294
295fn append_tail(tail: &mut Vec<u8>, bytes: &[u8]) {
296 tail.extend_from_slice(bytes);
297 if tail.len() > OUTPUT_CAP {
298 tail.drain(..tail.len() - OUTPUT_CAP);
299 }
300}
301
302fn reader(
303 mut pipe: impl Pipe + Send + 'static,
304 tail: Arc<Mutex<Vec<u8>>>,
305 stopped: Arc<AtomicBool>,
306) -> std::thread::JoinHandle<()> {
307 std::thread::spawn(move || {
308 let mut chunk = [0; 4096];
309 if pipe.nonblocking().is_err() {
310 return;
311 }
312 let mut final_budget = None;
313 loop {
314 if stopped.load(Ordering::Acquire) {
317 let remaining = final_budget.get_or_insert(OUTPUT_CAP * 16);
318 if *remaining == 0 {
319 break;
320 }
321 }
322 match pipe.read_available(&mut chunk) {
323 Ok(0) => break,
324 Ok(n) => {
325 append_tail(
326 &mut tail.lock().unwrap_or_else(|e| e.into_inner()),
327 &chunk[..n],
328 );
329 if let Some(remaining) = final_budget.as_mut() {
330 *remaining = remaining.saturating_sub(n);
331 }
332 }
333 Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
334 Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
335 if stopped.load(Ordering::Acquire) {
336 break;
337 }
338 std::thread::sleep(Duration::from_millis(10));
339 }
340 Err(_) => break,
341 }
342 }
343 })
344}
345
346#[cfg(unix)]
347fn kill_group(pid: u32) {
348 if let Ok(pid) = libc::pid_t::try_from(pid) {
349 unsafe {
352 libc::kill(-pid, libc::SIGKILL);
353 }
354 }
355}
356
357#[cfg(not(unix))]
358fn kill_group(_pid: u32) {}
359
360fn watch_timeout(
363 startup_deadline: Instant,
364 execution_deadline: &mut Option<Instant>,
365 executing: bool,
366 timeout: u64,
367 now: Instant,
368) -> Option<String> {
369 if executing && execution_deadline.is_none() {
370 *execution_deadline = Some(now + Duration::from_secs(timeout));
371 }
372 match *execution_deadline {
373 Some(deadline) if now >= deadline => Some(format!(
374 "timed out after {timeout} second{}",
375 if timeout == 1 { "" } else { "s" }
376 )),
377 None if now >= startup_deadline => {
378 Some("startup failed: watch wrapper did not start the command".to_owned())
379 }
380 _ => None,
381 }
382}
383
384pub fn supervise(home: &Path, id: &str) -> Result<()> {
387 if id.contains(['/', '\\']) || id == "." || id == ".." {
388 bail!("invalid watch id");
389 }
390 let dir = root(home).join(id);
391 let _lease = lock(&dir.join("lease.lock"))?;
392 let mut job = load(&dir)?;
393 if job.result.is_some() || job.supervisor.is_some() {
394 return Ok(());
395 }
396 job.supervisor = Some(identity(std::process::id())?);
397 save(&dir, &job)?;
398 let mut cmd = Command::new(crate::updater::current_exe()?);
399 cmd.arg("talk")
400 .arg("watch-exec")
401 .arg(home)
402 .arg(id)
403 .current_dir(&job.cwd)
404 .env_remove("MAGI_RUN")
405 .env_remove("MAGI_NODE")
406 .stdin(Stdio::null())
407 .stdout(Stdio::piped())
408 .stderr(Stdio::piped());
409 cmd.quiet();
410 crate::chat_control::bridge::clear_std_environment(&mut cmd);
411 #[cfg(unix)]
412 {
413 use std::os::unix::process::CommandExt;
414 cmd.process_group(0);
415 }
416 let mut child = match cmd.spawn() {
417 Ok(c) => c,
418 Err(e) => {
419 job.result = Some(format!("startup failed: {e}"));
420 save(&dir, &job)?;
421 return Ok(());
422 }
423 };
424 #[cfg(windows)]
425 let containment = match windows::Containment::assign(&child) {
426 Ok(c) => c,
427 Err(e) => {
428 let _ = child.kill();
429 let _ = child.wait();
430 return Err(e.into());
431 }
432 };
433 let registered = identity(child.id()).and_then(|pid| {
435 job.child = Some(pid);
436 save(&dir, &job)
437 });
438 if let Err(e) = registered {
439 kill_group(child.id());
440 #[cfg(windows)]
441 drop(containment);
442 let _ = child.wait();
443 return Err(e);
444 }
445 std::fs::write(dir.join("armed"), b"ready")?;
449 let tail = Arc::new(Mutex::new(Vec::new()));
450 let stopped = Arc::new(AtomicBool::new(false));
451 let out = reader(
452 child.stdout.take().context("missing stdout")?,
453 tail.clone(),
454 stopped.clone(),
455 );
456 let err = reader(
457 child.stderr.take().context("missing stderr")?,
458 tail.clone(),
459 stopped.clone(),
460 );
461 let startup_deadline = Instant::now() + Duration::from_secs(10);
462 let mut execution_deadline = None;
463 let outcome = loop {
464 match child.try_wait() {
465 Ok(Some(status)) => {
466 #[cfg(unix)]
467 {
468 use std::os::unix::process::ExitStatusExt;
469 break status.code().map_or_else(
470 || format!("terminated by signal {}", status.signal().unwrap_or(0)),
471 |code| format!("exited with status {code}"),
472 );
473 }
474 #[cfg(not(unix))]
475 break status.code().map_or_else(
476 || "terminated without an exit code".to_owned(),
477 |code| format!("exited with status {code}"),
478 );
479 }
480 Err(e) => break format!("result unknown: {e}"),
481 Ok(None) => {
482 let executing = execution_deadline.is_some() || dir.join("executing").is_file();
483 if let Some(result) = watch_timeout(
484 startup_deadline,
485 &mut execution_deadline,
486 executing,
487 job.timeout,
488 Instant::now(),
489 ) {
490 break result;
491 }
492 std::thread::sleep(Duration::from_millis(20));
493 }
494 }
495 };
496 kill_group(child.id());
497 #[cfg(windows)]
498 drop(containment);
499 let _ = child.wait();
500 stopped.store(true, Ordering::Release);
501 let _ = out.join();
502 let _ = err.join();
503 job.tail =
504 String::from_utf8_lossy(&tail.lock().unwrap_or_else(|e| e.into_inner())).into_owned();
505 job.result = Some(match std::fs::read_to_string(dir.join("spawn-error")) {
506 Ok(error) => format!("startup failed: {error}"),
507 Err(_) => outcome,
508 });
509 save(&dir, &job)
510}
511
512pub fn sweep(home: &Path, talks: &Talks) {
515 if !root(home).exists() {
516 return;
517 }
518 let sweep = || -> Result<()> {
519 let _store = lock(&root(home).join("store.lock"))?;
520 for dir in directories(home)? {
521 let Some(_lease) = try_lock(&dir.join("lease.lock"))? else {
522 continue;
523 };
524 let result = reconcile(&dir, talks);
525 if let Err(e) = result {
526 tracing::warn!("watch completion not queued: {e:#}");
527 }
528 }
529 Ok(())
530 };
531 if let Err(e) = sweep() {
532 tracing::warn!("watch sweep: {e:#}");
533 }
534}
535
536fn reconcile(dir: &Path, talks: &Talks) -> Result<()> {
537 let mut job = load(dir)?;
538 if job.delivered {
539 return Ok(());
540 }
541 if job.result.is_none() {
542 if let Some((pid, started)) = &job.child {
543 match (
544 crate::proc::pid_status(*pid),
545 crate::proc::process_started_at(*pid),
546 ) {
547 (Some(false), _) => kill_group(*pid),
548 (Some(true), Some(current)) if current == *started => kill_group(*pid),
549 (Some(true), Some(_)) => {} _ => return Ok(()), }
552 }
553 job.result =
554 Some("result unknown: supervisor was lost; job will not be restarted".to_owned());
555 save(dir, &job)?;
556 }
557 let gone = || {
560 matches!(
561 std::fs::symlink_metadata(talks.path_of(&job.talk)),
562 Err(error) if error.kind() == std::io::ErrorKind::NotFound
563 )
564 };
565 let mut t = match talks.get(&job.talk) {
566 Ok(t) if t.status.open() => t,
567 Ok(_) => {
568 job.delivered = true;
569 return save(dir, &job);
570 }
571 Err(_) if gone() => {
572 job.delivered = true;
573 return save(dir, &job);
574 }
575 Err(e) => return Err(e),
576 };
577 let (text, display) = crate::prompt::chat_watch_report(
578 &job.id,
579 job.result.as_deref().unwrap_or("unknown"),
580 &job.tail,
581 );
582 if let Err(e) = talk::queue_notice(
583 &mut t,
584 talks,
585 &text,
586 &format!("watch:{}:finished", job.id),
587 &|_| false,
588 crate::chat_control::standing::Event::Watch { id: job.id.clone() },
589 display,
590 ) {
591 match talks.get(&job.talk) {
592 Ok(t) if !t.status.open() => {}
593 Err(_) if gone() => {}
594 _ => return Err(e),
595 }
596 }
597 job.delivered = true;
598 save(dir, &job)
599}
600
601pub fn execute(home: &Path, id: &str) -> Result<()> {
604 #[cfg(unix)]
605 use std::os::unix::process::CommandExt;
606 if id.contains(['/', '\\']) || id == "." || id == ".." {
607 bail!("invalid watch id");
608 }
609 let dir = root(home).join(id);
610 let deadline = Instant::now() + Duration::from_secs(10);
611 loop {
612 let job = load(&dir)?;
613 let (pid, started) = job.supervisor.as_ref().context("missing supervisor")?;
614 if job.result.is_some()
615 || crate::proc::pid_status(*pid) == Some(false)
616 || crate::proc::process_started_at(*pid).is_some_and(|s| s != *started)
617 {
618 bail!("watch supervisor was lost before launch");
619 }
620 if dir.join("armed").exists() {
621 if job.child.as_ref() != Some(&identity(std::process::id())?) {
622 bail!("watch launch belongs to a different process");
623 }
624 let mut command = Command::new(&job.command[0]);
625 command
626 .args(&job.command[1..])
627 .current_dir(&job.cwd)
628 .env_remove("MAGI_RUN")
629 .env_remove("MAGI_NODE");
630 crate::chat_control::bridge::clear_std_environment(&mut command);
631 command.quiet();
632 std::fs::write(dir.join("executing"), b"ready")?;
635 #[cfg(unix)]
636 let error = command.exec();
637 #[cfg(windows)]
638 let error = match command.status() {
639 Ok(status) => std::process::exit(status.code().unwrap_or(1)),
640 Err(error) => error,
641 };
642 std::fs::write(dir.join("spawn-error"), error.to_string())?;
643 return Err(error.into());
644 }
645 if Instant::now() >= deadline {
646 bail!("watch launch was not armed");
647 }
648 std::thread::sleep(Duration::from_millis(10));
649 }
650}
651
652trait Pipe: Read {
653 fn nonblocking(&self) -> std::io::Result<()>;
654 fn read_available(&mut self, bytes: &mut [u8]) -> std::io::Result<usize>;
655}
656
657#[cfg(unix)]
658impl<T: Read + std::os::fd::AsRawFd> Pipe for T {
659 fn nonblocking(&self) -> std::io::Result<()> {
660 let fd = self.as_raw_fd();
661 unsafe {
663 let flags = libc::fcntl(fd, libc::F_GETFL);
664 if flags < 0 || libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK) < 0 {
665 return Err(std::io::Error::last_os_error());
666 }
667 }
668 Ok(())
669 }
670 fn read_available(&mut self, bytes: &mut [u8]) -> std::io::Result<usize> {
671 self.read(bytes)
672 }
673}
674
675#[cfg(windows)]
676impl<T: Read + std::os::windows::io::AsRawHandle> Pipe for T {
677 fn nonblocking(&self) -> std::io::Result<()> {
678 Ok(())
679 }
680 fn read_available(&mut self, bytes: &mut [u8]) -> std::io::Result<usize> {
681 let available = windows::available(self.as_raw_handle())?;
682 if available == 0 {
683 return Err(std::io::ErrorKind::WouldBlock.into());
684 }
685 let count = bytes.len().min(available as usize);
686 self.read(&mut bytes[..count])
687 }
688}
689
690#[cfg(windows)]
693pub(crate) mod windows {
694 use std::ffi::c_void;
695 use std::os::windows::io::AsRawHandle;
696 type Handle = *mut c_void;
697 #[repr(C)]
698 #[derive(Default)]
699 struct Overlapped {
700 internal: usize,
701 internal_high: usize,
702 offset: u32,
703 offset_high: u32,
704 event: Handle,
705 }
706 #[repr(C)]
707 #[derive(Default)]
708 struct BasicLimits {
709 process_time: i64,
710 job_time: i64,
711 flags: u32,
712 min_working_set: usize,
713 max_working_set: usize,
714 active_processes: u32,
715 affinity: usize,
716 priority: u32,
717 scheduling: u32,
718 }
719 #[repr(C)]
720 #[derive(Default)]
721 struct ExtendedLimits {
722 basic: BasicLimits,
723 io: [u64; 6],
724 process_memory: usize,
725 job_memory: usize,
726 peak_process_memory: usize,
727 peak_job_memory: usize,
728 }
729 #[repr(C)]
730 #[derive(Default)]
731 struct ThreadEntry {
732 size: u32,
733 usage: u32,
734 id: u32,
735 owner: u32,
736 base_priority: i32,
737 delta_priority: i32,
738 flags: u32,
739 }
740 #[repr(C)]
741 #[derive(Default)]
742 struct Accounting {
743 times: [i64; 4],
744 faults: u32,
745 total: u32,
746 active: u32,
747 terminated: u32,
748 }
749 #[link(name = "kernel32")]
750 unsafe extern "system" {
751 fn LockFileEx(
752 file: Handle,
753 flags: u32,
754 reserved: u32,
755 bytes: u32,
756 bytes_high: u32,
757 overlapped: *mut Overlapped,
758 ) -> i32;
759 fn UnlockFileEx(
760 file: Handle,
761 reserved: u32,
762 bytes: u32,
763 bytes_high: u32,
764 overlapped: *mut Overlapped,
765 ) -> i32;
766 fn CreateJobObjectW(attributes: Handle, name: *const u16) -> Handle;
767 fn SetInformationJobObject(job: Handle, class: i32, info: *const c_void, size: u32) -> i32;
768 fn AssignProcessToJobObject(job: Handle, process: Handle) -> i32;
769 fn TerminateJobObject(job: Handle, code: u32) -> i32;
770 fn CreateToolhelp32Snapshot(flags: u32, pid: u32) -> Handle;
771 fn Thread32First(snapshot: Handle, entry: *mut ThreadEntry) -> i32;
772 fn Thread32Next(snapshot: Handle, entry: *mut ThreadEntry) -> i32;
773 fn OpenThread(access: u32, inherit: i32, id: u32) -> Handle;
774 fn ResumeThread(thread: Handle) -> u32;
775 fn CloseHandle(handle: Handle) -> i32;
776 fn GetCurrentProcess() -> Handle;
777 fn IsProcessInJob(process: Handle, job: Handle, result: *mut i32) -> i32;
778 fn QueryInformationJobObject(
779 job: Handle,
780 class: i32,
781 info: *mut c_void,
782 size: u32,
783 returned: *mut u32,
784 ) -> i32;
785 fn PeekNamedPipe(
786 pipe: Handle,
787 buffer: Handle,
788 size: u32,
789 read: *mut u32,
790 available: *mut u32,
791 left: *mut u32,
792 ) -> i32;
793 }
794 pub fn lock_file(file: Handle, immediate: bool) -> std::io::Result<bool> {
795 lock_file_mode(file, immediate, true)
796 }
797 pub(crate) fn lock_file_mode(
798 file: Handle,
799 immediate: bool,
800 exclusive: bool,
801 ) -> std::io::Result<bool> {
802 let mut overlapped = Overlapped::default();
803 let flags = (if exclusive { 2 } else { 0 }) | u32::from(immediate);
804 if unsafe { LockFileEx(file, flags, 0, 1, 0, &mut overlapped) } != 0 {
805 return Ok(true);
806 }
807 let error = std::io::Error::last_os_error();
808 if immediate && error.raw_os_error() == Some(33) {
809 return Ok(false);
810 }
811 Err(error)
812 }
813 pub fn unlock_file(file: Handle) {
814 let mut overlapped = Overlapped::default();
815 unsafe {
816 UnlockFileEx(file, 0, 1, 0, &mut overlapped);
817 }
818 }
819 pub(crate) fn detached_flags() -> std::io::Result<u32> {
822 let mut in_job = 0;
823 if unsafe { IsProcessInJob(GetCurrentProcess(), std::ptr::null_mut(), &mut in_job) } == 0 {
824 return Err(std::io::Error::last_os_error());
825 }
826 if in_job == 0 {
827 return Ok(0x0000_0008 | 0x0000_0200);
828 }
829 let mut limits = BasicLimits::default();
830 if unsafe {
831 QueryInformationJobObject(
832 std::ptr::null_mut(),
833 2,
834 std::ptr::from_mut(&mut limits).cast(),
835 std::mem::size_of::<BasicLimits>() as u32,
836 std::ptr::null_mut(),
837 )
838 } == 0
839 {
840 return Err(std::io::Error::last_os_error());
841 }
842 let detached = 0x0000_0008 | 0x0000_0200;
843 if limits.flags & 0x1000 != 0 {
844 return Ok(detached);
845 } if limits.flags & 0x0800 != 0 {
847 return Ok(detached | 0x0100_0000);
848 } Ok(detached)
852 }
853
854 pub struct Containment(Handle);
855 unsafe impl Send for Containment {}
857 impl Containment {
858 pub fn assign(child: &std::process::Child) -> std::io::Result<Self> {
859 Self::assign_handle(child.as_raw_handle())
860 }
861
862 pub(crate) fn assign_handle(process: Handle) -> std::io::Result<Self> {
863 unsafe {
864 let handle = CreateJobObjectW(std::ptr::null_mut(), std::ptr::null());
865 if handle.is_null() {
866 return Err(std::io::Error::last_os_error());
867 }
868 let job = Self(handle);
869 let mut limits = ExtendedLimits::default();
870 limits.basic.flags = 0x2000; if SetInformationJobObject(
872 handle,
873 9,
874 std::ptr::from_ref(&limits).cast(),
875 std::mem::size_of::<ExtendedLimits>() as u32,
876 ) == 0
877 || AssignProcessToJobObject(handle, process) == 0
878 {
879 return Err(std::io::Error::last_os_error());
880 }
881 Ok(job)
882 }
883 }
884
885 pub(crate) fn resume_suspended(&self, pid: u32) -> std::io::Result<()> {
886 use std::os::windows::io::{AsRawHandle as _, FromRawHandle as _, OwnedHandle};
887 unsafe {
889 let snapshot = CreateToolhelp32Snapshot(4, 0); if snapshot as isize == -1 {
891 return Err(std::io::Error::last_os_error());
892 }
893 let snapshot = OwnedHandle::from_raw_handle(snapshot);
894 let mut entry = ThreadEntry {
895 size: std::mem::size_of::<ThreadEntry>() as u32,
896 ..ThreadEntry::default()
897 };
898 let mut found = Thread32First(snapshot.as_raw_handle(), &mut entry);
899 while found != 0 {
900 if entry.owner == pid {
901 let thread = OpenThread(2, 0, entry.id); if thread.is_null() {
903 return Err(std::io::Error::last_os_error());
904 }
905 let thread = OwnedHandle::from_raw_handle(thread);
906 return match ResumeThread(thread.as_raw_handle()) {
907 1 => Ok(()),
908 u32::MAX => Err(std::io::Error::last_os_error()),
909 _ => Err(std::io::Error::other("unexpected process suspend count")),
910 };
911 }
912 entry.size = std::mem::size_of::<ThreadEntry>() as u32;
913 found = Thread32Next(snapshot.as_raw_handle(), &mut entry);
914 }
915 }
916 Err(std::io::Error::other("primary thread not found"))
917 }
918
919 pub(crate) fn stop_and_wait(&self) {
920 let mut info = Accounting::default();
921 loop {
922 unsafe {
924 TerminateJobObject(self.0, 1);
925 if QueryInformationJobObject(
926 self.0,
927 1,
928 std::ptr::from_mut(&mut info).cast(),
929 std::mem::size_of::<Accounting>() as u32,
930 std::ptr::null_mut(),
931 ) != 0
932 && info.active == 0
933 {
934 return;
935 }
936 }
937 std::thread::sleep(std::time::Duration::from_millis(20));
938 }
939 }
940 }
941 impl Drop for Containment {
942 fn drop(&mut self) {
943 unsafe {
944 CloseHandle(self.0);
945 }
946 }
947 }
948 pub fn available(pipe: Handle) -> std::io::Result<u32> {
949 let mut available = 0;
950 if unsafe {
951 PeekNamedPipe(
952 pipe,
953 std::ptr::null_mut(),
954 0,
955 std::ptr::null_mut(),
956 &mut available,
957 std::ptr::null_mut(),
958 )
959 } == 0
960 {
961 return Err(std::io::Error::last_os_error());
962 }
963 Ok(available)
964 }
965}
966
967#[cfg(test)]
968mod tests {
969 use super::*;
970
971 #[test]
972 fn later_report_watch_evidence_requires_successful_registration() {
973 let tmp = tempfile::tempdir().unwrap();
974 let home = tmp.path();
975 assert!(registered_ids(home, "chat").unwrap().is_empty());
976 let dir = root(home).join("watch-id");
977 std::fs::create_dir_all(&dir).unwrap();
978 let mut job = Job {
979 id: "watch-id".into(),
980 talk: "chat".into(),
981 cwd: PathBuf::from("."),
982 command: vec!["test".into()],
983 timeout: 1,
984 supervisor: None,
985 child: None,
986 result: Some("supervisor startup failed".into()),
987 tail: String::new(),
988 delivered: false,
989 };
990 save(&dir, &job).unwrap();
991 assert!(registered_ids(home, "chat").unwrap().is_empty());
992 job.supervisor = Some((1, "identity".into()));
993 save(&dir, &job).unwrap();
994 assert_eq!(
996 registered_ids(home, "chat").unwrap(),
997 ["watch-id".into()].into()
998 );
999 assert!(registered_ids(home, "another-chat").unwrap().is_empty());
1000 job.result = None;
1001 save(&dir, &job).unwrap();
1002 assert!(registered_ids(home, "chat").unwrap().is_empty());
1003 job.child = Some((2, "child".into()));
1004 save(&dir, &job).unwrap();
1005 assert_eq!(
1006 registered_ids(home, "chat").unwrap(),
1007 ["watch-id".into()].into()
1008 );
1009 std::fs::write(dir.join("job.json"), "{").unwrap();
1010 assert!(registered_ids(home, "chat").is_err());
1011 }
1012
1013 struct EndlessOutput;
1014 impl Read for EndlessOutput {
1015 fn read(&mut self, bytes: &mut [u8]) -> std::io::Result<usize> {
1016 bytes.fill(b'x');
1017 Ok(bytes.len())
1018 }
1019 }
1020 impl Pipe for EndlessOutput {
1021 fn nonblocking(&self) -> std::io::Result<()> {
1022 Ok(())
1023 }
1024 fn read_available(&mut self, bytes: &mut [u8]) -> std::io::Result<usize> {
1025 self.read(bytes)
1026 }
1027 }
1028
1029 #[test]
1030 fn wrapper_startup_does_not_spend_the_command_timeout() {
1031 let start = Instant::now();
1032 let startup = start + Duration::from_secs(10);
1033 let mut execution = None;
1034 let ready = start + Duration::from_secs(9);
1035 assert_eq!(
1036 watch_timeout(startup, &mut execution, false, 1, ready),
1037 None
1038 );
1039 assert_eq!(watch_timeout(startup, &mut execution, true, 1, ready), None);
1040 assert_eq!(
1041 watch_timeout(
1042 startup,
1043 &mut execution,
1044 true,
1045 1,
1046 ready + Duration::from_millis(999)
1047 ),
1048 None
1049 );
1050 assert_eq!(
1051 watch_timeout(
1052 startup,
1053 &mut execution,
1054 false,
1055 1,
1056 ready + Duration::from_secs(1)
1057 ),
1058 Some("timed out after 1 second".into())
1059 );
1060 }
1061
1062 #[test]
1063 fn an_unstarted_wrapper_has_a_bounded_startup_failure() {
1064 let deadline = Instant::now();
1065 let mut execution = None;
1066 assert_eq!(
1067 watch_timeout(deadline, &mut execution, false, 1, deadline),
1068 Some("startup failed: watch wrapper did not start the command".into())
1069 );
1070 assert!(execution.is_none());
1071 }
1072
1073 #[test]
1074 fn stopped_readers_finish_even_if_an_inherited_pipe_never_stops_writing() {
1075 let tail = Arc::new(Mutex::new(Vec::new()));
1076 reader(EndlessOutput, tail.clone(), Arc::new(AtomicBool::new(true)))
1077 .join()
1078 .expect("reader finished");
1079 assert_eq!(tail.lock().expect("tail").len(), OUTPUT_CAP);
1080 }
1081}