strop-engine 0.26.0

strop editor engine: documents, grammar dispatch, services, sessions — no terminal
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
//! Concurrent bounded shell I/O with synchronous cancellation signalling.
//! Unix children lead a private process group. The leader is never reaped
//! while a group-signalling capability exists, even when descendants keep
//! its pipes open. Cancellation never waits for a process or joins a thread.

use super::jobs::ProcessOutput;
use strop_core::worker::{CancelToken, FailureKind, Outcome};

#[cfg(not(unix))]
pub(super) fn run_shell(
    _command: &str,
    _cwd: &std::path::Path,
    _input: Option<String>,
    _token: &CancelToken,
) -> Outcome<ProcessOutput> {
    Outcome::failed(
        FailureKind::Unavailable,
        "shell process-group supervision requires Unix",
    )
}

#[cfg(unix)]
pub(super) fn run_shell(
    command: &str,
    cwd: &std::path::Path,
    input: Option<String>,
    token: &CancelToken,
) -> Outcome<ProcessOutput> {
    unix::run(command, cwd, input, token)
}

#[cfg(unix)]
mod unix {
    use super::*;
    use std::io::{self, Read, Write};
    use std::process::{Command, ExitStatus, Stdio};
    use std::sync::mpsc::{channel, RecvTimeoutError};
    use std::time::Duration;
    use strop_core::process::OwnedProcess;
    use strop_core::worker::{self, CancelReason, Failure};

    const POLL: Duration = Duration::from_millis(20);
    const OUTPUT_LIMIT: usize = 8 * 1024 * 1024;

    enum IoDone {
        Input(Outcome<()>),
        Stdout(Outcome<Vec<u8>>),
        Stderr(Outcome<Vec<u8>>),
    }
    #[derive(Default)]
    struct Drain {
        stdout: Option<Vec<u8>>,
        stderr: Option<Vec<u8>>,
        input_done: bool,
        failure: Option<Failure>,
    }
    fn collect<T: Default>(outcome: Outcome<T>, failure: &mut Option<Failure>) -> T {
        match outcome {
            Outcome::Success(value) => value,
            Outcome::Failed {
                failure: error,
                partial,
            } => {
                failure.get_or_insert(error);
                partial.unwrap_or_default()
            }
            Outcome::Cancelled(_) => {
                failure.get_or_insert_with(|| {
                    Failure::new(FailureKind::Disconnected, "shell stream cancelled")
                });
                T::default()
            }
        }
    }
    impl Drain {
        fn step(&mut self, event: IoDone) {
            match event {
                IoDone::Input(result) => {
                    self.input_done = true;
                    collect(result, &mut self.failure);
                }
                IoDone::Stdout(result) => self.stdout = Some(collect(result, &mut self.failure)),
                IoDone::Stderr(result) => self.stderr = Some(collect(result, &mut self.failure)),
            }
        }
        fn settled(&self) -> bool {
            self.input_done && self.stdout.is_some() && self.stderr.is_some()
        }
        fn finish(self, status: Option<ExitStatus>, cancelled: bool) -> Outcome<ProcessOutput> {
            let mut failure = self.failure;
            let mut decode = |bytes: Vec<u8>| match String::from_utf8(bytes) {
                Ok(text) => text,
                Err(error) => {
                    failure.get_or_insert_with(|| {
                        Failure::new(FailureKind::Io, "shell output is not UTF-8")
                    });
                    String::from_utf8_lossy(error.as_bytes()).into_owned()
                }
            };
            let output = ProcessOutput {
                stdout: decode(self.stdout.unwrap_or_default()),
                stderr: decode(self.stderr.unwrap_or_default()),
            };
            if let Some(failure) = failure {
                return Outcome::Failed {
                    failure,
                    partial: Some(output),
                };
            }
            if cancelled {
                return Outcome::Cancelled(CancelReason::OwnerClosed);
            }
            match status {
                Some(status) if status.success() => Outcome::Success(output),
                Some(status) => Outcome::Failed {
                    failure: Failure::new(FailureKind::Exit, format!("shell exited with {status}")),
                    partial: Some(output),
                },
                None => Outcome::Failed {
                    failure: Failure::new(FailureKind::Wait, "shell wait failed"),
                    partial: Some(output),
                },
            }
        }
    }
    fn reader(
        mut pipe: impl Read + Send + 'static,
        emit: impl FnOnce(Outcome<Vec<u8>>) + Send + 'static,
    ) -> worker::CancelHandle {
        worker::spawn("shell-read", emit, move |_| {
            let mut bytes = Vec::new();
            let mut buffer = [0; 16384];
            loop {
                match pipe.read(&mut buffer) {
                    Ok(0) => return Outcome::Success(bytes),
                    Ok(count) => {
                        let keep = count.min(OUTPUT_LIMIT - bytes.len());
                        bytes.extend_from_slice(&buffer[..keep]);
                        if keep != count {
                            return Outcome::Failed {
                                failure: Failure::new(
                                    FailureKind::Io,
                                    "shell output limit exceeded",
                                ),
                                partial: Some(bytes),
                            };
                        }
                    }
                    Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
                    Err(error) => {
                        return Outcome::Failed {
                            failure: Failure::new(FailureKind::Io, error.to_string()),
                            partial: Some(bytes),
                        }
                    }
                }
            }
        })
    }

    pub(super) fn run(
        command_text: &str,
        cwd: &std::path::Path,
        input: Option<String>,
        token: &CancelToken,
    ) -> Outcome<ProcessOutput> {
        let mut command = Command::new("sh");
        command
            .arg("-c")
            .arg(command_text)
            .current_dir(cwd)
            .stdin(if input.is_some() {
                Stdio::piped()
            } else {
                Stdio::null()
            })
            .stdout(Stdio::piped())
            .stderr(Stdio::piped());
        let mut process = match OwnedProcess::spawn(&mut command, token) {
            Ok(process) => process,
            Err(failure) => {
                return Outcome::Failed {
                    failure,
                    partial: None,
                }
            }
        };
        if token.is_cancelled() {
            if let Err(failure) = process.terminate() {
                return Outcome::Failed {
                    failure,
                    partial: None,
                };
            }
            return Outcome::Cancelled(CancelReason::OwnerClosed);
        }
        let Some(stdout) = process.take_stdout() else {
            return Outcome::failed(FailureKind::Protocol, "missing shell stdout");
        };
        let Some(stderr) = process.take_stderr() else {
            return Outcome::failed(FailureKind::Protocol, "missing shell stderr");
        };
        let (tx, rx) = channel();
        let out = reader(stdout, {
            let tx = tx.clone();
            move |r| {
                let _ = tx.send(IoDone::Stdout(r));
            }
        });
        let err = reader(stderr, {
            let tx = tx.clone();
            move |r| {
                let _ = tx.send(IoDone::Stderr(r));
            }
        });
        let writer = if let Some(text) = input {
            let Some(mut stdin) = process.take_stdin() else {
                return Outcome::failed(FailureKind::Protocol, "missing shell stdin");
            };
            Some(worker::spawn(
                "shell-write",
                {
                    let tx = tx.clone();
                    move |r| {
                        let _ = tx.send(IoDone::Input(r));
                    }
                },
                move |_| {
                    match stdin.write_all(text.as_bytes()) {
                        Ok(()) => Outcome::Success(()),
                        // Early consumers are judged by the child exit status.
                        Err(error) if error.kind() == io::ErrorKind::BrokenPipe => {
                            Outcome::Success(())
                        }
                        Err(error) => {
                            Outcome::failed(FailureKind::Io, format!("stdin write failed: {error}"))
                        }
                    }
                },
            ))
        } else {
            let _ = tx.send(IoDone::Input(Outcome::Success(())));
            None
        };
        drop(tx);
        let _streams = (out, err, writer);
        let mut drain = Drain::default();
        let mut exited = false;
        let mut signalled = false;
        loop {
            if !exited {
                match process.has_exited() {
                    Ok(value) => exited = value,
                    Err(failure) => {
                        drain.failure.get_or_insert(failure);
                        break;
                    }
                }
            }
            // A finished leader must not leave background children holding the
            // readers forever. Its zombie still reserves the PGID here.
            if !signalled && (exited || drain.failure.is_some() || token.is_cancelled()) {
                if let Err(failure) = process.terminate() {
                    drain.failure.get_or_insert(failure);
                    break;
                }
                signalled = true;
            }
            if exited && drain.settled() {
                break;
            }
            match rx.recv_timeout(POLL) {
                Ok(event) => drain.step(event),
                Err(RecvTimeoutError::Timeout) => {}
                Err(RecvTimeoutError::Disconnected) if drain.settled() => {
                    // Pipes can close before the process exits. Avoid spinning
                    // on a disconnected receiver; this wait is supervisor-only.
                    if !exited {
                        match process.has_exited() {
                            Ok(true) => exited = true,
                            Ok(false) => {
                                // Keep cancellation capability until exit is
                                // observed, not until std::wait reaps it.
                                std::thread::park_timeout(POLL);
                                continue;
                            }
                            Err(failure) => {
                                drain.failure.get_or_insert(failure);
                            }
                        }
                    }
                }
                Err(RecvTimeoutError::Disconnected) => {
                    drain.failure.get_or_insert_with(|| {
                        Failure::new(FailureKind::Disconnected, "shell streams disconnected")
                    });
                    break;
                }
            }
        }
        if let Err(failure) = process.terminate() {
            drain.failure.get_or_insert(failure);
        }
        let status = match process.wait() {
            Ok(status) => Some(status),
            Err(failure) => {
                drain.failure.get_or_insert(failure);
                None
            }
        };
        drain.finish(status, token.is_cancelled())
    }

    #[cfg(test)]
    mod tests {
        use super::*;
        use std::os::unix::net::{UnixListener, UnixStream};
        use std::path::Path;

        fn run(command: &'static str, input: Option<String>) -> Outcome<ProcessOutput> {
            let (tx, rx) = channel();
            let handle = worker::spawn(
                "shell-test",
                move |r| {
                    tx.send(r).unwrap();
                },
                move |token| super::run(command, Path::new("."), input, &token),
            );
            let result = rx.recv().unwrap();
            drop(handle);
            result
        }
        #[test]
        fn concurrent_io_and_early_broken_pipe() {
            let text = "payload line\n".repeat(65536);
            match run("cat", Some(text.clone())) {
                Outcome::Success(out) => assert_eq!(out.stdout, text),
                other => panic!("{other:?}"),
            }
            match run("head -c 16", Some("A".repeat(1024 * 1024))) {
                Outcome::Success(out) => assert_eq!(out.stdout, "A".repeat(16)),
                other => panic!("{other:?}"),
            }
        }
        #[test]
        fn nonzero_exit_keeps_output_and_output_is_bounded() {
            assert!(matches!(run("printf kept; exit 3", None),
                Outcome::Failed { failure, partial: Some(out) }
                if failure.kind == FailureKind::Exit && out.stdout == "kept"));
            assert!(
                matches!(run("yes", None), Outcome::Failed { failure, partial: Some(out) }
                if failure.kind == FailureKind::Io && out.stdout.len() <= OUTPUT_LIMIT)
            );
        }

        // A test subprocess connects to a Unix socket then blocks on its read
        // side, inheriting sh's stdout/stderr. No timer coordinates readiness.
        #[test]
        fn descendant_helper() {
            let Ok(path) = std::env::var("STROP_PROCESS_TEST_SOCKET") else {
                return;
            };
            let mut socket = UnixStream::connect(path).unwrap();
            socket.write_all(b"R").unwrap();
            let mut byte = [0];
            let _ = socket.read(&mut byte);
        }
        #[test]
        fn cancellation_kills_non_exec_shell_descendant_then_supervisor_progresses() {
            let directory = tempfile::tempdir().unwrap();
            let path = directory.path().join("process.sock");
            let listener = UnixListener::bind(&path).unwrap();
            fn quote(value: &str) -> String {
                format!("'{}'", value.replace('\'', "'\\''"))
            }
            let exe = std::env::current_exe().unwrap();
            // Background + wait forces sh to remain a separate process.
            let command = format!(
                "STROP_PROCESS_TEST_SOCKET={} {} descendant_helper --nocapture & wait",
                quote(path.to_str().unwrap()),
                quote(exe.to_str().unwrap())
            );
            let (tx, rx) = channel();
            let (done_tx, done_rx) = channel();
            let handle = worker::spawn(
                "shell-cancel-test",
                move |r| {
                    tx.send(r).unwrap();
                },
                move |token| {
                    let result = super::run(&command, Path::new("."), None, &token);
                    done_tx.send(()).unwrap();
                    result
                },
            );
            let (mut socket, _) = listener.accept().unwrap();
            let mut byte = [0];
            socket.read_exact(&mut byte).unwrap();
            assert_eq!(byte, *b"R");
            handle.cancel(CancelReason::Dismissed);
            assert!(matches!(
                rx.recv().unwrap(),
                Outcome::Cancelled(CancelReason::Dismissed)
            ));
            assert_eq!(socket.read(&mut byte).unwrap(), 0);
            done_rx.recv().unwrap();
            assert!(rx.recv().is_err());
            std::fs::remove_file(path).unwrap();
        }
    }
}