isothrum-runner 1.0.1

The Isothrum runner: executes the run manifest Isoloom writes next to a target's files (lifecycle, state and locks, drivers, checks, events).
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
//! Why an operation failed: one enum for the crate, each variant with a stable [`ErrorCode`].
//! Messages are plain and technical; the embedder maps codes to its own wording.

use std::path::PathBuf;

use serde::{Deserialize, Serialize};

/// The stable code of a failure, the same in the Rust API and the event stream (`error.code`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ErrorCode {
    /// The manifest isn't valid JSON or breaks the contract.
    ManifestInvalid,
    /// The manifest is another version of the contract.
    ManifestVersion,
    /// The manifest needs something this runner doesn't do yet (a driver, a delivery, a condition).
    Unsupported,
    /// A file or folder couldn't be read or written.
    Io,
    /// Another process runs an operation on this run.
    Locked,
    /// A tool a step runs isn't installed.
    ToolMissing,
    /// A step's tool ran and failed.
    ToolFailed,
    /// A tool answers at a version older than the run needs.
    ToolTooOld,
    /// A step ran out of time and was stopped, with what it started.
    Timeout,
    /// The run is already up.
    AlreadyRunning,
    /// The run is recorded on another place (server or account) than the one asked for.
    RunningElsewhere,
    /// A host port the run publishes is taken.
    PortInUse,
    /// The manifest has no park steps for that mode.
    NotParkable,
    /// Nothing of the run is left to resume.
    NothingToResume,
    /// The run isn't up.
    NotRunning,
    /// A ready condition didn't hold.
    NotReady,
    /// A required secret or input has no value.
    SecretMissing,
    /// A param is unknown, missing or holds a value it doesn't allow.
    ParamInvalid,
    /// A run name that can't name a run.
    RunName,
    /// The run's Vagrant provider is missing, unknown, not on this host, refused by the run, or
    /// lacks its plugin.
    ProviderRefused,
    /// The elevation Hyper-V's commands need couldn't be had (the permission prompt declined).
    ElevationDeclined,
    /// A machine the run doesn't have.
    MachineUnknown,
    /// Every slot of the place is held by another run.
    SlotsFull,
    /// A deployment can't be taken over as a run.
    AdoptRefused,
    /// A machine a step goes to over SSH never answered.
    Unreachable,
    /// The run's seal failed: it is up, but not sealed, so not ready.
    NotSealed,
}

impl ErrorCode {
    /// The code as written in JSON (`port_in_use`).
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            ErrorCode::ManifestInvalid => "manifest_invalid",
            ErrorCode::ManifestVersion => "manifest_version",
            ErrorCode::Unsupported => "unsupported",
            ErrorCode::Io => "io",
            ErrorCode::Locked => "locked",
            ErrorCode::ToolMissing => "tool_missing",
            ErrorCode::ToolFailed => "tool_failed",
            ErrorCode::ToolTooOld => "tool_too_old",
            ErrorCode::Timeout => "timeout",
            ErrorCode::AlreadyRunning => "already_running",
            ErrorCode::RunningElsewhere => "running_elsewhere",
            ErrorCode::PortInUse => "port_in_use",
            ErrorCode::NotParkable => "not_parkable",
            ErrorCode::NothingToResume => "nothing_to_resume",
            ErrorCode::NotRunning => "not_running",
            ErrorCode::NotReady => "not_ready",
            ErrorCode::SecretMissing => "secret_missing",
            ErrorCode::ParamInvalid => "param_invalid",
            ErrorCode::RunName => "run_name",
            ErrorCode::ProviderRefused => "provider_refused",
            ErrorCode::ElevationDeclined => "elevation_declined",
            ErrorCode::MachineUnknown => "machine_unknown",
            ErrorCode::SlotsFull => "slots_full",
            ErrorCode::AdoptRefused => "adopt_refused",
            ErrorCode::Unreachable => "unreachable",
            ErrorCode::NotSealed => "not_sealed",
        }
    }
}

/// The runner's `Result`: its error is a [`Error`] unless said otherwise.
pub type Result<T, E = Error> = std::result::Result<T, E>;

/// Why an operation of the runner failed.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    /// The manifest was refused (its own error names the field and the fix).
    #[error("{}: {source}", path.display())]
    Manifest {
        /// The manifest's file.
        path: PathBuf,
        /// Why, with Isoloom's stable code (`source.code()`).
        source: isoloom_manifest::Error,
    },
    /// The manifest needs something this runner doesn't do yet.
    #[error("{what} isn't supported by this runner yet")]
    Unsupported {
        /// What, as the manifest names it (`driver vagrant`, `delivery tf_var`).
        what: String,
    },
    /// A file or folder couldn't be read or written.
    #[error("{} couldn't be {action}: {source}", path.display())]
    Io {
        /// The file or folder.
        path: PathBuf,
        /// What was done to it (`read`, `written`, `created`, `locked`).
        action: &'static str,
        /// The OS's reason.
        source: std::io::Error,
    },
    /// Another process holds the run's lock.
    #[error("run `{run}` is busy: another process runs an operation on it")]
    Locked {
        /// The run.
        run: String,
    },
    /// A step's tool isn't on PATH.
    #[error("step `{step}`: `{tool}` isn't installed or isn't on PATH")]
    ToolMissing {
        /// The step.
        step: String,
        /// The tool.
        tool: String,
    },
    /// A tool answers at a version older than the manifest's `min_version` for it.
    #[error("`{tool}` is version {found}; this run needs {required} or later")]
    ToolTooOld {
        /// The tool.
        tool: String,
        /// The version it answered with.
        found: String,
        /// The oldest version the run takes.
        required: String,
    },
    /// A step's tool ran and failed.
    #[error("step `{step}` failed: {reason}")]
    ToolFailed {
        /// The step.
        step: String,
        /// Its last error lines, or its exit status (secrets masked).
        reason: String,
    },
    /// A step ran out of time.
    #[error("step `{step}` timed out after {after_s}s and was stopped")]
    Timeout {
        /// The step.
        step: String,
        /// Its limit, in seconds.
        after_s: u64,
    },
    /// The run is already up.
    #[error("run `{run}` is already running")]
    AlreadyRunning {
        /// The run.
        run: String,
    },
    /// The run is recorded somewhere else.
    #[error("run `{run}` is recorded on `{recorded}`, not `{asked}`")]
    RunningElsewhere {
        /// The run.
        run: String,
        /// Where its record says it is.
        recorded: String,
        /// Where this operation was asked to run.
        asked: String,
    },
    /// A host port the run publishes is taken.
    #[error("host port {port}/{protocol} is in use")]
    PortInUse {
        /// The port.
        port: u16,
        /// `tcp` or `udp`.
        protocol: &'static str,
    },
    /// No park steps for that mode.
    #[error("run `{run}` can't be parked ({mode}): its manifest has no steps for it")]
    NotParkable {
        /// The run.
        run: String,
        /// The mode asked for.
        mode: &'static str,
    },
    /// Nothing left to resume.
    #[error("run `{run}` has nothing left to resume: start it again")]
    NothingToResume {
        /// The run.
        run: String,
    },
    /// The run isn't up.
    #[error("run `{run}` isn't running")]
    NotRunning {
        /// The run.
        run: String,
    },
    /// A ready condition didn't hold.
    #[error("not ready: {condition}: {detail}")]
    NotReady {
        /// The condition (`step_ok up`, `tcp 127.0.0.1:8080`).
        condition: String,
        /// Why.
        detail: String,
    },
    /// A required secret or input has no value.
    #[error("secret `{name}` is required and has no value")]
    SecretMissing {
        /// The slot.
        name: String,
    },
    /// A param that can't be used as given.
    #[error("param `{name}`: {reason}")]
    Param {
        /// The param.
        name: String,
        /// Why.
        reason: String,
    },
    /// A placeholder with no value at run time.
    #[error("{at}: `${{{placeholder}}}` has no value in this operation")]
    Unbound {
        /// Where (`lifecycle.up.up`).
        at: String,
        /// The placeholder.
        placeholder: String,
    },
    /// A machine the run doesn't have (to provision).
    #[error("run `{run}` has no machine `{machine}`")]
    MachineUnknown {
        /// The run.
        run: String,
        /// The machine asked for.
        machine: String,
    },
    /// The elevation the run's commands need couldn't be had.
    #[error("elevation: {reason}")]
    Elevation {
        /// Why (the permission prompt declined, the elevated session ended).
        reason: String,
    },
    /// The run's Vagrant provider can't run it.
    #[error("provider `{provider}`: {reason}")]
    Provider {
        /// The provider asked for (empty when none was).
        provider: String,
        /// Why it can't run the run, and what to do.
        reason: String,
    },
    /// Every slot of the run's place is held by another run.
    #[error("no slot is free on `{place}`: {held} runs hold one; stop one first")]
    SlotsFull {
        /// The place (the embedder's label for it, or `this host`).
        place: String,
        /// How many runs hold a slot there.
        held: usize,
    },
    /// A machine a step goes to over SSH never answered within the step's `wait_s`.
    #[error("step `{step}`: {login} didn't answer over SSH within {after_s}s: {reason}")]
    Unreachable {
        /// The step.
        step: String,
        /// The login it tried (`user@host`).
        login: String,
        /// How long it tried, in seconds.
        after_s: u64,
        /// ssh's last word.
        reason: String,
    },
    /// The run's seal failed: it is up, unsealed, and never reported ready.
    #[error("run `{run}` couldn't be sealed, so it isn't ready (stop it to remove it): {reason}")]
    Unsealed {
        /// The run.
        run: String,
        /// Why the seal failed.
        reason: String,
    },
    /// A deployment that can't be taken over as a run.
    #[error("run `{run}` can't take the deployment over: {reason}")]
    Adopt {
        /// The run it would have become.
        run: String,
        /// Why.
        reason: String,
    },
    /// A run name that can't name a run.
    #[error("`{value}` can't name a run: use 1 to 63 lowercase letters, digits, `-` or `_`, starting with a letter or digit")]
    RunName {
        /// The name as given.
        value: String,
    },
}

impl Error {
    /// The failure's stable code.
    #[must_use]
    pub fn code(&self) -> ErrorCode {
        match self {
            Error::Manifest { source, .. } if source.code() == "version" => ErrorCode::ManifestVersion,
            Error::Manifest { .. } => ErrorCode::ManifestInvalid,
            Error::Unsupported { .. } | Error::Unbound { .. } => ErrorCode::Unsupported,
            Error::Io { .. } => ErrorCode::Io,
            Error::Locked { .. } => ErrorCode::Locked,
            Error::ToolMissing { .. } => ErrorCode::ToolMissing,
            Error::ToolTooOld { .. } => ErrorCode::ToolTooOld,
            Error::ToolFailed { .. } => ErrorCode::ToolFailed,
            Error::Timeout { .. } => ErrorCode::Timeout,
            Error::AlreadyRunning { .. } => ErrorCode::AlreadyRunning,
            Error::RunningElsewhere { .. } => ErrorCode::RunningElsewhere,
            Error::PortInUse { .. } => ErrorCode::PortInUse,
            Error::NotParkable { .. } => ErrorCode::NotParkable,
            Error::NothingToResume { .. } => ErrorCode::NothingToResume,
            Error::NotRunning { .. } => ErrorCode::NotRunning,
            Error::NotReady { .. } => ErrorCode::NotReady,
            Error::SecretMissing { .. } => ErrorCode::SecretMissing,
            Error::Param { .. } => ErrorCode::ParamInvalid,
            Error::RunName { .. } => ErrorCode::RunName,
            Error::Provider { .. } => ErrorCode::ProviderRefused,
            Error::Elevation { .. } => ErrorCode::ElevationDeclined,
            Error::MachineUnknown { .. } => ErrorCode::MachineUnknown,
            Error::SlotsFull { .. } => ErrorCode::SlotsFull,
            Error::Adopt { .. } => ErrorCode::AdoptRefused,
            Error::Unreachable { .. } => ErrorCode::Unreachable,
            Error::Unsealed { .. } => ErrorCode::NotSealed,
        }
    }

    /// An I/O failure on `path`.
    pub(crate) fn io(path: impl Into<PathBuf>, action: &'static str) -> impl FnOnce(std::io::Error) -> Error {
        let path = path.into();
        move |source| Error::Io { path, action, source }
    }
}

impl std::fmt::Display for ErrorCode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Every [`ErrorCode`], in declaration order. The match in [`all_lists_every_code_once`] fails
    /// to compile if a variant is added or removed without updating this list, so the exhaustive
    /// tests below can't silently cover only some codes.
    const ALL: &[ErrorCode] = &[
        ErrorCode::ManifestInvalid,
        ErrorCode::ManifestVersion,
        ErrorCode::Unsupported,
        ErrorCode::Io,
        ErrorCode::Locked,
        ErrorCode::ToolMissing,
        ErrorCode::ToolFailed,
        ErrorCode::ToolTooOld,
        ErrorCode::Timeout,
        ErrorCode::AlreadyRunning,
        ErrorCode::RunningElsewhere,
        ErrorCode::PortInUse,
        ErrorCode::NotParkable,
        ErrorCode::NothingToResume,
        ErrorCode::NotRunning,
        ErrorCode::NotReady,
        ErrorCode::SecretMissing,
        ErrorCode::ParamInvalid,
        ErrorCode::RunName,
        ErrorCode::ProviderRefused,
        ErrorCode::ElevationDeclined,
        ErrorCode::MachineUnknown,
        ErrorCode::SlotsFull,
        ErrorCode::AdoptRefused,
        ErrorCode::Unreachable,
        ErrorCode::NotSealed,
    ];

    #[test]
    fn all_lists_every_code_once() {
        // Exhaustiveness guard: this match fails to compile if a variant is added or removed, a
        // reminder to update ALL above. It is a no-op at run time.
        for &code in ALL {
            match code {
                ErrorCode::ManifestInvalid
                | ErrorCode::ManifestVersion
                | ErrorCode::Unsupported
                | ErrorCode::Io
                | ErrorCode::Locked
                | ErrorCode::ToolMissing
                | ErrorCode::ToolFailed
                | ErrorCode::ToolTooOld
                | ErrorCode::Timeout
                | ErrorCode::AlreadyRunning
                | ErrorCode::RunningElsewhere
                | ErrorCode::PortInUse
                | ErrorCode::NotParkable
                | ErrorCode::NothingToResume
                | ErrorCode::NotRunning
                | ErrorCode::NotReady
                | ErrorCode::SecretMissing
                | ErrorCode::ParamInvalid
                | ErrorCode::RunName
                | ErrorCode::ProviderRefused
                | ErrorCode::ElevationDeclined
                | ErrorCode::MachineUnknown
                | ErrorCode::SlotsFull
                | ErrorCode::AdoptRefused
                | ErrorCode::Unreachable
                | ErrorCode::NotSealed => {}
            }
        }
        let codes: Vec<&str> = ALL.iter().map(|c| c.as_str()).collect();
        let mut unique = codes.clone();
        unique.sort_unstable();
        unique.dedup();
        assert_eq!(unique.len(), codes.len(), "two variants share a code string: {codes:?}");
    }

    #[test]
    fn every_code_round_trips_through_json_as_its_written_form() {
        for &code in ALL {
            let json = serde_json::to_value(code).unwrap();
            assert_eq!(json, serde_json::json!(code.as_str()), "as_str() disagrees with serde for {code:?}");
            let back: ErrorCode = serde_json::from_value(json).unwrap();
            assert_eq!(back, code, "{code:?} didn't read back as itself");
        }
    }

    #[test]
    fn another_manifest_version_has_its_own_code() {
        let err = isoloom_manifest::parse(r#"{"manifest_version": 1}"#).unwrap_err();
        let err = Error::Manifest {
            path: "run.json".into(),
            source: err,
        };
        assert_eq!(err.code(), ErrorCode::ManifestVersion);
        assert!(err.to_string().starts_with("run.json: manifest_version 1"), "{err}");
    }
}