arcbox-cli 0.9.0

Command-line interface for ArcBox
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
//! User-facing CLI error context.

use std::fmt;

use anyhow::Error;
use connectrpc::{ConnectError, ErrorCode};

#[derive(Debug)]
struct ActionableError {
    message: String,
    source: ConnectError,
}

impl fmt::Display for ActionableError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(&self.message)
    }
}

impl std::error::Error for ActionableError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        Some(&self.source)
    }
}

pub fn machine_request(error: ConnectError, name: &str, operation: &str) -> Error {
    let message = match error.code {
        ErrorCode::NotFound => {
            format!("Machine '{name}' was not found. List machines with `abctl machine list`.")
        }
        ErrorCode::FailedPrecondition => format!(
            "Machine '{name}' must be running for {operation}. Start it with \
             `abctl machine start {name}`."
        ),
        ErrorCode::Unavailable => format!(
            "Machine '{name}' is unavailable during {operation}. Retry the command; if the \
             problem persists, check `abctl daemon status`."
        ),
        _ => format!(
            "Could not perform {operation} for machine '{name}'. Re-run with --debug for details."
        ),
    };
    actionable(message, error)
}

pub fn machine_operation(error: ConnectError, name: &str, action: &str) -> Error {
    let message = match error.code {
        ErrorCode::NotFound => {
            format!("Machine '{name}' was not found. List machines with `abctl machine list`.")
        }
        ErrorCode::FailedPrecondition => format!(
            "Machine '{name}' is not in a valid state for this operation. Inspect it with \
             `abctl machine inspect {name}`."
        ),
        ErrorCode::Unavailable => format!(
            "Machine '{name}' is unavailable. Retry the command; if the problem persists, \
             check `abctl daemon status`."
        ),
        _ => format!("Could not {action} machine '{name}'. Re-run with --debug for details."),
    };
    actionable(message, error)
}

/// Clone, export, import, resize and the default machine: the daemon's
/// message is the explanation — which image an archive needs, why a size
/// is refused, that the source must be stopped — so a refusal shows it as
/// is; only a lost connection or an internal failure gets the generic text.
pub fn machine_lifecycle(error: ConnectError, name: &str, action: &str) -> Error {
    let message = match error.code {
        ErrorCode::NotFound
        | ErrorCode::AlreadyExists
        | ErrorCode::InvalidArgument
        | ErrorCode::FailedPrecondition => format!(
            "Could not {action} machine '{name}': {}.",
            error
                .message
                .as_deref()
                .unwrap_or("the daemon refused the request")
                .trim_end_matches('.')
        ),
        ErrorCode::Unavailable => format!(
            "Could not {action} machine '{name}': the daemon is unavailable. Retry the command; \
             if the problem persists, check `abctl daemon status`."
        ),
        _ => format!("Could not {action} machine '{name}'. Re-run with --debug for details."),
    };
    actionable(message, error)
}

pub fn sandbox_request(error: ConnectError, id: &str, operation: &str) -> Error {
    let message = match error.code {
        ErrorCode::NotFound => {
            format!("Sandbox '{id}' was not found. List sandboxes with `abctl sandbox list`.")
        }
        ErrorCode::FailedPrecondition => format!(
            "Sandbox '{id}' is not ready for {operation}. Inspect it with \
             `abctl sandbox inspect {id}`."
        ),
        ErrorCode::Unavailable => format!(
            "Sandbox '{id}' is unavailable during {operation}. Retry the command; if the \
             problem persists, check `abctl daemon status`."
        ),
        _ => format!(
            "Could not perform {operation} for sandbox '{id}'. Re-run with --debug for details."
        ),
    };
    actionable(message, error)
}

pub fn snapshot_request(error: ConnectError, id: &str, operation: &str) -> Error {
    let message = match error.code {
        ErrorCode::NotFound => {
            format!("Snapshot '{id}' was not found. List snapshots with `abctl sandbox snapshots`.")
        }
        ErrorCode::FailedPrecondition => format!(
            "Snapshot '{id}' is not in a valid state for {operation}. List snapshots with \
             `abctl sandbox snapshots`."
        ),
        ErrorCode::Unavailable => format!(
            "Snapshot '{id}' is unavailable during {operation}. Retry the command; if the \
             problem persists, check `abctl daemon status`."
        ),
        _ => format!(
            "Could not perform {operation} for snapshot '{id}'. Re-run with --debug for details."
        ),
    };
    actionable(message, error)
}

pub fn execution_wait(error: ConnectError, sandbox_id: &str, execution_id: &str) -> Error {
    let message = match error.code {
        ErrorCode::NotFound => {
            format!("Execution '{execution_id}' was not found in sandbox '{sandbox_id}'.")
        }
        ErrorCode::Unavailable => format!(
            "Sandbox '{sandbox_id}' is unavailable while waiting for execution \
             '{execution_id}'. Retry the command; if the problem persists, check \
             `abctl daemon status`."
        ),
        _ => format!(
            "Could not determine the exit status of execution '{execution_id}' in sandbox \
             '{sandbox_id}'. Re-run with --debug for details."
        ),
    };
    actionable(message, error)
}

pub fn machine_exec_output(error: ConnectError, name: &str, command: &str) -> Error {
    let message = if connection_lost(&error) {
        format!("Connection to machine '{name}' was lost while running '{command}'.")
    } else {
        match error.code {
            ErrorCode::NotFound => {
                format!("Command '{command}' was not found in machine '{name}'.")
            }
            _ => format!(
                "Could not read output from '{command}' in machine '{name}'. Re-run with --debug \
                 for details."
            ),
        }
    };
    actionable(message, error)
}

pub fn debug_exec(error: ConnectError, container: &str) -> Error {
    let message = if connection_lost(&error) {
        format!("Connection to the debug session for container '{container}' was lost.")
    } else {
        match error.code {
            ErrorCode::NotFound => format!(
                "Container '{container}' was not found. List containers with `docker ps -a`."
            ),
            ErrorCode::FailedPrecondition => format!(
                "Container '{container}' is not running. Start it with `docker start {container}`."
            ),
            _ => format!(
                "Could not start a debug session in container '{container}'. Re-run with --debug \
                 for details."
            ),
        }
    };
    actionable(message, error)
}

fn actionable(message: String, source: ConnectError) -> Error {
    Error::new(ActionableError { message, source })
}

fn connection_lost(error: &ConnectError) -> bool {
    if error.code == ErrorCode::Unavailable {
        return true;
    }
    // connectrpc reports body-read and missing-END_STREAM failures as Internal
    // with these messages — it exposes no distinct code to match on, so the
    // message text is the only signal, and it is not a stability contract.
    //
    // The body-read wording moved between revisions: "error reading response
    // body" became "failed to read response body" when the three body-read
    // sites were centralised on one helper. Both are matched because a miss
    // here is silent — a lost connection degrades to the generic "could not
    // read output" message with nothing failing to say so.
    error.code == ErrorCode::Internal
        && error.message.as_deref().is_some_and(|message| {
            message.starts_with("error reading response body:")
                || message.starts_with("failed to read response body")
                || message == "Connect streaming response ended without END_STREAM envelope"
        })
}

pub fn render(error: &Error, debug: bool) -> String {
    if debug {
        format!("Error: {error:?}")
    } else if let Some(actionable) = error
        .chain()
        .find_map(|cause| cause.downcast_ref::<ActionableError>())
    {
        format!("Error: {actionable}")
    } else {
        format!("Error: {error:?}")
    }
}

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

    #[test]
    fn resource_errors_are_actionable_and_keep_debug_context() {
        let stopped = machine_request(
            ConnectError::failed_precondition("invalid state: CID not assigned"),
            "dev",
            "ping",
        );
        assert_eq!(
            render(&stopped, false),
            "Error: Machine 'dev' must be running for ping. Start it with \
             `abctl machine start dev`."
        );
        assert!(render(&stopped, true).contains("invalid state: CID not assigned"));

        let missing = sandbox_request(
            ConnectError::not_found("core error: VM not found"),
            "gone",
            "inspection",
        );
        assert_eq!(
            render(&missing, false),
            "Error: Sandbox 'gone' was not found. List sandboxes with \
             `abctl sandbox list`."
        );
        assert!(render(&missing, true).contains("core error: VM not found"));

        let already_running = machine_operation(
            ConnectError::failed_precondition("machine already running"),
            "dev",
            "start",
        );
        assert_eq!(
            render(&already_running, false),
            "Error: Machine 'dev' is not in a valid state for this operation. Inspect it with \
             `abctl machine inspect dev`."
        );
        assert!(render(&already_running, true).contains("machine already running"));

        let missing_execution = execution_wait(
            ConnectError::not_found("execution not found"),
            "sandbox-1",
            "exec-2",
        );
        assert_eq!(
            render(&missing_execution, false),
            "Error: Execution 'exec-2' was not found in sandbox 'sandbox-1'."
        );

        let unmapped = Error::msg("VM not found").context("Failed to inspect another resource");
        let rendered = render(&unmapped, false);
        assert!(rendered.contains("Failed to inspect another resource"));
        assert!(rendered.contains("VM not found"));
    }

    #[test]
    fn lifecycle_refusals_show_the_daemons_reason() {
        let running = machine_lifecycle(
            ConnectError::failed_precondition(
                "invalid state: machine 'dev' is running; stop it first",
            ),
            "dev",
            "clone",
        );
        assert_eq!(
            render(&running, false),
            "Error: Could not clone machine 'dev': invalid state: machine 'dev' is running; stop \
             it first."
        );
        let crashed = machine_lifecycle(ConnectError::internal("boom"), "dev", "export");
        assert_eq!(
            render(&crashed, false),
            "Error: Could not export machine 'dev'. Re-run with --debug for details."
        );
        assert!(render(&crashed, true).contains("boom"));
    }

    #[test]
    fn exec_errors_distinguish_command_transport_and_output_failures() {
        let missing = machine_exec_output(
            ConnectError::not_found("command not found: nope"),
            "dev",
            "nope",
        );
        assert_eq!(
            missing.to_string(),
            "Command 'nope' was not found in machine 'dev'."
        );

        let transport = machine_exec_output(
            ConnectError::unavailable("h2 connection closed"),
            "dev",
            "date",
        );
        assert_eq!(
            transport.to_string(),
            "Connection to machine 'dev' was lost while running 'date'."
        );

        let truncated = machine_exec_output(
            ConnectError::internal("Connect streaming response ended without END_STREAM envelope"),
            "dev",
            "date",
        );
        assert_eq!(
            truncated.to_string(),
            "Connection to machine 'dev' was lost while running 'date'."
        );

        // Both body-read wordings connectrpc has used. Only the message text
        // distinguishes these from an output failure, so a wording drift here
        // is invisible without a case per spelling.
        for message in [
            "error reading response body: connection reset",
            "failed to read response body: connection reset",
        ] {
            let body_read = machine_exec_output(ConnectError::internal(message), "dev", "date");
            assert_eq!(
                body_read.to_string(),
                "Connection to machine 'dev' was lost while running 'date'.",
                "body-read failure was not recognised as a lost connection: {message}"
            );
        }

        let output = machine_exec_output(
            ConnectError::internal("failed to decode response"),
            "dev",
            "date",
        );
        assert_eq!(
            output.to_string(),
            "Could not read output from 'date' in machine 'dev'. Re-run with --debug for details."
        );
    }

    #[test]
    fn debug_exec_maps_container_states_to_actionable_messages() {
        let missing = debug_exec(
            ConnectError::not_found("core error: No such container: nope"),
            "nope",
        );
        assert_eq!(
            missing.to_string(),
            "Container 'nope' was not found. List containers with `docker ps -a`."
        );
        assert!(render(&missing, true).contains("No such container: nope"));

        let stopped = debug_exec(
            ConnectError::failed_precondition("container 'db' is not running"),
            "db",
        );
        assert_eq!(
            stopped.to_string(),
            "Container 'db' is not running. Start it with `docker start db`."
        );

        let lost = debug_exec(ConnectError::unavailable("h2 connection closed"), "web");
        assert_eq!(
            lost.to_string(),
            "Connection to the debug session for container 'web' was lost."
        );

        let other = debug_exec(ConnectError::internal("raw"), "web");
        assert_eq!(
            other.to_string(),
            "Could not start a debug session in container 'web'. Re-run with --debug for details."
        );
    }

    #[test]
    fn unclassified_errors_point_to_debug_details() {
        let errors = [
            machine_request(ConnectError::internal("raw"), "dev", "ping"),
            machine_operation(ConnectError::internal("raw"), "dev", "start"),
            sandbox_request(ConnectError::internal("raw"), "box", "inspection"),
            snapshot_request(ConnectError::internal("raw"), "snap", "restore"),
            execution_wait(ConnectError::internal("raw"), "box", "exec"),
            machine_exec_output(ConnectError::internal("raw"), "dev", "date"),
        ];
        let expected = [
            "Error: Could not perform ping for machine 'dev'. Re-run with --debug for details.",
            "Error: Could not start machine 'dev'. Re-run with --debug for details.",
            "Error: Could not perform inspection for sandbox 'box'. Re-run with --debug for details.",
            "Error: Could not perform restore for snapshot 'snap'. Re-run with --debug for details.",
            "Error: Could not determine the exit status of execution 'exec' in sandbox 'box'. Re-run with --debug for details.",
            "Error: Could not read output from 'date' in machine 'dev'. Re-run with --debug for details.",
        ];

        for (error, expected) in errors.iter().zip(expected) {
            assert_eq!(render(error, false), expected);
        }
    }
}