Repository navigation
Expand file tree
/
Copy pathmain.rs
More file actions
1949 lines (1850 loc) · 78.6 KB
/
Copy pathmain.rs
File metadata and controls
1949 lines (1850 loc) · 78.6 KB
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
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! The minimal CLI which pairs/talks-with minimald.
// The in-process daemon's async bodies are deep: rustc's default query depth (128)
// overflows computing their layout (`queries overflow the depth limit!`), as the
// daemon crates themselves already declare.
#![recursion_limit = "256"]
use std::io::IsTerminal as _;
use std::process::ExitCode;
use clap::{CommandFactory as _, Parser};
use minimal::{ExecArgs, PolicyArgs, PolicyOutputFormat};
use tracing_subscriber::fmt::format::{FormatEvent, Writer};
use tracing_subscriber::fmt::{FmtContext, FormatFields};
use tracing_subscriber::{
EnvFilter, Layer, fmt, fmt::MakeWriter, prelude::*, registry::LookupSpan,
};
/// Custom main: handle shell completion requests before launching the async world.
fn main() -> ExitCode {
clap_complete::CompleteEnv::with_factory(minimal::Cli::command)
.var(minimal::COMPLETE_VAR)
.complete();
run()
}
#[tokio::main]
async fn run() -> ExitCode {
// True only when RUST_LOG parsed: a malformed RUST_LOG falls back to the
// default filter and keeps the plain user-facing format.
let (filter, rust_log_set) = match EnvFilter::try_from_default_env() {
Ok(filter) => (filter, true),
Err(_) => (
EnvFilter::new("warn")
.add_directive("topiary=off".parse().unwrap())
.add_directive("libcgroups=off".parse().unwrap()),
false,
),
};
// Invoked as `git-remote-min` (a symlink or copy of this binary): speak
// the git remote-helper protocol on stdout, so logs must go to stderr.
if minimal::git_remote::invoked_as_remote_helper() {
tracing_subscriber::registry()
.with(fmt::layer().with_writer(std::io::stderr))
.with(filter)
.init();
let args: Vec<String> = std::env::args().skip(1).collect();
return match minimal::git_remote::run(&args).await {
Ok(code) => code,
Err(e) => {
eprintln!("error: {e:#}");
ExitCode::FAILURE
}
};
}
// Parse before installing the subscriber, so the shell completion handler can
// be configured to log to stderr instead of stdout.
let cli = minimal::Cli::try_parse()
.unwrap_or_else(|err| minimal::with_retired_command_hint(err).exit());
minimal::theme::install();
// Publish `--vm` before any path resolution, so the socket, the state dir,
// and any autospawn all name the same VM (NET-052).
if let Err(e) = cli.global_args.publish_vm_name() {
eprintln!("error: {e:#}");
return ExitCode::FAILURE;
}
// OTel export (opt-in: MINIMAL_TELEMETRY=1 plus an OTLP endpoint; see
// mlog::otel): the layers are None when off and carry their own
// info-level filter when on; the console keeps its own filter, with the
// OTel SDK's errors silenced.
mlog::otel::init("minimal-cli");
// A CLI lives for one command: its exit flush is short, so a collector
// that is down or silent never shows in a command's wall time.
mlog::otel::set_exit_flush(mlog::otel::CLI_EXIT_FLUSH);
let filter = mlog::otel::quiet(filter);
let registry = tracing_subscriber::registry()
.with(mlog::otel::span_layer())
.with(mlog::otel::log_layer());
// `min dash` owns the terminal (alternate screen); a log line landing on
// stdout/stderr would corrupt the frame. Log to <state>/dash.log
// instead, discarding if the state dir can't be written.
if matches!(cli.command, Some(minimal::Command::Dash)) {
// Honor `--minimal-dir` so an isolated daemon's logs stay isolated.
let base = cli
.global_args
.minimal_dir
.clone()
.unwrap_or_else(|| paths::minimal_state_dir().as_utf8_path().into());
// Open the log file once; MakeWriter is per-write, so the closure
// must not re-open it per log event.
let file = {
let path = base.join("dash.log");
let _ = std::fs::create_dir_all(&base);
std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(path)
.map(std::sync::Arc::new)
.ok()
};
let log = move || -> Box<dyn std::io::Write + Send> {
match &file {
Some(f) => Box::new(DashLog(f.clone())),
None => Box::new(std::io::sink()),
}
};
registry
.with(
fmt::layer()
.with_writer(log)
.with_ansi(false)
.with_filter(filter),
)
.init();
} else if stdout_is_data_contract(&cli.command) {
registry
.with(
console_layer(
std::io::stderr,
std::io::stderr().is_terminal(),
!rust_log_set,
)
.with_filter(filter),
)
.init();
} else {
registry
.with(
console_layer(
ot::StderrWriter::new,
std::io::stderr().is_terminal(),
!rust_log_set,
)
.with_filter(filter),
)
.init();
}
mlog::otel::report_init();
// The output mode the run is under, read before the CLI is consumed:
// the error path keys on it (below), so a machine-output run answers a
// failure with its own contract rather than a plain-text line.
let output_mode = machine_output_mode(&cli);
// Only `version` writes its output through a fallible writer; a broken
// pipe from any other command (e.g. a daemon socket) is a real failure.
let quiet_on_closed_pipe = matches!(cli.command, Some(minimal::Command::Version));
// The daily update check (inbox#589): reads its cache, spawns the
// detached check when one is due, prints a notice once per new release.
// Never waits, never fails the command.
minimal::update_check::before_command(&cli.global_args, &cli.command);
let result = minimal::run(cli).await;
// Flush exported telemetry (bounded; a no-op when export is off). What
// the bound cuts off is in the spool already.
mlog::otel::shutdown(mlog::otel::CLI_EXIT_FLUSH);
if let Err(e) = result {
return answer_failure(
&e,
output_mode,
quiet_on_closed_pipe,
minimal::hosts::failed_run_alias_hint(),
&mut std::io::stderr(),
);
}
ExitCode::SUCCESS
}
/// How a failed run ends: the exit code, and what goes to `stderr`. The run's
/// stdout is not a parameter, so a failure writes nothing there.
#[expect(
clippy::let_underscore_must_use,
reason = "a closed stderr has no reader left to tell; the exit status is \
the failure's answer either way"
)]
fn answer_failure(
e: &anyhow::Error,
machine_mode: bool,
quiet_on_closed_pipe: bool,
alias_hint: Option<&str>,
stderr: &mut dyn std::io::Write,
) -> ExitCode {
// A task's non-zero exit (`min task run`) is a status to relay, not
// an error to print — the task's own output already streamed through
// (the git-remote helper's ExitCode precedent).
if let Some(&minimal::task::TaskExit(code)) = e.downcast_ref::<minimal::task::TaskExit>() {
if let Some(hint) = alias_hint {
let _ = writeln!(stderr, "{hint}");
}
return ExitCode::from(code);
}
// A machine-output run answers its failure with the one
// `min/v1/error` object a client parses (BCLI-033), written by the
// shared output writer, keyed on the output mode the run was under
// rather than on the command. The object is the contract, so there is
// no second, plain-text line to print for the same failure, only the
// non-zero status.
if machine_mode {
return match machine_mode_answer(e) {
MachineModeAnswer::Quiet => ExitCode::from(141),
MachineModeAnswer::Object(failure) => {
// BCLI-042: an old spelling's hint is the object's `hint`
// field, with no separate line.
let failure = match alias_hint {
Some(hint) => failure.with_alias_hint(hint),
None => failure,
};
emit_machine_mode_error(stderr, &failure);
ExitCode::from(failure_exit_code(e))
}
};
}
// A reader that went away (`min version | head -1`) is not an error
// worth reporting: exit quietly with the shell's SIGPIPE convention.
if quiet_on_closed_pipe && is_broken_pipe(e) {
return ExitCode::from(141);
}
// A run that its box's timeout ended already printed why on stderr
// (BCLI-014): it relays 124 with no second line for the same fact.
if let Some(timed_out) = e.downcast_ref::<minimal::BoxTimedOut>()
&& timed_out.is_printed()
{
if let Some(hint) = alias_hint {
let _ = writeln!(stderr, "{hint}");
}
return ExitCode::from(minimal::BoxTimedOut::EXIT_CODE);
}
let _ = writeln!(stderr, "error: {e:#}");
// BCLI-013: a wait that its `--timeout` ended gives the next step on
// its own line, as the machine-mode object gives it in `hint`.
if let Some(timed_out) = e.downcast_ref::<minimal::BoxTimedOut>()
&& !timed_out.hint().is_empty()
{
let _ = writeln!(stderr, "{}", timed_out.hint());
}
if let Some(hint) = alias_hint {
let _ = writeln!(stderr, "{hint}");
}
ExitCode::from(failure_exit_code(e))
}
/// The exit code a failed run ends with, from the architecture's reserved
/// codes ("Exit codes"): 2 when a running box holds the name a create
/// asked for (`minimald_rpc::HeldNameRefusal`) or a removal without
/// `--force` finds the box running (`minimal::BoxRunningRefusal`) or a run
/// names an entry with a terminal (`minimal::task::RunNeedsTerminal`) or
/// puts one of its network flags among the task's arguments
/// (`minimal::task::RunFlagMisplaced`), 3
/// when the activation refused the box spec
/// (`boxes::core::bep::ActivationRefused`) or found the project's
/// `minimal.toml` invalid (`minimal::ProjectFileInvalid`) or a GitHub
/// grant undeliverable (`minimal::GrantNotDelivered`), 7 when the VM host could not
/// be reached to register or resume an own-address box's row (provider/host
/// unreachable, #1790), 8 when the host refused the registration for want
/// of addresses (insufficient resources), the code a box address refusal
/// carries (`minimal::BoxAddressRefusal`: 2 when a name matches boxes on
/// more than one host, 4 when the address names no box, 7 when a host did
/// not answer the lookup), the code a `min box exec` refusal carries
/// (`minimal::BoxExecRefusal`: 2 for `-t` without a terminal or a box that
/// is not running, 5 when its spec turns exec off), the code an `--exec
/// <id>` refusal of `min box stop`, `logs` or `wait` carries
/// (`minimal::BoxExecIdRefusal`: 2 for text that is not an exec id, 4 for an
/// exec the box does not have), the code a start
/// refusal carries (`minimal::StartEntryRefusal`: 4 when the start does not
/// find the entry, 2 when it cannot pick or start it), 2 when a start needs a terminal
/// it does not have (`minimal::StartNeedsTerminal`) or asks for a held name
/// (`minimal::StartNameHeld`), 124 when an exec ran past its own timeout
/// (`minimal::BoxExecTimedOut`) or a box ran past its own timeout or a
/// `min box wait --timeout` ran out (`minimal::BoxTimedOut`), and 1, the unspecified error,
/// for everything else — a refusal the host answered included. Both
/// output modes end with the same code.
fn failure_exit_code(e: &anyhow::Error) -> u8 {
// BEP-008/009/010/017/056: a box spec refused at activation.
if let Some(refused) = e.downcast_ref::<boxes::core::bep::ActivationRefused>() {
return refused.exit_code();
}
// BCLI-004: `min box rm` of a running box without `--force`.
if e.downcast_ref::<minimal::BoxRunningRefusal>().is_some() {
return minimal::BoxRunningRefusal::EXIT_CODE;
}
// BCLI-010: `min task run` or `min box run` of an entry with a terminal.
if e.downcast_ref::<minimal::task::RunNeedsTerminal>()
.is_some()
{
return minimal::task::RunNeedsTerminal::EXIT_CODE;
}
// `min task run` or `min box run` with a network flag among the task's
// arguments: a usage error.
if e.downcast_ref::<minimal::task::RunFlagMisplaced>()
.is_some()
{
return minimal::task::RunFlagMisplaced::EXIT_CODE;
}
// BCLI-034: a network flag the box's network mode refuses is a usage
// error (2). A project file, a task name, a loadout name or a local
// host that is not there is a thing not found (4).
if e.downcast_ref::<minimal::NetworkFlagRefusal>().is_some() {
return minimal::NetworkFlagRefusal::EXIT_CODE;
}
if e.downcast_ref::<minimal::task::ProjectFileNotFound>()
.is_some()
{
return minimal::task::ProjectFileNotFound::EXIT_CODE;
}
if e.downcast_ref::<minimal::task::TaskNotFound>().is_some() {
return minimal::task::TaskNotFound::EXIT_CODE;
}
if e.downcast_ref::<minimal::loadouts::LoadoutNotFound>()
.is_some()
{
return minimal::loadouts::LoadoutNotFound::EXIT_CODE;
}
if e.downcast_ref::<minimal::hosts::LocalHostNotFound>()
.is_some()
{
return minimal::hosts::LocalHostNotFound::EXIT_CODE;
}
// BCLI-078: a task's `minimal.toml` that does not load exits 3.
if e.downcast_ref::<minimal::task::TaskFileInvalid>().is_some() {
return minimal::task::TaskFileInvalid::EXIT_CODE;
}
// BCLI-058: `min box rename` to a name BOX-010 refuses.
if e.downcast_ref::<minimal::BoxRenameRefusal>().is_some() {
return minimal::BoxRenameRefusal::EXIT_CODE;
}
// BCLI-074: `min box restart` refused, such as for a box that runs to
// completion (exit 2). The refusal carries its own code, never 0.
if let Some(refusal) = e.downcast_ref::<minimald_rpc::RestartRefusal>() {
return refusal.exit_code.max(1);
}
// BCLI-005: `min box prune` off a terminal without `--yes`.
if e.downcast_ref::<minimal::PruneNeedsYes>().is_some() {
return minimal::PruneNeedsYes::EXIT_CODE;
}
// BCLI-029: a start off a terminal of an entry with a terminal.
if e.downcast_ref::<minimal::StartNeedsTerminal>().is_some() {
return minimal::StartNeedsTerminal::EXIT_CODE;
}
// BCLI-071, BCLI-072: a start that cannot pick or start its entry.
if let Some(refusal) = e.downcast_ref::<minimal::StartEntryRefusal>() {
return refusal.exit_code();
}
// BCLI-069: a start whose name a running box holds.
if e.downcast_ref::<minimal::StartNameHeld>().is_some() {
return minimal::StartNameHeld::EXIT_CODE;
}
// BOX-163: a create under a name a running box holds.
if e.downcast_ref::<minimald_rpc::HeldNameRefusal>().is_some() {
return minimald_rpc::HeldNameRefusal::EXIT_CODE;
}
// NET-060: a project `minimal.toml` whose session entry the start
// cannot pick refuses the activation with exit 2.
if e.downcast_ref::<minimal::SessionEntryUndecided>().is_some() {
return minimal::SessionEntryUndecided::EXIT_CODE;
}
// An invalid project `minimal.toml` refuses the activation with exit 3.
if e.downcast_ref::<minimal::ProjectFileInvalid>().is_some() {
return 3;
}
// BCLI-019, BCLI-020: `min type` of a project whose box types do not
// load exits 3, and `min type show` of a name that is no type exits 4.
if e.downcast_ref::<minimal::BoxTypesInvalid>().is_some() {
return minimal::BoxTypesInvalid::EXIT_CODE;
}
if e.downcast_ref::<minimal::BoxTypeNotFound>().is_some() {
return minimal::BoxTypeNotFound::EXIT_CODE;
}
// BEP-007: a GitHub grant the box cannot receive in its environment.
if e.downcast_ref::<minimal::GrantNotDelivered>().is_some() {
return 3;
}
if e.downcast_ref::<minimal_client::box_registration::HostUnreachable>()
.is_some()
{
return 7;
}
if e.downcast_ref::<minimal_client::box_registration::HostAddressesExhausted>()
.is_some()
{
return 8;
}
// BCLI-002, BCLI-064: a box address that names no single box.
if let Some(refused) = e.downcast_ref::<minimal::BoxAddressRefusal>() {
return refused.exit_code();
}
// BCLI-068, BCLI-007, BCLI-009, BCLI-032: `min box attach`, `min box
// resume` or `min session attach` refused, or its connection failed.
if let Some(refused) = e.downcast_ref::<minimal::BoxAttachRefusal>() {
return refused.exit_code();
}
// BCLI-053: `min box exec -t` without a terminal, or into a box that is
// not running (2), or whose spec turns exec off (5).
if let Some(refused) = e.downcast_ref::<minimal::BoxExecRefusal>() {
return refused.exit_code();
}
// BCLI-055, BCLI-056, BCLI-057: `--exec <id>` on `min box stop`, `logs`
// or `wait` with text that is not an exec id (2), or an exec id the box
// does not have (4).
if let Some(refused) = e.downcast_ref::<minimal::BoxExecIdRefusal>() {
return refused.exit_code();
}
// BCLI-053: an exec that its own timeout ended.
if e.downcast_ref::<minimal::BoxExecTimedOut>().is_some() {
return minimal::BoxExecTimedOut::EXIT_CODE;
}
// BCLI-013, BCLI-014: a box that its own timeout ended, or a `min box
// wait --timeout` that ran out.
if e.downcast_ref::<minimal::BoxTimedOut>().is_some() {
return minimal::BoxTimedOut::EXIT_CODE;
}
// BCLI-018: `min init` refused a request (2) or a type (3).
if let Some(refusal) = e.downcast_ref::<minimal::InitRefusal>() {
return refusal.code;
}
// BCLI-034, BCLI-062: `min box cp` of a file the box does not have, or
// does not allow reading.
if let Some(refused) = e.downcast_ref::<minimal::BoxFileRefusal>() {
return refused.exit_code();
}
1
}
/// Whether the error's root cause is a broken pipe: the writer's reader
/// closed before all output was written. Rust ignores SIGPIPE by default, so
/// this surfaces as an `io::Error` of kind `BrokenPipe` instead of a signal.
fn is_broken_pipe(e: &anyhow::Error) -> bool {
e.chain().any(|cause| {
cause
.downcast_ref::<std::io::Error>()
.is_some_and(|io| io.kind() == std::io::ErrorKind::BrokenPipe)
})
}
/// How a machine-output run answers a failure.
#[derive(Debug, PartialEq, Eq)]
enum MachineModeAnswer {
/// The reader of the document went away: exit 141 (the shell's SIGPIPE
/// convention) with nothing on stderr, which nobody is reading either.
Quiet,
/// The one `min/v1/error` object, on stderr.
Object(minimal::MachineModeFailure),
}
/// The machine-mode answer to a failed run, shared by every command that
/// takes `-o json`: in a machine mode every failure is the one error object
/// (or, for a reader that hung up, nothing). A walk's own failure is the
/// payload it already failed into. A broken pipe means the consumer hung
/// up, so the run exits quietly. A failure the command tagged as its own
/// document write ([`minimal::OutputWriteError`]) is `output_failed`, so a
/// script can tell it from a crash. A VM host that could not be reached is
/// `host_unreachable`, and one out of addresses `insufficient_resources`,
/// beside the exit codes [`failure_exit_code`] gives them. Anything else is
/// `unspecified`, the exit table's unspecified error, with the chain as its
/// message and no hint, because nothing about it is known to name a remedy.
fn machine_mode_answer(e: &anyhow::Error) -> MachineModeAnswer {
if let Some(failure) = e.downcast_ref::<minimal::MachineModeFailure>() {
return MachineModeAnswer::Object(failure.clone());
}
if is_broken_pipe(e) {
return MachineModeAnswer::Quiet;
}
if e.downcast_ref::<minimal_client::box_registration::HostUnreachable>()
.is_some()
{
return MachineModeAnswer::Object(minimal::MachineModeFailure::new(
"host_unreachable",
format!("{e:#}"),
"the VM host daemon is not answering; check that it is running (`minvmd status`)"
.to_string(),
));
}
if e.downcast_ref::<minimal_client::box_registration::HostAddressesExhausted>()
.is_some()
{
return MachineModeAnswer::Object(minimal::MachineModeFailure::new(
"insufficient_resources",
format!("{e:#}"),
"the VM host has no address left for another box; destroy a session you no \
longer need and try again"
.to_string(),
));
}
if let Some(refused) = e.downcast_ref::<minimal::AuditSelfUnsupportedUnenrolled>() {
return MachineModeAnswer::Object(minimal::MachineModeFailure::new(
refused.code(),
format!("{e:#}"),
"on the host, run `min box audit <box>`".to_string(),
));
}
// BEP-003, Gatehouse §6.2: a refused activation with a defined error
// answers with that error and its next step.
if let Some((code, hint)) = e
.downcast_ref::<boxes::core::bep::ActivationRefused>()
.and_then(|refused| {
refused
.refusals
.iter()
.find_map(|refusal| Some((refusal.code()?, refusal.next_step()?)))
})
{
return MachineModeAnswer::Object(minimal::MachineModeFailure::new(
code,
format!("{e:#}"),
hint,
));
}
// BCLI-020: `min type show` of a name that is no type is `not_found`.
if e.downcast_ref::<minimal::BoxTypeNotFound>().is_some() {
return MachineModeAnswer::Object(minimal::MachineModeFailure::new(
"not_found",
format!("{e:#}"),
minimal::BoxTypeNotFound::HINT.to_string(),
));
}
// BCLI-053: an exec that its own timeout ended is `timeout`.
if let Some(timed_out) = e.downcast_ref::<minimal::BoxExecTimedOut>() {
return MachineModeAnswer::Object(minimal::MachineModeFailure::new(
minimal::BoxExecTimedOut::CODE,
format!("{e:#}"),
timed_out.hint().to_string(),
));
}
// BCLI-013, BCLI-014: a box timeout is `timeout`, and a wait timeout is
// `wait_timeout`.
if let Some(timed_out) = e.downcast_ref::<minimal::BoxTimedOut>() {
return MachineModeAnswer::Object(minimal::MachineModeFailure::new(
timed_out.code(),
format!("{e:#}"),
timed_out.hint().to_string(),
));
}
// BCLI-033: a box address refusal answers with the error kind its exit
// code stands for: `not_found` (4), `host_unreachable` (7) or `ambiguous` (2).
if let Some(refused) = e.downcast_ref::<minimal::BoxAddressRefusal>() {
return MachineModeAnswer::Object(minimal::MachineModeFailure::new(
refused.code(),
format!("{e:#}"),
refused.hint().to_string(),
));
}
if e.downcast_ref::<minimal::OutputWriteError>().is_some() {
return MachineModeAnswer::Object(minimal::MachineModeFailure::new(
"output_failed",
format!("{e:#}"),
"stdout could not be written; check the destination (a full disk, a closed \
descriptor)"
.to_string(),
));
}
MachineModeAnswer::Object(minimal::MachineModeFailure::new(
"unspecified",
format!("{e:#}"),
String::new(),
))
}
/// A cheaply clonable writer over the dash log file: every clone writes
/// through the same opened file (append mode) instead of re-opening it.
struct DashLog(std::sync::Arc<std::fs::File>);
impl std::io::Write for DashLog {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
(&*self.0).write(buf)
}
fn flush(&mut self) -> std::io::Result<()> {
(&*self.0).flush()
}
}
/// Whether the command's stdout is a data contract that tracing must not
/// pollute, so its logs go to stderr instead. The `completions` handlers emit a
/// shell shim on stdout, `session exec` carries only the exec'd
/// command's output, `box exec` carries the command's output or its exec
/// id, and `task run` / `session run` stream the task's stdout —
/// a log line in any of them would be read as content. A bare `min` (no subcommand) is
/// one too: its non-TTY twin promises an empty stdout to pipelines, and its
/// interactive activate path prints only the session id there. So is
/// `session policy -o json`, whose stdout is one document a script parses.
fn stdout_is_data_contract(command: &Option<minimal::Command>) -> bool {
matches!(
command,
None | Some(
minimal::Command::CompleteSessionStr(_)
| minimal::Command::Completions(_)
| minimal::Command::Session(minimal::SessionArgs {
command: minimal::SessionCommand::Exec(ExecArgs { .. })
| minimal::SessionCommand::Run(_)
| minimal::SessionCommand::Policy(PolicyArgs {
output: Some(PolicyOutputFormat::Json),
..
}),
})
| minimal::Command::Task(minimal::TaskArgs {
command: minimal::TaskCommand::Run(_),
})
| minimal::Command::Box(minimal::BoxArgs {
command: minimal::BoxCommand::Exec(_) | minimal::BoxCommand::Run(_),
})
)
)
}
/// The console log layer. `plain` (no `RUST_LOG` in effect) renders through
/// [`PlainFormat`]: `warning:`/`error:` lines matching the rest of the CLI;
/// otherwise the full tracing format is kept for debugging.
fn console_layer<S, W>(writer: W, ansi: bool, plain: bool) -> Box<dyn Layer<S> + Send + Sync>
where
S: tracing::Subscriber + for<'a> LookupSpan<'a>,
W: for<'w> MakeWriter<'w> + Send + Sync + 'static,
{
let layer = fmt::layer().with_writer(writer).with_ansi(ansi);
if plain {
layer.event_format(PlainFormat).boxed()
} else {
layer.boxed()
}
}
/// The plain console format: `warning: <message>` for WARN, `error: <message>`
/// for ERROR, and the bare message for INFO and below. A message that already
/// starts with `help:` is written as a help line with no level prefix. Span
/// context is omitted on purpose: these lines are for a person, not debugging.
struct PlainFormat;
impl<S, N> FormatEvent<S, N> for PlainFormat
where
S: tracing::Subscriber + for<'a> LookupSpan<'a>,
N: for<'a> FormatFields<'a> + 'static,
{
fn format_event(
&self,
ctx: &FmtContext<'_, S, N>,
mut writer: Writer<'_>,
event: &tracing::Event<'_>,
) -> std::fmt::Result {
let mut message = MessageVisitor::default();
event.record(&mut message);
match *event.metadata().level() {
tracing::Level::WARN => {
if !message.0.as_deref().is_some_and(|m| m.starts_with("help:")) {
write!(writer, "warning: ")?;
}
}
tracing::Level::ERROR => write!(writer, "error: ")?,
_ => {}
}
ctx.format_fields(writer.by_ref(), event)?;
writeln!(writer)
}
}
/// Captures the event's `message` field, so the formatter can decide whether
/// to prefix a level.
#[derive(Default)]
struct MessageVisitor(Option<String>);
impl tracing::field::Visit for MessageVisitor {
fn record_str(&mut self, field: &tracing::field::Field, value: &str) {
if field.name() == "message" {
self.0 = Some(value.to_owned());
}
}
fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) {
if field.name() == "message" {
self.0 = Some(format!("{value:?}"));
}
}
}
/// Whether a run is under the machine output mode: the command's `-o`, the
/// flag the architecture's machine-output contract hangs on — `json` for
/// `min session policy -o json` and `jsonl` for `min box audit -o jsonl`.
/// `false` for every text run, and for a command that has not taken a
/// machine `-o` yet, which is the same thing to the error path: its failure
/// is a plain-text line. The error path keys on this, so a command joins
/// the machine mode by growing an `output` flag, and nothing else about its
/// error path changes.
fn machine_output_mode(cli: &minimal::Cli) -> bool {
match &cli.command {
Some(minimal::Command::Session(minimal::SessionArgs {
command: minimal::SessionCommand::Policy(PolicyArgs { output, .. }),
})) => output.is_some(),
// Architecture line 379: a `-o jsonl` failure is one `min/v1/error`
// object too.
Some(minimal::Command::Box(minimal::BoxArgs {
command: minimal::BoxCommand::Audit(args),
})) => args.output == Some(minimal::BoxAuditOutputFormat::Jsonl),
// Architecture line 383: a `min box list -o json` failure is one
// `min/v1/error` object (BCLI-001).
Some(minimal::Command::Box(minimal::BoxArgs {
command: minimal::BoxCommand::List(args),
})) => args.output.is_some(),
// BCLI-016: a `min box events -o jsonl` failure is one
// `min/v1/error` object too.
Some(minimal::Command::Box(minimal::BoxArgs {
command: minimal::BoxCommand::Events(args),
})) => args.output == Some(minimal::BoxEventsOutputFormat::Jsonl),
// BCLI-033: a `min box show -o json|yaml` failure is one
// `min/v1/error` object.
Some(minimal::Command::Box(minimal::BoxArgs {
command: minimal::BoxCommand::Show(args),
})) => args.output.is_some(),
// BCLI-019, BCLI-020: `min type list|show -o json|yaml|toml`.
Some(minimal::Command::Type(minimal::TypeArgs {
command: minimal::TypeCommand::List(minimal::TypeListArgs { output }),
})) => output.is_some(),
Some(minimal::Command::Type(minimal::TypeArgs {
command: minimal::TypeCommand::Show(args),
})) => args.output.is_some(),
_ => false,
}
}
/// The machine-mode error object, encoded as one line by the shared output
/// writer: the `min/v1/error` stamp, the `code` a script branches on, the
/// message, and the hint — nothing else on the line, and no line beside it.
#[cfg(test)]
fn machine_mode_error_line(failure: &minimal::MachineModeFailure) -> anyhow::Result<String> {
Ok(minimal::output::error_line(failure)?)
}
/// The machine-mode error emitter: writes the one `min/v1/error` object on
/// stderr, the only thing the mode puts there on any failure, so a client
/// parses a failure the same way it parses the document. A command that
/// takes `-o json` fails its walk into [`minimal::MachineModeFailure`] —
/// carried through the `anyhow` chain, the way [`minimal::task::TaskExit`]
/// is — and needs nothing else. `min ls --json` and its kin are untouched:
/// their failure stays the plain-text line it always was.
#[expect(
clippy::let_underscore_must_use,
reason = "a closed stderr has no reader left to tell; the exit status is \
the failure's answer either way"
)]
fn emit_machine_mode_error(stderr: &mut dyn std::io::Write, failure: &minimal::MachineModeFailure) {
// One object, one line. The exit code is non-zero either way.
let _ = minimal::output::write_error(stderr, failure);
}
#[cfg(test)]
mod tests {
use super::*;
use minimal::Command;
/// BCLI-019, BCLI-020: `min type` exits 3 when the project's box types
/// do not load, and 4 for a name that is no type. Its `-o` forms are a
/// machine mode, and the unknown name is `not_found` there.
#[test]
fn type_refusals_exit_3_and_4() {
let parse = toml::from_str::<toml::Table>("[").unwrap_err();
let invalid = anyhow::Error::new(minimal::BoxTypesInvalid {
doing: "list the box types",
cause: minimal::BoxTypesCause::Parse {
path: "minimal.toml".into(),
error: parse,
},
});
assert_eq!(failure_exit_code(&invalid), 3);
let not_found = anyhow::Error::new(minimal::BoxTypeNotFound {
name: "nope".to_owned(),
});
assert_eq!(failure_exit_code(¬_found), 4);
let MachineModeAnswer::Object(failure) = machine_mode_answer(¬_found) else {
panic!("a not-found refusal is an error object");
};
assert_eq!(failure.code(), "not_found");
for (output, machine) in [(Some(minimal::TypeOutputFormat::Yaml), true), (None, false)] {
let list = minimal::Cli {
global_args: minimal::GlobalArgs::default(),
command: Some(Command::Type(minimal::TypeArgs {
command: minimal::TypeCommand::List(minimal::TypeListArgs { output }),
})),
};
assert_eq!(machine_output_mode(&list), machine);
let show = minimal::Cli {
global_args: minimal::GlobalArgs::default(),
command: Some(Command::Type(minimal::TypeArgs {
command: minimal::TypeCommand::Show(minimal::TypeShowArgs {
name: "session".to_owned(),
output,
}),
})),
};
assert_eq!(machine_output_mode(&show), machine);
}
}
/// A bare `min` (no subcommand) keeps stdout clean: the non-TTY twin
/// promises pipelines an empty stdout, so its tracing must go to stderr.
#[test]
fn bare_min_is_a_stdout_contract() {
assert!(stdout_is_data_contract(&None));
}
/// `min session run` streams the task's stdout over the exec channel, so
/// tracing must route to stderr like the other stdout contracts.
#[test]
fn session_run_is_a_stdout_contract() {
let cmd = Some(Command::Session(minimal::SessionArgs {
command: minimal::SessionCommand::Run(minimal::SessionRunArgs {
session: "web".to_string(),
task: "build".to_string(),
}),
}));
assert!(stdout_is_data_contract(&cmd));
}
/// `min task run` streams the task's stdout, so tracing must route to
/// stderr there like the other stdout contracts.
#[test]
fn task_run_is_a_stdout_contract() {
let cmd = Some(Command::Task(minimal::TaskArgs {
command: minimal::TaskCommand::Run(minimal::TaskRunArgs {
task: "build".to_string(),
path: None,
network: None,
egress: minimal::EgressArgs::default(),
other: minimal::BoxOverrideArgs::default(),
detach: false,
args: vec![],
}),
}));
assert!(stdout_is_data_contract(&cmd));
}
/// A `MakeWriter` that appends to a shared buffer, so tests can assert on
/// the exact rendered log line.
struct BufferWriter(std::sync::Arc<std::sync::Mutex<Vec<u8>>>);
impl std::io::Write for BufferWriter {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.0.lock().unwrap().extend_from_slice(buf);
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
/// Without `RUST_LOG`, a warning renders as `warning: <message>` — no
/// timestamp and no target.
#[test]
fn console_layer_renders_plain_warning() {
let buf = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
let writer = {
let buf = buf.clone();
move || BufferWriter(buf.clone())
};
let layer = console_layer(writer, false, true);
let subscriber = tracing_subscriber::registry().with(layer);
tracing::subscriber::with_default(subscriber, || {
tracing::warn!(key = "value", "lifecycle_hooks is unknown");
});
let out = String::from_utf8(buf.lock().unwrap().clone()).unwrap();
assert_eq!(out, "warning: lifecycle_hooks is unknown key=\"value\"\n");
}
/// A WARN event whose message already starts with `help:` renders as a
/// bare help line, with no level prefix.
#[test]
fn console_layer_renders_help_line_without_level() {
let buf = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
let writer = {
let buf = buf.clone();
move || BufferWriter(buf.clone())
};
let layer = console_layer(writer, false, true);
let subscriber = tracing_subscriber::registry().with(layer);
tracing::subscriber::with_default(subscriber, || {
tracing::warn!("help: do you need to update to a newer version of minimal?");
});
let out = String::from_utf8(buf.lock().unwrap().clone()).unwrap();
assert_eq!(
out,
"help: do you need to update to a newer version of minimal?\n"
);
}
/// An ERROR event renders as `error: <message>`.
#[test]
fn console_layer_renders_plain_error() {
let buf = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
let writer = {
let buf = buf.clone();
move || BufferWriter(buf.clone())
};
let layer = console_layer(writer, false, true);
let subscriber = tracing_subscriber::registry().with(layer);
tracing::subscriber::with_default(subscriber, || {
tracing::error!(key = "value", "something failed");
});
let out = String::from_utf8(buf.lock().unwrap().clone()).unwrap();
assert_eq!(out, "error: something failed key=\"value\"\n");
}
/// With `RUST_LOG` set, the full tracing format (timestamp and target) is
/// kept for debugging.
#[test]
fn console_layer_keeps_full_format_with_rust_log() {
let buf = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
let writer = {
let buf = buf.clone();
move || BufferWriter(buf.clone())
};
let layer = console_layer(writer, false, false);
let subscriber = tracing_subscriber::registry().with(layer);
tracing::subscriber::with_default(subscriber, || {
tracing::warn!(key = "value", "lifecycle_hooks is unknown");
});
let out = String::from_utf8(buf.lock().unwrap().clone()).unwrap();
assert!(out.contains("min::tests:"), "target missing: {out:?}");
assert!(out.contains(" WARN "), "level missing: {out:?}");
assert!(
out.contains("lifecycle_hooks is unknown"),
"message missing: {out:?}"
);
assert!(
out.as_bytes().first().is_some_and(u8::is_ascii_digit),
"timestamp missing: {out:?}"
);
}
/// `min session policy -o json` writes one document a script parses, so
/// its tracing must route to stderr — and the text rendering, whose
/// stdout is for a person, must not be caught by the same gate.
#[test]
fn session_policy_json_is_a_stdout_contract() {
let cmd = Some(Command::Session(minimal::SessionArgs {
command: minimal::SessionCommand::Policy(PolicyArgs {
session: "web".to_string(),
output: Some(PolicyOutputFormat::Json),
}),
}));
assert!(stdout_is_data_contract(&cmd));
let cmd = Some(Command::Session(minimal::SessionArgs {
command: minimal::SessionCommand::Policy(PolicyArgs {
session: "web".to_string(),
output: None,
}),
}));
assert!(!stdout_is_data_contract(&cmd));
}
/// The error path's key: a `-o json` run is a machine-output run, a text
/// run is not, and a command that has not taken `-o json` yet is not
/// either — the same three-way split the subscriber gate makes, read
/// before the CLI is consumed so the failed run can still be asked what
/// mode it was in.
/// A walk's payload, a hung-up reader, a tagged document write and any
/// other failure each get their own machine-mode answer.
#[test]
fn machine_mode_answers_write_failures() {
let walk = minimal::MachineModeFailure::new(
"not_found",
"no session".to_string(),
"hint".to_string(),
);
assert_eq!(
machine_mode_answer(&anyhow::Error::new(walk.clone())),
MachineModeAnswer::Object(walk)
);
let hung_up = anyhow::Error::new(std::io::Error::from(std::io::ErrorKind::BrokenPipe))
.context(minimal::OutputWriteError);
assert_eq!(machine_mode_answer(&hung_up), MachineModeAnswer::Quiet);
let full = anyhow::Error::new(std::io::Error::other("no space left on device"))
.context(minimal::OutputWriteError);
match machine_mode_answer(&full) {
MachineModeAnswer::Object(failure) => {
assert_eq!(failure.code(), "output_failed");
assert!(
failure.message().contains("no space left on device"),
"the message carries the io chain: {}",
failure.message()
);
}
other => panic!("a failed document write answers output_failed, got {other:?}"),
}
// An io error the run met elsewhere (a config read, a socket) is
// not the document's write: it must not claim stdout failed.
let elsewhere = anyhow::Error::new(std::io::Error::from(std::io::ErrorKind::NotFound))
.context("reading the config");
for unrelated in [elsewhere, anyhow::anyhow!("something else")] {
match machine_mode_answer(&unrelated) {
MachineModeAnswer::Object(failure) => {
assert_eq!(failure.code(), "unspecified", "for {unrelated:#}");
assert!(failure.hint().is_empty(), "no remedy is known");