laravel-rust-studio 0.1.1

See what a running Laravel for Rust application did: requests with their queries, errors with their source lines, mail, queued jobs, and durable workflows. For you in the browser, and for coding agents over MCP.
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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
//! Durable workflow runs: listing them, reading one with every step's output, and what the
//! `workflow:*` commands do: resume, cancel, retry, recover, and prune.
//!
//! Laravel's public API finds a run by its ID and resumes and cancels runs, in any store. Listing
//! runs, a step's output, and retries need the workflow tables themselves, which Studio reads when
//! the application keeps its runs in the `database` store and Studio's `database` feature is on.
//! With another store, Studio shows the runs it saw advance.

use std::collections::BTreeMap;

use jiff::Timestamp;
use laravel::config::workflow::StoreConfig;
use laravel::workflow::{self, Resumed, RunId, RunInfo};
use serde_json::{Value, json};

use crate::store::{StudioStore, round_ms, timestamp_ms};
use crate::types::{
    ActionResult, DiagnosticIssue, WorkflowRunDetail, WorkflowRunSummary, WorkflowStepDetail, WorkflowWaitDetail,
    WorkflowsListResponse,
};

/// Which runs [`list_workflows`] returns. The default is the newest 50.
#[derive(Debug, Default, Clone)]
pub struct WorkflowFilter {
    /// `pending`, `running`, `waiting`, `completed`, `failed`, or `cancelled`.
    pub status: Option<String>,
    /// A workflow's registered name, such as `users.onboard`.
    pub workflow: Option<String>,
    /// An attribute's name and the value it must have.
    pub attribute: Option<(String, String)>,
    /// Text in the run's ID, workflow name, or error.
    pub search: Option<String>,
    pub limit: usize,
}

/// The driver of the store the application keeps its runs in, such as `database` or `memory`.
fn store_driver() -> String {
    let config = laravel::config();

    config
        .workflow
        .stores
        .get(&config.workflow.default)
        .map_or("unknown", StoreConfig::driver)
        .to_owned()
}

fn parse_run_id(id: &str) -> laravel::Result<RunId> {
    id.parse()
        .map_err(|_| laravel::abort_with(400, format!("`{id}` isn't a workflow run ID.")))
}

/// The answer to an action that needs the workflow tables, when Studio can't reach them.
fn needs_tables(instead: &str) -> ActionResult {
    let why = if cfg!(feature = "database") {
        format!("this application keeps its runs in the `{}` store", store_driver())
    } else {
        "Studio's `database` feature is off".to_owned()
    };

    ActionResult {
        ok: false,
        message: format!("Studio does this through the workflow tables, and {why}. Run `{instead}` instead."),
        detail: None,
    }
}

/// The runs that match a filter, newest first, with how many runs are in each status.
pub async fn list_workflows(store: &StudioStore, filter: WorkflowFilter) -> WorkflowsListResponse {
    let limit = match filter.limit {
        0 => 50,
        limit => limit.min(200),
    };

    #[cfg(feature = "database")]
    if let Some(tables) = tables::Tables::of_default_store() {
        match tables.list(&filter, limit).await {
            Ok(list) => return list,
            Err(error) => {
                let mut seen = seen_runs(store, &filter, limit).await;
                seen.table_ready = !crate::queues::is_missing_table(&error);
                seen.note = Some(if seen.table_ready {
                    format!("Studio couldn't read the workflow tables: {error}")
                } else {
                    "The workflow tables don't exist yet. Before the application starts a workflow, add a migration that holds `laravel::workflow::tables!();` and run `laravel migrate`.".to_owned()
                });
                return seen;
            }
        }
    }

    seen_runs(store, &filter, limit).await
}

/// One run, with its input, output, steps, waits, and the values it was resumed with. Returns
/// `None` when no run has the ID.
///
/// # Errors
///
/// Returns a `400` error if `id` isn't a run ID, or an error if the workflow store fails.
pub async fn get_workflow(id: &str) -> laravel::Result<Option<WorkflowRunDetail>> {
    let run_id = parse_run_id(id)?;

    #[cfg(feature = "database")]
    if let Some(tables) = tables::Tables::of_default_store()
        && let Ok(Some(run)) = tables.find(run_id).await
    {
        return Ok(Some(run));
    }

    Ok(workflow::find(run_id).await?.as_ref().map(detail_of))
}

/// Give the run that waits for `token` its value, as the application's own `workflow::resume`
/// does. The value is the JSON that the workflow's `wait_for::<T>` or inbox decodes.
///
/// # Errors
///
/// Returns a `422` error if the token is empty, or an error if the store or the queue fails.
pub async fn resume_workflow(token: String, value: Value) -> laravel::Result<ActionResult> {
    if token.trim().is_empty() {
        return Err(laravel::abort_with(422, "A resume names the token the run waits for."));
    }

    let (ok, outcome, message) = match workflow::resume(token.clone(), value).await? {
        Resumed::NotFound => (
            false,
            "not_found",
            format!("No unfinished run owns the token `{token}`, so the value went nowhere."),
        ),
        Resumed::Pending => (
            true,
            "pending",
            format!("The value for `{token}` is delivered when the transaction commits."),
        ),
        _ => (
            true,
            "delivered",
            format!("The run that owns `{token}` has its value, and its next advance is queued."),
        ),
    };

    Ok(ActionResult {
        ok,
        message,
        detail: Some(json!({ "token": token, "outcome": outcome })),
    })
}

/// Cancel a run that hasn't finished, as `workflow:cancel` does. A step that's running finishes,
/// and nothing starts after it.
///
/// # Errors
///
/// Returns a `400` error if `id` isn't a run ID, or an error if the store fails.
pub async fn cancel_workflow(id: &str, reason: Option<String>) -> laravel::Result<ActionResult> {
    let run_id = parse_run_id(id)?;
    let mut cancel = workflow::cancel(run_id);
    if let Some(reason) = reason.filter(|reason| !reason.trim().is_empty()) {
        cancel = cancel.reason(reason);
    }
    let cancelled = cancel.await?;

    Ok(ActionResult {
        ok: cancelled,
        message: if cancelled {
            format!("Run {run_id} was cancelled.")
        } else {
            format!("Run {run_id} doesn't exist, or has already finished.")
        },
        detail: Some(json!({ "run_id": run_id.to_string(), "cancelled": cancelled })),
    })
}

/// Continue a failed run from the step that failed, as `workflow:retry` does. The steps before it
/// keep their recorded results.
///
/// # Errors
///
/// Returns a `400` error if `id` isn't a run ID, or an error if the database fails.
pub async fn retry_workflow(id: &str) -> laravel::Result<ActionResult> {
    let run_id = parse_run_id(id)?;

    #[cfg(feature = "database")]
    if let Some(tables) = tables::Tables::of_default_store() {
        return tables.retry(run_id).await;
    }

    Ok(needs_tables(&format!("laravel workflow:retry {run_id}")))
}

/// Queue the wake-ups of runs that are overdue, as `workflow:recover` does. A run is left
/// stranded when its wake-up job is lost, such as by a cleared queue.
///
/// # Errors
///
/// Returns an error if the database fails.
pub async fn recover_workflows() -> laravel::Result<ActionResult> {
    #[cfg(feature = "database")]
    if let Some(tables) = tables::Tables::of_default_store() {
        return tables.recover().await;
    }

    Ok(needs_tables("laravel workflow:recover"))
}

/// Delete the runs that finished more than `hours` ago, as `workflow:prune` does.
///
/// # Errors
///
/// Returns an error if the database fails.
pub async fn prune_workflows(hours: u32) -> laravel::Result<ActionResult> {
    #[cfg(feature = "database")]
    if let Some(tables) = tables::Tables::of_default_store() {
        return tables.prune(hours).await;
    }

    Ok(needs_tables(&format!("laravel workflow:prune --hours={hours}")))
}

/// The problems among `runs`: runs that failed, and runs whose wake-up time passed without a
/// worker advancing them.
#[must_use]
pub fn diagnose_workflows(runs: &[WorkflowRunSummary], mount: &str) -> Vec<DiagnosticIssue> {
    let now = laravel::now().timestamp();
    let mut issues = Vec::new();

    for run in runs {
        if run.status == "failed" {
            issues.push(DiagnosticIssue {
                severity: "critical".to_owned(),
                category: "workflow_failed".to_owned(),
                title: format!("Workflow `{}` failed", run.workflow),
                detail: run
                    .error
                    .clone()
                    .unwrap_or_else(|| "The run ended in the failed state.".to_owned()),
                location: None,
                trace_id: None,
                resource_id: Some(run.id.clone()),
                hint: "Fix what made the step fail, then retry the run, which continues from that step.".to_owned(),
                next: Some(format!(
                    "GET {mount}/api/workflows/{id}, then POST {mount}/api/workflows/{id}/retry",
                    id = run.id
                )),
                last_seen_ms: run.finished_at.as_deref().and_then(timestamp_ms),
            });
        } else if matches!(run.status.as_str(), "pending" | "waiting")
            && let Some(wake_at) = &run.wake_at
            && let Ok(wake_at) = wake_at.parse::<Timestamp>()
            && now.as_second() - wake_at.as_second() > 60
        {
            issues.push(DiagnosticIssue {
                severity: "warning".to_owned(),
                category: "workflow_overdue".to_owned(),
                title: format!("Workflow `{}` is overdue", run.workflow),
                detail: format!(
                    "Run {} is {} and was due to wake at {wake_at}, but no worker has advanced it.",
                    run.id, run.status
                ),
                location: None,
                trace_id: None,
                resource_id: Some(run.id.clone()),
                hint: "Check that a queue worker is running (`laravel queue:work`). If one is, the run's wake-up was lost, and recovering queues it again.".to_owned(),
                next: Some(format!("POST {mount}/api/workflows/recover")),
                last_seen_ms: None,
            });
        }
        if issues.len() >= 6 {
            break;
        }
    }

    issues
}

// ---- Runs in a store Studio can't list, known only from seeing them advance ----

/// The runs Studio saw advance, each read from the store by its ID.
async fn seen_runs(store: &StudioStore, filter: &WorkflowFilter, limit: usize) -> WorkflowsListResponse {
    let search = filter.search.as_deref().map(str::to_lowercase);
    let mut counts: BTreeMap<String, usize> = BTreeMap::new();
    let mut runs = Vec::new();

    for seen in store.list_workflow_activity(200) {
        let known = match seen.run_id.parse::<RunId>() {
            Ok(id) => workflow::find(id).await.ok().flatten(),
            Err(_) => None,
        };
        // A run the store has pruned is known only by what Studio saw of it...
        let run = known.as_ref().map_or_else(
            || WorkflowRunSummary {
                id: seen.run_id.clone(),
                workflow: seen.workflow.clone(),
                status: seen.status.clone(),
                connection: None,
                queue: None,
                error: seen.error.clone(),
                wake_at: None,
                created_at: None,
                finished_at: None,
                duration_ms: None,
                step_count: 0,
                waiting_tokens: Vec::new(),
                attributes: BTreeMap::new(),
                purged: false,
            },
            summary_of,
        );
        *counts.entry(run.status.clone()).or_insert(0) += 1;

        let matches = filter.status.as_ref().is_none_or(|status| run.status == *status)
            && filter.workflow.as_ref().is_none_or(|name| run.workflow == *name)
            && filter
                .attribute
                .as_ref()
                .is_none_or(|(name, value)| run.attributes.get(name) == Some(value))
            && search.as_ref().is_none_or(|needle| {
                run.id.to_lowercase().contains(needle) || run.workflow.to_lowercase().contains(needle)
            });
        if matches && runs.len() < limit {
            runs.push(run);
        }
    }

    let driver = store_driver();
    let note = if !cfg!(feature = "database") {
        "Studio's `database` feature is off, so it shows only the runs it saw advance, without their steps' outputs."
            .to_owned()
    } else {
        format!(
            "The application keeps its runs in the `{driver}` store, which Studio can't list. It shows the runs it saw advance."
        )
    };

    WorkflowsListResponse {
        source: "live".to_owned(),
        store_driver: driver,
        database_enabled: cfg!(feature = "database"),
        table_ready: true,
        note: Some(note),
        counts,
        runs,
    }
}

fn elapsed_ms(from: Timestamp, to: Option<Timestamp>) -> Option<f64> {
    to.map(|to| round_ms(to.duration_since(from).as_secs_f64().max(0.0) * 1000.0))
}

fn summary_of(run: &RunInfo) -> WorkflowRunSummary {
    WorkflowRunSummary {
        id: run.id().to_string(),
        workflow: run.workflow().to_owned(),
        status: run.status().as_str().to_owned(),
        connection: None,
        queue: None,
        error: run.error().map(str::to_owned),
        wake_at: run.wake_at().map(|at| at.to_string()),
        created_at: Some(run.created_at().to_string()),
        finished_at: run.finished_at().map(|at| at.to_string()),
        duration_ms: elapsed_ms(run.created_at(), run.finished_at()),
        step_count: run.steps().len(),
        waiting_tokens: run.waiting_for().map(str::to_owned).collect(),
        attributes: run.attributes().clone(),
        purged: run.purged(),
    }
}

/// A run as Laravel's public API describes it, which leaves out its input and its steps' outputs.
fn detail_of(run: &RunInfo) -> WorkflowRunDetail {
    let steps = run
        .steps()
        .iter()
        .map(|step| WorkflowStepDetail {
            kind: step.kind().as_str().to_owned(),
            name: step.name().to_owned(),
            status: step.status().as_str().to_owned(),
            tries: step.tries(),
            output: None,
            error: step.error().map(str::to_owned),
            wake_at: step.wake_at().map(|at| at.to_string()),
            started_at: step.started_at().to_string(),
            finished_at: step.finished_at().map(|at| at.to_string()),
            duration_ms: elapsed_ms(step.started_at(), step.finished_at()),
            timed_out: step.timed_out(),
        })
        .collect();
    let waits = run
        .waiting_for()
        .map(|token| WorkflowWaitDetail {
            token: token.to_owned(),
            number: None,
            resumed_at: None,
            is_waiting: true,
        })
        .collect();

    WorkflowRunDetail {
        id: run.id().to_string(),
        workflow: run.workflow().to_owned(),
        status: run.status().as_str().to_owned(),
        connection: None,
        queue: None,
        input: None,
        output: run.output::<Value>().ok().flatten(),
        context: None,
        error: run.error().map(str::to_owned),
        wake_at: run.wake_at().map(|at| at.to_string()),
        created_at: Some(run.created_at().to_string()),
        finished_at: run.finished_at().map(|at| at.to_string()),
        duration_ms: elapsed_ms(run.created_at(), run.finished_at()),
        attributes: run.attributes().clone(),
        purged: run.purged(),
        steps,
        waits,
        resumes: Vec::new(),
        can_retry: false,
        can_cancel: !run.status().has_ended(),
        source: "live".to_owned(),
    }
}

/// The five tables of the `database` workflow store, read and written as the store itself and the
/// `workflow:*` commands do.
#[cfg(feature = "database")]
mod tables {
    use std::collections::{BTreeMap, HashMap};

    use jiff::{SignedDuration, Timestamp};
    use laravel::config::queue::ConnectionConfig;
    use laravel::config::workflow::{DatabaseStore, StoreConfig};
    use laravel::db::{self, AnyConnection, Builder, col, values};
    use laravel::workflow::{RunId, Status};
    use serde_json::{Value, json};

    use super::{WorkflowFilter, elapsed_ms};
    use crate::store::counted;
    use crate::types::{
        ActionResult, WorkflowResumeMessage, WorkflowRunDetail, WorkflowRunSummary, WorkflowStepDetail,
        WorkflowWaitDetail, WorkflowsListResponse,
    };

    const RUN_COLUMNS: [&str; 13] = [
        "id",
        "workflow",
        "input",
        "context",
        "connection",
        "queue",
        "status",
        "output",
        "error",
        "wake_at",
        "created_at",
        "finished_at",
        "purge_data",
    ];

    type RunRow = (
        String,
        String,
        String,
        String,
        String,
        String,
        String,
        Option<String>,
        Option<String>,
        Option<Timestamp>,
        Timestamp,
        Option<Timestamp>,
        bool,
    );

    type StepRow = (
        String,
        String,
        String,
        i64,
        Option<String>,
        Option<String>,
        Option<Timestamp>,
        Timestamp,
        Option<Timestamp>,
    );

    /// The time on the application's clock, which runs and queued jobs keep their times by, and
    /// which a test can move.
    fn now() -> Timestamp {
        laravel::now().timestamp()
    }

    /// A stored value is JSON, except where an older run or another writer left plain text.
    fn json_or_text(raw: &str) -> Value {
        serde_json::from_str(raw).unwrap_or_else(|_| Value::String(raw.to_owned()))
    }

    fn has_ended(status: &str) -> bool {
        Status::from_name(status).is_some_and(Status::has_ended)
    }

    pub(super) struct Tables {
        store: DatabaseStore,
    }

    impl Tables {
        /// The tables of the application's default workflow store, when that's a `database` store.
        pub(super) fn of_default_store() -> Option<Self> {
            let config = laravel::config();
            match config.workflow.stores.get(&config.workflow.default) {
                Some(StoreConfig::Database(store)) => Some(Self { store: store.clone() }),
                _ => None,
            }
        }

        fn connection(&self) -> laravel::Result<AnyConnection> {
            match &self.store.connection {
                Some(name) => db::connection(name),
                None => db::default_connection(),
            }
        }

        fn runs(&self) -> laravel::Result<Builder> {
            Ok(self.connection()?.table(self.store.runs_table.as_str()))
        }

        fn steps(&self) -> laravel::Result<Builder> {
            Ok(self.connection()?.table(self.store.steps_table.as_str()))
        }

        fn waits(&self) -> laravel::Result<Builder> {
            Ok(self.connection()?.table(self.store.waits_table.as_str()))
        }

        fn resumes(&self) -> laravel::Result<Builder> {
            Ok(self.connection()?.table(self.store.resumes_table.as_str()))
        }

        fn attributes(&self) -> laravel::Result<Builder> {
            Ok(self.connection()?.table(self.store.attributes_table.as_str()))
        }

        pub(super) async fn list(
            &self,
            filter: &WorkflowFilter,
            limit: usize,
        ) -> laravel::Result<WorkflowsListResponse> {
            let counts: Vec<(String, i64)> = self
                .runs()?
                .select(("status", col("*").count().alias("runs")))
                .group_by(["status"])
                .get()
                .await?;

            let mut runs = self.runs()?.select(RUN_COLUMNS);
            if let Some(status) = &filter.status {
                runs = runs.filter(col("status").eq(status.as_str()));
            }
            if let Some(workflow) = &filter.workflow {
                runs = runs.filter(col("workflow").eq(workflow.as_str()));
            }
            if let Some((name, value)) = &filter.attribute {
                let labelled = self
                    .attributes()?
                    .filter(col("name").eq(name.as_str()) & col("value").eq(value.as_str()))
                    .select(["run_id"]);
                runs = runs.filter(col("id").is_in(labelled));
            }
            if let Some(search) = filter.search.as_deref().filter(|search| !search.is_empty()) {
                let pattern = format!("%{}%", search.replace(['%', '_'], ""));
                runs = runs.filter(
                    col("id").like(pattern.as_str())
                        | col("workflow").like(pattern.as_str())
                        | col("error").like(pattern.as_str()),
                );
            }
            // A run's ID is a UUIDv7, so the newest run has the greatest ID...
            let rows: Vec<RunRow> = runs.order_by(col("id").desc()).limit(limit as u64).get().await?;

            let ids: Vec<String> = rows.iter().map(|row| row.0.clone()).collect();
            let mut attributes: HashMap<String, BTreeMap<String, String>> = HashMap::new();
            let mut step_counts: HashMap<String, usize> = HashMap::new();
            let mut waiting: HashMap<String, Vec<String>> = HashMap::new();
            if !ids.is_empty() {
                let rows: Vec<(String, String, String)> = self
                    .attributes()?
                    .select(["run_id", "name", "value"])
                    .filter(col("run_id").is_in(&ids))
                    .get()
                    .await?;
                for (run, name, value) in rows {
                    attributes.entry(run).or_default().insert(name, value);
                }

                let rows: Vec<(String, i64)> = self
                    .steps()?
                    .select(("run_id", col("*").count().alias("steps")))
                    .filter(col("run_id").is_in(&ids))
                    .group_by(["run_id"])
                    .get()
                    .await?;
                step_counts.extend(
                    rows.into_iter()
                        .map(|(run, steps)| (run, usize::try_from(steps).unwrap_or(0))),
                );

                // A wait's `number` is set while the run waits, and `resumed_at` once a value came...
                let rows: Vec<(String, String)> = self
                    .waits()?
                    .select(["run_id", "token"])
                    .filter(col("run_id").is_in(&ids) & !col("number").is_null() & col("resumed_at").is_null())
                    .get()
                    .await?;
                for (run, token) in rows {
                    waiting.entry(run).or_default().push(token);
                }
            }

            let runs = rows
                .into_iter()
                .map(|row| {
                    let (
                        id,
                        workflow,
                        _,
                        _,
                        connection,
                        queue,
                        status,
                        _,
                        error,
                        wake_at,
                        created_at,
                        finished_at,
                        purge,
                    ) = row;
                    let ended = has_ended(&status);

                    WorkflowRunSummary {
                        step_count: step_counts.get(&id).copied().unwrap_or(0),
                        waiting_tokens: waiting.remove(&id).unwrap_or_default(),
                        attributes: attributes.remove(&id).unwrap_or_default(),
                        id,
                        workflow,
                        status,
                        connection: Some(connection),
                        queue: Some(queue),
                        error,
                        wake_at: wake_at.filter(|_| !ended).map(|at| at.to_string()),
                        created_at: Some(created_at.to_string()),
                        finished_at: finished_at.map(|at| at.to_string()),
                        duration_ms: elapsed_ms(created_at, finished_at),
                        purged: purge && ended,
                    }
                })
                .collect();

            Ok(WorkflowsListResponse {
                source: "database".to_owned(),
                store_driver: "database".to_owned(),
                database_enabled: true,
                table_ready: true,
                note: None,
                counts: counts
                    .into_iter()
                    .map(|(status, runs)| (status, usize::try_from(runs).unwrap_or(0)))
                    .collect(),
                runs,
            })
        }

        pub(super) async fn find(&self, id: RunId) -> laravel::Result<Option<WorkflowRunDetail>> {
            let key = id.to_string();
            let row = self
                .runs()?
                .select(RUN_COLUMNS)
                .filter(col("id").eq(key.as_str()))
                .first::<RunRow>()
                .await?;
            let Some(row) = row else {
                return Ok(None);
            };
            let (
                id,
                workflow,
                input,
                context,
                connection,
                queue,
                status,
                output,
                error,
                wake_at,
                created_at,
                finished_at,
                purge,
            ) = row;

            let steps: Vec<StepRow> = self
                .steps()?
                .select([
                    "kind",
                    "name",
                    "status",
                    "tries",
                    "output",
                    "error",
                    "wake_at",
                    "started_at",
                    "finished_at",
                ])
                .filter(col("run_id").eq(key.as_str()))
                .order_by("id")
                .get()
                .await?;
            let waits: Vec<(String, Option<i64>, Option<Timestamp>)> = self
                .waits()?
                .select(["token", "number", "resumed_at"])
                .filter(col("run_id").eq(key.as_str()))
                .get()
                .await?;
            let resumes: Vec<(String, i64, String, Timestamp)> = self
                .resumes()?
                .select(["token", "number", "value", "created_at"])
                .filter(col("run_id").eq(key.as_str()))
                .order_by("number")
                .get()
                .await?;
            let attributes: Vec<(String, String)> = self
                .attributes()?
                .select(["name", "value"])
                .filter(col("run_id").eq(key.as_str()))
                .get()
                .await?;

            let ended = has_ended(&status);
            // A run started with `purge_when_finished` loses its input and outputs when it ends...
            let purged = purge && ended;
            let steps = steps
                .into_iter()
                .map(
                    |(kind, name, status, tries, output, error, wake_at, started_at, finished_at)| {
                        WorkflowStepDetail {
                            // A wait that completed with no value gave up waiting...
                            timed_out: matches!(kind.as_str(), "wait" | "inbox")
                                && status == "completed"
                                && output.is_none(),
                            kind,
                            name,
                            status,
                            tries: u32::try_from(tries).unwrap_or(0),
                            output: output.as_deref().map(json_or_text),
                            error,
                            wake_at: wake_at.map(|at| at.to_string()),
                            started_at: started_at.to_string(),
                            finished_at: finished_at.map(|at| at.to_string()),
                            duration_ms: elapsed_ms(started_at, finished_at),
                        }
                    },
                )
                .collect();

            Ok(Some(WorkflowRunDetail {
                can_retry: status == "failed" && !purge,
                can_cancel: !ended,
                id,
                workflow,
                status,
                connection: Some(connection),
                queue: Some(queue),
                input: (!purged).then(|| json_or_text(&input)),
                output: output.as_deref().map(json_or_text),
                context: (!purged).then(|| json_or_text(&context)),
                error,
                wake_at: wake_at.filter(|_| !ended).map(|at| at.to_string()),
                created_at: Some(created_at.to_string()),
                finished_at: finished_at.map(|at| at.to_string()),
                duration_ms: elapsed_ms(created_at, finished_at),
                attributes: attributes.into_iter().collect(),
                purged,
                steps,
                waits: waits
                    .into_iter()
                    .map(|(token, number, resumed_at)| WorkflowWaitDetail {
                        is_waiting: number.is_some() && resumed_at.is_none(),
                        token,
                        number,
                        resumed_at: resumed_at.map(|at| at.to_string()),
                    })
                    .collect(),
                resumes: resumes
                    .into_iter()
                    .map(|(token, number, value, created_at)| WorkflowResumeMessage {
                        token,
                        number,
                        value: json_or_text(&value),
                        created_at: created_at.to_string(),
                    })
                    .collect(),
                source: "database".to_owned(),
            }))
        }

        /// Reset a failed run to pending and forget its failed steps, as the store's own `retry`
        /// does, then queue its next advance.
        pub(super) async fn retry(&self, id: RunId) -> laravel::Result<ActionResult> {
            let key = id.to_string();
            let run = self
                .runs()?
                .select(["workflow", "connection", "queue", "status", "purge_data"])
                .filter(col("id").eq(key.as_str()))
                .first::<(String, String, String, String, bool)>()
                .await?;
            let refusal = |message: String| {
                Ok(ActionResult {
                    ok: false,
                    message,
                    detail: None,
                })
            };
            let Some((workflow, connection, queue, status, purge)) = run else {
                return refusal(format!("No workflow run has the ID `{id}`."));
            };
            if status != "failed" {
                return refusal(format!("Run {id} is {status}. Only a failed run can be retried."));
            }
            if purge {
                return refusal(format!(
                    "Run {id} deleted its data when it failed, so it can't continue."
                ));
            }

            let reset = self
                .runs()?
                .filter(col("id").eq(key.as_str()) & col("status").eq("failed") & col("purge_data").eq(false))
                .update(values! {
                    status: "pending",
                    error: None::<String>,
                    wake_at: now(),
                    finished_at: None::<Timestamp>,
                })
                .await?;
            if reset == 0 {
                return refusal(format!("Run {id} was retried by something else just now."));
            }
            self.steps()?
                .filter(col("run_id").eq(key.as_str()) & col("status").eq("failed"))
                .delete()
                .await?;

            let queued = queue_advance(id, &workflow, &connection, &queue).await?;

            Ok(ActionResult {
                ok: true,
                message: if queued {
                    format!("Run {id} continues from its failed step. Its next advance is on {connection}:{queue}.")
                } else {
                    format!(
                        "Run {id} is pending again. Studio can't push to the `{connection}` connection, so run `laravel workflow:recover` to queue its advance."
                    )
                },
                detail: Some(json!({ "run_id": key, "queued": queued, "connection": connection, "queue": queue })),
            })
        }

        /// Queue an advance for each run that's overdue: its wake-up time has passed, the worker
        /// that held it stopped renewing its lease, or a value came for the token it waits on.
        pub(super) async fn recover(&self) -> laravel::Result<ActionResult> {
            // A run keeps its times by the application's clock, and a worker's lease by the system's...
            let due = col("status").is_in(["pending", "waiting"]) & col("wake_at").le(now());
            let abandoned = col("status").eq("running")
                & (col("leased_until").is_null() | col("leased_until").le(Timestamp::now()));
            let resumed: Vec<String> = self
                .waits()?
                .filter(!col("number").is_null() & !col("resumed_at").is_null())
                .pluck("run_id")
                .await?;
            let mut overdue = due | abandoned;
            if !resumed.is_empty() {
                overdue |= col("status").eq("waiting") & col("id").is_in(&resumed);
            }

            let runs: Vec<(String, String, String, String)> = self
                .runs()?
                .select(["id", "workflow", "connection", "queue"])
                .filter(overdue)
                .order_by("id")
                .get()
                .await?;

            let mut queued = 0;
            for (id, workflow, connection, queue) in &runs {
                if let Ok(id) = id.parse::<RunId>()
                    && queue_advance(id, workflow, connection, queue).await?
                {
                    queued += 1;
                }
            }

            Ok(ActionResult {
                ok: true,
                message: match (runs.len(), queued) {
                    (0, _) => "No run is overdue.".to_owned(),
                    (found, queued) if found == queued => format!(
                        "{} queued to advance.",
                        counted(queued, "overdue run was", "overdue runs were")
                    ),
                    (found, queued) => format!(
                        "{} overdue, and Studio queued {queued} of them. The rest are on connections it can't push to, so run `laravel workflow:recover`.",
                        counted(found, "run is", "runs are")
                    ),
                },
                detail: Some(json!({ "found": runs.len(), "enqueued": queued })),
            })
        }

        pub(super) async fn prune(&self, hours: u32) -> laravel::Result<ActionResult> {
            let before = now()
                .checked_sub(SignedDuration::from_hours(i64::from(hours)))
                .unwrap_or(Timestamp::MIN);
            let ids: Vec<String> = self.runs()?.filter(col("finished_at").lt(before)).pluck("id").await?;

            let mut deleted = 0;
            // In chunks, to stay under every database's limit on bound values...
            for ids in ids.chunks(200) {
                let ids = ids.to_vec();
                for table in [self.steps()?, self.attributes()?, self.waits()?, self.resumes()?] {
                    table.filter(col("run_id").is_in(&ids)).delete().await?;
                }
                deleted += self.runs()?.filter(col("id").is_in(&ids)).delete().await?;
            }

            Ok(ActionResult {
                ok: true,
                message: format!(
                    "Deleted {} that finished more than {} ago.",
                    counted(deleted, "run", "runs"),
                    counted(hours, "hour", "hours")
                ),
                detail: Some(json!({ "deleted": deleted })),
            })
        }
    }

    /// Queue the job that advances a run once. The job is the framework's own, which only the
    /// framework can dispatch, so Studio writes the job's row itself, in the payload format the
    /// `database` queue driver reads. Returns `false` when the run's connection isn't a database
    /// queue.
    async fn queue_advance(id: RunId, workflow: &str, connection: &str, queue: &str) -> laravel::Result<bool> {
        let config = laravel::config();
        let Some(ConnectionConfig::Database(settings)) = config.queue.connections.get(connection) else {
            return Ok(false);
        };
        let jobs = match &settings.connection {
            Some(name) => db::connection(name)?,
            None => db::default_connection()?,
        };
        let now = now();
        let payload = json!({
            "version": 1,
            "id": uuid::Uuid::now_v7().to_string(),
            "job": "laravel.workflow.advance.v1",
            "display_name": format!("workflow {}", workflow.rsplit("::").next().unwrap_or(workflow)),
            "data": { "run_id": id.to_string() },
            "dispatched_at": now.as_second(),
        });

        jobs.table(settings.table.as_str())
            .insert(values! {
                queue: queue,
                payload: payload.to_string(),
                attempts: 0,
                available_at: now,
                created_at: now,
            })
            .await?;

        Ok(true)
    }
}