Skip to main content

oxdock_pipe/
slot.rs

1//! Owned pipe handles: a mutex cell holding a lazily materializing slot.
2//!
3//! A [`PipeHandle`] starts [`Slot::Unbound`] and materializes on first
4//! binding : never eagerly at declaration, so the backend choice always
5//! has full usage context. Cloning the handle shares the backend (natural
6//! fan-out for explicit sharing); the last drop closes. No central index
7//! exists: resolution, keepers, and assertions all operate on handles
8//! already in hand.
9
10use std::sync::{
11    Arc, Mutex,
12    atomic::{AtomicBool, Ordering},
13};
14
15#[cfg_attr(miri, allow(unused_imports))]
16use oxdock_diagnostics::DiagnosticResult;
17
18use crate::backend::{PipeInner, ScriptPipe};
19use crate::diagnostics as pipe_diag;
20
21/// Shared reader half: mutex-guarded `Read` behind an `Arc`, so every
22/// binding aliases one channel.
23pub type SharedInput = Arc<Mutex<dyn std::io::Read + Send>>;
24
25/// Shared writer half: mutex-guarded `Write` behind an `Arc`.
26pub type SharedOutput = Arc<Mutex<dyn std::io::Write + Send>>;
27
28/// Owned OS kernel pipe reader half behind a single use slot. `Clone`
29/// shares the slot; `take` transfers the handle exactly once so no parent
30/// copy survives spawn to starve the consumer of EOF. Backed by
31/// `std::io::pipe` (stable since Rust 1.87): `pipe` on Unix, `CreatePipe`
32/// on Windows. Moved verbatim from `oxdock-process` so handle slots can
33/// own kernel pairs without a dependency cycle; behavior is unchanged.
34#[cfg(not(miri))]
35#[derive(Clone)]
36pub struct OsPipeReader {
37    inner: Arc<Mutex<Option<std::io::PipeReader>>>,
38}
39
40/// Owned OS kernel pipe writer half behind a single use slot. See
41/// [`OsPipeReader`] for the shared slot semantics. Moved verbatim from
42/// `oxdock-process`; behavior is unchanged.
43#[cfg(not(miri))]
44#[derive(Clone)]
45pub struct OsPipeWriter {
46    inner: Arc<Mutex<Option<std::io::PipeWriter>>>,
47}
48
49#[cfg(not(miri))]
50impl OsPipeReader {
51    fn new(reader: std::io::PipeReader) -> Self {
52        Self {
53            inner: Arc::new(Mutex::new(Some(reader))),
54        }
55    }
56
57    /// Take the handle for `Stdio::from`. Bails deterministically if the
58    /// descriptor was already consumed so a second spawn can never reuse a
59    /// spent pipe or leave stdio unbound.
60    pub fn take(&self) -> DiagnosticResult<std::io::PipeReader> {
61        self.inner
62            .lock()
63            .map_err(|_| pipe_diag::os_reader_lock_poisoned())?
64            .take()
65            .ok_or_else(pipe_diag::os_handle_consumed)
66    }
67
68    /// Whether this half was already taken. A poisoned slot reports live
69    /// so callers never recycle what they cannot inspect.
70    pub fn is_consumed(&self) -> bool {
71        self.inner.lock().map(|g| g.is_none()).unwrap_or(false)
72    }
73}
74
75#[cfg(not(miri))]
76impl OsPipeWriter {
77    fn new(writer: std::io::PipeWriter) -> Self {
78        Self {
79            inner: Arc::new(Mutex::new(Some(writer))),
80        }
81    }
82
83    /// Take the handle for `Stdio::from`. Bails deterministically if the
84    /// descriptor was already consumed so a second spawn can never reuse a
85    /// spent pipe or leave stdio unbound.
86    pub fn take(&self) -> DiagnosticResult<std::io::PipeWriter> {
87        self.inner
88            .lock()
89            .map_err(|_| pipe_diag::os_writer_lock_poisoned())?
90            .take()
91            .ok_or_else(pipe_diag::os_handle_consumed)
92    }
93
94    /// Whether this half was already taken. A poisoned slot reports live
95    /// so callers never recycle what they cannot inspect.
96    pub fn is_consumed(&self) -> bool {
97        self.inner.lock().map(|g| g.is_none()).unwrap_or(false)
98    }
99}
100
101/// Create a cross platform anonymous OS pipe pair for concurrent `ASYNC`
102/// pipelines. The caller moves each half into a spawn and drops any other
103/// copies immediately after spawning, otherwise the reader never sees EOF.
104/// Moved verbatim from `oxdock-process`; behavior is unchanged.
105#[cfg(not(miri))]
106pub fn create_os_pipe() -> std::io::Result<(OsPipeReader, OsPipeWriter)> {
107    let (reader, writer) = std::io::pipe()?;
108    Ok((OsPipeReader::new(reader), OsPipeWriter::new(writer)))
109}
110
111/// One anonymous OS kernel pipe pair behind take-once slots. The first
112/// producer and the first consumer each take their half; any further
113/// binding to the same handle bails deterministically instead of
114/// interleaving bytes or stealing the descriptor.
115#[cfg(not(miri))]
116#[derive(Clone)]
117pub struct OsPipeEntry {
118    /// Writer half. Only `RUN` consumes this directly; DSL commands
119    /// observe bridged shared handles instead.
120    pub writer: OsPipeWriter,
121    /// Reader half. Only `RUN` consumes this directly; DSL commands
122    /// observe bridged shared handles instead.
123    pub reader: OsPipeReader,
124}
125
126#[cfg(not(miri))]
127impl OsPipeEntry {
128    /// Mint a fresh kernel pair.
129    pub fn new() -> std::io::Result<Self> {
130        let (reader, writer) = create_os_pipe()?;
131        Ok(Self { writer, reader })
132    }
133
134    /// Both halves taken. The takers hold raw descriptors outside the
135    /// entry, so a spent entry can never serve another resolve.
136    pub fn is_spent(&self) -> bool {
137        self.reader.is_consumed() && self.writer.is_consumed()
138    }
139}
140
141/// Backend state behind a [`PipeHandle`]. Starts unbound; the first
142/// binding decides the kind under the cell lock and later bindings adapt
143/// through the existing resolution machinery instead of failing or
144/// upgrading in place.
145pub enum Slot {
146    /// Declared but never bound: no backend, no bytes.
147    Unbound,
148    /// Store-and-forward buffer shared by every binding.
149    Script {
150        /// Live backend. Cloned out for keepers, peeks, and diagnostics.
151        backend: Arc<PipeInner>,
152    },
153    /// Zero-copy OS kernel pair behind take-once slots.
154    #[cfg(not(miri))]
155    Os {
156        /// Live kernel pair. Takes are single-use per end.
157        entry: OsPipeEntry,
158    },
159}
160
161impl std::fmt::Debug for Slot {
162    /// Opaque by design: backend internals (buffers, fds) never enter
163    /// debug output; only the materialization kind shows.
164    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
165        match self {
166            Slot::Unbound => write!(f, "Unbound"),
167            Slot::Script { .. } => write!(f, "Script(..)"),
168            #[cfg(not(miri))]
169            Slot::Os { .. } => write!(f, "Os(..)"),
170        }
171    }
172}
173
174/// Owned pipe handle: cheap to clone, shared backend, no registry.
175/// `LET $p: PIPE` mints one; `LET $q: PIPE = $p` clones it.
176///
177/// Clones share everything: the backend cell, the declaring task id, and
178/// the escape flag. Identity is the cell (`Arc::ptr_eq` on it), exactly
179/// like the old bare-`Arc` handle.
180#[derive(Clone, Debug)]
181pub struct PipeHandle {
182    cell: Arc<Mutex<Slot>>,
183    declaring_task_id: u64,
184    escaped_to_child: Arc<AtomicBool>,
185}
186
187/// Mint a fresh unbound handle declared by `task_id` (`0` = root flow).
188/// The id travels with every clone so promotion checks always see the
189/// declaration origin, no matter how far the value aliases.
190pub fn new_handle_in_task(task_id: u64) -> PipeHandle {
191    PipeHandle {
192        cell: Arc::new(Mutex::new(Slot::Unbound)),
193        declaring_task_id: task_id,
194        escaped_to_child: Arc::new(AtomicBool::new(false)),
195    }
196}
197
198impl PipeHandle {
199    /// Task that executed the `LET $p: PIPE` declaration (`0` = root flow).
200    pub fn declaring_task(&self) -> u64 {
201        self.declaring_task_id
202    }
203
204    /// Whether any spawned child task can observe this handle. Set at
205    /// `ASYNC` fork time for every pipe visible in scope; sticky, since a
206    /// share, once possible, never un-happens.
207    pub fn has_escaped(&self) -> bool {
208        self.escaped_to_child.load(Ordering::SeqCst)
209    }
210
211    /// Mark escaped (see [`PipeHandle::has_escaped`]). Idempotent.
212    pub fn mark_escaped(&self) {
213        self.escaped_to_child.store(true, Ordering::SeqCst);
214    }
215
216    /// Borrow the backend cell for materialization and lock-step transitions.
217    pub(crate) fn cell(&self) -> &Arc<Mutex<Slot>> {
218        &self.cell
219    }
220
221    /// Handle identity: true iff both handles share the same backend cell
222    /// (aliases of one declaration). Never compares bytes.
223    pub fn ptr_eq(&self, other: &Self) -> bool {
224        Arc::ptr_eq(&self.cell, &other.cell)
225    }
226}
227
228/// Decided backend cloned out from under the cell lock. OS entries clone
229/// their take-once slots (takes still race deterministically at take
230/// time); script backends clone their `Arc`.
231pub enum Materialized {
232    /// Store-and-forward backend.
233    Script(Arc<PipeInner>),
234    /// Kernel pair behind take-once slots.
235    #[cfg(not(miri))]
236    Os(OsPipeEntry),
237}
238
239/// First-binding-wins materialization under the cell lock: an unbound
240/// handle decides its kind from `promote` (the caller supplies full usage
241/// context : RUN-terminated ⇒ OS, else script); a decided handle returns
242/// its kind unchanged. Later bindings with different needs adapt through
243/// the caller's resolution machinery instead of failing or upgrading here.
244pub fn materialize(handle: &PipeHandle, promote: bool) -> DiagnosticResult<Materialized> {
245    let mut guard = handle
246        .cell()
247        .lock()
248        .map_err(|_| pipe_diag::handle_lock_poisoned())?;
249    match &*guard {
250        Slot::Script { backend } => Ok(Materialized::Script(Arc::clone(backend))),
251        #[cfg(not(miri))]
252        Slot::Os { entry } => Ok(Materialized::Os(entry.clone())),
253        Slot::Unbound => {
254            #[cfg(not(miri))]
255            if promote {
256                let entry =
257                    OsPipeEntry::new().map_err(|e| pipe_diag::os_pipe_creation_failed(&e))?;
258                let out = entry.clone();
259                *guard = Slot::Os { entry };
260                return Ok(Materialized::Os(out));
261            }
262            #[cfg(miri)]
263            let _ = promote;
264            let pipe = ScriptPipe::new();
265            let backend = pipe.pipe_inner();
266            *guard = Slot::Script {
267                backend: Arc::clone(&backend),
268            };
269            Ok(Materialized::Script(backend))
270        }
271    }
272}