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
//! rustc-style diagnostics for sysg.
//!
//! Every user-facing failure renders as a [`crate::diag::Diagnostic`]: what happened, the
//! evidence sysg captured while it happened, and the exact next commands to
//! run — colored on a terminal, plain when piped, structured over IPC. The
//! design goal is the Rust compiler's: assume the user made an honest mistake
//! and hand it back with a map, not a dead end.
//!
//! Every diagnostic carries a typed [`crate::diag::SgCode`]. The enum *is* the error
//! taxonomy: a code that isn't a variant cannot be constructed, and adding a
//! failure mode means adding a variant. There is no stringly-typed seam.
use std::{fmt, io::IsTerminal};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
/// Base URL for per-code documentation pages.
pub const DOCS_BASE: &str = "https://sysg.dev/how-it-works/dialog/codes";
const RED: &str = "\x1b[1;91m";
const YELLOW: &str = "\x1b[1;33m";
const CYAN: &str = "\x1b[36m";
const GREEN: &str = "\x1b[32m";
const BOLD: &str = "\x1b[1m";
const DIM: &str = "\x1b[2m";
const UNDERLINE: &str = "\x1b[4;34m";
const RESET: &str = "\x1b[0m";
/// The stable sysg error taxonomy. Each variant owns its `SG####` string, a
/// canonical one-line title, and its docs slug; the wire form is the code
/// string so scripts and IPC stay stable across renames of the Rust variant.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SgCode {
/// SG0001 — a failure with no more specific diagnosis yet.
Catchall,
/// SG0002 — cron history/active state could not be restored.
CronStateRecoveryFailed,
/// SG0003 — a cron unit could not be safely registered.
CronRegistrationConflict,
/// SG0004 — a finite unit that exited cleanly was misclassified as failed.
FiniteUnitMisclassified,
/// SG0005 — the supervisor is using an outdated or wrong manifest.
StaleProjectConfiguration,
/// SG0006 — a command resolves ambiguously between projects/services.
TargetScopeAmbiguous,
/// SG0007 — the supervisor cannot safely restart or transfer ownership.
SupervisorRestartConflict,
/// SG0008 — a service or `pre_start` failed during boot or restart.
UnitStartFailed,
/// SG0009 — status/inspect disagrees with live process state.
StatusStateInconsistent,
/// SG0010 — expected service logs are unavailable or misrouted.
LogSourceUnavailable,
/// SG0011 — a live log-follow session is stale or cannot reconnect.
LogStreamDesynchronized,
/// SG0012 — log output exceeded safe storage/display bounds.
LogLimitExceeded,
/// SG0013 — a daemonized service inherited an invalid environment.
DaemonEnvironmentInvalid,
/// SG0014 — the installer cannot obtain the expected binary.
ReleaseArtifactUnavailable,
/// SG0015 — IPC/PID/tracking disagrees with the running processes.
SupervisorStateDesynchronized,
/// SG0016 — a rolling deployment failed without a useful error.
RollingDeploymentFailed,
/// SG0017 — `logs --prune` was run without a `--max-size` or `--max-age`
/// bound, so there is nothing to prune against.
PruneBoundMissing,
/// SG0019 — `logs` ran with no `-s`/`-p`/`--supervisor` selector, so there is
/// no target to read.
LogsTargetRequired,
/// SG0020 — `logs --supervisor` was combined with a `-s`/`-p` selector.
LogsSupervisorConflict,
/// SG0021 — `logs -s <service>` (with no `-p`) named a service that is not in
/// the loose bundle.
LooseServiceNotFound,
/// SG0022 — every health check probe failed to connect; the endpoint was
/// never reached (wrong address, or nothing listening).
HealthCheckUnreachable,
/// SG0023 — no health check probe completed within the per-attempt budget.
HealthCheckTimeout,
/// SG0101 — a direct lifecycle command targeted a schedule-driven cron unit.
CronDirectControl,
/// SG0102 — a service exited immediately at start, before it came up.
UnitImmediateExit,
/// SG0103 — a service's `pre_start` failed, so it was not started.
PreStartFailed,
/// SG0104 — a service never passed its configured health check.
HealthUnmet,
/// SG0105 — a service could not bind its port because it is already in use.
PortInUse,
/// SG0107 — reserved, no longer emitted. It reported the supervisor as
/// having *refused* a command it was too busy to take, but mutations are
/// queued onto the owner thread rather than refused, so the command it
/// blamed had in fact been accepted and usually went on to succeed. The
/// code is kept so a published diagnostic is not withdrawn; the conditions
/// it was raised for are now [`SgCode::CommandStillRunning`] and
/// [`SgCode::SupervisorNotResponding`].
SupervisorBusy,
/// SG0106 — a project was registered but one or more of its services never
/// came up. Reported by an attaching `start`, which returns as soon as the
/// supervisor QUEUES the boot: without this the CLI printed "loaded" and
/// exited 0 while the project had comprehensively failed to start.
ProjectServicesNotUp,
/// SG0108 - a service's `pre_start` command exceeded its execution budget
/// and was terminated before the service could launch.
PreStartTimeout,
/// SG0109 - a service was not started because one of its declared
/// dependencies did not reach the condition required by the manifest.
DependencyUnavailable,
/// SG0110 — automatic restarts for a service were stopped because it
/// exhausted its restart budget without ever staying up.
RestartBreakerOpen,
/// SG0111 — the supervisor is answering and still working on the command,
/// but has not finished within the client's budget. The command was
/// accepted and keeps running; only the wait was abandoned.
CommandStillRunning,
/// SG0201 — the `-p` project does not match the resolved config.
TargetConfigMismatch,
/// SG0202 — the command names a service or project that does not exist.
TargetNotFound,
/// SG0203 — a config file could not be found or read.
ConfigFileUnreadable,
/// SG0204 — mutually exclusive selectors were combined (e.g. --supervisor
/// with a service/project selector).
ConflictingSelectors,
/// SG0205 — the resident supervisor's process is alive but it is not
/// answering its control socket, so the command was refused rather than
/// routed into a dying daemon.
SupervisorNotResponding,
/// SG0206 — no supervisor is running, so the reported state is off disk and
/// unsupervised; any surviving processes are orphaned.
SupervisorOffline,
/// SG0207 — an `!include`d file is missing, unreadable, or not valid YAML.
IncludeUnresolved,
/// SG0208 — a manifest's includes form a cycle.
IncludeCycle,
/// SG0209 — includes exceed the nesting depth or cumulative size cap.
IncludeLimit,
/// SG0210 — a manifest field holds a value systemg cannot interpret, so the
/// manifest was refused before anything was started.
ManifestFieldInvalid,
/// SG0301 —a restart's new manifest is invalid; nothing was changed.
ManifestRejected,
/// SG0302 — a reconcile ran but left units short of their manifest target.
ReconcileIncomplete,
/// SG0303 — a supervisor recycle stopped the old daemon but the new one did
/// not come up.
SupervisorRecycleFailed,
/// SG0304 — a restart completed without bouncing a single unit, so whatever
/// the caller wanted reloaded is still running the old process.
RestartTouchedNothing,
/// SG0401 — a purge was refused because a live supervisor is still managing
/// processes; stop it (or pass `--force`) before wiping its state.
PurgeSupervisorActive,
/// SG0402 — a purge removed some state but hit an IO error before finishing,
/// so the on-disk state may be partial.
PurgeIncomplete,
/// SG0403 — a scoped purge named a project that has no state on disk.
PurgeProjectNotFound,
/// SG0404 — a purge target did not name a single project directory, so it
/// was refused before anything was deleted.
PurgeTargetInvalid,
/// SG0501 — the proposed live-upgrade binary is missing, malformed, or
/// unsafe for the supervisor to execute.
UpgradeTargetInvalid,
/// SG0502 — the proposed binary does not support a compatible live-reexec
/// protocol/schema contract or valid upgrade direction.
UpgradeIncompatible,
/// SG0503 — live runtime activity prevents the supervisor from reaching a
/// stable handoff point without risking workload ownership.
UpgradeEnvironmentUnsafe,
/// SG0504 — the resident supervisor could not serialize or execute its
/// validated handoff.
UpgradeHandoffFailed,
/// SG0505 — the replacement supervisor could not restore the handed-off
/// runtime and returned control to the previous binary.
UpgradeResumeFailed,
/// SG0601 — legacy `__loose__` state is present and must be migrated before
/// the loose manifests that own it can be managed separately.
MigrationRequired,
/// SG0602 — a state migration was refused because a supervisor is live.
MigrationSupervisorActive,
/// SG0603 — legacy state could not be attributed to a single manifest, so it
/// was archived rather than assigned.
MigrationAmbiguous,
/// SG0604 — a previous state migration did not finish; the layout is part
/// legacy and part migrated until it is resumed.
MigrationIncomplete,
/// SG0605 — a migrated artifact did not match its recorded checksum.
MigrationVerificationFailed,
/// SG0405 — a purge was refused because the resident supervisor did not
/// exit after a shutdown request; deleting its state would orphan it.
PurgeSupervisorShutdownTimeout,
/// SG0701 — running as root without `--sys`, so state would land in
/// user-mode paths instead of the system runtime.
SystemModeNotSelected,
/// SG0702 — on-disk state belongs to the other runtime mode than the one
/// this command targets.
RuntimeModeMismatch,
/// SG0703 — system-mode integration (unit or plist) is missing, wrong, or
/// stale for the installed binary.
SystemIntegrationBroken,
/// SG0704 — `--sys` was requested without root privileges.
SystemModeRequiresRoot,
/// SG0705 — the manifest declares root-only keys and is not startable in
/// user mode.
ManifestRequiresSystemMode,
/// SG0706 — a boot unit could not be generated or installed as asked.
BootUnitRefused,
/// SG0711 — container-init was requested on a platform or process that
/// cannot be PID 1 (not Linux, or not actually PID 1).
ContainerInitUnsupported,
/// SG0712 — PID 1 prerequisites are missing (procfs not mounted, not
/// root).
ContainerInitPrereqMissing,
/// SG0713 — PID 1 shutdown incomplete: services survived reverse-order
/// teardown, so init exited nonzero.
ContainerInitShutdownIncomplete,
/// SG0714 — live supervisor upgrade is forbidden in container-init mode: a
/// failed exec as PID 1 kills the container and every service in it.
ContainerInitUpgradeForbidden,
/// SG0721 — a security key was accepted by the schema but cannot be
/// enforced on this platform; the diagnostic names the exact key.
SandboxKeyUnenforceable,
/// SG0722 — a seccomp filter could not be built, compiled, or applied.
SeccompFilterFailed,
/// SG0723 — `prctl(PR_SET_NO_NEW_PRIVS)` failed, so seccomp and Landlock
/// cannot be applied safely.
NoNewPrivsFailed,
/// SG0724 — Landlock was requested but the kernel ABI is unavailable or
/// insufficient to enforce the requested rules.
LandlockUnavailable,
/// SG0725 — the manifest named a seccomp profile that does not exist.
SeccompProfileUnknown,
/// SG0726 — seccomp is not supported on this CPU architecture.
SeccompArchUnsupported,
/// SG0727 — a requested namespace could not be unshared.
NamespaceUnshareFailed,
/// SG0741 — a resource limit (`nofile`, `nproc`, `memlock`) could not be
/// set for the service.
ResourceLimitFailed,
/// SG0742 — the requested scheduling priority could not be set.
PriorityFailed,
/// SG0743 — the requested CPU affinity could not be applied.
CpuAffinityFailed,
/// SG0744 — the supplementary group list could not be set, so the service
/// would have kept the supervisor's groups.
SupplementaryGroupsFailed,
/// SG0745 — the primary group could not be switched.
PrimaryGidFailed,
/// SG0746 — the user could not be switched, so the service would have run
/// with the supervisor's identity.
UidSwitchFailed,
/// SG0747 — the requested capabilities could not be retained across the
/// identity switch.
CapabilityRetentionFailed,
/// SG0748 — capabilities could not be fully dropped, so the service would
/// have kept more privilege than configured.
CapabilityReductionIncomplete,
}
impl SgCode {
/// The stable `SG####` string. This is the wire and docs identity.
pub fn as_str(self) -> &'static str {
match self {
SgCode::Catchall => "SG0001",
SgCode::CronStateRecoveryFailed => "SG0002",
SgCode::CronRegistrationConflict => "SG0003",
SgCode::FiniteUnitMisclassified => "SG0004",
SgCode::StaleProjectConfiguration => "SG0005",
SgCode::TargetScopeAmbiguous => "SG0006",
SgCode::SupervisorRestartConflict => "SG0007",
SgCode::UnitStartFailed => "SG0008",
SgCode::StatusStateInconsistent => "SG0009",
SgCode::LogSourceUnavailable => "SG0010",
SgCode::LogStreamDesynchronized => "SG0011",
SgCode::LogLimitExceeded => "SG0012",
SgCode::DaemonEnvironmentInvalid => "SG0013",
SgCode::ReleaseArtifactUnavailable => "SG0014",
SgCode::SupervisorStateDesynchronized => "SG0015",
SgCode::RollingDeploymentFailed => "SG0016",
SgCode::PruneBoundMissing => "SG0017",
SgCode::LogsTargetRequired => "SG0019",
SgCode::LogsSupervisorConflict => "SG0020",
SgCode::LooseServiceNotFound => "SG0021",
SgCode::HealthCheckUnreachable => "SG0022",
SgCode::HealthCheckTimeout => "SG0023",
SgCode::CronDirectControl => "SG0101",
SgCode::UnitImmediateExit => "SG0102",
SgCode::PreStartFailed => "SG0103",
SgCode::HealthUnmet => "SG0104",
SgCode::PortInUse => "SG0105",
SgCode::ProjectServicesNotUp => "SG0106",
SgCode::SupervisorBusy => "SG0107",
SgCode::PreStartTimeout => "SG0108",
SgCode::DependencyUnavailable => "SG0109",
SgCode::RestartBreakerOpen => "SG0110",
SgCode::CommandStillRunning => "SG0111",
SgCode::TargetConfigMismatch => "SG0201",
SgCode::TargetNotFound => "SG0202",
SgCode::ConfigFileUnreadable => "SG0203",
SgCode::ConflictingSelectors => "SG0204",
SgCode::SupervisorNotResponding => "SG0205",
SgCode::SupervisorOffline => "SG0206",
SgCode::IncludeUnresolved => "SG0207",
SgCode::IncludeCycle => "SG0208",
SgCode::IncludeLimit => "SG0209",
SgCode::ManifestFieldInvalid => "SG0210",
SgCode::ManifestRejected => "SG0301",
SgCode::ReconcileIncomplete => "SG0302",
SgCode::SupervisorRecycleFailed => "SG0303",
SgCode::RestartTouchedNothing => "SG0304",
SgCode::PurgeSupervisorActive => "SG0401",
SgCode::PurgeIncomplete => "SG0402",
SgCode::PurgeProjectNotFound => "SG0403",
SgCode::PurgeTargetInvalid => "SG0404",
SgCode::UpgradeTargetInvalid => "SG0501",
SgCode::UpgradeIncompatible => "SG0502",
SgCode::UpgradeEnvironmentUnsafe => "SG0503",
SgCode::UpgradeHandoffFailed => "SG0504",
SgCode::UpgradeResumeFailed => "SG0505",
SgCode::MigrationRequired => "SG0601",
SgCode::MigrationSupervisorActive => "SG0602",
SgCode::MigrationAmbiguous => "SG0603",
SgCode::MigrationIncomplete => "SG0604",
SgCode::MigrationVerificationFailed => "SG0605",
SgCode::PurgeSupervisorShutdownTimeout => "SG0405",
SgCode::SystemModeNotSelected => "SG0701",
SgCode::RuntimeModeMismatch => "SG0702",
SgCode::SystemIntegrationBroken => "SG0703",
SgCode::SystemModeRequiresRoot => "SG0704",
SgCode::ManifestRequiresSystemMode => "SG0705",
SgCode::BootUnitRefused => "SG0706",
SgCode::ContainerInitUnsupported => "SG0711",
SgCode::ContainerInitPrereqMissing => "SG0712",
SgCode::ContainerInitShutdownIncomplete => "SG0713",
SgCode::ContainerInitUpgradeForbidden => "SG0714",
SgCode::SandboxKeyUnenforceable => "SG0721",
SgCode::SeccompFilterFailed => "SG0722",
SgCode::NoNewPrivsFailed => "SG0723",
SgCode::LandlockUnavailable => "SG0724",
SgCode::SeccompProfileUnknown => "SG0725",
SgCode::SeccompArchUnsupported => "SG0726",
SgCode::NamespaceUnshareFailed => "SG0727",
SgCode::ResourceLimitFailed => "SG0741",
SgCode::PriorityFailed => "SG0742",
SgCode::CpuAffinityFailed => "SG0743",
SgCode::SupplementaryGroupsFailed => "SG0744",
SgCode::PrimaryGidFailed => "SG0745",
SgCode::UidSwitchFailed => "SG0746",
SgCode::CapabilityRetentionFailed => "SG0747",
SgCode::CapabilityReductionIncomplete => "SG0748",
}
}
/// The docs URL for this code.
pub fn docs_url(self) -> String {
format!("{DOCS_BASE}#{}", self.as_str().to_lowercase())
}
/// Every code, so callers can enumerate or round-trip the taxonomy.
pub const ALL: [SgCode; 87] = [
SgCode::Catchall,
SgCode::CronStateRecoveryFailed,
SgCode::CronRegistrationConflict,
SgCode::FiniteUnitMisclassified,
SgCode::StaleProjectConfiguration,
SgCode::TargetScopeAmbiguous,
SgCode::SupervisorRestartConflict,
SgCode::UnitStartFailed,
SgCode::StatusStateInconsistent,
SgCode::LogSourceUnavailable,
SgCode::LogStreamDesynchronized,
SgCode::LogLimitExceeded,
SgCode::DaemonEnvironmentInvalid,
SgCode::ReleaseArtifactUnavailable,
SgCode::SupervisorStateDesynchronized,
SgCode::RollingDeploymentFailed,
SgCode::PruneBoundMissing,
SgCode::LogsTargetRequired,
SgCode::LogsSupervisorConflict,
SgCode::LooseServiceNotFound,
SgCode::HealthCheckUnreachable,
SgCode::HealthCheckTimeout,
SgCode::CronDirectControl,
SgCode::UnitImmediateExit,
SgCode::PreStartFailed,
SgCode::HealthUnmet,
SgCode::PortInUse,
SgCode::ProjectServicesNotUp,
SgCode::SupervisorBusy,
SgCode::PreStartTimeout,
SgCode::DependencyUnavailable,
SgCode::RestartBreakerOpen,
SgCode::CommandStillRunning,
SgCode::TargetConfigMismatch,
SgCode::TargetNotFound,
SgCode::ConfigFileUnreadable,
SgCode::ConflictingSelectors,
SgCode::SupervisorNotResponding,
SgCode::SupervisorOffline,
SgCode::IncludeUnresolved,
SgCode::IncludeCycle,
SgCode::IncludeLimit,
SgCode::ManifestFieldInvalid,
SgCode::ManifestRejected,
SgCode::ReconcileIncomplete,
SgCode::SupervisorRecycleFailed,
SgCode::RestartTouchedNothing,
SgCode::PurgeSupervisorActive,
SgCode::PurgeIncomplete,
SgCode::PurgeProjectNotFound,
SgCode::PurgeTargetInvalid,
SgCode::UpgradeTargetInvalid,
SgCode::UpgradeIncompatible,
SgCode::UpgradeEnvironmentUnsafe,
SgCode::UpgradeHandoffFailed,
SgCode::UpgradeResumeFailed,
SgCode::MigrationRequired,
SgCode::MigrationSupervisorActive,
SgCode::MigrationAmbiguous,
SgCode::MigrationIncomplete,
SgCode::MigrationVerificationFailed,
SgCode::PurgeSupervisorShutdownTimeout,
SgCode::SystemModeNotSelected,
SgCode::RuntimeModeMismatch,
SgCode::SystemIntegrationBroken,
SgCode::SystemModeRequiresRoot,
SgCode::ManifestRequiresSystemMode,
SgCode::BootUnitRefused,
SgCode::ContainerInitUnsupported,
SgCode::ContainerInitPrereqMissing,
SgCode::ContainerInitShutdownIncomplete,
SgCode::ContainerInitUpgradeForbidden,
SgCode::SandboxKeyUnenforceable,
SgCode::SeccompFilterFailed,
SgCode::NoNewPrivsFailed,
SgCode::LandlockUnavailable,
SgCode::SeccompProfileUnknown,
SgCode::SeccompArchUnsupported,
SgCode::NamespaceUnshareFailed,
SgCode::ResourceLimitFailed,
SgCode::PriorityFailed,
SgCode::CpuAffinityFailed,
SgCode::SupplementaryGroupsFailed,
SgCode::PrimaryGidFailed,
SgCode::UidSwitchFailed,
SgCode::CapabilityRetentionFailed,
SgCode::CapabilityReductionIncomplete,
];
}
impl fmt::Display for SgCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
/// The wire form does not resolve to a known code.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnknownSgCode(pub String);
impl fmt::Display for UnknownSgCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "unknown sysg code `{}`", self.0)
}
}
impl std::error::Error for UnknownSgCode {}
impl std::str::FromStr for SgCode {
type Err = UnknownSgCode;
fn from_str(code: &str) -> Result<Self, Self::Err> {
Self::ALL
.iter()
.copied()
.find(|c| c.as_str() == code)
.ok_or_else(|| UnknownSgCode(code.to_string()))
}
}
impl Serialize for SgCode {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(self.as_str())
}
}
impl<'de> Deserialize<'de> for SgCode {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let raw = String::deserialize(deserializer)?;
raw.parse().map_err(serde::de::Error::custom)
}
}
/// How severe a diagnostic is; controls the header color and label.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum Severity {
/// The operation failed.
Error,
/// The operation proceeded but something is off.
Warning,
/// Informational context.
Note,
}
impl Severity {
fn label(self) -> &'static str {
match self {
Severity::Error => "error",
Severity::Warning => "warning",
Severity::Note => "note",
}
}
fn color(self) -> &'static str {
match self {
Severity::Error => RED,
Severity::Warning => YELLOW,
Severity::Note => CYAN,
}
}
}
/// Where in the user's world the problem originates, e.g. a config file key.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Origin {
/// Path to the file, as the user knows it.
pub file: String,
/// 1-indexed line, when resolvable.
pub line: Option<usize>,
/// Dotted key path inside the file, e.g. `services.api.health_check`.
pub key: Option<String>,
}
/// A labeled block of captured facts, e.g. the service's last output.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Evidence {
/// Short label, e.g. `last output`.
pub label: String,
/// The captured lines, already trimmed to a reasonable count.
pub lines: Vec<String>,
}
/// An actionable next step.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum Help {
/// A command the user can run, with a short reason.
Command {
/// What running it shows or does, e.g. `view logs`.
label: String,
/// The exact command line.
cmd: String,
},
/// A documentation link.
Link {
/// The URL.
url: String,
},
}
/// A structured, renderable failure report.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Diagnostic {
/// Severity of the report.
pub severity: Severity,
/// Stable sysg error code.
pub code: SgCode,
/// One-line statement of what happened.
pub title: String,
/// Where the problem originates, when known.
pub origin: Option<Origin>,
/// Plain-sentence facts about what sysg observed.
pub notes: Vec<String>,
/// Captured output blocks.
pub evidence: Vec<Evidence>,
/// Next steps.
pub help: Vec<Help>,
}
impl Diagnostic {
/// Starts an error-severity diagnostic with the given code and title.
pub fn error(code: SgCode, title: impl Into<String>) -> Self {
Self {
severity: Severity::Error,
code,
title: title.into(),
origin: None,
notes: Vec::new(),
evidence: Vec::new(),
help: Vec::new(),
}
}
/// Starts a warning-severity diagnostic — a degraded but non-fatal reading,
/// such as a status shown off disk while the supervisor is offline.
pub fn warn(code: SgCode, title: impl Into<String>) -> Self {
Self {
severity: Severity::Warning,
code,
title: title.into(),
origin: None,
notes: Vec::new(),
evidence: Vec::new(),
help: Vec::new(),
}
}
/// The stable `SG####` string for this diagnostic's code.
pub fn code_str(&self) -> &'static str {
self.code.as_str()
}
/// Attaches the originating file/key.
pub fn origin(
mut self,
file: impl Into<String>,
line: Option<usize>,
key: Option<String>,
) -> Self {
self.origin = Some(Origin {
file: file.into(),
line,
key,
});
self
}
/// Adds a plain-sentence observation.
pub fn note(mut self, note: impl Into<String>) -> Self {
self.notes.push(note.into());
self
}
/// Adds a labeled block of captured lines.
pub fn evidence(mut self, label: impl Into<String>, lines: Vec<String>) -> Self {
if !lines.is_empty() {
self.evidence.push(Evidence {
label: label.into(),
lines,
});
}
self
}
/// Adds a runnable next step.
pub fn help_cmd(mut self, label: impl Into<String>, cmd: impl Into<String>) -> Self {
self.help.push(Help::Command {
label: label.into(),
cmd: cmd.into(),
});
self
}
/// Adds the documentation link for this diagnostic's code.
pub fn help_docs(mut self) -> Self {
self.help.push(Help::Link {
url: self.code.docs_url(),
});
self
}
/// Renders with ANSI colors when appropriate for stderr.
pub fn render_for_terminal(&self) -> String {
let color =
std::io::stderr().is_terminal() && std::env::var_os("NO_COLOR").is_none();
self.render(color)
}
/// Renders the diagnostic; `color` toggles ANSI escapes.
pub fn render(&self, color: bool) -> String {
let paint = |code: &'static str| if color { code } else { "" };
let reset = paint(RESET);
let mut out = String::new();
out.push_str(&format!(
"{}{}[{}]{}{}: {}{}\n",
paint(self.severity.color()),
self.severity.label(),
self.code.as_str(),
reset,
paint(BOLD),
self.title,
reset,
));
if let Some(origin) = &self.origin {
let mut place = origin.file.clone();
if let Some(line) = origin.line {
place.push_str(&format!(":{line}"));
}
if let Some(key) = &origin.key {
place.push_str(&format!(" ({key})"));
}
out.push_str(&format!(" {}-->{} {}\n", paint(CYAN), reset, place));
}
if !self.notes.is_empty() {
out.push('\n');
for note in &self.notes {
out.push_str(&format!(" {note}\n"));
}
}
for block in &self.evidence {
out.push('\n');
out.push_str(&format!(" {}{}:{}\n", paint(DIM), block.label, reset));
for line in &block.lines {
out.push_str(&format!(" {}\u{2502}{} {}\n", paint(DIM), reset, line));
}
}
if !self.help.is_empty() {
out.push('\n');
out.push_str(&format!(" {}help:{}\n", paint(GREEN), reset));
let width = self
.help
.iter()
.map(|h| match h {
Help::Command { label, .. } => label.len(),
Help::Link { .. } => 4,
})
.max()
.unwrap_or(0);
for help in &self.help {
match help {
Help::Command { label, cmd } => {
out.push_str(&format!(
" {label:<width$} {}{}{}\n",
paint(BOLD),
cmd,
reset,
));
}
Help::Link { url } => {
out.push_str(&format!(
" {:<width$} {}{}{}\n",
"docs",
paint(UNDERLINE),
url,
reset,
));
}
}
}
}
out
}
}
impl fmt::Display for Diagnostic {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.render(false))
}
}
#[cfg(test)]
mod tests {
use super::*;
fn sample() -> Diagnostic {
Diagnostic::error(
SgCode::HealthUnmet,
"service `api` failed to become healthy",
)
.origin(
"sysg.yaml",
Some(31),
Some("services.api.health_check".into()),
)
.note("5 health checks failed over 45s")
.evidence(
"last output",
vec!["password authentication failed".to_string()],
)
.help_cmd("view logs", "sysg logs -s api")
.help_docs()
}
#[test]
fn plain_render_has_code_title_evidence_and_help() {
let text = sample().render(false);
assert!(text.contains("error[SG0104]"));
assert!(text.contains("failed to become healthy"));
assert!(text.contains("--> sysg.yaml:31 (services.api.health_check)"));
assert!(text.contains("password authentication failed"));
assert!(text.contains("sysg logs -s api"));
assert!(text.contains(&format!("{DOCS_BASE}#sg0104")));
assert!(!text.contains('\x1b'));
}
#[test]
fn colored_render_uses_ansi_and_survives_roundtrip() {
let text = sample().render(true);
assert!(text.contains(RED));
let json = serde_json::to_string(&sample()).unwrap();
let back: Diagnostic = serde_json::from_str(&json).unwrap();
assert_eq!(back.code, SgCode::HealthUnmet);
assert_eq!(back.render(false), sample().render(false));
}
#[test]
fn code_strings_are_unique_and_round_trip() {
let mut seen = std::collections::HashSet::new();
for code in SgCode::ALL {
assert!(
seen.insert(code.as_str()),
"duplicate code {}",
code.as_str()
);
assert_eq!(code.as_str().parse(), Ok(code));
}
}
#[test]
fn every_code_is_listed_in_all() {
// `FromStr` and `Deserialize` both search `ALL`, so a variant missing
// from it is unparseable even though `as_str` yields its code. Read the
// `as_str` arms straight from the source so a new variant that is never
// added to `ALL` fails here instead of at a caller.
let src = include_str!("diag.rs");
let declared: Vec<&str> = src
.lines()
.filter_map(|line| line.split_once("=> \"SG"))
.filter_map(|(_, rest)| rest.split_once('"'))
.map(|(code, _)| code)
.collect();
assert_eq!(declared.len(), SgCode::ALL.len());
for code in declared {
let code = format!("SG{code}");
assert!(
code.parse::<SgCode>().is_ok(),
"{code} is not reachable through SgCode::ALL"
);
}
}
#[test]
fn unknown_code_fails_to_deserialize() {
assert!(serde_json::from_str::<SgCode>("\"SG9999\"").is_err());
}
}