strop_remote/exec.rs
1//! Supervised remote process execution for Git commands and language
2//! servers (0036 "Remote execution and services").
3//!
4//! One [`RemoteCommand`] is a pure, cloned description: executable,
5//! native argv and absolute remote cwd. Filenames never become
6//! executable shell text — they travel base64-encoded inside a fixed
7//! Python supervisor's spec and are executed remotely through
8//! `os.chdir(bytes)` + `os.execvpe` with byte argv. Constructors have
9//! no spawn side effect:
10//!
11//! - [`command`] builds the ssh invocation for an owned stdio client
12//! (language server): all three pipes are `Stdio::piped()` and the
13//! caller owns spawning, the stdin lease and reaping.
14//! - [`command_supervised`] additionally hands back the
15//! [`SupervisionKey`] that identifies this session's supervisor
16//! records, and lets a caller pick finite stdin explicitly.
17//! - [`run`] executes one finite command to completion on a worker
18//! under a [`CancelToken`], with bounded output and a deadline.
19//!
20//! ## Local + remote child ownership
21//!
22//! Local: spawn the returned command through
23//! `strop_core::process::OwnedProcess` (or set `process_group(0)`
24//! yourself when using another spawner). Cancellation SIGKILLs the
25//! local ssh group and revokes the PID before reaping it; nothing here
26//! holds editor state.
27//!
28//! Remote: SSH stdin is the lifetime lease. Keep the local stdin
29//! writer open while the remote process should live; dropping it (or
30//! the local ssh process dying) makes the remote supervisor SIGTERM
31//! the worker's whole process group, escalate after a bounded grace,
32//! SIGKILL it and reap — a worker that exited normally is cleaned up
33//! the same way, because finite commands can leave descendants. A
34//! graceful shutdown is therefore an application-level exchange first
35//! (LSP `shutdown`/`exit`), *then* a lease close.
36//!
37//! The remote guarantee is conditional and stated honestly: cleanup
38//! runs once the remote sshd observes the disconnection, so a network
39//! partition delays it until sshd's own dead-peer detection fires;
40//! descendants that create their own session escape a process-group
41//! kill; and nothing survives a remote SIGKILL of the supervisor
42//! itself. See `exec::supervisor` for the full topology and limits.
43
44mod python;
45mod run;
46mod spec;
47mod supervisor;
48
49use crate::address::RemoteEndpoint;
50use std::ffi::OsString;
51use std::path::{Path, PathBuf};
52use std::time::Duration;
53use strop_core::worker::CancelToken;
54
55/// Program identity is distinct from argv. Built-in scripts reuse the already
56/// selected supervisor interpreter, never another PATH lookup for `python3`.
57#[derive(Debug, Clone)]
58pub enum RemoteProgram {
59 Executable(OsString),
60 SupervisorPython,
61}
62/// A checked description of one remote process. Pure data: nothing is
63/// spawned by constructing, cloning or inspecting it.
64#[derive(Debug, Clone)]
65pub struct RemoteCommand {
66 program: RemoteProgram,
67 args: Vec<OsString>,
68 cwd: PathBuf,
69 deadline: Duration,
70}
71
72impl RemoteCommand {
73 /// Admit one command. Refuses an empty program, NUL bytes in the
74 /// program, arguments or working directory, a non-absolute working
75 /// directory, and values that cannot be represented as native
76 /// POSIX bytes. The program may be a bare name (remote `PATH`
77 /// lookup) or contain `/` (direct path).
78 pub fn new(
79 program: impl Into<OsString>,
80 args: Vec<OsString>,
81 cwd: &Path,
82 ) -> Result<Self, RemoteCommandError> {
83 Self::admit(RemoteProgram::Executable(program.into()), args, cwd)
84 }
85
86 pub fn python(
87 script: &str,
88 args: Vec<OsString>,
89 cwd: &Path,
90 ) -> Result<Self, RemoteCommandError> {
91 let mut arguments = Vec::with_capacity(args.len() + 2);
92 arguments.push("-c".into());
93 arguments.push(script.into());
94 arguments.extend(args);
95 Self::admit(RemoteProgram::SupervisorPython, arguments, cwd)
96 }
97
98 fn admit(
99 program: RemoteProgram,
100 args: Vec<OsString>,
101 cwd: &Path,
102 ) -> Result<Self, RemoteCommandError> {
103 let command = Self {
104 program,
105 args,
106 cwd: cwd.to_path_buf(),
107 deadline: run::DEFAULT_DEADLINE,
108 };
109 // Re-run the full validation so later mutations can never
110 // bypass admission; it is pure and cheap.
111 spec::Spec::encode(
112 StdinMode::Finite,
113 [0u8; 16],
114 &command.program,
115 &command.args,
116 &command.cwd,
117 )
118 .map_err(|error| match error {
119 RemoteCommandError::ArgvTooLarge { .. } => RemoteCommandError::Invalid {
120 detail: "program and arguments are too large for a remote command line".into(),
121 },
122 other => other,
123 })?;
124 Ok(command)
125 }
126
127 pub fn program(&self) -> &RemoteProgram {
128 &self.program
129 }
130
131 pub fn args(&self) -> &[OsString] {
132 &self.args
133 }
134
135 pub fn cwd(&self) -> &Path {
136 &self.cwd
137 }
138
139 /// Wall-clock budget for [`run`]. Defaults to 120 seconds.
140 pub fn deadline(&self) -> Duration {
141 self.deadline
142 }
143
144 /// Override the wall-clock budget. Still a pure description.
145 pub fn with_deadline(mut self, deadline: Duration) -> Self {
146 self.deadline = deadline;
147 self
148 }
149}
150
151/// What the supervised ssh connection does with the local stdin lease.
152#[derive(Debug, Clone, Copy, PartialEq, Eq)]
153pub enum StdinMode {
154 /// The worker's stdin is `/dev/null`; the supervisor drains SSH
155 /// stdin only to observe the lease. Finite Git commands.
156 Finite,
157 /// SSH stdin is relayed byte-for-byte into the worker's stdin with
158 /// a bounded buffer. Language servers.
159 Relayed,
160}
161
162/// The remote worker's termination outcome, when the supervisor
163/// reported it. Non-zero codes are ordinary results — exit codes are
164/// data for Git (`diff --quiet` exits 1), not transport failures.
165#[derive(Debug, Clone, Copy, PartialEq, Eq)]
166pub enum RemoteExitStatus {
167 /// The worker exited with code 0–255.
168 Exited(u32),
169 /// The worker was terminated by the named signal.
170 Signaled(u32),
171}
172
173impl RemoteExitStatus {
174 pub fn code(&self) -> Option<u32> {
175 match *self {
176 RemoteExitStatus::Exited(code) => Some(code),
177 RemoteExitStatus::Signaled(_) => None,
178 }
179 }
180
181 pub fn signal(&self) -> Option<u32> {
182 match *self {
183 RemoteExitStatus::Exited(_) => None,
184 RemoteExitStatus::Signaled(signal) => Some(signal),
185 }
186 }
187
188 pub fn success(&self) -> bool {
189 *self == RemoteExitStatus::Exited(0)
190 }
191}
192
193/// Bounded captured output of one finished remote command. `stdout`
194/// keeps its first `STDOUT_LIMIT` bytes; `stderr` its first
195/// `STDERR_LIMIT` bytes plus the last `STDERR_TAIL` bytes (where the
196/// supervisor's status record lives). The dropped counters say how
197/// many further bytes arrived; treat any non-zero counter as
198/// truncation, never as silence.
199#[derive(Debug, Clone, PartialEq, Eq)]
200pub struct CommandOutput {
201 pub status: RemoteExitStatus,
202 pub stdout: Vec<u8>,
203 pub stderr: Vec<u8>,
204 pub stdout_dropped: u64,
205 pub stderr_dropped: u64,
206 /// Any upload failure is retained even when the program returned diagnostics.
207 pub stdin_error: Option<String>,
208}
209
210/// Identifies one supervised session's status records: the supervisor
211/// writes `STROP-SUP-v1 <nonce> ...` lines to stderr, and only lines
212/// carrying this session's nonce are its. Not a secret — it travels
213/// inside the spec and is visible in remote process listings.
214#[derive(Debug, Clone, PartialEq, Eq)]
215pub struct SupervisionKey {
216 nonce: [u8; 16],
217}
218
219impl SupervisionKey {
220 pub(crate) fn generate() -> Self {
221 Self {
222 nonce: spec::nonce(),
223 }
224 }
225
226 pub(crate) fn nonce(&self) -> [u8; 16] {
227 self.nonce
228 }
229
230 /// Every supervisor record found in a captured stderr buffer, in
231 /// order. An empty result means the supervision layer never
232 /// reported; ssh's exit code is then the only evidence.
233 pub fn records(&self, stderr: &[u8]) -> Vec<SupervisionOutcome> {
234 supervisor::records(stderr, &self.hex())
235 }
236
237 /// Remove only this session's framing, including the delimiter that the
238 /// supervisor inserts before a record. Worker stderr remains byte-exact.
239 pub(crate) fn remove_records(&self, stderr: &mut Vec<u8>) {
240 let marker = format!("STROP-SUP-v1 {} ", self.hex());
241 let mut cursor = 0;
242 while cursor < stderr.len() {
243 let Some(relative) = stderr[cursor..]
244 .windows(marker.len())
245 .position(|bytes| bytes == marker.as_bytes())
246 else {
247 break;
248 };
249 let start = cursor + relative;
250 if start != 0 && stderr[start - 1] != b'\n' {
251 cursor = start + marker.len();
252 continue;
253 }
254 let Some(length) = stderr[start..].iter().position(|&byte| byte == b'\n') else {
255 break;
256 };
257 let end = start + length + 1;
258 if !self.records(&stderr[start..end]).is_empty() {
259 let first = start.saturating_sub(1);
260 stderr.drain(first..end);
261 cursor = first;
262 } else {
263 cursor = end;
264 }
265 }
266 }
267
268 fn hex(&self) -> String {
269 self.nonce
270 .iter()
271 .map(|byte| format!("{byte:02x}"))
272 .collect()
273 }
274}
275
276/// One parsed supervisor record. [`SupervisionOutcome::LaunchFailure`]
277/// outranks a later exit record: the program never started.
278#[derive(Debug, Clone, PartialEq, Eq)]
279pub enum SupervisionOutcome {
280 Exited(u32),
281 Signaled(u32),
282 Cancelled,
283 LaunchFailure(String),
284 SupervisorError(String),
285}
286
287/// Why a remote command could not be admitted, spawned, supervised or
288/// completed. Every variant is descriptive; none guesses success.
289#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
290pub enum RemoteCommandError {
291 #[error("remote command refused: {detail}")]
292 Invalid { detail: String },
293 #[error("cannot spawn ssh: {message}")]
294 Spawn { message: String },
295 #[error(
296 "remote command line cannot carry {bytes} encoded bytes (argv/cwd too large for one ssh command)"
297 )]
298 ArgvTooLarge { bytes: usize },
299 #[error(
300 "remote execution needs compatible Python 3.8+ on remote PATH or STROP_REMOTE_PYTHON: {diagnostics}"
301 )]
302 MissingPython { diagnostics: String },
303 #[error("remote program could not start: {diagnostics}")]
304 Launch { diagnostics: String },
305 #[error("remote supervisor failed at {stage}: {diagnostics}")]
306 Supervisor { stage: String, diagnostics: String },
307 #[error("ssh transport failed (exit {exit:?}): {diagnostics}")]
308 Transport {
309 exit: Option<i32>,
310 diagnostics: String,
311 },
312 #[error("remote command cancelled before completion: {diagnostics}")]
313 Cancelled { diagnostics: String },
314 #[error("remote command did not finish within {seconds} seconds")]
315 Timeout { seconds: u64 },
316 #[error("local process supervision failed: {message}")]
317 Local { message: String },
318}
319
320/// The ssh invocation for an owned stdio client — a language server.
321/// Relayed stdin, all three pipes piped, no spawn. The caller owns the
322/// local child (see the module docs for the lease and cancel story)
323/// and may parse the supervisor's stderr records via
324/// [`command_supervised`].
325pub fn command(
326 endpoint: &RemoteEndpoint,
327 command: &RemoteCommand,
328) -> Result<std::process::Command, RemoteCommandError> {
329 command_supervised(endpoint, command, StdinMode::Relayed).map(|(process, _)| process)
330}
331
332/// [`command`] with the leash visible: choose the stdin mode explicitly
333/// and keep the [`SupervisionKey`] for parsing status records out of
334/// the session's stderr tail.
335pub fn command_supervised(
336 endpoint: &RemoteEndpoint,
337 command: &RemoteCommand,
338 mode: StdinMode,
339) -> Result<(std::process::Command, SupervisionKey), RemoteCommandError> {
340 run::supervised(endpoint, command, mode)
341}
342
343/// Run one finite remote command to completion. Worker-only: it blocks
344/// for the whole exchange, bounded by the command's deadline. Each run
345/// uses its own dedicated, noninteractive ssh connection — no pooled
346/// session or lease is involved. Output is bounded per
347/// [`CommandOutput`]; cancellation kills the local ssh group and the
348/// remote supervisor tears down the remote group.
349pub fn run(
350 endpoint: &RemoteEndpoint,
351 command: &RemoteCommand,
352 token: &CancelToken,
353) -> Result<CommandOutput, RemoteCommandError> {
354 run::run(endpoint, command, token)
355}
356
357/// Worker-only framed input. Chunks are borrowed; no whole-rope copy is needed.
358/// The stdin lease remains open after the final chunk until the program exits.
359pub fn run_with_input(
360 endpoint: &RemoteEndpoint,
361 command: &RemoteCommand,
362 token: &CancelToken,
363 chunks: &[&[u8]],
364) -> Result<CommandOutput, RemoteCommandError> {
365 run::run_input(endpoint, command, token, Some(chunks))
366}
367
368#[cfg(all(test, unix))]
369mod tests;