Skip to main content

magi/
chat_watch.rs

1//! Durable, supervised jobs started by a standing chat. Results use the same
2//! draft/turn delivery as task completion notices; jobs never run twice.
3
4use 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
18/// Default and maximum job durations, in seconds.
19pub const DEFAULT_TIMEOUT: u64 = 900;
20/// Long jobs should be filed as tasks instead.
21pub const MAX_TIMEOUT: u64 = 3600;
22/// Reservations count against this global limit too.
23pub const MAX_CONCURRENT: usize = 4;
24/// Maximum retained output, shared by stdout and stderr.
25pub 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
145/// Only the standing chat's own environment chooses the destination.
146pub fn authorize(talks: &Talks, run: &str, node: &str) -> Result<String> {
147    if node != crate::queue::CHAT_NODE || run.trim().is_empty() {
148        bail!("talk watch requires MAGI_NODE=chat and MAGI_RUN from a standing chat");
149    }
150    let t = talks.get(run)?;
151    if t.id != run || !t.status.open() {
152        bail!("talk watch requires the exact id of an open conversation");
153    }
154    Ok(t.id)
155}
156
157/// Reserve a slot and detach a supervisor. Return only after it has recorded
158/// startup (including an executable spawn failure, which is reported normally).
159pub fn start(
160    home: &Path,
161    talks: &Talks,
162    run: &str,
163    node: &str,
164    command: Vec<String>,
165    timeout: u64,
166) -> Result<String> {
167    let talk = authorize(talks, run, node)?;
168    if command.is_empty() || !(1..=MAX_TIMEOUT).contains(&timeout) {
169        bail!("watch needs a command and a timeout between 1 and {MAX_TIMEOUT} seconds");
170    }
171    std::fs::create_dir_all(root(home))?;
172    let _store = lock(&root(home).join("store.lock"))?;
173    let active = directories(home)?
174        .iter()
175        .try_fold(0, |n, dir| -> Result<usize> {
176            Ok(n + usize::from(load(dir)?.result.is_none()))
177        })?;
178    if active >= MAX_CONCURRENT {
179        bail!("at most {MAX_CONCURRENT} chat watches may run concurrently");
180    }
181    let id = crate::rng::SplitMix64::new(crate::rng::entropy()).uuid_v4();
182    let dir = root(home).join(&id);
183    let staging = root(home).join(format!(".new-{id}"));
184    std::fs::create_dir(&staging)?;
185    let mut job = Job {
186        id: id.clone(),
187        talk,
188        cwd: std::env::current_dir()?,
189        command,
190        timeout,
191        supervisor: None,
192        child: None,
193        result: None,
194        tail: String::new(),
195        delivered: false,
196    };
197    save(&staging, &job)?;
198    std::fs::rename(&staging, &dir)?;
199    let mut cmd = Command::new(std::env::current_exe()?);
200    cmd.arg("talk")
201        .arg("watch-run")
202        .arg(home)
203        .arg(&id)
204        .env_remove("MAGI_RUN")
205        .env_remove("MAGI_NODE")
206        .stdin(Stdio::null())
207        .stdout(Stdio::null())
208        .stderr(Stdio::null());
209    #[cfg(unix)]
210    {
211        use std::os::unix::process::CommandExt;
212        // A separate session also survives the calling agent's group cleanup.
213        unsafe {
214            cmd.pre_exec(|| {
215                if libc::setsid() < 0 {
216                    return Err(std::io::Error::last_os_error());
217                }
218                Ok(())
219            });
220        }
221    }
222    #[cfg(windows)]
223    {
224        use std::os::windows::process::CommandExt;
225        // DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP: no console to inherit,
226        // and the calling agent's terminal must not end supervision.
227        cmd.creation_flags(0x0000_0008 | 0x0000_0200);
228    }
229    let mut supervisor = match cmd.spawn() {
230        Ok(child) => child,
231        Err(e) => {
232            job.result = Some(format!("supervisor startup failed: {e}"));
233            save(&dir, &job)?;
234            return Err(e.into());
235        }
236    };
237    let deadline = Instant::now() + Duration::from_secs(10);
238    loop {
239        let fresh = load(&dir)?;
240        if fresh.supervisor.is_some() && (fresh.child.is_some() || fresh.result.is_some()) {
241            // Reap while the calling process is alive; after it exits the
242            // detached supervisor is reparented and reaped by the platform.
243            std::thread::spawn(move || {
244                let _ = supervisor.wait();
245            });
246            return Ok(id);
247        }
248        if supervisor.try_wait()?.is_some() || Instant::now() >= deadline {
249            let _ = supervisor.kill();
250            let _ = supervisor.wait();
251            bail!(
252                "watch supervisor did not acknowledge startup; its durable reservation will be reconciled"
253            );
254        }
255        std::thread::sleep(Duration::from_millis(20));
256    }
257}
258
259fn identity(pid: u32) -> Result<(u32, String)> {
260    Ok((
261        pid,
262        crate::proc::process_started_at(pid).context("cannot identify watch process")?,
263    ))
264}
265
266fn append_tail(tail: &mut Vec<u8>, bytes: &[u8]) {
267    tail.extend_from_slice(bytes);
268    if tail.len() > OUTPUT_CAP {
269        tail.drain(..tail.len() - OUTPUT_CAP);
270    }
271}
272
273fn reader(
274    mut pipe: impl Pipe + Send + 'static,
275    tail: Arc<Mutex<Vec<u8>>>,
276    stopped: Arc<AtomicBool>,
277) -> std::thread::JoinHandle<()> {
278    std::thread::spawn(move || {
279        let mut chunk = [0; 4096];
280        if pipe.nonblocking().is_err() {
281            return;
282        }
283        let mut final_budget = None;
284        loop {
285            // Drain buffered output after exit, but even an escaped process
286            // continuously writing to an inherited pipe cannot keep us here.
287            if stopped.load(Ordering::Acquire) {
288                let remaining = final_budget.get_or_insert(OUTPUT_CAP * 16);
289                if *remaining == 0 {
290                    break;
291                }
292            }
293            match pipe.read_available(&mut chunk) {
294                Ok(0) => break,
295                Ok(n) => {
296                    append_tail(
297                        &mut tail.lock().unwrap_or_else(|e| e.into_inner()),
298                        &chunk[..n],
299                    );
300                    if let Some(remaining) = final_budget.as_mut() {
301                        *remaining = remaining.saturating_sub(n);
302                    }
303                }
304                Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
305                Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
306                    if stopped.load(Ordering::Acquire) {
307                        break;
308                    }
309                    std::thread::sleep(Duration::from_millis(10));
310                }
311                Err(_) => break,
312            }
313        }
314    })
315}
316
317#[cfg(unix)]
318fn kill_group(pid: u32) {
319    if let Ok(pid) = libc::pid_t::try_from(pid) {
320        // Every watch child gets its own group, so this also closes pipes
321        // inherited by its descendants after the direct child exits.
322        unsafe {
323            libc::kill(-pid, libc::SIGKILL);
324        }
325    }
326}
327
328#[cfg(not(unix))]
329fn kill_group(_pid: u32) {}
330
331/// Internal supervisor entry point. The per-job OS lock is a durable lease:
332/// released on process death, without age-based guesses or restarting the job.
333pub fn supervise(home: &Path, id: &str) -> Result<()> {
334    if id.contains(['/', '\\']) || id == "." || id == ".." {
335        bail!("invalid watch id");
336    }
337    let dir = root(home).join(id);
338    let _lease = lock(&dir.join("lease.lock"))?;
339    let mut job = load(&dir)?;
340    if job.result.is_some() || job.supervisor.is_some() {
341        return Ok(());
342    }
343    job.supervisor = Some(identity(std::process::id())?);
344    save(&dir, &job)?;
345    let mut cmd = Command::new(std::env::current_exe()?);
346    cmd.arg("talk")
347        .arg("watch-exec")
348        .arg(home)
349        .arg(id)
350        .current_dir(&job.cwd)
351        .env_remove("MAGI_RUN")
352        .env_remove("MAGI_NODE")
353        .stdin(Stdio::null())
354        .stdout(Stdio::piped())
355        .stderr(Stdio::piped());
356    cmd.quiet();
357    #[cfg(unix)]
358    {
359        use std::os::unix::process::CommandExt;
360        cmd.process_group(0);
361    }
362    let mut child = match cmd.spawn() {
363        Ok(c) => c,
364        Err(e) => {
365            job.result = Some(format!("startup failed: {e}"));
366            save(&dir, &job)?;
367            return Ok(());
368        }
369    };
370    #[cfg(windows)]
371    let containment = match windows::Containment::assign(&child) {
372        Ok(c) => c,
373        Err(e) => {
374            let _ = child.kill();
375            let _ = child.wait();
376            return Err(e.into());
377        }
378    };
379    // If identity or persistence fails, do not leave an untracked process.
380    let registered = identity(child.id()).and_then(|pid| {
381        job.child = Some(pid);
382        save(&dir, &job)
383    });
384    if let Err(e) = registered {
385        kill_group(child.id());
386        #[cfg(windows)]
387        drop(containment);
388        let _ = child.wait();
389        return Err(e);
390    }
391    // The wrapper may execute only after its PID has been persisted. A
392    // supervisor crash in the spawn/save gap leaves an inert wrapper, not an
393    // untracked command. It exits when it detects the supervisor is gone.
394    std::fs::write(dir.join("armed"), b"ready")?;
395    let tail = Arc::new(Mutex::new(Vec::new()));
396    let stopped = Arc::new(AtomicBool::new(false));
397    let out = reader(
398        child.stdout.take().context("missing stdout")?,
399        tail.clone(),
400        stopped.clone(),
401    );
402    let err = reader(
403        child.stderr.take().context("missing stderr")?,
404        tail.clone(),
405        stopped.clone(),
406    );
407    let deadline = Instant::now() + Duration::from_secs(job.timeout);
408    let outcome = loop {
409        match child.try_wait() {
410            Ok(Some(status)) => {
411                #[cfg(unix)]
412                {
413                    use std::os::unix::process::ExitStatusExt;
414                    break status.code().map_or_else(
415                        || format!("terminated by signal {}", status.signal().unwrap_or(0)),
416                        |code| format!("exited with status {code}"),
417                    );
418                }
419                #[cfg(not(unix))]
420                break status.code().map_or_else(
421                    || "terminated without an exit code".to_owned(),
422                    |code| format!("exited with status {code}"),
423                );
424            }
425            Err(e) => break format!("result unknown: {e}"),
426            Ok(None) if Instant::now() >= deadline => {
427                break format!(
428                    "timed out after {} second{}",
429                    job.timeout,
430                    if job.timeout == 1 { "" } else { "s" }
431                );
432            }
433            Ok(None) => std::thread::sleep(Duration::from_millis(20)),
434        }
435    };
436    kill_group(child.id());
437    #[cfg(windows)]
438    drop(containment);
439    let _ = child.wait();
440    stopped.store(true, Ordering::Release);
441    let _ = out.join();
442    let _ = err.join();
443    job.tail =
444        String::from_utf8_lossy(&tail.lock().unwrap_or_else(|e| e.into_inner())).into_owned();
445    job.result = Some(match std::fs::read_to_string(dir.join("spawn-error")) {
446        Ok(error) => format!("startup failed: {error}"),
447        Err(_) => outcome,
448    });
449    save(&dir, &job)
450}
451
452/// Reconcile completed or abandoned watches and queue each notice once. Lock
453/// order is watch store, job lease, talk store. Transient errors are retried.
454pub fn sweep(home: &Path, talks: &Talks) {
455    if !root(home).exists() {
456        return;
457    }
458    let sweep = || -> Result<()> {
459        let _store = lock(&root(home).join("store.lock"))?;
460        for dir in directories(home)? {
461            let Some(_lease) = try_lock(&dir.join("lease.lock"))? else {
462                continue;
463            };
464            let result = reconcile(&dir, talks);
465            if let Err(e) = result {
466                tracing::warn!("watch completion not queued: {e:#}");
467            }
468        }
469        Ok(())
470    };
471    if let Err(e) = sweep() {
472        tracing::warn!("watch sweep: {e:#}");
473    }
474}
475
476fn reconcile(dir: &Path, talks: &Talks) -> Result<()> {
477    let mut job = load(dir)?;
478    if job.delivered {
479        return Ok(());
480    }
481    if job.result.is_none() {
482        if let Some((pid, started)) = &job.child {
483            match (
484                crate::proc::pid_status(*pid),
485                crate::proc::process_started_at(*pid),
486            ) {
487                (Some(false), _) => kill_group(*pid),
488                (Some(true), Some(current)) if current == *started => kill_group(*pid),
489                (Some(true), Some(_)) => {} // PID reused: never kill it.
490                _ => return Ok(()),         // Uncertain identity retains the slot.
491            }
492        }
493        job.result =
494            Some("result unknown: supervisor was lost; job will not be restarted".to_owned());
495        save(dir, &job)?;
496    }
497    // Listing omits unreadable records, so it cannot prove deletion. Only
498    // a missing path settles delivery; read/parse/permission errors retry.
499    let gone = || {
500        matches!(
501            std::fs::symlink_metadata(talks.path_of(&job.talk)),
502            Err(error) if error.kind() == std::io::ErrorKind::NotFound
503        )
504    };
505    let mut t = match talks.get(&job.talk) {
506        Ok(t) if t.status.open() => t,
507        Ok(_) => {
508            job.delivered = true;
509            return save(dir, &job);
510        }
511        Err(_) if gone() => {
512            job.delivered = true;
513            return save(dir, &job);
514        }
515        Err(e) => return Err(e),
516    };
517    let text = crate::prompt::chat_watch_notice(
518        &job.id,
519        job.result.as_deref().unwrap_or("unknown"),
520        &job.tail,
521    );
522    if let Err(e) = talk::queue_once(&mut t, talks, &text, &format!("watch:{}:finished", job.id)) {
523        match talks.get(&job.talk) {
524            Ok(t) if !t.status.open() => {}
525            Err(_) if gone() => {}
526            _ => return Err(e),
527        }
528    }
529    job.delivered = true;
530    save(dir, &job)
531}
532
533/// The launch gate prevents commands from starting before their identity is
534/// durable. This internal entry point cannot execute a job from another PID.
535pub fn execute(home: &Path, id: &str) -> Result<()> {
536    #[cfg(unix)]
537    use std::os::unix::process::CommandExt;
538    if id.contains(['/', '\\']) || id == "." || id == ".." {
539        bail!("invalid watch id");
540    }
541    let dir = root(home).join(id);
542    let deadline = Instant::now() + Duration::from_secs(10);
543    loop {
544        let job = load(&dir)?;
545        let (pid, started) = job.supervisor.as_ref().context("missing supervisor")?;
546        if job.result.is_some()
547            || crate::proc::pid_status(*pid) == Some(false)
548            || crate::proc::process_started_at(*pid).is_some_and(|s| s != *started)
549        {
550            bail!("watch supervisor was lost before launch");
551        }
552        if dir.join("armed").exists() {
553            if job.child.as_ref() != Some(&identity(std::process::id())?) {
554                bail!("watch launch belongs to a different process");
555            }
556            let mut command = Command::new(&job.command[0]);
557            command
558                .args(&job.command[1..])
559                .current_dir(&job.cwd)
560                .env_remove("MAGI_RUN")
561                .env_remove("MAGI_NODE");
562            command.quiet();
563            #[cfg(unix)]
564            let error = command.exec();
565            #[cfg(windows)]
566            let error = match command.status() {
567                Ok(status) => std::process::exit(status.code().unwrap_or(1)),
568                Err(error) => error,
569            };
570            std::fs::write(dir.join("spawn-error"), error.to_string())?;
571            return Err(error.into());
572        }
573        if Instant::now() >= deadline {
574            bail!("watch launch was not armed");
575        }
576        std::thread::sleep(Duration::from_millis(10));
577    }
578}
579
580trait Pipe: Read {
581    fn nonblocking(&self) -> std::io::Result<()>;
582    fn read_available(&mut self, bytes: &mut [u8]) -> std::io::Result<usize>;
583}
584
585#[cfg(unix)]
586impl<T: Read + std::os::fd::AsRawFd> Pipe for T {
587    fn nonblocking(&self) -> std::io::Result<()> {
588        let fd = self.as_raw_fd();
589        // Do not let escaped descendants keep the supervisor waiting on pipes.
590        unsafe {
591            let flags = libc::fcntl(fd, libc::F_GETFL);
592            if flags < 0 || libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK) < 0 {
593                return Err(std::io::Error::last_os_error());
594            }
595        }
596        Ok(())
597    }
598    fn read_available(&mut self, bytes: &mut [u8]) -> std::io::Result<usize> {
599        self.read(bytes)
600    }
601}
602
603#[cfg(windows)]
604impl<T: Read + std::os::windows::io::AsRawHandle> Pipe for T {
605    fn nonblocking(&self) -> std::io::Result<()> {
606        Ok(())
607    }
608    fn read_available(&mut self, bytes: &mut [u8]) -> std::io::Result<usize> {
609        let available = windows::available(self.as_raw_handle())?;
610        if available == 0 {
611            return Err(std::io::ErrorKind::WouldBlock.into());
612        }
613        let count = bytes.len().min(available as usize);
614        self.read(&mut bytes[..count])
615    }
616}
617
618// Native job objects close the whole Windows process tree when a supervisor
619// exits, even involuntarily. The launch gate stays closed until assignment.
620#[cfg(windows)]
621mod windows {
622    use std::ffi::c_void;
623    use std::os::windows::io::AsRawHandle;
624    type Handle = *mut c_void;
625    #[repr(C)]
626    #[derive(Default)]
627    struct Overlapped {
628        internal: usize,
629        internal_high: usize,
630        offset: u32,
631        offset_high: u32,
632        event: Handle,
633    }
634    #[repr(C)]
635    #[derive(Default)]
636    struct BasicLimits {
637        process_time: i64,
638        job_time: i64,
639        flags: u32,
640        min_working_set: usize,
641        max_working_set: usize,
642        active_processes: u32,
643        affinity: usize,
644        priority: u32,
645        scheduling: u32,
646    }
647    #[repr(C)]
648    #[derive(Default)]
649    struct ExtendedLimits {
650        basic: BasicLimits,
651        io: [u64; 6],
652        process_memory: usize,
653        job_memory: usize,
654        peak_process_memory: usize,
655        peak_job_memory: usize,
656    }
657    #[link(name = "kernel32")]
658    unsafe extern "system" {
659        fn LockFileEx(
660            file: Handle,
661            flags: u32,
662            reserved: u32,
663            bytes: u32,
664            bytes_high: u32,
665            overlapped: *mut Overlapped,
666        ) -> i32;
667        fn UnlockFileEx(
668            file: Handle,
669            reserved: u32,
670            bytes: u32,
671            bytes_high: u32,
672            overlapped: *mut Overlapped,
673        ) -> i32;
674        fn CreateJobObjectW(attributes: Handle, name: *const u16) -> Handle;
675        fn SetInformationJobObject(job: Handle, class: i32, info: *const c_void, size: u32) -> i32;
676        fn AssignProcessToJobObject(job: Handle, process: Handle) -> i32;
677        fn CloseHandle(handle: Handle) -> i32;
678        fn PeekNamedPipe(
679            pipe: Handle,
680            buffer: Handle,
681            size: u32,
682            read: *mut u32,
683            available: *mut u32,
684            left: *mut u32,
685        ) -> i32;
686    }
687    pub fn lock_file(file: Handle, immediate: bool) -> std::io::Result<bool> {
688        let mut overlapped = Overlapped::default();
689        if unsafe { LockFileEx(file, 2 | u32::from(immediate), 0, 1, 0, &mut overlapped) } != 0 {
690            return Ok(true);
691        }
692        let error = std::io::Error::last_os_error();
693        if immediate && error.raw_os_error() == Some(33) {
694            return Ok(false);
695        }
696        Err(error)
697    }
698    pub fn unlock_file(file: Handle) {
699        let mut overlapped = Overlapped::default();
700        unsafe {
701            UnlockFileEx(file, 0, 1, 0, &mut overlapped);
702        }
703    }
704    pub struct Containment(Handle);
705    impl Containment {
706        pub fn assign(child: &std::process::Child) -> std::io::Result<Self> {
707            unsafe {
708                let handle = CreateJobObjectW(std::ptr::null_mut(), std::ptr::null());
709                if handle.is_null() {
710                    return Err(std::io::Error::last_os_error());
711                }
712                let job = Self(handle);
713                let mut limits = ExtendedLimits::default();
714                limits.basic.flags = 0x2000; // JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
715                if SetInformationJobObject(
716                    handle,
717                    9,
718                    std::ptr::from_ref(&limits).cast(),
719                    std::mem::size_of::<ExtendedLimits>() as u32,
720                ) == 0
721                    || AssignProcessToJobObject(handle, child.as_raw_handle()) == 0
722                {
723                    return Err(std::io::Error::last_os_error());
724                }
725                Ok(job)
726            }
727        }
728    }
729    impl Drop for Containment {
730        fn drop(&mut self) {
731            unsafe {
732                CloseHandle(self.0);
733            }
734        }
735    }
736    pub fn available(pipe: Handle) -> std::io::Result<u32> {
737        let mut available = 0;
738        if unsafe {
739            PeekNamedPipe(
740                pipe,
741                std::ptr::null_mut(),
742                0,
743                std::ptr::null_mut(),
744                &mut available,
745                std::ptr::null_mut(),
746            )
747        } == 0
748        {
749            return Err(std::io::Error::last_os_error());
750        }
751        Ok(available)
752    }
753}
754
755#[cfg(test)]
756mod tests {
757    use super::*;
758
759    struct EndlessOutput;
760    impl Read for EndlessOutput {
761        fn read(&mut self, bytes: &mut [u8]) -> std::io::Result<usize> {
762            bytes.fill(b'x');
763            Ok(bytes.len())
764        }
765    }
766    impl Pipe for EndlessOutput {
767        fn nonblocking(&self) -> std::io::Result<()> {
768            Ok(())
769        }
770        fn read_available(&mut self, bytes: &mut [u8]) -> std::io::Result<usize> {
771            self.read(bytes)
772        }
773    }
774
775    #[test]
776    fn stopped_readers_finish_even_if_an_inherited_pipe_never_stops_writing() {
777        let tail = Arc::new(Mutex::new(Vec::new()));
778        reader(EndlessOutput, tail.clone(), Arc::new(AtomicBool::new(true)))
779            .join()
780            .expect("reader finished");
781        assert_eq!(tail.lock().expect("tail").len(), OUTPUT_CAP);
782    }
783}