dekopon-shell 0.86.0

Sandboxed bash-flavored script interpreter whose commands dispatch to Dekopon capabilities
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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
use crate::interp::telemetry::StageObservation;
use crate::{
    builtins::{
        CommandFailure,
        text::{
            grep::{GrepConfig, GrepMode},
            sed::Substitution,
        },
    },
    limits::Budget,
};
use dekopon_process::pipe::{PipeReader, ReadOutcome};
use dekopon_process::{ExitCode, RetainedBytes};

pub(crate) fn grep(arguments: &[String]) -> Result<(Operation, Option<String>), CommandFailure> {
    GrepConfig::parse(arguments).map(|(config, input)| (Operation::Grep(config), input))
}
pub(crate) fn sed(arguments: &[String]) -> Result<(Operation, Option<String>), CommandFailure> {
    Ok((
        Operation::Sed(super::sed::parse_arguments(arguments)?),
        None,
    ))
}

pub(crate) enum Operation {
    Grep(GrepConfig),
    Sed(Substitution),
}

#[derive(Default)]
struct LineProgress {
    index: usize,
    matches: usize,
    last_emitted: usize,
    after_until: usize,
    before: std::collections::VecDeque<(usize, Vec<u8>, Vec<RetainedBytes>)>,
}

pub(crate) fn run_parsed(
    operation: Operation,
    reader: &mut PipeReader<StageObservation>,
    budget: &mut Budget,

    mut emit: impl FnMut(&[u8]) -> Result<bool, CommandFailure>,
) -> Result<ExitCode, CommandFailure> {
    let mut pending = Vec::new();
    let mut charges: Vec<RetainedBytes> = Vec::new();
    let mut progress = LineProgress::default();
    while let ReadOutcome::Bytes(chunk) = reader.read(budget.tree())? {
        budget.charge_step()?;
        let mut rest = chunk.as_slice();
        while !rest.is_empty() {
            let end = rest.iter().position(|byte| *byte == b'\n').map(|at| at + 1);
            let part = &rest[..end.unwrap_or(rest.len())];
            charges.push(budget.charge_value_bytes(part.len() as u64)?);
            pending.extend_from_slice(part);
            rest = &rest[part.len()..];
            if end.is_some() {
                progress.index += 1;
                if !process_line(
                    &operation,
                    (&pending, &mut charges),
                    &mut progress,
                    budget,
                    &mut emit,
                )? {
                    return Ok(ExitCode::SUCCESS);
                }
                pending.clear();
                charges.clear();
            }
        }
    }
    if !pending.is_empty() {
        progress.index += 1;
        if !process_line(
            &operation,
            (&pending, &mut charges),
            &mut progress,
            budget,
            &mut emit,
        )? {
            return Ok(ExitCode::SUCCESS);
        }
    }
    if let Operation::Grep(config) = &operation {
        if let GrepMode::Count = config.mode
            && !super::sed::emit_chunks(
                format!("{}\n", progress.matches).as_bytes(),
                budget,
                &mut emit,
            )?
        {
            return Ok(ExitCode::SUCCESS);
        }
        return Ok(if progress.matches == 0 {
            ExitCode::FAILURE
        } else {
            ExitCode::SUCCESS
        });
    }
    Ok(ExitCode::SUCCESS)
}

fn process_line(
    operation: &Operation,
    line_bytes: (&[u8], &mut Vec<RetainedBytes>),
    progress: &mut LineProgress,
    budget: &mut Budget,

    emit: &mut impl FnMut(&[u8]) -> Result<bool, CommandFailure>,
) -> Result<bool, CommandFailure> {
    let (bytes, charges) = line_bytes;
    let terminated = bytes.ends_with(b"\n");
    let line = std::str::from_utf8(bytes.strip_suffix(b"\n").unwrap_or(bytes)).map_err(
        |_invalid_utf8| CommandFailure::failed("standard input is not valid UTF-8 text"),
    )?;
    let emitted = match operation {
        Operation::Grep(config) => {
            let selected = config.selects(line, budget)?;
            if selected {
                progress.matches += 1;
                if let GrepMode::Quiet = config.mode {
                    return Ok(false);
                }
            }
            if let GrepMode::Count = config.mode {
                return Ok(true);
            }
            if matches!(config.mode, GrepMode::Lines) && (config.before > 0 || config.after > 0) {
                if selected {
                    for (index, saved, _charges) in std::mem::take(&mut progress.before) {
                        if !emit_grep(config, progress, (index, &saved, false), budget, emit)? {
                            return Ok(false);
                        }
                    }
                    progress.after_until = progress.index.saturating_add(config.after);
                }
                if selected || progress.index <= progress.after_until {
                    if !emit_grep(
                        config,
                        progress,
                        (progress.index, bytes, selected),
                        budget,
                        emit,
                    )? {
                        return Ok(false);
                    }
                } else if config.before > 0 {
                    progress.before.push_back((
                        progress.index,
                        bytes.to_vec(),
                        std::mem::take(charges),
                    ));
                    if progress.before.len() > config.before {
                        progress.before.pop_front();
                    }
                }
                return Ok(true);
            }
            if !selected {
                return Ok(true);
            }
            if config.number()
                && !super::sed::emit_chunks(
                    format!("{}:", progress.index).as_bytes(),
                    budget,
                    emit,
                )?
            {
                return Ok(false);
            }
            super::sed::emit_chunks(line.as_bytes(), budget, emit)?
        }
        Operation::Sed(substitution) => substitution.emit(line, budget, emit)?,
    };
    if !emitted {
        return Ok(false);
    }
    if terminated {
        super::sed::emit_chunks(b"\n", budget, emit)
    } else {
        Ok(true)
    }
}

fn emit_grep(
    config: &GrepConfig,
    progress: &mut LineProgress,
    line: (usize, &[u8], bool),
    budget: &mut Budget,

    emit: &mut impl FnMut(&[u8]) -> Result<bool, CommandFailure>,
) -> Result<bool, CommandFailure> {
    let (index, bytes, selected) = line;
    if progress.last_emitted > 0
        && index > progress.last_emitted.saturating_add(1)
        && !super::sed::emit_chunks(b"--\n", budget, emit)?
    {
        return Ok(false);
    }
    progress.last_emitted = index;
    if config.number() {
        let marker = if selected { ':' } else { '-' };
        if !super::sed::emit_chunks(format!("{index}{marker}").as_bytes(), budget, emit)? {
            return Ok(false);
        }
    }
    super::sed::emit_chunks(bytes, budget, emit)
}

#[cfg(test)]
use crate::builtins::Builtin;

#[cfg(test)]
pub(crate) fn run_test(
    command: Builtin,
    arguments: &[&str],
    input: serde_json::Value,
) -> Result<crate::builtins::CommandResult, CommandFailure> {
    use crate::{builtins::CommandResult, value::to_lines};
    use dekopon_process::Limits;
    let lines = to_lines(&input);
    let bytes = if lines.is_empty() {
        Vec::new()
    } else {
        format!("{}\n", lines.join("\n")).into_bytes()
    };
    let mut reader = PipeReader::from_bytes(bytes, None, crate::interp::telemetry::stage_read);
    let mut budget = Budget::start(Limits::default());
    let mut output = Vec::new();
    let operation = command.parse_text(
        &arguments
            .iter()
            .map(|arg| (*arg).to_owned())
            .collect::<Vec<_>>(),
    )?;
    let status = run_parsed(operation.0, &mut reader, &mut budget, |bytes| {
        output.extend_from_slice(bytes);
        Ok(true)
    })?;
    let output = String::from_utf8(output).expect("text stream emits UTF-8");
    let mut result = if command == Builtin::Grep && arguments.contains(&"-c") {
        CommandResult::value(serde_json::Value::from(
            output.trim().parse::<usize>().expect("grep count"),
        ))
    } else {
        CommandResult::lines(output.lines().map(str::to_owned).collect())
    };
    result.status = status;
    Ok(result)
}

#[cfg(test)]
mod tests {

    use super::*;
    use crate::pipe;
    use dekopon_process::{LimitExceeded, Limits};

    #[test]
    fn case_insensitive_sed_charges_unicode_fold_before_allocation() {
        let arguments = ["s/i/y/i".to_owned()];
        let input = "İ\n".as_bytes().to_vec();
        let mut reader =
            PipeReader::from_bytes(input.clone(), None, crate::interp::telemetry::stage_read);
        let mut budget = Budget::start(Limits {
            max_value_bytes: 5,
            ..Limits::default()
        });
        let error = Builtin::Sed
            .run_text(&arguments, &mut reader, &mut budget, |_| Ok(true))
            .expect_err("folded scratch exceeds retention after pending input");
        assert!(matches!(
            error,
            CommandFailure::Fatal(crate::builtins::FatalError::Limit(
                LimitExceeded::ValueBytes { maximum: 5 }
            ))
        ));

        let mut reader = PipeReader::from_bytes(input, None, crate::interp::telemetry::stage_read);
        let mut budget = Budget::start(Limits {
            max_value_bytes: 6,
            ..Limits::default()
        });
        let mut output = Vec::new();
        let status = Builtin::Sed
            .run_text(&arguments, &mut reader, &mut budget, |chunk| {
                output.extend_from_slice(chunk);
                Ok(true)
            })
            .expect("pending input and folded scratch fit");
        assert_eq!(status, ExitCode::SUCCESS);
        assert_eq!(output, "İ\n".as_bytes());
    }

    #[test]
    fn a_text_builtin_notices_cancellation_between_fixed_input_chunks() {
        for command in [Builtin::Grep, Builtin::Sed] {
            let args = match command {
                Builtin::Grep => vec!["x".to_owned()],
                Builtin::Sed => vec!["s/x/y/".to_owned()],
                Builtin::Awk
                | Builtin::Echo
                | Builtin::Printf
                | Builtin::Test
                | Builtin::TestBracket
                | Builtin::True
                | Builtin::False
                | Builtin::Progress
                | Builtin::Sleep
                | Builtin::Cat
                | Builtin::Jobs
                | Builtin::Wait
                | Builtin::Kill
                | Builtin::Cap
                | Builtin::Head
                | Builtin::Tail
                | Builtin::Cut
                | Builtin::Uniq
                | Builtin::Wc
                | Builtin::Sort
                | Builtin::Jq
                | Builtin::Base64
                | Builtin::Xargs => panic!("not a grep/sed test"),
            };
            let error = crate::builtins::test_support::cancel_after_first_step(|reader, budget| {
                command.run_text(&args, reader, budget, |_| Ok(true))
            })
            .expect_err("a later charge notices cancellation");
            assert!(matches!(
                error,
                CommandFailure::Fatal(crate::builtins::FatalError::Limit(LimitExceeded::Cancelled))
            ));
        }
    }

    #[test]
    fn context_across_chunks_emits_one_numbered_unterminated_tail() {
        let mut input = b"x\n".repeat(pipe::CHUNK_BYTES / 2 - 1);
        input.extend_from_slice(b"P\nx\nP\ntail");
        let mut reader = PipeReader::from_bytes(input, None, crate::interp::telemetry::stage_read);
        let mut budget = Budget::start(Limits::default());
        let mut output = Vec::new();
        let status = Builtin::Grep
            .run_text(
                &["-nB1".to_owned(), "-A1".to_owned(), "P".to_owned()],
                &mut reader,
                &mut budget,
                |bytes| {
                    output.extend_from_slice(bytes);
                    Ok(true)
                },
            )
            .expect("context across the chunk boundary");
        assert_eq!(status, ExitCode::SUCCESS);
        assert_eq!(
            output,
            format!(
                "{}-x\n{}:P\n{}-x\n{}:P\n{}-tail",
                pipe::CHUNK_BYTES / 2 - 1,
                pipe::CHUNK_BYTES / 2,
                pipe::CHUNK_BYTES / 2 + 1,
                pipe::CHUNK_BYTES / 2 + 2,
                pipe::CHUNK_BYTES / 2 + 3
            )
            .as_bytes()
        );
    }

    #[test]
    fn quiet_grep_does_not_retain_before_context() {
        let mut reader = PipeReader::from_bytes(
            b"abc\nabc\nmatch\n".to_vec(),
            None,
            crate::interp::telemetry::stage_read,
        );
        let mut budget = Budget::start(Limits {
            max_value_bytes: 7,
            ..Limits::default()
        });
        let status = Builtin::Grep
            .run_text(
                &["-q".to_owned(), "-B2".to_owned(), "match".to_owned()],
                &mut reader,
                &mut budget,
                |_| panic!("quiet grep must not emit context"),
            )
            .expect("quiet grep needs no retained before window");
        assert_eq!(status, ExitCode::SUCCESS);
    }

    #[test]
    fn grep_before_window_retains_charges() {
        let mut reader = PipeReader::from_bytes(
            b"abc\nabc\nabc\nmatch\n".to_vec(),
            None,
            crate::interp::telemetry::stage_read,
        );
        let mut budget = Budget::start(Limits {
            max_value_bytes: 7,
            ..Limits::default()
        });
        let failure = Builtin::Grep
            .run_text(
                &["-B2".to_owned(), "match".to_owned()],
                &mut reader,
                &mut budget,
                |_| Ok(true),
            )
            .expect_err("two retained context lines exceed the budget");
        assert!(matches!(
            failure,
            CommandFailure::Fatal(crate::builtins::FatalError::Limit(
                LimitExceeded::ValueBytes { maximum: 7 }
            ))
        ));
    }

    #[test]
    fn grep_after_context_emits_before_exhausting_the_next_chunk_step() {
        let mut bytes = b"match\nctx\n".to_vec();
        bytes.extend(std::iter::repeat_n(b'x', 2 * pipe::CHUNK_BYTES));
        let mut reader = PipeReader::from_bytes(bytes, None, crate::interp::telemetry::stage_read);
        let mut budget = Budget::start(Limits {
            max_steps: 3,
            ..Limits::default()
        });
        let mut emitted = Vec::new();
        let failure = Builtin::Grep
            .run_text(
                &["-A2".to_owned(), "match".to_owned()],
                &mut reader,
                &mut budget,
                |part| {
                    emitted.extend_from_slice(part);
                    Ok(true)
                },
            )
            .expect_err("context processing charges the next chunk");
        assert_eq!(emitted, b"match\nctx\n");
        assert!(matches!(
            failure,
            CommandFailure::Fatal(crate::builtins::FatalError::Limit(LimitExceeded::Steps {
                maximum: 3
            }))
        ));
    }

    #[test]
    fn repeated_replacements_emit_bounded_chunks_without_retaining_output() {
        let replacement = "y".repeat(8 * 1024);
        let script = format!("s/x/{replacement}/g");
        let mut reader = PipeReader::from_bytes(
            b"xxxxx".to_vec(),
            None,
            crate::interp::telemetry::stage_read,
        );
        let mut budget = Budget::start(Limits {
            max_value_bytes: 9 * 1024,
            ..Limits::default()
        });
        let mut total = 0;
        let status = Builtin::Sed
            .run_text(&[script], &mut reader, &mut budget, |bytes| {
                assert!(bytes.len() <= pipe::CHUNK_BYTES);
                total += bytes.len();
                Ok(true)
            })
            .expect("only the pending input is retained");
        assert_eq!(status, ExitCode::SUCCESS);
        assert_eq!(total, 40 * 1024);
    }

    #[test]
    fn a_matching_line_is_emitted_before_stdin_closes() {
        let (mut writer, mut reader) = pipe::pipe(
            None,
            None,
            crate::interp::telemetry::stage_read,
            crate::interp::telemetry::stage_write,
        );
        let (sent, received) = std::sync::mpsc::sync_channel(1);
        let mut budget = Budget::start(Limits::default());
        let [permit] = budget.tree().shell_threads().reserve().unwrap();
        std::thread::scope(|scope| {
            let worker = permit
                .spawn(
                    scope,
                    dekopon_process::ThreadName::new("sh-stream-test"),
                    || {
                        Builtin::Grep.run_text(
                            &["x".to_owned()],
                            &mut reader,
                            &mut budget,
                            |bytes| {
                                sent.send(bytes.to_vec()).expect("the consumer is alive");
                                Ok(true)
                            },
                        )
                    },
                )
                .unwrap();
            assert_eq!(writer.write(b"x\n"), pipe::WriteOutcome::Accepted);
            assert_eq!(
                received
                    .recv_timeout(std::time::Duration::from_secs(2))
                    .expect("line arrives before close"),
                b"x"
            );
            assert_eq!(
                received
                    .recv_timeout(std::time::Duration::from_secs(2))
                    .expect("newline arrives before close"),
                b"\n"
            );
            drop(writer);
            assert_eq!(
                worker.join().expect("stage joins").expect("grep completes"),
                ExitCode::SUCCESS
            );
        });
    }

    #[test]
    fn text_builtins_release_completed_lines_before_reading_more() {
        for command in [Builtin::Grep, Builtin::Sed] {
            let args = match command {
                Builtin::Grep => vec!["x".to_owned()],
                Builtin::Sed => vec!["s/x/y/".to_owned()],
                Builtin::Awk
                | Builtin::Echo
                | Builtin::Printf
                | Builtin::Test
                | Builtin::TestBracket
                | Builtin::True
                | Builtin::False
                | Builtin::Progress
                | Builtin::Sleep
                | Builtin::Cat
                | Builtin::Jobs
                | Builtin::Wait
                | Builtin::Kill
                | Builtin::Cap
                | Builtin::Head
                | Builtin::Tail
                | Builtin::Cut
                | Builtin::Uniq
                | Builtin::Wc
                | Builtin::Sort
                | Builtin::Jq
                | Builtin::Base64
                | Builtin::Xargs => panic!("not a grep/sed test"),
            };
            let mut reader = PipeReader::from_bytes(
                b"x\nx\nx\nx\nx\n".to_vec(),
                None,
                crate::interp::telemetry::stage_read,
            );
            let mut budget = Budget::start(Limits {
                max_value_bytes: 3,
                ..Limits::default()
            });
            let mut output = Vec::new();
            let status = command
                .run_text(&args, &mut reader, &mut budget, |bytes| {
                    output.extend_from_slice(bytes);
                    Ok(true)
                })
                .expect("completed lines refund their retained bytes");
            assert_eq!(status, ExitCode::SUCCESS);
            assert_eq!(output.len(), 10);
        }
    }

    #[test]
    fn text_builtins_charge_each_chunk_and_observe_cancel() {
        for command in [Builtin::Grep, Builtin::Sed] {
            let args = match command {
                Builtin::Grep => vec!["x".to_owned()],
                Builtin::Sed => vec!["s/x/y/".to_owned()],
                Builtin::Awk
                | Builtin::Echo
                | Builtin::Printf
                | Builtin::Test
                | Builtin::TestBracket
                | Builtin::True
                | Builtin::False
                | Builtin::Progress
                | Builtin::Sleep
                | Builtin::Cat
                | Builtin::Jobs
                | Builtin::Wait
                | Builtin::Kill
                | Builtin::Cap
                | Builtin::Head
                | Builtin::Tail
                | Builtin::Cut
                | Builtin::Uniq
                | Builtin::Wc
                | Builtin::Sort
                | Builtin::Jq
                | Builtin::Base64
                | Builtin::Xargs => panic!("not a grep/sed test"),
            };
            let (mut writer, mut reader) = pipe::pipe(
                None,
                None,
                crate::interp::telemetry::stage_read,
                crate::interp::telemetry::stage_write,
            );
            for _ in 0..5 {
                assert_eq!(writer.write(b"x"), pipe::WriteOutcome::Accepted);
            }
            drop(writer);
            let mut budget = Budget::start(Limits {
                max_steps: 2,
                ..Limits::default()
            });
            let error = command
                .run_text(&args, &mut reader, &mut budget, |_| Ok(true))
                .expect_err("the third chunk exceeds the budget");
            assert!(matches!(
                error,
                CommandFailure::Fatal(crate::builtins::FatalError::Limit(LimitExceeded::Steps {
                    maximum: 2
                }))
            ));

            let mut reader =
                PipeReader::from_bytes(b"x".to_vec(), None, crate::interp::telemetry::stage_read);
            let (handle, signal) = dekopon_process::CancelSignal::pair();
            let limits = Limits::default();
            let mut budget = Budget::start_tree(
                limits,
                dekopon_process::TreeContext::new(
                    limits,
                    dekopon_process::CallBudget::new(32),
                    crate::test_threads(),
                )
                .with_cancel(vec![signal]),
            );
            handle.cancel();
            let error = command
                .run_text(&args, &mut reader, &mut budget, |_| Ok(true))
                .expect_err("cancel is checked for each chunk");
            assert!(matches!(
                error,
                CommandFailure::Fatal(crate::builtins::FatalError::Limit(LimitExceeded::Cancelled))
            ));
        }
    }
}