clipasm 0.3.2

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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
use std::collections::VecDeque;
use std::io::{self, BufRead, BufReader, Read};
use std::process::{Child, Command, ExitStatus, Stdio};
use std::thread::JoinHandle;
use std::time::Duration;

use crate::diagnostic::{BuiltinDiagnostic, Diagnostic, Result};
use crate::source::SourceSpan;

const CAPTURE_LIMIT: usize = 8 * 1024 * 1024;
const STDERR_TAIL_LIMIT: usize = 64 * 1024;
const START_ATTEMPTS: usize = 5;
const START_RETRY_DELAY: Duration = Duration::from_millis(10);

pub(crate) struct CapturedOutput {
    pub(crate) stdout: Vec<u8>,
    pub(crate) stderr: Vec<u8>,
}

struct RetainedOutput {
    bytes: Vec<u8>,
    truncated: bool,
}

pub(crate) fn capture(
    mut command: Command,
    diagnostic: BuiltinDiagnostic,
    span: &SourceSpan,
) -> Result<CapturedOutput> {
    let debug = format!("{command:?}");
    command.stdout(Stdio::piped()).stderr(Stdio::piped());
    let mut child = spawn(command, diagnostic, span, &debug)?;
    let stdout = child.stdout.take().expect("piped media-tool stdout");
    let stderr = child.stderr.take().expect("piped media-tool stderr");
    let stdout_reader = std::thread::spawn(move || read_prefix(stdout, CAPTURE_LIMIT));
    let stderr_reader = std::thread::spawn(move || read_tail(stderr, CAPTURE_LIMIT));
    let status = wait(&mut child, diagnostic, span, &debug);
    let stdout = join_reader(stdout_reader, "stdout", diagnostic, span, &debug);
    let stderr = join_reader(stderr_reader, "stderr", diagnostic, span, &debug);
    let status = status?;
    let stdout = stdout?;
    let stderr = stderr?;

    if !status.success() {
        return Err(exit_diagnostic(
            diagnostic,
            span,
            &debug,
            status,
            &stderr.bytes,
            stderr.truncated,
            CAPTURE_LIMIT,
        ));
    }
    if stdout.truncated {
        return Err(output_limit_diagnostic(
            diagnostic,
            span,
            &debug,
            "stdout",
            CAPTURE_LIMIT,
        ));
    }
    if stderr.truncated {
        return Err(output_limit_diagnostic(
            diagnostic,
            span,
            &debug,
            "stderr",
            CAPTURE_LIMIT,
        ));
    }

    Ok(CapturedOutput {
        stdout: stdout.bytes,
        stderr: stderr.bytes,
    })
}

pub(crate) fn run(
    mut command: Command,
    diagnostic: BuiltinDiagnostic,
    span: &SourceSpan,
) -> Result<()> {
    let debug = format!("{command:?}");
    command.stdout(Stdio::null()).stderr(Stdio::piped());
    let mut child = spawn(command, diagnostic, span, &debug)?;
    let stderr = child.stderr.take().expect("piped media-tool stderr");
    let stderr_reader = std::thread::spawn(move || read_tail(stderr, STDERR_TAIL_LIMIT));
    let status = wait(&mut child, diagnostic, span, &debug);
    let stderr = join_reader(stderr_reader, "stderr", diagnostic, span, &debug);
    let status = status?;
    let stderr = stderr?;
    if !status.success() {
        return Err(exit_diagnostic(
            diagnostic,
            span,
            &debug,
            status,
            &stderr.bytes,
            stderr.truncated,
            STDERR_TAIL_LIMIT,
        ));
    }
    Ok(())
}

pub(crate) fn stream_stdout_lines(
    mut command: Command,
    line_limit: usize,
    diagnostic: BuiltinDiagnostic,
    span: &SourceSpan,
    mut visitor: impl FnMut(&[u8]) -> Result<()>,
) -> Result<()> {
    let debug = format!("{command:?}");
    command.stdout(Stdio::piped()).stderr(Stdio::piped());
    let mut child = spawn(command, diagnostic, span, &debug)?;
    let stdout = child.stdout.take().expect("piped media-tool stdout");
    let stderr = child.stderr.take().expect("piped media-tool stderr");
    let stderr_reader = std::thread::spawn(move || read_tail(stderr, STDERR_TAIL_LIMIT));

    let lines = for_each_bounded_line(
        BufReader::new(stdout),
        line_limit,
        diagnostic,
        span,
        &mut visitor,
    );
    if lines.is_err() {
        let _ = child.kill();
    }
    let status = wait(&mut child, diagnostic, span, &debug);
    let stderr = join_reader(stderr_reader, "stderr", diagnostic, span, &debug);
    let status = status?;
    let stderr = stderr?;

    if let Err(error) = lines {
        return Err(error.note(debug));
    }
    if !status.success() {
        return Err(exit_diagnostic(
            diagnostic,
            span,
            &debug,
            status,
            &stderr.bytes,
            stderr.truncated,
            STDERR_TAIL_LIMIT,
        ));
    }
    Ok(())
}

fn spawn(
    mut command: Command,
    diagnostic: BuiltinDiagnostic,
    span: &SourceSpan,
    debug: &str,
) -> Result<Child> {
    for attempt in 1..=START_ATTEMPTS {
        match command.spawn() {
            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(Diagnostic::builtin(
                    diagnostic,
                    format!("could not start external media tool: {error}"),
                    span.clone(),
                )
                .note(debug));
            }
        }
    }
    unreachable!("the final media-tool start attempt always returns")
}

fn wait(
    child: &mut Child,
    diagnostic: BuiltinDiagnostic,
    span: &SourceSpan,
    debug: &str,
) -> Result<ExitStatus> {
    match child.wait() {
        Ok(status) => Ok(status),
        Err(error) => {
            let _ = child.kill();
            let _ = child.wait();
            Err(Diagnostic::builtin(
                diagnostic,
                format!("could not wait for external media tool: {error}"),
                span.clone(),
            )
            .note(debug))
        }
    }
}

fn join_reader(
    reader: JoinHandle<io::Result<RetainedOutput>>,
    stream: &str,
    diagnostic: BuiltinDiagnostic,
    span: &SourceSpan,
    debug: &str,
) -> Result<RetainedOutput> {
    reader
        .join()
        .map_err(|_| {
            Diagnostic::builtin(
                diagnostic,
                format!("external media-tool {stream} reader panicked"),
                span.clone(),
            )
            .note(debug)
        })?
        .map_err(|error| {
            Diagnostic::builtin(
                diagnostic,
                format!("could not read external media-tool {stream}: {error}"),
                span.clone(),
            )
            .note(debug)
        })
}

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 })
}

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 for_each_bounded_line(
    mut reader: impl BufRead,
    limit: usize,
    diagnostic: BuiltinDiagnostic,
    span: &SourceSpan,
    visitor: &mut impl FnMut(&[u8]) -> Result<()>,
) -> Result<()> {
    let mut line = Vec::with_capacity(limit.min(256));
    let mut overflow = false;
    loop {
        let available = reader.fill_buf().map_err(|error| {
            Diagnostic::builtin(
                diagnostic,
                format!("could not read streamed media-tool output: {error}"),
                span.clone(),
            )
        })?;
        if available.is_empty() {
            if overflow {
                return Err(line_limit_diagnostic(limit, span));
            }
            if !line.is_empty() {
                visitor(&line)?;
            }
            return Ok(());
        }
        let newline = available.iter().position(|byte| *byte == b'\n');
        let segment_end = newline.unwrap_or(available.len());
        if !overflow {
            let remaining = limit.saturating_sub(line.len());
            let retained = segment_end.min(remaining);
            line.extend_from_slice(&available[..retained]);
            overflow = retained < segment_end;
        }
        let consumed = segment_end + usize::from(newline.is_some());
        reader.consume(consumed);
        if newline.is_some() {
            if overflow {
                return Err(line_limit_diagnostic(limit, span));
            }
            if line.last() == Some(&b'\r') {
                line.pop();
            }
            visitor(&line)?;
            line.clear();
        }
    }
}

fn line_limit_diagnostic(limit: usize, span: &SourceSpan) -> Diagnostic {
    Diagnostic::builtin(
        BuiltinDiagnostic::ToolOutputLimit,
        format!("external media-tool output line exceeds the {limit}-byte limit"),
        span.clone(),
    )
}

fn exit_diagnostic(
    diagnostic: BuiltinDiagnostic,
    span: &SourceSpan,
    debug: &str,
    status: ExitStatus,
    stderr: &[u8],
    truncated: bool,
    retained_limit: usize,
) -> Diagnostic {
    let stderr = String::from_utf8_lossy(stderr);
    let marker = if truncated {
        format!("[stderr truncated to final {retained_limit} bytes]\n")
    } else {
        String::new()
    };
    Diagnostic::builtin(
        diagnostic,
        format!(
            "external media tool exited with {status}\n{marker}{}",
            stderr.trim()
        ),
        span.clone(),
    )
    .note(debug)
}

fn output_limit_diagnostic(
    diagnostic: BuiltinDiagnostic,
    span: &SourceSpan,
    debug: &str,
    stream: &str,
    limit: usize,
) -> Diagnostic {
    Diagnostic::builtin(
        diagnostic,
        format!("external media-tool {stream} exceeds the {limit}-byte capture limit"),
        span.clone(),
    )
    .note(debug)
}

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 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 stderr_tail_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);
    }

    #[test]
    fn streamed_lines_do_not_accumulate_the_complete_output() {
        let reader = BufReader::with_capacity(
            17,
            RepeatingReader {
                pattern: b"1024\n",
                repetitions: 100_000,
                offset: 0,
            },
        );
        let mut lines = 0_u64;
        let span = SourceSpan::file_start("test");
        for_each_bounded_line(
            reader,
            16,
            BuiltinDiagnostic::ToolOutputLimit,
            &span,
            &mut |line| {
                assert_eq!(line, b"1024");
                lines += 1;
                Ok(())
            },
        )
        .expect("streamed lines");
        assert_eq!(lines, 100_000);
    }

    #[test]
    fn streamed_lines_reject_one_overlong_record() {
        let reader = BufReader::new(std::io::Cursor::new(vec![b'x'; 257]));
        let span = SourceSpan::file_start("test");
        let error = for_each_bounded_line(
            reader,
            256,
            BuiltinDiagnostic::ToolOutputLimit,
            &span,
            &mut |_| Ok(()),
        )
        .expect_err("long line");
        assert_eq!(error.code, "E_TOOL_OUTPUT_LIMIT");
    }
}