mirror of
https://github.com/windmill-labs/windmill.git
synced 2026-12-04 00:06:39 +00:00
fix: address review findings on workspace job pause
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
e73d2b3845
commit
b8eda8c9a8
+22
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "WITH candidates AS (\n SELECT q.id, q.scheduled_for\n FROM v2_job_queue q\n JOIN v2_job j ON j.id = q.id\n LEFT JOIN job_perms p ON p.job_id = q.id\n WHERE q.workspace_id = $1\n AND NOT q.running\n -- a flow requeued after its preprocessor is not running but has started\n AND q.started_at IS NULL\n AND j.parent_job IS NULL\n AND j.kind IN ('script', 'flow', 'singlestepflow')\n AND NOT (\n COALESCE(p.is_admin, false)\n AND j.permissioned_as = 'u/' || j.created_by\n AND j.trigger IS NULL\n AND (j.trigger_kind IS NULL OR j.trigger_kind = 'webhook')\n )\n FOR UPDATE OF q SKIP LOCKED\n ),\n held AS (\n INSERT INTO workspace_held_job (job_id, workspace_id, scheduled_for)\n SELECT id, $1, scheduled_for FROM candidates\n ON CONFLICT (job_id) DO NOTHING\n ),\n queued AS (\n UPDATE v2_job_queue q SET scheduled_for = now() + interval '30 days'\n FROM candidates c WHERE q.id = c.id\n ),\n kinds AS (\n UPDATE v2_job j SET kind = CASE j.kind\n WHEN 'script' THEN 'unassigned_script'::JOB_KIND\n WHEN 'flow' THEN 'unassigned_flow'::JOB_KIND\n ELSE 'unassigned_singlestepflow'::JOB_KIND\n END\n FROM candidates c WHERE j.id = c.id\n )\n SELECT count(*) AS \"count!\" FROM candidates",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "count!",
|
||||
"type_info": "Int8"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Text"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
null
|
||||
]
|
||||
},
|
||||
"hash": "5df5a1e0da9ac421438c45df31e191072dbe3c1163fe88b4baefc0341b0c1ac2"
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "UPDATE v2_job_queue q SET scheduled_for = now() + interval '30 days'\n FROM workspace_held_job h\n WHERE h.job_id = q.id AND h.workspace_id = $1 AND NOT q.running",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Text"
|
||||
]
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "a911205d8e0ec77018f169377dc360d1ae85d0b22c7dff2e22dcd1d0dfa4946c"
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "INSERT INTO workspace_held_job (job_id, workspace_id, scheduled_for) VALUES ($1, $2, now())\n ON CONFLICT (job_id) DO NOTHING",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Uuid",
|
||||
"Varchar"
|
||||
]
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "c48eece8bcac0bc6faf0111276abaeb0e576bc98daedab269160467886a301e9"
|
||||
}
|
||||
-22
@@ -1,22 +0,0 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "WITH candidates AS (\n SELECT q.id, q.scheduled_for\n FROM v2_job_queue q\n JOIN v2_job j ON j.id = q.id\n LEFT JOIN job_perms p ON p.job_id = q.id\n WHERE q.workspace_id = $1\n AND NOT q.running\n AND j.parent_job IS NULL\n AND j.kind IN ('script', 'flow', 'singlestepflow')\n AND NOT (\n COALESCE(p.is_admin, false)\n AND j.trigger IS NULL\n AND (j.trigger_kind IS NULL OR j.trigger_kind = 'webhook')\n )\n FOR UPDATE OF q SKIP LOCKED\n ),\n held AS (\n INSERT INTO workspace_held_job (job_id, workspace_id, scheduled_for)\n SELECT id, $1, scheduled_for FROM candidates\n ON CONFLICT (job_id) DO NOTHING\n ),\n queued AS (\n UPDATE v2_job_queue q SET scheduled_for = now() + interval '30 days'\n FROM candidates c WHERE q.id = c.id\n ),\n kinds AS (\n UPDATE v2_job j SET kind = CASE j.kind\n WHEN 'script' THEN 'unassigned_script'::JOB_KIND\n WHEN 'flow' THEN 'unassigned_flow'::JOB_KIND\n ELSE 'unassigned_singlestepflow'::JOB_KIND\n END\n FROM candidates c WHERE j.id = c.id\n )\n SELECT count(*) AS \"count!\" FROM candidates",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "count!",
|
||||
"type_info": "Int8"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Text"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
null
|
||||
]
|
||||
},
|
||||
"hash": "cc1797618f9633bb884b24d3c4523a5ad824a6bac86c3efd640fe7999069ce93"
|
||||
}
|
||||
@@ -40,12 +40,29 @@ async fn pause_holds_and_resume_releases(db: Pool<Postgres>) -> anyhow::Result<(
|
||||
.send()
|
||||
.await?;
|
||||
assert_eq!(resp.status(), 201, "{}", resp.text().await?);
|
||||
// Runs as the admin whoever starts it.
|
||||
let resp = post(format!("{ws}/scripts/create"), ADMIN)
|
||||
.json(&json!({
|
||||
"path": "u/test-user/obo", "summary": "", "description": "",
|
||||
"content": "echo hi", "language": "bash", "on_behalf_of": "u/test-user",
|
||||
"schema": {"type": "object", "properties": {}, "required": []}
|
||||
}))
|
||||
.send()
|
||||
.await?;
|
||||
assert_eq!(resp.status(), 201, "{}", resp.text().await?);
|
||||
let resp = post(format!("{ws}/acls/add/script/u/test-user/obo"), ADMIN)
|
||||
.json(&json!({"owner": "u/test-user-2", "write": false}))
|
||||
.send()
|
||||
.await?;
|
||||
assert_eq!(resp.status(), 200, "{}", resp.text().await?);
|
||||
let run = |token: &'static str, query: &str| {
|
||||
post(format!("{ws}/jobs/run/p/u/test-user-2/s{query}"), token).json(&json!({}))
|
||||
};
|
||||
let job_id = |resp: reqwest::Response| async move {
|
||||
assert_eq!(resp.status(), 201);
|
||||
resp.text().await.unwrap().parse::<Uuid>().unwrap()
|
||||
let status = resp.status();
|
||||
let body = resp.text().await.unwrap();
|
||||
assert_eq!(status, 201, "{body}");
|
||||
body.parse::<Uuid>().unwrap()
|
||||
};
|
||||
|
||||
// Queued before the pause, due later: the pause holds it and resume keeps its time.
|
||||
@@ -90,6 +107,21 @@ async fn pause_holds_and_resume_releases(db: Pool<Postgres>) -> anyhow::Result<(
|
||||
.await;
|
||||
assert_eq!(kind_and_due(&db, forged).await.0, "unassigned_script");
|
||||
|
||||
// Running a script on behalf of an admin does not make the run an admin's.
|
||||
let obo = job_id(
|
||||
post(format!("{ws}/jobs/run/p/u/test-user/obo"), MEMBER)
|
||||
.json(&json!({}))
|
||||
.send()
|
||||
.await?,
|
||||
)
|
||||
.await;
|
||||
let run_as: String = sqlx::query_scalar("SELECT permissioned_as FROM v2_job WHERE id = $1")
|
||||
.bind(obo)
|
||||
.fetch_one(&db)
|
||||
.await?;
|
||||
assert_eq!(run_as, "u/test-user");
|
||||
assert_eq!(kind_and_due(&db, obo).await.0, "unassigned_script");
|
||||
|
||||
// An admin's direct run is not held.
|
||||
let direct = job_id(run(ADMIN, "").send().await?).await;
|
||||
assert_eq!(kind_and_due(&db, direct).await.0, "script");
|
||||
@@ -109,7 +141,7 @@ async fn pause_holds_and_resume_releases(db: Pool<Postgres>) -> anyhow::Result<(
|
||||
.send()
|
||||
.await?;
|
||||
assert_eq!(resp.status(), 200);
|
||||
assert_eq!(resp.json::<i64>().await?, 3);
|
||||
assert_eq!(resp.json::<i64>().await?, 4);
|
||||
|
||||
for id in [held, forged] {
|
||||
let (kind, at) = kind_and_due(&db, id).await;
|
||||
|
||||
@@ -78,9 +78,11 @@ async fn pause_jobs(
|
||||
require_admin(authed.is_admin, &authed.username)?;
|
||||
|
||||
let now = Utc::now();
|
||||
let max = Duration::days(MAX_PAUSE_DAYS);
|
||||
let until = match (req.until, req.duration_s) {
|
||||
(Some(until), None) => until,
|
||||
(None, Some(secs)) if secs > 0 => now + Duration::seconds(secs),
|
||||
// Bounded before the arithmetic, which panics on a large enough duration.
|
||||
(None, Some(secs)) if secs > 0 => now + Duration::seconds(secs.min(max.num_seconds() + 1)),
|
||||
_ => {
|
||||
return Err(Error::BadRequest(
|
||||
"give either `until` or a positive `duration_s`".to_string(),
|
||||
@@ -92,7 +94,7 @@ async fn pause_jobs(
|
||||
"`until` must be in the future".to_string(),
|
||||
));
|
||||
}
|
||||
if until > now + Duration::days(MAX_PAUSE_DAYS) {
|
||||
if until > now + max {
|
||||
return Err(Error::BadRequest(format!(
|
||||
"jobs cannot be paused for more than {MAX_PAUSE_DAYS} days"
|
||||
)));
|
||||
|
||||
@@ -884,22 +884,19 @@ async fn route_job(
|
||||
)
|
||||
.await
|
||||
.map_err(|e| e.into_response()),
|
||||
RequestType::Sync => with_policy(
|
||||
PausePolicy::Refuse,
|
||||
trigger_runnable_and_wait_for_result(
|
||||
&db,
|
||||
Some(user_db),
|
||||
authed,
|
||||
&trigger.workspace_id,
|
||||
&trigger.script_path,
|
||||
trigger.is_flow,
|
||||
args,
|
||||
trigger.retry.as_ref(),
|
||||
trigger.error_handler_path.as_deref(),
|
||||
trigger.error_handler_args.as_ref(),
|
||||
format!("http_trigger/{}", trigger.path),
|
||||
trigger_info,
|
||||
),
|
||||
RequestType::Sync => trigger_runnable_and_wait_for_result(
|
||||
&db,
|
||||
Some(user_db),
|
||||
authed,
|
||||
&trigger.workspace_id,
|
||||
&trigger.script_path,
|
||||
trigger.is_flow,
|
||||
args,
|
||||
trigger.retry.as_ref(),
|
||||
trigger.error_handler_path.as_deref(),
|
||||
trigger.error_handler_args.as_ref(),
|
||||
format!("http_trigger/{}", trigger.path),
|
||||
trigger_info,
|
||||
)
|
||||
.await
|
||||
.map_err(|e| e.into_response()),
|
||||
|
||||
@@ -36,8 +36,12 @@ pub const JOB_PAUSE_CHANGE_CHANNEL: &str = "notify_workspace_job_pause_change";
|
||||
|
||||
/// The deadline of the workspace's pause, `None` when it is not paused. A pause past its deadline
|
||||
/// reads as over even before the monitor deletes it. Fails open: a job is never held because the
|
||||
/// pause could not be read.
|
||||
pub async fn jobs_paused_until(db: &DB, w_id: &str) -> Option<DateTime<Utc>> {
|
||||
/// pause could not be read. Takes the caller's connection: `push` reads it inside its own
|
||||
/// transaction, where asking the pool for a second connection can starve it.
|
||||
pub async fn jobs_paused_until<'c, E: sqlx::PgExecutor<'c>>(
|
||||
db: E,
|
||||
w_id: &str,
|
||||
) -> Option<DateTime<Utc>> {
|
||||
let now = Utc::now();
|
||||
let cached = JOB_PAUSE_CACHE
|
||||
.get(w_id)
|
||||
@@ -138,8 +142,8 @@ pub fn current_policy() -> Option<PausePolicy> {
|
||||
|
||||
/// Applies the pause to a top-level job about to be pushed: `Ok(None)` runs it, `Ok(Some(until))`
|
||||
/// holds it, an error refuses it.
|
||||
pub async fn check_push(
|
||||
db: &DB,
|
||||
pub async fn check_push<'c, E: sqlx::PgExecutor<'c>>(
|
||||
db: E,
|
||||
w_id: &str,
|
||||
kind: JobKind,
|
||||
trigger_kind: Option<&JobTriggerKind>,
|
||||
@@ -162,7 +166,20 @@ pub async fn check_push(
|
||||
|
||||
/// Holds the workspace's queued jobs that have not started and that the pause would have held had
|
||||
/// they been pushed now, keeping when each was due. A worker that already claimed a job keeps it.
|
||||
///
|
||||
/// Like [`release_held_jobs`] and [`resume`], it checks no permission: the caller must be a
|
||||
/// workspace admin's request or the monitor.
|
||||
pub async fn hold_queued_jobs(tx: &mut Transaction<'_, Postgres>, w_id: &str) -> Result<i64> {
|
||||
// Extending a pause moves the jobs it already holds out of reach again, so a pause renewed
|
||||
// past 30 days never lets a worker reach (and fail) one of them.
|
||||
sqlx::query!(
|
||||
"UPDATE v2_job_queue q SET scheduled_for = now() + interval '30 days'
|
||||
FROM workspace_held_job h
|
||||
WHERE h.job_id = q.id AND h.workspace_id = $1 AND NOT q.running",
|
||||
w_id
|
||||
)
|
||||
.execute(&mut **tx)
|
||||
.await?;
|
||||
let held = sqlx::query_scalar!(
|
||||
r#"WITH candidates AS (
|
||||
SELECT q.id, q.scheduled_for
|
||||
@@ -171,10 +188,13 @@ pub async fn hold_queued_jobs(tx: &mut Transaction<'_, Postgres>, w_id: &str) ->
|
||||
LEFT JOIN job_perms p ON p.job_id = q.id
|
||||
WHERE q.workspace_id = $1
|
||||
AND NOT q.running
|
||||
-- a flow requeued after its preprocessor is not running but has started
|
||||
AND q.started_at IS NULL
|
||||
AND j.parent_job IS NULL
|
||||
AND j.kind IN ('script', 'flow', 'singlestepflow')
|
||||
AND NOT (
|
||||
COALESCE(p.is_admin, false)
|
||||
AND j.permissioned_as = 'u/' || j.created_by
|
||||
AND j.trigger IS NULL
|
||||
AND (j.trigger_kind IS NULL OR j.trigger_kind = 'webhook')
|
||||
)
|
||||
@@ -207,7 +227,7 @@ pub async fn hold_queued_jobs(tx: &mut Transaction<'_, Postgres>, w_id: &str) ->
|
||||
|
||||
/// Releases every job the workspace's pause holds, each due when it was before being held, or now.
|
||||
/// Jobs held by a suspended trigger are not in `workspace_held_job` and stay held.
|
||||
pub async fn release_held_jobs(tx: &mut Transaction<'_, Postgres>, w_id: &str) -> Result<i64> {
|
||||
async fn release_held_jobs(tx: &mut Transaction<'_, Postgres>, w_id: &str) -> Result<i64> {
|
||||
let released = sqlx::query_scalar!(
|
||||
r#"WITH held AS (
|
||||
DELETE FROM workspace_held_job WHERE workspace_id = $1
|
||||
@@ -236,7 +256,26 @@ pub async fn release_held_jobs(tx: &mut Transaction<'_, Postgres>, w_id: &str) -
|
||||
Ok(released)
|
||||
}
|
||||
|
||||
/// Ends the pause of `w_id` and releases its jobs.
|
||||
/// Hands an `unassigned_*` job a suspended trigger held over to the workspace pause, which then
|
||||
/// releases it with the jobs it holds itself. Used when the trigger releases its jobs mid-pause.
|
||||
pub async fn hold_released_trigger_job(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
w_id: &str,
|
||||
job_id: uuid::Uuid,
|
||||
) -> Result<()> {
|
||||
sqlx::query!(
|
||||
"INSERT INTO workspace_held_job (job_id, workspace_id, scheduled_for) VALUES ($1, $2, now())
|
||||
ON CONFLICT (job_id) DO NOTHING",
|
||||
job_id,
|
||||
w_id,
|
||||
)
|
||||
.execute(&mut **tx)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Ends the pause of `w_id` and releases its jobs. Checks no permission: the caller must be a
|
||||
/// workspace admin's request.
|
||||
pub async fn resume(tx: &mut Transaction<'_, Postgres>, w_id: &str) -> Result<i64> {
|
||||
sqlx::query!(
|
||||
"DELETE FROM workspace_job_pause WHERE workspace_id = $1",
|
||||
|
||||
@@ -7672,12 +7672,14 @@ async fn push_inner<'c, 'd>(
|
||||
// A suspended trigger holds its jobs itself; they are not the workspace pause's to release.
|
||||
let held_by_pause = if parent_job.is_none() && !running && !suspended_mode.unwrap_or(false) {
|
||||
windmill_common::job_pause::check_push(
|
||||
db,
|
||||
&mut *tx,
|
||||
workspace_id,
|
||||
job_kind,
|
||||
trigger_kind.as_ref(),
|
||||
trigger_path.as_ref().and_then(|p| p.as_deref()),
|
||||
job_authed.is_admin,
|
||||
// Who started the job, not who it runs as: a member running an on-behalf-of-admin
|
||||
// runnable is not an admin's run. Callers pass no `authed` for such runs.
|
||||
authed.is_some_and(|a| a.is_admin),
|
||||
)
|
||||
.await?
|
||||
.map(|_| scheduled_for_o.unwrap_or_else(Utc::now))
|
||||
|
||||
@@ -175,11 +175,21 @@ pub async fn resume_suspended_trigger_jobs(
|
||||
|
||||
let l = jobs.len();
|
||||
let mut unsuspended_in_place = 0;
|
||||
// Released in place mid-pause, a job would start during the deploy the pause protects; a
|
||||
// repushed one goes through `push`, which applies the pause itself.
|
||||
let workspace_paused = windmill_common::job_pause::jobs_paused_until(&mut *tx, &w_id)
|
||||
.await
|
||||
.is_some();
|
||||
|
||||
for job in jobs {
|
||||
// If job was created after trigger was edited, simply update it to unsuspend
|
||||
// instead of deleting and repushing
|
||||
if job.created_at > trigger.edited_at {
|
||||
if workspace_paused {
|
||||
windmill_common::job_pause::hold_released_trigger_job(&mut tx, &w_id, job.id)
|
||||
.await?;
|
||||
continue;
|
||||
}
|
||||
unsuspended_in_place += 1;
|
||||
// Map the placeholder unassigned kind back to its assigned counterpart so
|
||||
// singlestepflow wrappers (retry/error_handler/skip_handler) keep their
|
||||
|
||||
@@ -7,6 +7,7 @@ use sqlx::types::Json;
|
||||
use std::collections::HashMap;
|
||||
use std::future::Future;
|
||||
use uuid::Uuid;
|
||||
use windmill_common::job_pause::{with_policy, PausePolicy};
|
||||
use windmill_common::{
|
||||
db::{UserDB, UserDbWithAuthed, DB},
|
||||
error::Result,
|
||||
@@ -638,22 +639,26 @@ pub async fn trigger_runnable_and_wait_for_result(
|
||||
trigger: TriggerMetadata,
|
||||
) -> Result<axum::response::Response> {
|
||||
let username = authed.username.clone();
|
||||
let (uuid, resolved_delete_secs, early_return, has_failure_module, _) = trigger_runnable_inner(
|
||||
db,
|
||||
None,
|
||||
user_db,
|
||||
authed,
|
||||
workspace_id,
|
||||
runnable_path,
|
||||
is_flow,
|
||||
args,
|
||||
retry,
|
||||
error_handler_path,
|
||||
error_handler_args,
|
||||
trigger_path,
|
||||
None,
|
||||
trigger,
|
||||
None,
|
||||
// The trigger waits for the result: a job a workspace pause would hold is refused instead.
|
||||
let (uuid, resolved_delete_secs, early_return, has_failure_module, _) = with_policy(
|
||||
PausePolicy::Refuse,
|
||||
trigger_runnable_inner(
|
||||
db,
|
||||
None,
|
||||
user_db,
|
||||
authed,
|
||||
workspace_id,
|
||||
runnable_path,
|
||||
is_flow,
|
||||
args,
|
||||
retry,
|
||||
error_handler_path,
|
||||
error_handler_args,
|
||||
trigger_path,
|
||||
None,
|
||||
trigger,
|
||||
None,
|
||||
),
|
||||
)
|
||||
.await?;
|
||||
let (result, success) = run_wait_result_internal(
|
||||
@@ -691,22 +696,26 @@ pub async fn trigger_runnable_and_wait_for_raw_result(
|
||||
trigger: TriggerMetadata,
|
||||
) -> Result<(Box<RawValue>, bool)> {
|
||||
let username = authed.username.clone();
|
||||
let (uuid, resolved_delete_secs, early_return, has_failure_module, _) = trigger_runnable_inner(
|
||||
db,
|
||||
None,
|
||||
user_db,
|
||||
authed,
|
||||
workspace_id,
|
||||
runnable_path,
|
||||
is_flow,
|
||||
args,
|
||||
retry,
|
||||
error_handler_path,
|
||||
error_handler_args,
|
||||
trigger_path,
|
||||
None,
|
||||
trigger,
|
||||
None,
|
||||
// The trigger waits for the result: a job a workspace pause would hold is refused instead.
|
||||
let (uuid, resolved_delete_secs, early_return, has_failure_module, _) = with_policy(
|
||||
PausePolicy::Refuse,
|
||||
trigger_runnable_inner(
|
||||
db,
|
||||
None,
|
||||
user_db,
|
||||
authed,
|
||||
workspace_id,
|
||||
runnable_path,
|
||||
is_flow,
|
||||
args,
|
||||
retry,
|
||||
error_handler_path,
|
||||
error_handler_args,
|
||||
trigger_path,
|
||||
None,
|
||||
trigger,
|
||||
None,
|
||||
),
|
||||
)
|
||||
.await?;
|
||||
|
||||
|
||||
@@ -6804,7 +6804,7 @@ export async function push(
|
||||
}
|
||||
let jobsResumed = false;
|
||||
if (jobsPause) {
|
||||
const depsDone = await waitForDependencyJobs(
|
||||
const deps = await waitForDependencyJobs(
|
||||
workspace.workspaceId,
|
||||
pushStartedAt,
|
||||
new Date(jobsPause.paused_until),
|
||||
@@ -6815,12 +6815,14 @@ export async function push(
|
||||
`Jobs stay paused until ${jobsPause.paused_until} (--keep-paused). Run 'wmill workspace resume-jobs' when ready.`,
|
||||
),
|
||||
);
|
||||
} else if (failedChanges.length > 0 || !depsDone) {
|
||||
} else if (failedChanges.length > 0 || !deps.finished || deps.failed > 0) {
|
||||
log.warn(
|
||||
`Jobs stay paused until ${jobsPause.paused_until} because ` +
|
||||
(failedChanges.length > 0
|
||||
? "some changes failed to push"
|
||||
: "dependency jobs are still running") +
|
||||
: deps.failed > 0
|
||||
? `${deps.failed} dependency job(s) failed`
|
||||
: "dependency jobs are still running") +
|
||||
". Run 'wmill workspace resume-jobs' once the workspace is consistent.",
|
||||
);
|
||||
} else {
|
||||
|
||||
@@ -53,27 +53,33 @@ const DEPENDENCY_JOB_KINDS = "dependencies,flowdependencies,appdependencies";
|
||||
|
||||
/**
|
||||
* Waits until no dependency job created since `sinceIso` is still queued or running, or until
|
||||
* `deadline`. Returns whether they all finished.
|
||||
* `deadline`. `finished` is false when some are still running at the deadline; `failed` counts
|
||||
* those that failed.
|
||||
*/
|
||||
export async function waitForDependencyJobs(
|
||||
workspaceId: string,
|
||||
sinceIso: string,
|
||||
deadline: Date,
|
||||
): Promise<boolean> {
|
||||
// Raw fetch: the generated client has no `created_after` filter on the queue list.
|
||||
): Promise<{ finished: boolean; failed: number }> {
|
||||
// Raw fetch: the generated client has no `created_after` filter on the job lists.
|
||||
const { OpenAPI } = await import("../../../gen/index.ts");
|
||||
const url =
|
||||
`${OpenAPI.BASE}/w/${workspaceId}/jobs/queue/list?job_kinds=${DEPENDENCY_JOB_KINDS}` +
|
||||
`&created_after=${encodeURIComponent(sinceIso)}&per_page=100`;
|
||||
let announced = false;
|
||||
while (true) {
|
||||
const resp = await fetch(url, {
|
||||
const filter =
|
||||
`job_kinds=${DEPENDENCY_JOB_KINDS}&created_after=${encodeURIComponent(sinceIso)}&per_page=100`;
|
||||
const list = async (route: string) => {
|
||||
const resp = await fetch(`${OpenAPI.BASE}/w/${workspaceId}/jobs/${route}`, {
|
||||
headers: { ...getHeaders(), Authorization: `Bearer ${OpenAPI.TOKEN}` },
|
||||
});
|
||||
if (!resp.ok) throw new Error(`Listing dependency jobs failed: ${resp.status}`);
|
||||
const queued = (await resp.json()) as unknown[];
|
||||
if (queued.length === 0) return true;
|
||||
if (Date.now() >= deadline.getTime()) return false;
|
||||
return (await resp.json()) as unknown[];
|
||||
};
|
||||
let announced = false;
|
||||
while (true) {
|
||||
const queued = await list(`queue/list?${filter}`);
|
||||
const finished = queued.length === 0;
|
||||
if (finished || Date.now() >= deadline.getTime()) {
|
||||
const failed = await list(`completed/list?${filter}&success=false`);
|
||||
return { finished, failed: failed.length };
|
||||
}
|
||||
if (!announced) {
|
||||
log.info(
|
||||
colors.gray(
|
||||
|
||||
@@ -20,7 +20,6 @@ import { mergeWorkspaces } from "./merge.ts";
|
||||
import { connectSlack, disconnectSlack } from "./slack.ts";
|
||||
import { applySettings, getSettings } from "./settings.ts";
|
||||
import {
|
||||
DEFAULT_PAUSE_DURATION,
|
||||
jobsPausedCommand,
|
||||
pauseJobsCommand,
|
||||
resumeJobsCommand,
|
||||
@@ -933,7 +932,7 @@ Arguments (omit both to be prompted interactively):
|
||||
.description(
|
||||
"Pause new jobs of the active workspace, e.g. while a deploy or a migration is in progress. Jobs from triggers, schedules and async runs are held until 'wmill workspace resume-jobs' or the end of the pause; callers waiting for a result get a 503. Dependency and git sync jobs, steps of running flows and runs started directly by an admin are not held. Admin only."
|
||||
)
|
||||
.option("--for <duration:string>", "How long the pause lasts at most (e.g. 30m, 2h, 1d; at most 7d)", { default: DEFAULT_PAUSE_DURATION })
|
||||
.option("--for <duration:string>", "How long the pause lasts at most (e.g. 30m, 2h, 1d; at most 7d; default 30m)")
|
||||
.option("--reason <reason:string>", "Shown to users of the workspace while paused")
|
||||
.action(pauseJobsCommand as any)
|
||||
.command("resume-jobs")
|
||||
|
||||
Generated
+1
-1
@@ -9340,7 +9340,7 @@ Arguments (omit both to be prompted interactively):
|
||||
- \`--replace\` - Also clear the settings the file omits, as 'wmill sync push' does
|
||||
- \`-y --yes\` - Apply without asking
|
||||
- \`workspace pause-jobs\` - Pause new jobs of the active workspace, e.g. while a deploy or a migration is in progress. Jobs from triggers, schedules and async runs are held until 'wmill workspace resume-jobs' or the end of the pause; callers waiting for a result get a 503. Dependency and git sync jobs, steps of running flows and runs started directly by an admin are not held. Admin only.
|
||||
- \`--for <duration:string>\` - How long the pause lasts at most (e.g. 30m, 2h, 1d; at most 7d)
|
||||
- \`--for <duration:string>\` - How long the pause lasts at most (e.g. 30m, 2h, 1d; at most 7d; default 30m)
|
||||
- \`--reason <reason:string>\` - Shown to users of the workspace while paused
|
||||
- \`workspace resume-jobs\` - Resume new jobs of the active workspace and release the jobs the pause held. Admin only.
|
||||
- \`workspace jobs-paused\` - Show whether new jobs of the active workspace are paused
|
||||
|
||||
@@ -12,6 +12,8 @@ General tab of workspace settings, or `pauseWorkspaceJobs` / `pause_workspace_jo
|
||||
directly by an admin (no trigger path and a `webhook` or empty trigger kind, see
|
||||
`pause_decision`); anything pushed under `PausePolicy::Exempt` (datatable migrations, raw app
|
||||
bundles). A job with a parent always runs: the flow or job it belongs to already started.
|
||||
"Admin" is the caller (`push`'s `authed`), never the identity the job runs as: a member running
|
||||
an on-behalf-of-admin script is held.
|
||||
- **Held**: script, flow and single-step-flow jobs are queued as `unassigned_*`, 30 days out, the
|
||||
same way a suspended trigger holds its jobs, plus a `workspace_held_job` row carrying when the
|
||||
job was due.
|
||||
@@ -20,7 +22,8 @@ General tab of workspace settings, or `pauseWorkspaceJobs` / `pause_workspace_jo
|
||||
|
||||
A caller that waits for the result must push under `with_policy(PausePolicy::Refuse, ..)`, or a
|
||||
held job leaves it waiting until it times out. That covers `run_wait_result*`, `run_and_stream`,
|
||||
`run_flow_and_wait_result`, dynamic selects, app components and sync HTTP routes. A new
|
||||
`run_flow_and_wait_result`, dynamic selects, app components and the trigger helpers that wait for
|
||||
a result (sync and SSE HTTP routes, websocket return messages, initial messages and URLs). A new
|
||||
synchronous entry point needs the same wrapper. The policy is a task-local: it does not cross
|
||||
`tokio::spawn`, so the push must run on the task that entered the scope.
|
||||
|
||||
@@ -37,6 +40,7 @@ synchronous entry point needs the same wrapper. The policy is a task-local: it d
|
||||
A pause past its deadline reads as over immediately; `monitor_db` deletes it and releases its
|
||||
jobs, and also releases held rows left without a pause (a push that read a stale cache).
|
||||
- `MAX_PAUSE_DAYS` (7) must stay well under the 30-day horizon after which a worker fails an
|
||||
`unassigned_*` job it reaches.
|
||||
`unassigned_*` job it reaches. A pause can be renewed indefinitely, so every renewal also moves
|
||||
the jobs it already holds 30 days out again.
|
||||
- Held jobs run the version they were pushed with; resume does not re-resolve them to the latest
|
||||
deployed version.
|
||||
|
||||
@@ -856,7 +856,7 @@ Arguments (omit both to be prompted interactively):
|
||||
- `--replace` - Also clear the settings the file omits, as 'wmill sync push' does
|
||||
- `-y --yes` - Apply without asking
|
||||
- `workspace pause-jobs` - Pause new jobs of the active workspace, e.g. while a deploy or a migration is in progress. Jobs from triggers, schedules and async runs are held until 'wmill workspace resume-jobs' or the end of the pause; callers waiting for a result get a 503. Dependency and git sync jobs, steps of running flows and runs started directly by an admin are not held. Admin only.
|
||||
- `--for <duration:string>` - How long the pause lasts at most (e.g. 30m, 2h, 1d; at most 7d)
|
||||
- `--for <duration:string>` - How long the pause lasts at most (e.g. 30m, 2h, 1d; at most 7d; default 30m)
|
||||
- `--reason <reason:string>` - Shown to users of the workspace while paused
|
||||
- `workspace resume-jobs` - Resume new jobs of the active workspace and release the jobs the pause held. Admin only.
|
||||
- `workspace jobs-paused` - Show whether new jobs of the active workspace are paused
|
||||
|
||||
@@ -4645,7 +4645,7 @@ Arguments (omit both to be prompted interactively):
|
||||
- \`--replace\` - Also clear the settings the file omits, as 'wmill sync push' does
|
||||
- \`-y --yes\` - Apply without asking
|
||||
- \`workspace pause-jobs\` - Pause new jobs of the active workspace, e.g. while a deploy or a migration is in progress. Jobs from triggers, schedules and async runs are held until 'wmill workspace resume-jobs' or the end of the pause; callers waiting for a result get a 503. Dependency and git sync jobs, steps of running flows and runs started directly by an admin are not held. Admin only.
|
||||
- \`--for <duration:string>\` - How long the pause lasts at most (e.g. 30m, 2h, 1d; at most 7d)
|
||||
- \`--for <duration:string>\` - How long the pause lasts at most (e.g. 30m, 2h, 1d; at most 7d; default 30m)
|
||||
- \`--reason <reason:string>\` - Shown to users of the workspace while paused
|
||||
- \`workspace resume-jobs\` - Resume new jobs of the active workspace and release the jobs the pause held. Admin only.
|
||||
- \`workspace jobs-paused\` - Show whether new jobs of the active workspace are paused
|
||||
|
||||
@@ -861,7 +861,7 @@ Arguments (omit both to be prompted interactively):
|
||||
- `--replace` - Also clear the settings the file omits, as 'wmill sync push' does
|
||||
- `-y --yes` - Apply without asking
|
||||
- `workspace pause-jobs` - Pause new jobs of the active workspace, e.g. while a deploy or a migration is in progress. Jobs from triggers, schedules and async runs are held until 'wmill workspace resume-jobs' or the end of the pause; callers waiting for a result get a 503. Dependency and git sync jobs, steps of running flows and runs started directly by an admin are not held. Admin only.
|
||||
- `--for <duration:string>` - How long the pause lasts at most (e.g. 30m, 2h, 1d; at most 7d)
|
||||
- `--for <duration:string>` - How long the pause lasts at most (e.g. 30m, 2h, 1d; at most 7d; default 30m)
|
||||
- `--reason <reason:string>` - Shown to users of the workspace while paused
|
||||
- `workspace resume-jobs` - Resume new jobs of the active workspace and release the jobs the pause held. Admin only.
|
||||
- `workspace jobs-paused` - Show whether new jobs of the active workspace are paused
|
||||
|
||||
Reference in New Issue
Block a user