Skip to main content

kaish_types/
kernel.rs

1//! Kernel-level execution options.
2//!
3//! `ExecuteOptions` is the input to a single kernel `execute` call. It collects
4//! the per-call knobs (variables, timeout, cancellation) so embedders don't need
5//! to manage half a dozen execute-method overloads.
6
7use std::collections::{BTreeMap, HashMap};
8use std::path::PathBuf;
9use std::time::Duration;
10
11use tokio_util::sync::CancellationToken;
12
13use crate::value::Value;
14
15/// Per-call options for `Kernel::execute_with_options`.
16///
17/// Construct with `ExecuteOptions::new()` and the chainable `with_*` builders,
18/// or via `Default`.
19///
20/// # Cancellation vs. timeout — embedder note
21///
22/// If a `cancel_token` is supplied, it is **raced** against the kernel's
23/// internal token. The kernel does NOT cancel the embedder's token on its
24/// own timeouts — it cancels its internal token and returns exit code 124.
25/// So `your_token.is_cancelled()` after the call returns reflects only
26/// whether *you* (or someone sharing your token) cancelled, not whether the
27/// kernel timed out. Distinguish via the returned `ExecResult.code`:
28/// `124` = kernel timeout, `130` = cancellation (Ctrl-C / `Kernel::cancel`).
29#[derive(Default, Clone)]
30pub struct ExecuteOptions {
31    /// Variables exported into this call's environment (per-call overlay).
32    pub vars: HashMap<String, Value>,
33    /// Per-call timeout. Overrides `KernelConfig::request_timeout`.
34    ///
35    /// `None` means no timeout (or whatever the kernel-config default is).
36    /// `Some(Duration::ZERO)` returns exit 124 immediately without spawning
37    /// anything — useful for tests and dry-run paths.
38    /// Any other `Some(d)` lets the kernel run for at most `d` before cancelling
39    /// (which kills external children with the configured grace) and returning 124.
40    pub timeout: Option<Duration>,
41    /// Optional externally-owned cancellation token, *raced* against the kernel's
42    /// internal token. Either firing cancels the request and kills any running
43    /// external children. The kernel does not store this token in its own state —
44    /// it's a per-call read-only input, so embedders are free to drop or reuse
45    /// the original token after the call returns. CancellationToken is internally
46    /// `Arc`-shared, so `clone()` it into the builder if you want to keep your
47    /// original handle.
48    pub cancel_token: Option<CancellationToken>,
49    /// Per-call working directory override.
50    ///
51    /// When `Some(path)`, the kernel runs this call as if `cd path` happened
52    /// first, then restores the prior cwd on return. Useful for embedders that
53    /// run scripts in workspace contexts (notebook cells, per-tool dirs)
54    /// without polluting the long-lived kernel's cwd.
55    pub cwd: Option<PathBuf>,
56    /// W3C `traceparent` of the embedder's active span, e.g.
57    /// `"00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"`. When set,
58    /// the kernel's execution span parents onto it, so kaish's spans appear as
59    /// children of the embedder's trace rather than as orphan roots.
60    pub traceparent: Option<String>,
61    /// W3C `tracestate` (vendor-specific list) that rides alongside
62    /// `traceparent`. Per the W3C spec, `tracestate` is meaningless without a
63    /// `traceparent`, so the kernel ignores it unless `traceparent` is also set.
64    pub tracestate: Option<String>,
65    /// W3C baggage — cross-cutting identifiers (owner, connection, tenant, …)
66    /// the embedder wants stamped onto the trace. Propagated to every child
67    /// span. Independent of `traceparent`: baggage with no trace context starts
68    /// a fresh root that still carries the identifiers.
69    pub baggage: BTreeMap<String, String>,
70    /// Standard input for this call, seeded to the first top-level command
71    /// that reads stdin. A command that consumes less than the whole buffer
72    /// (`read`, a pipeline stage that never reads stdin) leaves the remainder
73    /// for the next statement in the same call — it is not drained wholesale
74    /// to the first reader.
75    ///
76    /// Lets a non-interactive frontend feed piped input, e.g.
77    /// `printf '…' | kaish -c 'sort'`. Without it a bare top-level builtin
78    /// reading stdin has no input source and silently produces nothing.
79    /// Bytes-typed (GH #176) to match `ExecContext::set_stdin`: a byte-aware
80    /// builtin (`wc -c`, `cat`, `cmp`, `checksum`, …) sees binary content
81    /// exactly, while a text-only builtin (`grep`, `sed`, …) still refuses it
82    /// loudly at the point it asks for text (`read_stdin_to_text`), not here.
83    /// Embedders that already hold a complete buffer use this; one that wants
84    /// to avoid pre-draining an open process stdin should prefer
85    /// `Kernel::execute_with_pipe_stdin` instead.
86    pub stdin: Option<Vec<u8>>,
87    /// Polled interrupt check, for embedders whose thread cannot fire
88    /// `cancel_token` while execution runs — the motivating case is
89    /// single-threaded wasm, where the browser's main thread flips a
90    /// SharedArrayBuffer flag and this closure reads it. The kernel polls at
91    /// its cancellation checkpoints (each loop iteration, among others) and,
92    /// on `true`, fires its internal cancel — the same exit-130 path as
93    /// `Kernel::cancel()`. Keep the closure cheap: it runs on the hot path.
94    /// `None` (the default) polls nothing.
95    pub interrupt: Option<std::sync::Arc<dyn Fn() -> bool + Send + Sync>>,
96    /// Per-call override for errexit (`set -e`): abort on a statement's
97    /// first nonzero exit instead of continuing to the next one.
98    ///
99    /// **Precedence:** `Some(enabled)` wins over `KernelConfig::errexit_enabled`
100    /// for this call only, and is restored to whatever the kernel already had
101    /// (the config default, or a prior call's `set -e`/`set +e`) when the call
102    /// returns. `None` (the default) leaves errexit exactly as the kernel
103    /// already has it — no override, no restore. Either way, a `set -e` /
104    /// `set +e` the script itself runs still applies for the rest of that
105    /// call: this and the config default only pick the *starting* value of
106    /// the one piece of state (`Scope::error_exit`) that `set -e` also
107    /// mutates, so `set -o` always reports the true, single answer.
108    ///
109    /// Use this to run one call (e.g. a security/gating hook) with errexit
110    /// on while the kernel's other calls keep the shell-standard default off.
111    pub errexit: Option<bool>,
112}
113
114impl ExecuteOptions {
115    pub fn new() -> Self {
116        Self::default()
117    }
118
119    /// Replace the entire vars overlay with the given map.
120    pub fn with_vars(mut self, vars: HashMap<String, Value>) -> Self {
121        self.vars = vars;
122        self
123    }
124
125    /// Add a single variable to the overlay (extending; last write wins).
126    pub fn with_var(mut self, name: impl Into<String>, value: Value) -> Self {
127        self.vars.insert(name.into(), value);
128        self
129    }
130
131    /// Install a polled interrupt check (see the `interrupt` field).
132    pub fn with_interrupt(
133        mut self,
134        check: std::sync::Arc<dyn Fn() -> bool + Send + Sync>,
135    ) -> Self {
136        self.interrupt = Some(check);
137        self
138    }
139
140    pub fn with_timeout(mut self, timeout: Duration) -> Self {
141        self.timeout = Some(timeout);
142        self
143    }
144
145    pub fn with_cancel_token(mut self, token: CancellationToken) -> Self {
146        self.cancel_token = Some(token);
147        self
148    }
149
150    /// Run this call as if `cd path` had happened first; the prior cwd is
151    /// restored on return.
152    pub fn with_cwd(mut self, cwd: PathBuf) -> Self {
153        self.cwd = Some(cwd);
154        self
155    }
156
157    /// Set the W3C `traceparent` the kernel's execution span should parent onto.
158    pub fn with_traceparent(mut self, traceparent: impl Into<String>) -> Self {
159        self.traceparent = Some(traceparent.into());
160        self
161    }
162
163    /// Set the W3C `tracestate` that rides alongside `traceparent`. Ignored by
164    /// the kernel unless a `traceparent` is also present.
165    pub fn with_tracestate(mut self, tracestate: impl Into<String>) -> Self {
166        self.tracestate = Some(tracestate.into());
167        self
168    }
169
170    /// Replace the entire baggage map with the given identifiers.
171    pub fn with_baggage(mut self, baggage: BTreeMap<String, String>) -> Self {
172        self.baggage = baggage;
173        self
174    }
175
176    /// Add a single baggage identifier (extending; last write wins).
177    pub fn with_baggage_entry(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
178        self.baggage.insert(key.into(), value.into());
179        self
180    }
181
182    /// Set the standard input fed to this call, starting with the first
183    /// stdin-reading command; whatever a command doesn't consume carries
184    /// forward to the next one in the same call.
185    ///
186    /// Accepts anything `Into<Vec<u8>>` — a `&str`/`String` (the common text
187    /// case) or a raw `Vec<u8>` (binary, GH #176) both work.
188    pub fn with_stdin(mut self, stdin: impl Into<Vec<u8>>) -> Self {
189        self.stdin = Some(stdin.into());
190        self
191    }
192
193    /// Force errexit on or off for this call only, overriding
194    /// `KernelConfig::errexit_enabled`. See the `errexit` field doc for
195    /// exact precedence and restore behavior.
196    pub fn with_errexit(mut self, enabled: bool) -> Self {
197        self.errexit = Some(enabled);
198        self
199    }
200}