laravel-rust-workflow 0.2.0

Internal crate of Laravel for Rust: durable workflows. Depend on `laravel-rust` instead
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
use crate::console::ConsoleInternals as _;
use std::collections::BTreeMap;

use comfy_table::Cell;
use jiff::{SignedDuration, Timestamp};

use super::advance::{self, now};
use super::store::{Entry, Filter, RunRecord};
use super::store::{EntryStatus, Kind};
use super::{Manager, RunId, Status};
use crate::Result;
use crate::console::theme::{Tone, elapsed, type_label};
use crate::console::{Commands, Console, clap};
use crate::context::{Context, Internals};

pub fn register(commands: &mut Commands) {
    commands
        .add::<List>()
        .add::<Show>()
        .add::<Retry>()
        .add::<Cancel>()
        .add::<Recover>()
        .add::<Prune>();
}

fn store() -> Result<std::sync::Arc<dyn super::ErasedStore>> {
    Manager::of(Context::expect("a workflow command").services()).store()
}

/// The run with the ID a user typed, or `None` when no run has it or it isn't a run ID.
async fn find(store: &dyn super::ErasedStore, id: &str) -> Result<Option<RunRecord>> {
    match id.parse() {
        Ok(id) => store.find(id).await,
        Err(_) => Ok(None),
    }
}

fn missing(id: &str) -> String {
    format!("no workflow run has the ID `{id}`")
}

/// A time in the application's time zone, as `queue:failed` shows it.
fn time(time: Timestamp) -> String {
    time.to_zoned_datetime(crate::now().time_zone().clone())
        .strftime("%Y-%m-%d %H:%M:%S")
        .to_string()
}

/// A run's status color, as `migrate:status` colors migrations: unfinished runs amber.
const fn tone(status: Status) -> Tone {
    match status {
        Status::Completed => Tone::Success,
        Status::Failed | Status::Cancelled => Tone::Error,
        Status::Pending | Status::Running | Status::Waiting => Tone::Warning,
    }
}

const fn entry_tone(status: EntryStatus) -> Tone {
    match status {
        EntryStatus::Completed => Tone::Success,
        EntryStatus::Failed => Tone::Error,
        EntryStatus::Pending => Tone::Warning,
    }
}

/// Which runs `workflow:list` and `workflow:cancel` select.
#[derive(clap::Args)]
struct Select {
    /// Only runs with this status: pending, running, waiting, completed, failed, or cancelled.
    #[arg(long, value_name = "STATUS", value_parser = parse_status)]
    status: Option<Status>,
    /// Only runs of the workflow with this registered name.
    #[arg(long, value_name = "NAME")]
    name: Option<String>,
    /// Only runs with this attribute, as `name=value`. Repeat it to require several.
    #[arg(long = "attribute", value_name = "NAME=VALUE", value_parser = parse_attribute)]
    attributes: Vec<(String, String)>,
    /// Select at most this many runs.
    #[arg(long, default_value_t = 50, value_name = "COUNT")]
    limit: usize,
}

impl Select {
    fn is_empty(&self) -> bool {
        self.status.is_none() && self.name.is_none() && self.attributes.is_empty()
    }

    fn filter(self) -> Filter {
        Filter {
            status: self.status,
            workflow: self.name,
            attributes: self.attributes.into_iter().collect(),
            limit: self.limit,
        }
    }
}

fn parse_status(status: &str) -> Result<Status, String> {
    Status::from_name(status)
        .ok_or_else(|| "expected pending, running, waiting, completed, failed, or cancelled".to_owned())
}

fn parse_attribute(attribute: &str) -> Result<(String, String), String> {
    attribute
        .split_once('=')
        .map(|(name, value)| (name.to_owned(), value.to_owned()))
        .ok_or_else(|| "expected `name=value`".to_owned())
}

/// List workflow runs, newest first.
#[derive(clap::Parser)]
#[command(name = "workflow:list")]
struct List {
    #[command(flatten)]
    select: Select,
    /// Print the runs as JSON.
    #[arg(long)]
    json: bool,
}

/// A run as `workflow:list --json` prints it.
#[derive(serde::Serialize)]
struct Listed<'a> {
    id: RunId,
    workflow: &'a str,
    status: Status,
    attributes: &'a BTreeMap<String, String>,
    wake_at: Option<Timestamp>,
    created_at: Timestamp,
    finished_at: Option<Timestamp>,
}

#[crate::console::command]
impl List {
    async fn handle(self, console: &mut Console) -> Result<()> {
        let runs = store()?.list(self.select.filter()).await?;
        if self.json {
            let listed: Vec<Listed<'_>> = runs
                .iter()
                .map(|run| Listed {
                    id: run.id,
                    workflow: &run.workflow,
                    status: run.status,
                    attributes: &run.attributes,
                    wake_at: run.wake_at.filter(|_| !run.status.has_ended()),
                    created_at: run.created_at,
                    finished_at: run.finished_at,
                })
                .collect();
            console.line(serde_json::to_string(&listed)?);
            return Ok(());
        }
        if runs.is_empty() {
            console.info("No workflow runs found.");
            return Ok(());
        }

        let colors = console.stdout_colors();
        console.listing(
            vec!["ID", "Workflow", "Status", "Started at"],
            runs.iter().map(|run| {
                vec![
                    Cell::new(run.id),
                    Cell::new(type_label(&run.workflow)),
                    Cell::new(run.status).fg(tone(run.status).table(colors)),
                    Cell::new(time(run.created_at)),
                ]
            }),
        );
        Ok(())
    }
}

/// Show a workflow run with its steps.
#[derive(clap::Parser)]
#[command(name = "workflow:show")]
struct Show {
    /// The run's ID.
    id: String,
    /// Print the run as JSON.
    #[arg(long)]
    json: bool,
}

#[crate::console::command]
impl Show {
    async fn handle(self, console: &mut Console) -> Result<u8> {
        let store = store()?;
        let Some(run) = find(&*store, &self.id).await? else {
            console.error(missing(&self.id));
            return Ok(1);
        };
        let id = run.id;
        let entries = store.entries(id).await?;
        if self.json {
            console.line(serde_json::to_string(&super::RunInfo::new(run, entries))?);
            return Ok(0);
        }

        show(&run, &entries, console);
        Ok(0)
    }
}

fn show(run: &RunRecord, entries: &[Entry], console: &mut Console) {
    let colors = console.stdout_colors();
    console.line(format!("Run       {}", run.id));
    console.line(format!("Workflow  {}", type_label(&run.workflow)));
    console.line(format!("Status    {}", tone(run.status).paint(run.status, colors)));
    console.line(format!("Queue     {}:{}", run.connection, run.queue));
    if run.purge && run.status.has_ended() {
        console.line(format!("Input     {}", Tone::Muted.paint("<data deleted>", colors)));
    } else {
        console.line(format!("Input     {}", run.input));
    }
    for (name, value) in &run.attributes {
        console.line(format!("Attribute {name}={value}"));
    }
    console.line(format!("Started   {}", time(run.created_at)));
    if let Some(finished_at) = run.finished_at {
        console.line(format!("Finished  {}", time(finished_at)));
    }
    if let Some(wake_at) = run.wake_at.filter(|_| !run.status.has_ended()) {
        console.line(format!("Wakes     {}", time(wake_at)));
    }
    if let Some(output) = &run.output {
        console.line(format!("Output    {output}"));
    }
    if let Some(error) = &run.error {
        let label = if run.status == Status::Cancelled {
            "Reason"
        } else {
            "Error"
        };
        console.line(format!("{label:<10}{error}"));
    }
    if entries.is_empty() {
        return;
    }

    console.new_line();
    console.listing(
        vec!["Kind", "Name", "Status", "Tries", "Took", "Error"],
        entries.iter().map(|entry| {
            let took = entry
                .finished_at
                .map(|finished_at| {
                    elapsed(
                        finished_at
                            .duration_since(entry.started_at)
                            .try_into()
                            .unwrap_or_default(),
                    )
                })
                .unwrap_or_default();
            vec![
                Cell::new(entry.kind.as_str()),
                Cell::new(&entry.name),
                Cell::new(entry.status.as_str()).fg(entry_tone(entry.status).table(colors)),
                Cell::new(if entry.kind == Kind::Step {
                    entry.tries.to_string()
                } else {
                    String::new()
                }),
                Cell::new(took).fg(Tone::Muted.table(colors)),
                Cell::new(entry.error.as_deref().unwrap_or_default()),
            ]
        }),
    );
}

/// Continue failed workflow runs from the step that failed.
#[derive(clap::Parser)]
#[command(name = "workflow:retry")]
struct Retry {
    /// The IDs of the failed runs.
    #[arg(required = true)]
    ids: Vec<String>,
}

#[crate::console::command]
impl Retry {
    async fn handle(self, console: &mut Console) -> Result<u8> {
        let store = store()?;
        let mut failing = false;
        for given in &self.ids {
            let Some(run) = find(&*store, given).await? else {
                console.error(missing(given));
                failing = true;
                continue;
            };
            let id = run.id;
            if !store.retry(id, now()).await? {
                console.error(format!("workflow run `{id}` hasn't failed, or its data was deleted"));
                failing = true;
                continue;
            }
            advance::schedule(id, &run.workflow, &run.connection, &run.queue, None).await?;
            console.success(format!("Workflow run `{id}` retried."));
        }

        Ok(u8::from(failing))
    }
}

/// Cancel workflow runs, by ID or by a filter.
#[derive(clap::Parser)]
#[command(name = "workflow:cancel")]
struct Cancel {
    /// The IDs of the runs. Without IDs, cancel the unfinished runs the filters select.
    ids: Vec<String>,
    #[command(flatten)]
    select: Select,
    /// Why the runs are cancelled, which `workflow:show` shows.
    #[arg(long, value_name = "REASON")]
    reason: Option<String>,
    /// Cancel the runs a filter selects without asking.
    #[arg(long)]
    force: bool,
}

#[crate::console::command]
impl Cancel {
    async fn handle(self, console: &mut Console) -> Result<u8> {
        let context = Context::expect("a workflow command");
        let mut failing = false;
        let ids = if self.ids.is_empty() {
            if self.select.is_empty() {
                return Ok(console.usage_error(
                    "workflow:cancel",
                    "give the IDs of the runs to cancel, or select them with `--status`, `--name`, or `--attribute`",
                ));
            }
            if self.select.status.is_some_and(Status::has_ended) {
                return Ok(console.usage_error(
                    "workflow:cancel",
                    "a run that has completed, failed, or been cancelled can't be cancelled",
                ));
            }
            let ids: Vec<RunId> = store()?
                .list(self.select.filter())
                .await?
                .into_iter()
                .filter(|run| !run.status.has_ended())
                .map(|run| run.id)
                .collect();
            if ids.is_empty() {
                console.info("No unfinished workflow runs found.");
                return Ok(0);
            }
            let question = match ids.len() {
                1 => "Cancel 1 workflow run?".to_owned(),
                count => format!("Cancel {count} workflow runs?"),
            };
            if !self.force && !console.confirm(question).default(false).await? {
                console.info("Command cancelled.");
                return Ok(1);
            }
            ids
        } else {
            if !self.select.is_empty() {
                return Ok(console.usage_error(
                    "workflow:cancel",
                    "give either the IDs of the runs to cancel or filters, not both",
                ));
            }
            let mut ids = Vec::new();
            for given in &self.ids {
                match given.parse() {
                    Ok(id) => ids.push(id),
                    Err(_) => {
                        console.error(missing(given));
                        failing = true;
                    }
                }
            }
            ids
        };

        for id in ids {
            if advance::cancel(&context, id, self.reason.clone()).await? {
                console.success(format!("Workflow run `{id}` cancelled."));
                continue;
            }
            failing = true;
            if store()?.find(id).await?.is_some() {
                console.error(format!("workflow run `{id}` has already ended"));
            } else {
                console.error(missing(&id.to_string()));
            }
        }

        Ok(u8::from(failing))
    }
}

/// Wake overdue workflow runs.
#[derive(clap::Parser)]
#[command(name = "workflow:recover")]
struct Recover;

#[crate::console::command]
impl Recover {
    async fn handle(self, console: &mut Console) -> Result<()> {
        let runs = store()?.overdue(now()).await?;
        for run in &runs {
            advance::schedule(run.id, &run.workflow, &run.connection, &run.queue, None).await?;
        }

        match runs.len() {
            0 => console.info("No overdue workflow runs found."),
            1 => console.success("1 workflow run woken."),
            woken => console.success(format!("{woken} workflow runs woken.")),
        }
        Ok(())
    }
}

/// Delete old workflow runs.
#[derive(clap::Parser)]
#[command(name = "workflow:prune")]
struct Prune {
    /// Delete runs that finished more than this many hours ago.
    #[arg(long, default_value_t = 24, value_name = "HOURS")]
    hours: u32,
}

fn hours_ago(hours: u32) -> Timestamp {
    now()
        .checked_sub(SignedDuration::from_hours(i64::from(hours)))
        .unwrap_or(Timestamp::MIN)
}

#[crate::console::command]
impl Prune {
    async fn handle(self, console: &mut Console) -> Result<()> {
        let store = store()?;
        match store.prune(hours_ago(self.hours)).await? {
            0 => console.info("No finished workflow runs found."),
            1 => console.success("1 workflow run deleted."),
            deleted => console.success(format!("{deleted} workflow runs deleted.")),
        }
        Ok(())
    }
}