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
//! The queues: what waits on each, what failed for good, the batches, and the same controls the
//! `queue:*` commands give: retry, forget, flush, pause, continue, and restart.
//!
//! Depths come from the queue manager, so they cover every driver that counts its jobs. The jobs
//! themselves, the failed jobs, and the batches are read from their tables, which needs the
//! `database` feature.

use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::time::Duration;

use futures_util::future::join_all;
use laravel::cache;
use laravel::queue::{self, BatchId};
use serde_json::json;

use crate::store::{StudioStore, counted, timestamp_ms};
use crate::types::{
    ActionResult, BatchRecord, DiagnosticIssue, FailedJobRecord, PendingJobRecord, QueueDepth, QueuesOverviewResponse,
};

// The cache keys `queue:restart` and `queue:pause` write, which every worker reads between jobs...
const RESTART: &str = "laravel:queue-restart";
const ALL_PAUSED: &str = "laravel:queues-paused";
const KEPT_FOR: Duration = Duration::from_secs(10 * 365 * 24 * 60 * 60);

/// How long a connection has to say how many jobs it holds, before Studio stops waiting for it.
const ANSWERS_WITHIN: Duration = Duration::from_secs(2);

fn paused_key(connection: &str, queue: &str) -> String {
    format!("laravel:queue-paused:{connection}:{queue}")
}

/// What the queue tables hold, and the queues they name.
#[derive(Debug, Default)]
struct Tables {
    pending_jobs: Vec<PendingJobRecord>,
    failed_jobs: Vec<FailedJobRecord>,
    batches: Vec<BatchRecord>,
    /// The queues with jobs on them, by connection, besides each connection's default queue.
    queues: HashMap<String, BTreeSet<String>>,
    note: Option<String>,
}

/// Each queue's depth and whether it's paused, the jobs waiting, the failed jobs, the batches, and
/// the attempts workers reported lately.
pub async fn queue_overview(store: &StudioStore) -> QueuesOverviewResponse {
    let config = laravel::config();
    let tables = tables::load(&config.queue).await;
    let recent_activity = store.list_job_activity(100);
    let all_paused = cache::has(ALL_PAUSED).await.unwrap_or(false);

    // Every application has a `redis` and an `sqs` connection configured, whether it uses them or
    // not, and asking a connection for its depth connects to it. So Studio asks the connections
    // in use: the default one, and those with jobs in the tables or attempts that workers reported.
    let mut in_use: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
    in_use.entry(config.queue.default.clone()).or_default();
    for (connection, queues) in &tables.queues {
        in_use
            .entry(connection.clone())
            .or_default()
            .extend(queues.iter().cloned());
    }
    for attempt in &recent_activity {
        in_use
            .entry(attempt.connection.clone())
            .or_default()
            .insert(attempt.queue.clone());
    }

    let mut asked = Vec::new();
    for (connection, mut names) in in_use {
        // A failed job can outlive the connection it was dispatched to...
        let Some(settings) = config.queue.connections.get(&connection) else {
            continue;
        };
        names.insert(settings.queue().to_owned());
        asked.extend(
            names
                .into_iter()
                .map(|name| queue_depth(connection.clone(), settings.driver().to_owned(), name, all_paused)),
        );
    }

    QueuesOverviewResponse {
        default_connection: config.queue.default.clone(),
        all_paused,
        database_enabled: cfg!(feature = "database"),
        queues: join_all(asked).await,
        pending_jobs: tables.pending_jobs,
        failed_jobs: tables.failed_jobs,
        batches: tables.batches,
        recent_activity,
        note: tables.note,
    }
}

/// How many jobs one queue holds, and whether it's paused. A queue that can't be read shows as
/// empty, with the reason.
async fn queue_depth(connection: String, driver: String, queue: String, all_paused: bool) -> QueueDepth {
    let manager = queue::manager();
    let (sizes, error) = match tokio::time::timeout(ANSWERS_WITHIN, manager.sizes(&connection, &queue)).await {
        // A driver that can't count its jobs answers `None`...
        Ok(Ok(sizes)) => (sizes.unwrap_or_default(), None),
        // The page's note already says how to create a table that's missing...
        Ok(Err(error)) if tables::is_missing_table(&error) => (queue::QueueSizes::default(), None),
        Ok(Err(error)) => (queue::QueueSizes::default(), Some(error.to_string())),
        Err(_) => (
            queue::QueueSizes::default(),
            Some(format!(
                "The connection didn't answer within {} seconds.",
                ANSWERS_WITHIN.as_secs()
            )),
        ),
    };
    let paused = all_paused || cache::has(&paused_key(&connection, &queue)).await.unwrap_or(false);

    QueueDepth {
        connection,
        driver,
        queue,
        pending: sizes.pending,
        reserved: sizes.reserved,
        delayed: sizes.delayed,
        oldest_pending: sizes.oldest_pending.map(|oldest| oldest.to_string()),
        approximate: sizes.approximate,
        paused,
        error,
    }
}

/// The failed jobs, newest first. `search` looks in a job's name, error, queue, and ID.
pub async fn list_failed_jobs(limit: usize, search: Option<&str>) -> Vec<FailedJobRecord> {
    tables::failed_jobs(&laravel::config().queue, limit, search)
        .await
        .unwrap_or_default()
}

/// Put a failed job back on its queue, as `queue:retry` does. `id` is the job's ID, which
/// `queue:failed` lists, or the number of its row in the failed jobs table.
///
/// # Errors
///
/// Returns an error if the database fails.
pub async fn retry_failed_job(id: &str) -> laravel::Result<ActionResult> {
    tables::retry(&laravel::config().queue, id).await
}

/// Put every failed job back on its queue, as `queue:retry all` does.
///
/// # Errors
///
/// Returns an error if the database fails.
pub async fn retry_all_failed_jobs() -> laravel::Result<ActionResult> {
    tables::retry_all(&laravel::config().queue).await
}

/// Delete a failed job, as `queue:forget` does.
///
/// # Errors
///
/// Returns an error if the database fails.
pub async fn forget_failed_job(id: &str) -> laravel::Result<ActionResult> {
    tables::forget(&laravel::config().queue, id).await
}

/// Delete the failed jobs, or with `hours`, those that failed longer ago, as `queue:flush` does.
///
/// # Errors
///
/// Returns an error if the database fails.
pub async fn flush_failed_jobs(hours: Option<u32>) -> laravel::Result<ActionResult> {
    tables::flush(&laravel::config().queue, hours).await
}

/// Cancel a batch, so its jobs that haven't run are skipped.
///
/// # Errors
///
/// Returns a `400` error if `id` isn't a batch ID, or an error if the batch can't be cancelled.
pub async fn cancel_batch(id: &str) -> laravel::Result<ActionResult> {
    let batch: BatchId = id
        .parse()
        .map_err(|_| laravel::abort_with(400, format!("`{id}` isn't a batch ID.")))?;
    queue::cancel_batch(batch).await?;

    Ok(ActionResult {
        ok: true,
        message: format!("Batch {batch} was cancelled."),
        detail: Some(json!({ "batch_id": batch.to_string() })),
    })
}

/// The cache key that pauses one queue, or every queue, and how to name it in a message.
fn pause_target(connection: Option<String>, queue: Option<String>, all: bool) -> (String, String) {
    match queue.filter(|_| !all) {
        Some(queue) => {
            let connection = connection.unwrap_or_else(|| laravel::config().queue.default.clone());
            (paused_key(&connection, &queue), format!("Queue {connection}:{queue}"))
        }
        None => (ALL_PAUSED.to_owned(), "Every queue".to_owned()),
    }
}

/// Pause a queue, or every queue, as `queue:pause` does. Workers finish the job they're on and
/// take no more from it.
///
/// # Errors
///
/// Returns an error if the cache, which carries the signal to the workers, fails.
pub async fn pause_queue(
    connection: Option<String>,
    queue: Option<String>,
    all: bool,
) -> laravel::Result<ActionResult> {
    let (key, name) = pause_target(connection, queue, all);
    cache::put(&key, true, KEPT_FOR).await?;

    Ok(ActionResult {
        ok: true,
        message: format!("{name} is paused."),
        detail: Some(json!({ "key": key })),
    })
}

/// Resume a queue, or every queue paused together, as `queue:continue` does.
///
/// # Errors
///
/// Returns an error if the cache fails.
pub async fn continue_queue(
    connection: Option<String>,
    queue: Option<String>,
    all: bool,
) -> laravel::Result<ActionResult> {
    let (key, name) = pause_target(connection, queue, all);
    cache::forget(&key).await?;

    Ok(ActionResult {
        ok: true,
        message: format!("{name} is running again."),
        detail: Some(json!({ "key": key })),
    })
}

/// Tell every worker to exit after its current job, as `queue:restart` does. Whatever supervises
/// the workers, such as `laravel dev` or systemd, starts them again.
///
/// # Errors
///
/// Returns an error if the cache fails.
pub async fn restart_workers() -> laravel::Result<ActionResult> {
    cache::put(RESTART, uuid::Uuid::now_v7().to_string(), KEPT_FOR).await?;

    Ok(ActionResult {
        ok: true,
        message:
            "The workers were told to restart. Each exits after its current job, for its supervisor to start again."
                .to_owned(),
        detail: None,
    })
}

/// The problems in a queue overview: jobs that failed for good, queues that can't be read, and
/// paused queues.
#[must_use]
pub fn diagnose_queues(overview: &QueuesOverviewResponse, mount: &str) -> Vec<DiagnosticIssue> {
    let mut issues = Vec::new();

    if overview.all_paused {
        issues.push(DiagnosticIssue {
            severity: "warning".to_owned(),
            category: "queue_paused".to_owned(),
            title: "Every queue is paused".to_owned(),
            detail: "`queue:pause --all` is in effect, so workers take no jobs.".to_owned(),
            location: None,
            trace_id: None,
            resource_id: None,
            hint: "Resume the queues when the work may go on.".to_owned(),
            next: Some(format!(
                "POST {mount}/api/queues/continue with the body {{\"all\": true}}"
            )),
            last_seen_ms: None,
        });
    }
    for queue in overview
        .queues
        .iter()
        .filter(|queue| queue.paused && !overview.all_paused)
    {
        issues.push(DiagnosticIssue {
            severity: "warning".to_owned(),
            category: "queue_paused".to_owned(),
            title: format!("Queue `{}:{}` is paused", queue.connection, queue.queue),
            detail: format!(
                "{} waiting on it.",
                counted(queue.pending + queue.delayed, "job is", "jobs are")
            ),
            location: None,
            trace_id: None,
            resource_id: None,
            hint: "Resume the queue when its work may go on.".to_owned(),
            next: Some(format!(
                "POST {mount}/api/queues/continue with the body {{\"connection\": \"{}\", \"queue\": \"{}\"}}",
                queue.connection, queue.queue
            )),
            last_seen_ms: None,
        });
    }

    for queue in overview.queues.iter().filter(|queue| queue.error.is_some()) {
        issues.push(DiagnosticIssue {
            severity: "warning".to_owned(),
            category: "queue_unreachable".to_owned(),
            title: format!("Queue `{}:{}` can't be read", queue.connection, queue.queue),
            detail: queue.error.clone().unwrap_or_default(),
            location: None,
            trace_id: None,
            resource_id: None,
            hint: format!(
                "Check that the `{}` connection's server is running and that its settings in `.env` are right. Jobs dispatched to it fail until it answers.",
                queue.connection
            ),
            next: None,
            last_seen_ms: None,
        });
    }

    for job in overview.failed_jobs.iter().take(6) {
        issues.push(DiagnosticIssue {
            severity: "critical".to_owned(),
            category: "job_failed".to_owned(),
            title: format!(
                "Job `{}` failed on `{}:{}`",
                job.display_name.as_deref().unwrap_or(&job.job_name),
                job.connection,
                job.queue
            ),
            detail: job.error.clone(),
            location: None,
            trace_id: None,
            // The job's own ID, which `queue:retry` and `queue:forget` take too...
            resource_id: Some(job.job_id.clone()),
            hint: "Fix what made the job fail, then retry it. A retry runs the same job with the same data.".to_owned(),
            next: Some(format!("POST {mount}/api/queues/failed/{}/retry", job.job_id)),
            last_seen_ms: timestamp_ms(&job.failed_at),
        });
    }

    issues
}

/// Without the `database` feature, Studio can't read the queue tables.
#[cfg(not(feature = "database"))]
mod tables {
    use laravel::config::queue::Queue;

    use super::Tables;
    use crate::types::{ActionResult, FailedJobRecord};

    const NEEDS_DATABASE: &str = "Studio reads the queue tables with its `database` feature, which is off.";

    fn unavailable() -> laravel::Result<ActionResult> {
        Ok(ActionResult {
            ok: false,
            message: NEEDS_DATABASE.to_owned(),
            detail: None,
        })
    }

    pub(super) async fn load(_: &Queue) -> Tables {
        Tables {
            note: Some(NEEDS_DATABASE.to_owned()),
            ..Tables::default()
        }
    }

    pub(super) fn is_missing_table(_: &laravel::Error) -> bool {
        false
    }

    pub(super) async fn failed_jobs(_: &Queue, _: usize, _: Option<&str>) -> laravel::Result<Vec<FailedJobRecord>> {
        Ok(Vec::new())
    }

    pub(super) async fn retry(_: &Queue, _: &str) -> laravel::Result<ActionResult> {
        unavailable()
    }

    pub(super) async fn retry_all(_: &Queue) -> laravel::Result<ActionResult> {
        unavailable()
    }

    pub(super) async fn forget(_: &Queue, _: &str) -> laravel::Result<ActionResult> {
        unavailable()
    }

    pub(super) async fn flush(_: &Queue, _: Option<u32>) -> laravel::Result<ActionResult> {
        unavailable()
    }
}

/// The `jobs`, `failed_jobs`, and `job_batches` tables, read and written as the framework's own
/// database queue driver and `queue:*` commands do.
#[cfg(feature = "database")]
mod tables {
    use jiff::{SignedDuration, Timestamp};
    use laravel::config::queue::{ConnectionConfig, DatabaseFailedJobs, FailedJobs, Queue};
    use laravel::db::{self, AnyConnection, Condition, col, values};
    use serde_json::{Value, json};

    use super::Tables;
    use crate::store::counted;
    use crate::types::{ActionResult, BatchRecord, FailedJobRecord, PendingJobRecord};

    type JobRow = (i64, String, String, i64, Option<Timestamp>, Timestamp, Timestamp);
    type FailedRow = (i64, String, String, String, String, String, Timestamp);
    type BatchRow = (
        String,
        Option<String>,
        i64,
        i64,
        i64,
        Timestamp,
        Option<Timestamp>,
        Option<Timestamp>,
    );

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

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

    /// Whether a query failed because its table hasn't been migrated, in any database's words.
    pub(crate) fn is_missing_table(error: &laravel::Error) -> bool {
        let message = error.to_string().to_ascii_lowercase();

        ["no such table", "does not exist", "doesn't exist", "unknown table"]
            .iter()
            .any(|phrase| message.contains(phrase))
    }

    pub(super) async fn load(config: &Queue) -> Tables {
        let mut tables = Tables::default();
        let now = now();
        // A worker that died keeps its job reserved until the reservation lapses...
        let lease_start = now.checked_sub(laravel::queue::LEASE).unwrap_or(Timestamp::MIN);

        for (name, settings) in &config.connections {
            let ConnectionConfig::Database(settings) = settings else {
                continue;
            };
            let rows = match connection(settings.connection.as_deref()) {
                Ok(connection) => {
                    connection
                        .table(settings.table.as_str())
                        .select([
                            "id",
                            "queue",
                            "payload",
                            "attempts",
                            "reserved_at",
                            "available_at",
                            "created_at",
                        ])
                        .order_by(col("id").desc())
                        .limit(100)
                        .get::<JobRow>()
                        .await
                }
                Err(error) => Err(error),
            };
            let rows = match rows {
                Ok(rows) => rows,
                Err(error) => {
                    if *name == config.default && is_missing_table(&error) {
                        tables.note = Some(format!(
                            "The `{}` table doesn't exist yet. Add a migration that holds `laravel::queue::tables!();` and run `laravel migrate`.",
                            settings.table
                        ));
                    }
                    continue;
                }
            };

            for (id, queue, payload, attempts, reserved_at, available_at, created_at) in rows {
                tables.queues.entry(name.clone()).or_default().insert(queue.clone());
                let payload = Payload::decode(&payload);
                let state = if reserved_at.is_some_and(|reserved_at| reserved_at > lease_start) {
                    "reserved"
                } else if available_at > now {
                    "delayed"
                } else {
                    "pending"
                };

                tables.pending_jobs.push(PendingJobRecord {
                    id,
                    connection: name.clone(),
                    queue,
                    job_id: payload.id,
                    job_name: payload.job,
                    display_name: payload.display_name,
                    state: state.to_owned(),
                    attempts,
                    available_at: available_at.to_string(),
                    reserved_at: reserved_at.map(|reserved_at| reserved_at.to_string()),
                    created_at: created_at.to_string(),
                    batch_id: payload.batch,
                    data: payload.data,
                });
            }
        }

        tables.failed_jobs = failed_jobs(config, 100, None).await.unwrap_or_default();
        for job in &tables.failed_jobs {
            tables
                .queues
                .entry(job.connection.clone())
                .or_default()
                .insert(job.queue.clone());
        }
        tables.batches = batches(config, 50).await.unwrap_or_default();

        tables
    }

    /// Where failed jobs are kept, or `None` when the application discards them.
    fn failed_table(config: &Queue) -> laravel::Result<Option<(AnyConnection, &DatabaseFailedJobs)>> {
        match &config.failed {
            FailedJobs::Database(settings) => Ok(Some((connection(settings.connection.as_deref())?, settings))),
            _ => Ok(None),
        }
    }

    fn discarded() -> ActionResult {
        ActionResult {
            ok: false,
            message: "The application discards its failed jobs, so there are none to act on.".to_owned(),
            detail: None,
        }
    }

    pub(super) async fn failed_jobs(
        config: &Queue,
        limit: usize,
        search: Option<&str>,
    ) -> laravel::Result<Vec<FailedJobRecord>> {
        let Some((connection, settings)) = failed_table(config)? else {
            return Ok(Vec::new());
        };
        let rows = connection
            .table(settings.table.as_str())
            .select(["id", "job_id", "connection", "queue", "payload", "error", "failed_at"])
            .order_by(col("id").desc())
            .limit(500)
            .get::<FailedRow>()
            .await;
        let rows = match rows {
            Ok(rows) => rows,
            Err(error) if is_missing_table(&error) => return Ok(Vec::new()),
            Err(error) => return Err(error),
        };

        let search = search.map(str::to_lowercase);
        Ok(rows
            .into_iter()
            .map(|(id, job_id, connection, queue, payload, error, failed_at)| {
                let payload = Payload::decode(&payload);

                FailedJobRecord {
                    id,
                    job_id,
                    connection,
                    queue,
                    job_name: payload.job,
                    display_name: payload.display_name,
                    error,
                    failed_at: failed_at.to_string(),
                    batch_id: payload.batch,
                    data: payload.data,
                }
            })
            .filter(|job| {
                search.as_ref().is_none_or(|needle| {
                    [&job.job_name, &job.error, &job.queue, &job.job_id]
                        .iter()
                        .any(|text| text.to_lowercase().contains(needle))
                })
            })
            .take(limit)
            .collect())
    }

    async fn batches(config: &Queue, limit: u64) -> laravel::Result<Vec<BatchRecord>> {
        let rows = connection(config.batches.connection.as_deref())?
            .table(config.batches.table.as_str())
            .select([
                "id",
                "name",
                "total_jobs",
                "pending_jobs",
                "failed_jobs",
                "created_at",
                "cancelled_at",
                "finished_at",
            ])
            .order_by(col("created_at").desc())
            .limit(limit)
            .get::<BatchRow>()
            .await?;

        Ok(rows
            .into_iter()
            .map(
                |(id, name, total, pending, failed, created_at, cancelled_at, finished_at)| {
                    let processed = (total - pending).max(0);
                    let status = match (cancelled_at, finished_at) {
                        (Some(_), _) => "cancelled",
                        (None, Some(_)) if failed > 0 => "finished_with_failures",
                        (None, Some(_)) => "finished",
                        (None, None) => "running",
                    };

                    BatchRecord {
                        id,
                        name,
                        total_jobs: total,
                        pending_jobs: pending,
                        failed_jobs: failed,
                        processed_jobs: processed,
                        progress_pct: if total > 0 {
                            (processed as f64 / total as f64 * 1000.0).round() / 10.0
                        } else {
                            100.0
                        },
                        status: status.to_owned(),
                        created_at: created_at.to_string(),
                        cancelled_at: cancelled_at.map(|at| at.to_string()),
                        finished_at: finished_at.map(|at| at.to_string()),
                    }
                },
            )
            .collect())
    }

    /// A failed job is known by its row's number, or by the ID its dispatch returned.
    fn identified_by(id: &str) -> Condition {
        match id.parse::<i64>() {
            Ok(number) => col("id").eq(number),
            Err(_) => col("job_id").eq(id),
        }
    }

    pub(super) async fn retry(config: &Queue, id: &str) -> laravel::Result<ActionResult> {
        let Some((connection, settings)) = failed_table(config)? else {
            return Ok(discarded());
        };
        let job = connection
            .table(settings.table.as_str())
            .select(["id", "job_id", "connection", "queue", "payload"])
            .filter(identified_by(id))
            .first::<(i64, String, String, String, String)>()
            .await?;
        let Some((number, job_id, queue_connection, queue, payload)) = job else {
            return Ok(ActionResult {
                ok: false,
                message: format!("No failed job has the ID `{id}`."),
                detail: None,
            });
        };

        if !requeue(config, &queue_connection, &queue, &payload).await? {
            return Ok(ActionResult {
                ok: false,
                message: format!(
                    "Studio can put jobs back on database queues only, and `{queue_connection}` isn't one. Run `laravel queue:retry {job_id}`."
                ),
                detail: None,
            });
        }
        connection
            .table(settings.table.as_str())
            .filter(col("id").eq(number))
            .delete()
            .await?;

        Ok(ActionResult {
            ok: true,
            message: format!("Failed job {number} is back on {queue_connection}:{queue}."),
            detail: Some(json!({ "id": number, "job_id": job_id, "connection": queue_connection, "queue": queue })),
        })
    }

    pub(super) async fn retry_all(config: &Queue) -> laravel::Result<ActionResult> {
        let Some((connection, settings)) = failed_table(config)? else {
            return Ok(discarded());
        };
        // Oldest first, so the jobs run in the order they were dispatched...
        let jobs: Vec<(i64, String, String, String)> = connection
            .table(settings.table.as_str())
            .select(["id", "connection", "queue", "payload"])
            .order_by("id")
            .get()
            .await?;

        let (mut retried, mut skipped) = (0_u64, 0_u64);
        for (number, queue_connection, queue, payload) in jobs {
            if requeue(config, &queue_connection, &queue, &payload).await? {
                connection
                    .table(settings.table.as_str())
                    .filter(col("id").eq(number))
                    .delete()
                    .await?;
                retried += 1;
            } else {
                skipped += 1;
            }
        }

        let back = match retried {
            1 => "1 failed job is back on its queue.".to_owned(),
            _ => format!("{retried} failed jobs are back on their queues."),
        };

        Ok(ActionResult {
            ok: true,
            message: match skipped {
                0 => back,
                _ => format!(
                    "{back} {} on other kinds of queue stayed failed, since Studio pushes to database queues only. Run `laravel queue:retry all` for the rest.",
                    counted(skipped, "job", "jobs")
                ),
            },
            detail: Some(json!({ "retried": retried, "skipped": skipped })),
        })
    }

    pub(super) async fn forget(config: &Queue, id: &str) -> laravel::Result<ActionResult> {
        let Some((connection, settings)) = failed_table(config)? else {
            return Ok(discarded());
        };
        let deleted = connection
            .table(settings.table.as_str())
            .filter(identified_by(id))
            .delete()
            .await?;

        Ok(ActionResult {
            ok: deleted > 0,
            message: match deleted {
                0 => format!("No failed job has the ID `{id}`."),
                _ => format!("Failed job {id} was deleted."),
            },
            detail: Some(json!({ "deleted": deleted })),
        })
    }

    pub(super) async fn flush(config: &Queue, hours: Option<u32>) -> laravel::Result<ActionResult> {
        let Some((connection, settings)) = failed_table(config)? else {
            return Ok(discarded());
        };
        let mut jobs = connection.table(settings.table.as_str());
        if let Some(hours) = hours {
            let before = now()
                .checked_sub(SignedDuration::from_hours(i64::from(hours)))
                .unwrap_or(Timestamp::MIN);
            jobs = jobs.filter(col("failed_at").lt(before));
        }
        let deleted = jobs.delete().await?;

        Ok(ActionResult {
            ok: true,
            message: format!("{} deleted.", counted(deleted, "failed job was", "failed jobs were")),
            detail: Some(json!({ "deleted": deleted })),
        })
    }

    /// Push a failed job's payload back onto its queue as though it were just dispatched, as
    /// `queue:retry` does. Returns `false` when the connection isn't a database queue, which is
    /// the only kind Studio can push to from outside the framework.
    async fn requeue(config: &Queue, queue_connection: &str, queue: &str, payload: &str) -> laravel::Result<bool> {
        let Some(ConnectionConfig::Database(settings)) = config.connections.get(queue_connection) else {
            return Ok(false);
        };
        let now = now();
        let mut payload: Value = serde_json::from_str(payload)?;
        if let Some(payload) = payload.as_object_mut() {
            payload.insert("dispatched_at".to_owned(), now.as_second().into());
            payload.remove("deduplication_id");
        }

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

        Ok(true)
    }

    /// The parts of a queued job's payload that Studio shows.
    struct Payload {
        id: Option<String>,
        job: String,
        display_name: Option<String>,
        batch: Option<String>,
        data: Value,
    }

    impl Payload {
        fn decode(raw: &str) -> Self {
            let Ok(Value::Object(mut payload)) = serde_json::from_str(raw) else {
                return Self {
                    id: None,
                    job: "a job Studio can't decode".to_owned(),
                    display_name: None,
                    batch: None,
                    data: Value::String(raw.to_owned()),
                };
            };
            let mut text = |name: &str| payload.remove(name).and_then(|value| value.as_str().map(str::to_owned));

            Self {
                id: text("id"),
                job: text("job").unwrap_or_else(|| "unknown".to_owned()),
                display_name: text("display_name"),
                batch: text("batch"),
                data: payload.remove("data").unwrap_or(Value::Null),
            }
        }
    }
}

#[cfg(feature = "database")]
pub(crate) use tables::is_missing_table;