aion-cli 0.31.0

The `aion` command line: operate Aion durable workflows over gRPC and run the Aion server.
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
//! JSON output helpers for the CLI.

use std::io::{self, Write};

use aion_client::{PauseOutcome, ReopenOutcome, ResumeOutcome, StartOutcome};
use anyhow::{Context, Result};
use serde::Serialize;
use serde_json::{Map, Value, json};

/// What `aion start` prints.
///
/// [`StartOutcome::display_name_not_applied`] is deliberately NOT rendered
/// here. The SDK raises that report only on an idempotency-key replay, and this
/// binary cannot produce one: no CLI verb takes an idempotency key, and the
/// SDK's replay cache is per-`Client`, so a key could not survive between
/// invocations even if a verb took one. A field that can never carry a value is
/// a promise the output does not keep, so it is absent rather than always-null.
/// A verb that grows an idempotency key grows this output with it.
#[derive(Serialize)]
pub(crate) struct StartOutput {
    workflow_id: String,
    run_id: String,
}

#[derive(Serialize)]
pub(crate) struct AcknowledgementOutput<'a> {
    pub(crate) workflow_id: &'a str,
    pub(crate) accepted: bool,
}

/// What `aion retire` answers with: the loop and the reason its history now
/// records. The reason is echoed back from the SERVER rather than from the
/// argument, so the operator sees what was recorded rather than what was
/// asked for.
#[derive(Serialize)]
pub(crate) struct RetireOutput<'a> {
    pub(crate) workflow_id: &'a str,
    pub(crate) retired: bool,
    pub(crate) reason: &'a str,
}

#[derive(Serialize)]
pub(crate) struct QueryOutput {
    pub(crate) result: Value,
}

#[derive(Serialize)]
pub(crate) struct ReopenOutput {
    pub(crate) workflow_id: String,
    pub(crate) run_id: String,
    pub(crate) status: String,
    pub(crate) reopened: bool,
}

#[derive(Serialize)]
pub(crate) struct DescribeOutput<TSummary, TRunId, TTerminal> {
    pub(crate) summary: TSummary,
    pub(crate) run_id: TRunId,
    pub(crate) history_head_seq: u64,
    pub(crate) terminal_event: Option<TTerminal>,
    /// What the serving install said about itself (ADR-016): the count an
    /// operator holds an unattributed `summary.current_worker` against;
    /// `null` when the server did not report one (pre-R4 server).
    pub(crate) provenance: Option<aion_core::ReadProvenance>,
}

pub(crate) fn start_output(outcome: &StartOutcome) -> StartOutput {
    StartOutput {
        workflow_id: outcome.handle.workflow_id().to_string(),
        run_id: outcome.handle.run_id().to_string(),
    }
}

pub(crate) fn reopen_output(workflow_id: &str, outcome: &ReopenOutcome) -> ReopenOutput {
    ReopenOutput {
        workflow_id: workflow_id.to_owned(),
        run_id: outcome.run_id.to_string(),
        status: format!("{:?}", outcome.status),
        reopened: true,
    }
}

/// Output of a pause request (#204).
#[derive(Serialize)]
pub(crate) struct PauseOutput {
    pub(crate) workflow_id: String,
    pub(crate) run_id: String,
    pub(crate) status: String,
    pub(crate) paused: bool,
}

pub(crate) fn pause_output(workflow_id: &str, outcome: &PauseOutcome) -> PauseOutput {
    PauseOutput {
        workflow_id: workflow_id.to_owned(),
        run_id: outcome.run_id.to_string(),
        status: format!("{:?}", outcome.status),
        paused: true,
    }
}

/// Output of a resume request (#204).
#[derive(Serialize)]
pub(crate) struct ResumeOutput {
    pub(crate) workflow_id: String,
    pub(crate) run_id: String,
    pub(crate) status: String,
    pub(crate) resumed: bool,
}

pub(crate) fn resume_output(workflow_id: &str, outcome: &ResumeOutcome) -> ResumeOutput {
    ResumeOutput {
        workflow_id: workflow_id.to_owned(),
        run_id: outcome.run_id.to_string(),
        status: format!("{:?}", outcome.status),
        resumed: true,
    }
}

pub(crate) fn to_value<T>(value: T) -> Result<Value>
where
    T: Serialize,
{
    serde_json::to_value(value).context("failed to encode command output")
}

pub(crate) fn describe_output<TSummary, TRunId, TTerminal>(
    summary: TSummary,
    run_id: TRunId,
    history_head_seq: u64,
    terminal_event: Option<TTerminal>,
    provenance: Option<aion_core::ReadProvenance>,
    raw: bool,
) -> Result<Value>
where
    TSummary: Serialize,
    TRunId: Serialize,
    TTerminal: Serialize,
{
    let mut value = to_value(DescribeOutput {
        summary,
        run_id,
        history_head_seq,
        terminal_event,
        provenance,
    })?;
    if !raw
        && let Value::Object(object) = &mut value
        && let Some(terminal_event) = object.get_mut("terminal_event")
    {
        decode_payloads_in_value(terminal_event);
    }
    Ok(value)
}

fn decode_payloads_in_value(value: &mut Value) {
    match value {
        Value::Array(items) => {
            for item in items {
                decode_payloads_in_value(item);
            }
        }
        Value::Object(object) => {
            if let Some(display_value) = payload_display_value(object) {
                *value = display_value;
            } else {
                for item in object.values_mut() {
                    decode_payloads_in_value(item);
                }
            }
        }
        Value::Null | Value::Bool(_) | Value::Number(_) | Value::String(_) => {}
    }
}

fn payload_display_value(object: &Map<String, Value>) -> Option<Value> {
    let content_type = object.get("content_type")?.as_str()?;
    let raw = object.get("bytes")?;
    // A payload whose bytes cannot be decoded is shown WITH the refusal, never
    // passed through as if it were not a payload: the reader learns what shape
    // arrived and why it did not decode, instead of a silent raw dump.
    let bytes = match aion_core::payload_bytes::from_json_value(raw) {
        Ok(bytes) => bytes,
        Err(error) => {
            return Some(json!({
                "content_type": content_type,
                "bytes": raw,
                "undecodable": error.to_string(),
            }));
        }
    };

    if bytes.is_empty() {
        return Some(json!({
            "content_type": content_type,
            "empty": true
        }));
    }

    if content_type == "Json"
        && let Ok(decoded) = serde_json::from_slice::<Value>(&bytes)
    {
        return Some(decoded);
    }

    Some(json!({
        "content_type": content_type,
        "encoding": "hex",
        "data": hex_encode(&bytes)
    }))
}

fn hex_encode(bytes: &[u8]) -> String {
    const HEX: &[u8; 16] = b"0123456789abcdef";
    let mut encoded = String::with_capacity(bytes.len() * 2);
    for byte in bytes {
        encoded.push(char::from(HEX[usize::from(byte >> 4)]));
        encoded.push(char::from(HEX[usize::from(byte & 0x0f)]));
    }
    encoded
}

pub(crate) fn print_json(value: &Value, pretty: bool) -> Result<()> {
    let stdout = io::stdout();
    let mut handle = stdout.lock();
    if pretty {
        serde_json::to_writer_pretty(&mut handle, value).context("failed to write JSON output")?;
    } else {
        serde_json::to_writer(&mut handle, value).context("failed to write JSON output")?;
    }
    writeln!(handle).context("failed to write trailing newline")
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use super::{decode_payloads_in_value, describe_output};

    #[test]
    fn describe_output_decodes_terminal_payload_and_carries_identity() -> anyhow::Result<()> {
        let terminal =
            json!({"event_type":"WorkflowCompleted","result":payload(r#"{"done":true}"#)});
        let output = describe_output(
            json!({"workflow_id":"wf"}),
            "run",
            42,
            Some(terminal),
            Some(aion_core::ReadProvenance::new(2)),
            false,
        )?;
        assert_eq!(output["summary"]["workflow_id"], json!("wf"));
        assert_eq!(output["run_id"], json!("run"));
        assert_eq!(output["history_head_seq"], json!(42));
        assert_eq!(
            output["provenance"]["lease_record_failures_total"],
            json!(2),
            "the install's lease-loss count rides beside the summary"
        );
        assert_eq!(output["terminal_event"]["result"], json!({"done":true}));
        assert!(output.get("history").is_none());
        Ok(())
    }

    #[test]
    fn raw_describe_output_preserves_terminal_payload_bytes() -> anyhow::Result<()> {
        let terminal = json!({"result":payload(r#"{\"value\":1}"#)});
        let output = describe_output(
            json!({"workflow_id":"wf"}),
            "run",
            2,
            Some(terminal),
            None,
            true,
        )?;
        assert_eq!(
            output["terminal_event"]["result"],
            payload(r#"{\"value\":1}"#)
        );
        Ok(())
    }

    #[test]
    fn describe_output_does_not_decode_summary_payload_shapes() -> anyhow::Result<()> {
        let summary = json!({"workflow_id":"wf","metadata":payload(r#"{\"raw\":true}"#)});
        let output = describe_output(
            summary,
            "run",
            1,
            Option::<serde_json::Value>::None,
            None,
            false,
        )?;
        assert_eq!(output["summary"]["metadata"], payload(r#"{\"raw\":true}"#));
        Ok(())
    }

    #[test]
    fn malformed_json_payload_falls_back_to_hex() {
        let mut value = json!({
            "payload": {
                "content_type": "Json",
                "bytes": [123, 110, 111, 116]
            }
        });

        decode_payloads_in_value(&mut value);

        assert_eq!(
            value["payload"],
            json!({
                "content_type": "Json",
                "encoding": "hex",
                "data": "7b6e6f74"
            })
        );
    }

    #[test]
    fn invalid_utf8_json_payload_falls_back_to_hex() {
        let mut value = json!({
            "payload": {
                "content_type": "Json",
                "bytes": [255, 254, 253]
            }
        });

        decode_payloads_in_value(&mut value);

        assert_eq!(
            value["payload"],
            json!({
                "content_type": "Json",
                "encoding": "hex",
                "data": "fffefd"
            })
        );
    }

    #[test]
    fn non_json_payload_falls_back_to_hex_with_content_type() {
        let mut value = json!({
            "payload": {
                "content_type": "Binary",
                "bytes": [0, 15, 16, 255]
            }
        });

        decode_payloads_in_value(&mut value);

        assert_eq!(
            value["payload"],
            json!({
                "content_type": "Binary",
                "encoding": "hex",
                "data": "000f10ff"
            })
        );
    }

    #[test]
    fn empty_payload_uses_clear_empty_indicator() {
        let mut value = json!({
            "payload": {
                "content_type": "Json",
                "bytes": []
            }
        });

        decode_payloads_in_value(&mut value);

        assert_eq!(
            value["payload"],
            json!({
                "content_type": "Json",
                "empty": true
            })
        );
    }

    #[test]
    fn invalid_payload_shape_is_named_not_hidden() {
        let mut value = json!({
            "content_type": "Json",
            "bytes": [256]
        });

        decode_payloads_in_value(&mut value);

        assert_eq!(value["content_type"], json!("Json"));
        assert_eq!(value["bytes"], json!([256]), "the raw shape stays visible");
        let refusal = value["undecodable"].as_str().unwrap_or_default();
        assert!(
            refusal.contains("payload byte 0 is 256") && refusal.contains("outside 0..=255"),
            "the refusal names the shape: {refusal:?}"
        );
    }

    #[test]
    fn a_base64_payload_decodes_like_its_array_twin() {
        let mut as_string = json!({ "content_type": "Json", "bytes": "eyJvayI6dHJ1ZX0=" });
        let mut as_array = payload(r#"{"ok":true}"#);

        decode_payloads_in_value(&mut as_string);
        decode_payloads_in_value(&mut as_array);

        assert_eq!(as_string, json!({ "ok": true }));
        assert_eq!(as_string, as_array);
    }

    fn payload(json: &str) -> serde_json::Value {
        json!({
            "content_type": "Json",
            "bytes": json.as_bytes()
        })
    }
}