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,
};
#[derive(Debug, Default, Clone)]
pub struct WorkflowFilter {
pub status: Option<String>,
pub workflow: Option<String>,
pub attribute: Option<(String, String)>,
pub search: Option<String>,
pub limit: usize,
}
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.")))
}
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,
}
}
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
}
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))
}
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 })),
})
}
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 })),
})
}
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}")))
}
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"))
}
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}")))
}
#[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
}
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,
};
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(),
}
}
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(),
}
}
#[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>,
);
fn now() -> Timestamp {
laravel::now().timestamp()
}
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 {
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()),
);
}
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))),
);
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);
let purged = purge && ended;
let steps = steps
.into_iter()
.map(
|(kind, name, status, tries, output, error, wake_at, started_at, finished_at)| {
WorkflowStepDetail {
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(),
}))
}
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 })),
})
}
pub(super) async fn recover(&self) -> laravel::Result<ActionResult> {
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;
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 })),
})
}
}
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)
}
}