clipasm 0.5.0

A strict, typed language for compiling and rendering Video and Audio graphs
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
//! Shared child-process lifecycle and bounded pipe retention.
//!
//! Command construction, protocols, and diagnostics remain owned by their
//! phase adapters. This module owns the operating-system lifecycle invariants
//! those adapters must share: retrying a temporarily busy executable, draining
//! bounded output, joining reader threads, and killing plus reaping after a
//! failed wait.

use std::collections::VecDeque;
use std::io::{self, Read};
use std::process::{Command, ExitStatus};
use std::thread::JoinHandle;
use std::time::Duration;

#[cfg(windows)]
pub(crate) enum Child {
    Direct(std::process::Child),
    Managed(command_group::GroupChild),
}
#[cfg(not(windows))]
pub(crate) type Child = std::process::Child;

const START_ATTEMPTS: usize = 5;
const START_RETRY_DELAY: Duration = Duration::from_millis(10);

#[derive(Debug)]
pub(crate) struct RetainedOutput {
    pub(crate) bytes: Vec<u8>,
    pub(crate) truncated: bool,
}

#[derive(Debug)]
pub(crate) enum ReaderError {
    Panicked,
    Io(io::Error),
}

#[derive(Clone, Copy)]
enum ProcessScope {
    Direct,
    Managed,
}

pub(crate) fn spawn(command: Command) -> io::Result<Child> {
    spawn_with_scope(command, ProcessScope::Direct)
}

pub(crate) fn spawn_managed(command: Command) -> io::Result<Child> {
    spawn_with_scope(command, ProcessScope::Managed)
}

fn spawn_with_scope(mut command: Command, scope: ProcessScope) -> io::Result<Child> {
    #[cfg(unix)]
    {
        use std::os::unix::process::CommandExt as _;

        command.process_group(0);
    }
    for attempt in 1..=START_ATTEMPTS {
        match spawn_once(&mut command, scope) {
            Ok(child) => return Ok(child),
            Err(error) if executable_is_temporarily_busy(&error) && attempt < START_ATTEMPTS => {
                std::thread::sleep(START_RETRY_DELAY);
            }
            Err(error) => return Err(error),
        }
    }
    unreachable!("the final process start attempt always returns")
}

pub(crate) fn wait(child: &mut Child) -> io::Result<ExitStatus> {
    let status = wait_with(child, wait_direct)?;
    terminate_group(child);
    Ok(status)
}

pub(crate) fn terminate(child: &mut Child) {
    terminate_group(child);
    let _ = kill_direct(child);
    let _ = wait_direct(child);
    // The direct child can create another group member after the first signal
    // was sent but before it is reaped. Sweep the now-orphaned group again.
    terminate_group(child);
}

fn terminate_group(child: &mut Child) {
    #[cfg(unix)]
    {
        let group = rustix::process::Pid::from_child(child);
        let _ = rustix::process::kill_process_group(group, rustix::process::Signal::KILL);
    }
    #[cfg(windows)]
    if let Child::Managed(child) = child {
        let _ = child.kill();
    }
    #[cfg(not(any(unix, windows)))]
    {
        let _ = child;
    }
}

#[cfg(windows)]
fn spawn_once(command: &mut Command, scope: ProcessScope) -> io::Result<Child> {
    if matches!(scope, ProcessScope::Managed) {
        use command_group::CommandGroup as _;

        command
            .group()
            .kill_on_drop(true)
            .spawn()
            .map(Child::Managed)
    } else {
        command.spawn().map(Child::Direct)
    }
}

#[cfg(not(windows))]
fn spawn_once(command: &mut Command, scope: ProcessScope) -> io::Result<Child> {
    let _ = scope;
    command.spawn()
}

#[cfg(windows)]
fn wait_direct(child: &mut Child) -> io::Result<ExitStatus> {
    match child {
        Child::Direct(child) => child.wait(),
        Child::Managed(child) => child.inner().wait(),
    }
}

#[cfg(not(windows))]
fn wait_direct(child: &mut Child) -> io::Result<ExitStatus> {
    child.wait()
}

#[cfg(windows)]
fn kill_direct(child: &mut Child) -> io::Result<()> {
    match child {
        Child::Direct(child) => child.kill(),
        Child::Managed(child) => child.inner().kill(),
    }
}

#[cfg(not(windows))]
fn kill_direct(child: &mut Child) -> io::Result<()> {
    child.kill()
}

pub(crate) fn take_stdin(child: &mut Child) -> Option<std::process::ChildStdin> {
    child_inner(child).stdin.take()
}

pub(crate) fn take_stdout(child: &mut Child) -> Option<std::process::ChildStdout> {
    child_inner(child).stdout.take()
}

pub(crate) fn take_stderr(child: &mut Child) -> Option<std::process::ChildStderr> {
    child_inner(child).stderr.take()
}

#[cfg(windows)]
fn child_inner(child: &mut Child) -> &mut std::process::Child {
    match child {
        Child::Direct(child) => child,
        Child::Managed(child) => child.inner(),
    }
}

#[cfg(not(windows))]
fn child_inner(child: &mut Child) -> &mut std::process::Child {
    child
}

pub(crate) fn join_reader(
    reader: JoinHandle<io::Result<RetainedOutput>>,
) -> Result<RetainedOutput, ReaderError> {
    reader
        .join()
        .map_err(|_| ReaderError::Panicked)?
        .map_err(ReaderError::Io)
}

pub(crate) fn read_prefix(mut reader: impl Read, limit: usize) -> io::Result<RetainedOutput> {
    let mut bytes = Vec::with_capacity(limit.min(64 * 1024));
    let mut buffer = vec![0_u8; 16 * 1024].into_boxed_slice();
    let mut truncated = false;
    loop {
        let read = reader.read(&mut buffer)?;
        if read == 0 {
            break;
        }
        let remaining = limit.saturating_sub(bytes.len());
        let retained = read.min(remaining);
        bytes.extend_from_slice(&buffer[..retained]);
        truncated |= retained < read;
    }
    Ok(RetainedOutput { bytes, truncated })
}

pub(crate) fn read_tail(mut reader: impl Read, limit: usize) -> io::Result<RetainedOutput> {
    let mut bytes = VecDeque::with_capacity(limit.min(64 * 1024));
    let mut buffer = vec![0_u8; 16 * 1024].into_boxed_slice();
    let mut truncated = false;
    loop {
        let read = reader.read(&mut buffer)?;
        if read == 0 {
            break;
        }
        if read >= limit {
            bytes.clear();
            bytes.extend(&buffer[read - limit..read]);
            truncated = true;
            continue;
        }
        let overflow = bytes.len().saturating_add(read).saturating_sub(limit);
        if overflow > 0 {
            bytes.drain(..overflow);
            truncated = true;
        }
        bytes.extend(&buffer[..read]);
    }
    Ok(RetainedOutput {
        bytes: bytes.into_iter().collect(),
        truncated,
    })
}

fn wait_with(
    child: &mut Child,
    wait: impl FnOnce(&mut Child) -> io::Result<ExitStatus>,
) -> io::Result<ExitStatus> {
    match wait(child) {
        Ok(status) => Ok(status),
        Err(error) => {
            terminate(child);
            Err(error)
        }
    }
}

fn executable_is_temporarily_busy(error: &io::Error) -> bool {
    #[cfg(unix)]
    {
        error.raw_os_error() == Some(26)
    }
    #[cfg(not(unix))]
    {
        let _ = error;
        false
    }
}

#[cfg(test)]
mod tests {
    use std::process::Command;

    use super::*;

    struct RepeatingReader {
        pattern: &'static [u8],
        repetitions: usize,
        offset: usize,
    }

    impl Read for RepeatingReader {
        fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
            if self.repetitions == 0 || buffer.is_empty() {
                return Ok(0);
            }
            let mut written = 0;
            while written < buffer.len() && self.repetitions > 0 {
                let remaining = &self.pattern[self.offset..];
                let count = remaining.len().min(buffer.len() - written);
                buffer[written..written + count].copy_from_slice(&remaining[..count]);
                written += count;
                self.offset += count;
                if self.offset == self.pattern.len() {
                    self.offset = 0;
                    self.repetitions -= 1;
                }
            }
            Ok(written)
        }
    }

    #[test]
    fn prefix_capture_drains_without_growing_past_the_limit() {
        let output = read_prefix(
            RepeatingReader {
                pattern: b"0123456789",
                repetitions: 10_000,
                offset: 0,
            },
            128,
        )
        .expect("bounded prefix");
        assert_eq!(output.bytes.len(), 128);
        assert!(output.truncated);
    }

    #[test]
    fn tail_capture_keeps_only_the_final_bytes() {
        let output = read_tail(
            RepeatingReader {
                pattern: b"0123456789",
                repetitions: 10_000,
                offset: 0,
            },
            11,
        )
        .expect("bounded tail");
        assert_eq!(output.bytes, b"90123456789");
        assert!(output.truncated);
    }

    #[cfg(unix)]
    #[test]
    fn successful_wait_terminates_descendants_holding_pipes() {
        use std::process::Stdio;
        use std::time::{Duration, Instant};

        let mut command = Command::new("sh");
        command
            .args(["-c", "sleep 5 & exit 0"])
            .stderr(Stdio::piped());
        let mut child = spawn(command).expect("shell child");
        let stderr = take_stderr(&mut child).expect("stderr pipe");
        let reader = std::thread::spawn(move || read_tail(stderr, 1024));
        let started = Instant::now();

        let status = wait(&mut child).expect("successful wait");
        let retained = join_reader(reader).expect("closed descendant pipe");

        assert!(status.success());
        assert!(retained.bytes.is_empty());
        assert!(
            started.elapsed() < Duration::from_secs(2),
            "successful parent left a descendant holding stderr open"
        );
    }

    #[cfg(unix)]
    #[test]
    fn wait_failure_kills_and_reaps_the_child() {
        let mut child = spawn({
            let mut command = Command::new("sh");
            command.args(["-c", "sleep 60"]);
            command
        })
        .expect("sleeping child");

        let error = wait_with(&mut child, |_| {
            Err(io::Error::other("injected wait failure"))
        })
        .expect_err("injected wait failure");

        assert_eq!(error.kind(), io::ErrorKind::Other);
        assert!(
            child_inner(&mut child)
                .try_wait()
                .expect("reaped child status")
                .is_some(),
            "child must be reaped before returning"
        );
    }

    #[cfg(windows)]
    const MANAGED_PARENT_HELPER: &str = "CLIPASM_MANAGED_PARENT_HELPER";
    #[cfg(windows)]
    const MANAGED_DESCENDANT_HELPER: &str = "CLIPASM_MANAGED_DESCENDANT_HELPER";

    #[cfg(windows)]
    #[test]
    fn managed_parent_helper() {
        if std::env::var_os(MANAGED_PARENT_HELPER).is_none() {
            return;
        }
        Command::new(std::env::current_exe().expect("test executable"))
            .args([
                "--exact",
                "process::tests::managed_descendant_helper",
                "--nocapture",
            ])
            .env(MANAGED_DESCENDANT_HELPER, "1")
            .spawn()
            .expect("managed descendant");
    }

    #[cfg(windows)]
    #[test]
    fn managed_descendant_helper() {
        if std::env::var_os(MANAGED_DESCENDANT_HELPER).is_none() {
            return;
        }
        std::thread::sleep(Duration::from_secs(60));
    }

    #[cfg(windows)]
    #[test]
    fn successful_wait_terminates_descendants_holding_pipes() {
        use std::process::Stdio;
        use std::time::Instant;

        let mut command = Command::new(std::env::current_exe().expect("test executable"));
        command
            .args([
                "--exact",
                "process::tests::managed_parent_helper",
                "--nocapture",
            ])
            .env(MANAGED_PARENT_HELPER, "1")
            .stdout(Stdio::null())
            .stderr(Stdio::piped());
        let mut child = spawn_managed(command).expect("managed parent");
        let stderr = take_stderr(&mut child).expect("stderr pipe");
        let reader = std::thread::spawn(move || read_tail(stderr, 1024));
        let started = Instant::now();

        let status = wait(&mut child).expect("successful wait");
        let retained = join_reader(reader).expect("closed descendant pipe");

        assert!(status.success());
        assert!(retained.bytes.is_empty());
        assert!(
            started.elapsed() < Duration::from_secs(10),
            "successful parent left a descendant holding stderr open"
        );
    }
}