processkit 3.3.3

Async child-process management for tokio: whole-tree kill-on-drop (no orphans), plus streaming, pipelines, timeouts, and supervision
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
use std::collections::HashSet;
use std::fmt::{self, Write as _};
use std::path::PathBuf;

use crate::{
    ErrorKind, LimitKind, LimitReason, LimitVerdict, LineTerminator, Mechanism, Outcome,
    OutputLine, OutputStream, OverflowMode, ParentDeathCleanup, Priority, ProcessEvent,
    RestartPolicy, RlimitResource, Signal, SoftSignal, SoftStopScope, StdioMode, StopReason,
    SupervisionEvent,
};

struct Variant {
    rust_name: &'static str,
    identifier: &'static str,
}

struct EnumSpec {
    path: &'static str,
    class: &'static str,
    variants: Vec<Variant>,
}

fn configurable<T, N, P>(
    path: &'static str,
    values: &[(&'static str, T)],
    name: N,
    from_name: P,
) -> EnumSpec
where
    T: Copy + fmt::Debug + Eq,
    N: Fn(T) -> &'static str,
    P: Fn(&str) -> Option<T>,
{
    let variants = values
        .iter()
        .map(|(rust_name, value)| {
            let identifier = name(*value);
            assert_eq!(
                from_name(identifier),
                Some(*value),
                "{path}::{rust_name} does not round-trip through from_name"
            );
            Variant {
                rust_name,
                identifier,
            }
        })
        .collect();
    EnumSpec {
        path,
        class: "configurable",
        variants,
    }
}

fn configurable_optional<T, N, P>(
    path: &'static str,
    values: &[(&'static str, T)],
    name: N,
    from_name: P,
) -> EnumSpec
where
    T: Copy + fmt::Debug + Eq,
    N: Fn(T) -> Option<&'static str>,
    P: Fn(&str) -> Option<T>,
{
    configurable(
        path,
        values,
        |value| name(value).expect("curated manifest variants must have names"),
        from_name,
    )
}

fn report_only<T, N>(path: &'static str, values: &[(&'static str, T)], name: N) -> EnumSpec
where
    N: Fn(&T) -> &'static str,
{
    EnumSpec {
        path,
        class: "report_only",
        variants: values
            .iter()
            .map(|(rust_name, value)| Variant {
                rust_name,
                identifier: name(value),
            })
            .collect(),
    }
}

/// Curate one dictionary enum's variant list **with a compile-time completeness
/// guard**.
///
/// Expands a single list into two things: the `(rust_name, value)` pairs the
/// generator serializes, and a private `match` over the same enum carrying one arm
/// per listed variant. Inside the defining crate that `match` is exhaustive
/// (`#[non_exhaustive]` binds only downstream crates), so adding a variant to a
/// dictionary enum without listing it here is a **compile error** — the list can no
/// longer drift silently behind the type it claims to describe.
///
/// That drift is exactly what shipped `Mechanism::ProcessReaper` against a
/// three-mechanism `spec/identifiers.json`: the generator carried a hand-written
/// array rather than a `match`, so the new variant compiled fine, the generator and
/// the committed baseline went stale together, and `identifiers_manifest_matches`
/// stayed green comparing two equally stale artifacts. A hand-written array cannot
/// fail closed; this one does.
///
/// A unit variant is written bare — the manifest value *is* the variant. One
/// carrying data is written `Variant = <expr>` with a representative value, since
/// the manifest names variants and cannot invent payloads. A variant that must stay
/// **out** of the dictionary is listed under `omitted:`: it still has to be
/// acknowledged here, but contributes no manifest entry.
macro_rules! curated {
    (@value $ty:ident, $variant:ident) => { $ty::$variant };
    (@value $ty:ident, $variant:ident, $value:expr) => { $value };
    (
        $ty:ident,
        [ $( $variant:ident $( = $value:expr )? ),+ $(,)? ]
        $(, omitted: [ $( $omitted:ident ),+ $(,)? ] )?
    ) => {{
        #[allow(dead_code)]
        fn completeness(value: &$ty) {
            // Exhaustive on purpose (no `_` arm): a new variant fails to compile
            // here until it is either curated into the manifest or explicitly
            // omitted above.
            match value {
                $( $ty::$variant { .. } => (), )+
                $( $( $ty::$omitted { .. } => (), )+ )?
            }
        }
        [ $( (stringify!($variant), curated!(@value $ty, $variant $(, $value)?)) ),+ ]
    }};
}

fn dictionary() -> Vec<EnumSpec> {
    vec![
        configurable(
            "processkit::Mechanism",
            &curated!(
                Mechanism,
                [JobObject, CgroupV2, ProcessGroup, ProcessReaper]
            ),
            |value| value.name(),
            Mechanism::from_name,
        ),
        configurable(
            "processkit::ParentDeathCleanup",
            &curated!(
                ParentDeathCleanup,
                [WholeTree, DirectChildOnly, Unsupported]
            ),
            |value| value.name(),
            ParentDeathCleanup::from_name,
        ),
        configurable(
            "processkit::SoftStopScope",
            &curated!(SoftStopScope, [WholeTree, OptInMembers, Unsupported]),
            |value| value.name(),
            SoftStopScope::from_name,
        ),
        configurable(
            "processkit::StopReason",
            &curated!(
                StopReason,
                [
                    Predicate,
                    PolicySatisfied,
                    GaveUp,
                    RestartsExhausted,
                    Unhealthy,
                    Stopped
                ]
            ),
            |value| value.name(),
            StopReason::from_name,
        ),
        configurable(
            "processkit::LimitKind",
            &curated!(LimitKind, [Memory, Processes, Cpu]),
            |value| value.name(),
            LimitKind::from_name,
        ),
        configurable(
            "processkit::LimitReason",
            &curated!(LimitReason, [Invalid, Unsupported, Unenforceable]),
            |value| value.name(),
            LimitReason::from_name,
        ),
        configurable(
            "processkit::LimitVerdict",
            &curated!(LimitVerdict, [Tripped, NotTripped, Unknown]),
            |value| value.name(),
            LimitVerdict::from_name,
        ),
        configurable(
            "processkit::StdioMode",
            &curated!(StdioMode, [Piped, Inherit, Null]),
            |value| value.name(),
            StdioMode::from_name,
        ),
        configurable(
            "processkit::LineTerminator",
            &curated!(LineTerminator, [Newline, CarriageReturn]),
            |value| value.name(),
            LineTerminator::from_name,
        ),
        configurable(
            "processkit::OverflowMode",
            &curated!(OverflowMode, [DropOldest, DropNewest, Error]),
            |value| value.name(),
            OverflowMode::from_name,
        ),
        configurable(
            "processkit::OutputStream",
            &curated!(OutputStream, [Stdout, Stderr]),
            |value| value.name(),
            OutputStream::from_name,
        ),
        configurable(
            "processkit::Priority",
            &curated!(Priority, [Idle, BelowNormal, Normal, AboveNormal, High]),
            |value| value.name(),
            Priority::from_name,
        ),
        configurable(
            "processkit::RestartPolicy",
            &curated!(RestartPolicy, [Always, OnCrash, Never]),
            |value| value.name(),
            RestartPolicy::from_name,
        ),
        configurable_optional(
            "processkit::Signal",
            // `Other(n)` is the raw-number escape hatch: `name()` answers `None`
            // for it by design (render the `i32`), so it carries no stable
            // identifier and stays out of the dictionary — deliberately, not by
            // omission.
            &curated!(
                Signal,
                [Term, Kill, Int, Hup, Quit, Usr1, Usr2],
                omitted: [Other]
            ),
            |value| value.name(),
            Signal::from_name,
        ),
        configurable(
            "processkit::RlimitResource",
            &curated!(RlimitResource, [Cpu, Core, Data, FileSize, NoFile, Stack]),
            RlimitResource::name,
            RlimitResource::from_name,
        ),
        report_only(
            "processkit::Outcome",
            &curated!(
                Outcome,
                [
                    Exited = Outcome::Exited(0),
                    Signalled = Outcome::Signalled(None),
                    TimedOut,
                    InactivityTimedOut
                ]
            ),
            |value| value.name(),
        ),
        report_only(
            "processkit::ErrorKind",
            &curated!(
                ErrorKind,
                [
                    NotFound,
                    Spawn,
                    PermissionDenied,
                    ResourceLimit,
                    Unsupported,
                    Timeout,
                    Cancelled,
                    Predicate,
                    Exit,
                    Signalled,
                    Other
                ]
            ),
            |value| value.name(),
        ),
        report_only(
            "processkit::ProcessEvent",
            &curated!(
                ProcessEvent,
                [
                    Started = ProcessEvent::Started { pid: None },
                    Stdout = ProcessEvent::Stdout(OutputLine::for_test("")),
                    Stderr = ProcessEvent::Stderr(OutputLine::for_test("")),
                    Exited = ProcessEvent::Exited(Outcome::Exited(0))
                ]
            ),
            ProcessEvent::name,
        ),
        report_only(
            "processkit::SupervisionEvent",
            &curated!(
                SupervisionEvent,
                [
                    IncarnationStarted = SupervisionEvent::IncarnationStarted {
                        attempt: 1,
                        pid: None,
                    },
                    IncarnationFinished = SupervisionEvent::IncarnationFinished {
                        attempt: 1,
                        outcome: Outcome::Exited(0),
                        duration: std::time::Duration::from_secs(0),
                        success: true,
                    },
                    IncarnationFailed = SupervisionEvent::IncarnationFailed {
                        attempt: 1,
                        error: ErrorKind::Spawn,
                    },
                    RestartScheduled = SupervisionEvent::RestartScheduled {
                        restart: 1,
                        delay: std::time::Duration::from_secs(0),
                    },
                    StormPaused = SupervisionEvent::StormPaused {
                        pause: 1,
                        delay: std::time::Duration::from_secs(0),
                    },
                    HealthCheckFailed = SupervisionEvent::HealthCheckFailed {
                        attempt: 1,
                        terminal: false,
                    },
                    GaveUp = SupervisionEvent::GaveUp { attempt: 1 },
                    Stopped = SupervisionEvent::Stopped {
                        reason: StopReason::Stopped,
                    },
                    SupervisionFailed = SupervisionEvent::SupervisionFailed {
                        error: ErrorKind::Other,
                    },
                    Lagged = SupervisionEvent::Lagged { skipped: 1 }
                ]
            ),
            |value| value.name(),
        ),
        report_only(
            "processkit::SoftSignal",
            &curated!(
                SoftSignal,
                [
                    Sent = SoftSignal::Sent(Signal::Term),
                    Unsupported,
                    Failed = SoftSignal::Failed(Signal::Term)
                ]
            ),
            |value| value.name(),
        ),
    ]
}

fn push_json_string(output: &mut String, value: &str) {
    output.push('"');
    for character in value.chars() {
        match character {
            '"' => output.push_str("\\\""),
            '\\' => output.push_str("\\\\"),
            '\n' => output.push_str("\\n"),
            '\r' => output.push_str("\\r"),
            '\t' => output.push_str("\\t"),
            character if character.is_control() => {
                write!(output, "\\u{:04x}", u32::from(character)).expect("writing to String")
            }
            character => output.push(character),
        }
    }
    output.push('"');
}

fn generated_manifest() -> String {
    let enums = dictionary();
    let mut paths = HashSet::new();
    let mut output = String::from(
        "{\n  \"schema_version\": 1,\n  \"maintenance\": \"Canonical stable-identifier dictionary; update docs/errors.md together with this manifest.\",\n  \"enums\": [\n",
    );

    for (enum_index, enum_spec) in enums.iter().enumerate() {
        assert!(paths.insert(enum_spec.path), "duplicate enum path");
        let mut identifiers = HashSet::new();
        output.push_str("    {\n      \"path\": ");
        push_json_string(&mut output, enum_spec.path);
        output.push_str(",\n      \"class\": ");
        push_json_string(&mut output, enum_spec.class);
        output.push_str(",\n      \"variants\": [\n");

        for (variant_index, variant) in enum_spec.variants.iter().enumerate() {
            assert!(
                identifiers.insert(variant.identifier),
                "{} has duplicate identifier {:?}",
                enum_spec.path,
                variant.identifier
            );
            output.push_str("        { \"variant\": ");
            push_json_string(&mut output, variant.rust_name);
            output.push_str(", \"identifier\": ");
            push_json_string(&mut output, variant.identifier);
            output.push_str(" }");
            if variant_index + 1 != enum_spec.variants.len() {
                output.push(',');
            }
            output.push('\n');
        }

        output.push_str("      ]\n    }");
        if enum_index + 1 != enums.len() {
            output.push(',');
        }
        output.push('\n');
    }
    output.push_str("  ]\n}\n");
    output
}

fn manifest_path() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("spec/identifiers.json")
}

#[test]
fn identifiers_manifest_matches() {
    let expected = std::fs::read(manifest_path()).expect("read spec/identifiers.json");
    let actual = generated_manifest();
    assert!(
        expected == actual.as_bytes(),
        "spec/identifiers.json differs byte-for-byte from the live dictionary; run `just identifiers-diff`"
    );
}

#[test]
#[ignore = "used by the identifiers-diff recipe"]
fn write_identifiers_manifest() {
    let Some(output) = std::env::var_os("PROCESSKIT_IDENTIFIERS_OUTPUT").map(PathBuf::from) else {
        return;
    };
    std::fs::write(output, generated_manifest()).expect("write generated identifier manifest");
}