feat: pause new jobs of a workspace during a deploy

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ruben Fiszel
2026-10-23 15:41:13 +02:00
co-authored by Claude Opus 5.5
parent fb193d7a81
commit e73d2b3845
63 changed files with 2633 additions and 353 deletions
+3
View File
@@ -41,6 +41,9 @@ Open-source platform for internal tools, workflows, API integrations, background
for an inline app runnable that opts in), why an admin's roles are not added, the per-role-set
logins and the order their rows and logins are written in
- **Enterprise**: `docs/enterprise.md` — EE file conventions and PR workflow
- **Workspace job pause**: `docs/workspace-job-pause.md` — which pushed jobs a pause runs, holds
or refuses, why a synchronous entry point must push under `PausePolicy::Refuse`, and how held
jobs are told apart from a suspended trigger's
- **Workspace roles**: `docs/workspace-roles.md` — instance-defined roles with per-workspace
overrides, the capabilities a role holds, why `ApiAuthed::is_operator` must be derived from the
role, and the `role_seat` table billing reads
@@ -0,0 +1,22 @@
{
"db_name": "PostgreSQL",
"query": "SELECT paused_until FROM workspace_job_pause WHERE workspace_id = $1",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "paused_until",
"type_info": "Timestamptz"
}
],
"parameters": {
"Left": [
"Text"
]
},
"nullable": [
false
]
},
"hash": "015adf2239a34462212dd927281adbc370a0bc35a7a7dc5bbba80ac2432c6360"
}
@@ -0,0 +1,22 @@
{
"db_name": "PostgreSQL",
"query": "SELECT EXISTS (SELECT 1 FROM workspace_job_pause WHERE workspace_id = $1) AS \"exists!\"",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "exists!",
"type_info": "Bool"
}
],
"parameters": {
"Left": [
"Text"
]
},
"nullable": [
null
]
},
"hash": "111ce9bef31798a72024704087556b9ddaf9d39c0749c0f1fc022233ee0bab1f"
}
@@ -0,0 +1,53 @@
{
"db_name": "PostgreSQL",
"query": "SELECT id FROM v2_job\n WHERE workspace_id = $1\n AND (kind = 'unassigned_script'::JOB_KIND OR kind = 'unassigned_flow'::JOB_KIND OR kind = 'unassigned_singlestepflow'::JOB_KIND)\n AND trigger_kind = $2\n AND trigger = $3\n AND NOT EXISTS (SELECT 1 FROM workspace_held_job h WHERE h.job_id = v2_job.id)",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Uuid"
}
],
"parameters": {
"Left": [
"Text",
{
"Custom": {
"name": "job_trigger_kind",
"kind": {
"Enum": [
"webhook",
"http",
"websocket",
"kafka",
"email",
"nats",
"schedule",
"app",
"ui",
"postgres",
"sqs",
"gcp",
"mqtt",
"nextcloud",
"google",
"ci_test",
"github",
"azure",
"asset",
"freshness",
"amqp"
]
}
}
},
"Text"
]
},
"nullable": [
false
]
},
"hash": "22bca2f5ed54a016d79063361430d2c561e3fe57c8ed36cfc32b390e704add39"
}
@@ -0,0 +1,102 @@
{
"db_name": "PostgreSQL",
"query": "\n SELECT\n id,\n args as \"args: _\",\n created_at,\n kind AS \"kind: _\"\n FROM v2_job\n WHERE workspace_id = $1\n AND (\n kind = 'unassigned_script'::JOB_KIND OR\n kind = 'unassigned_flow'::JOB_KIND OR\n kind = 'unassigned_singlestepflow'::JOB_KIND\n )\n AND trigger_kind = $2\n AND trigger = $3\n AND NOT EXISTS (SELECT 1 FROM workspace_held_job h WHERE h.job_id = v2_job.id)\n AND id = ANY($4)\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Uuid"
},
{
"ordinal": 1,
"name": "args: _",
"type_info": "Jsonb"
},
{
"ordinal": 2,
"name": "created_at",
"type_info": "Timestamptz"
},
{
"ordinal": 3,
"name": "kind: _",
"type_info": {
"Custom": {
"name": "job_kind",
"kind": {
"Enum": [
"script",
"preview",
"flow",
"dependencies",
"flowpreview",
"script_hub",
"identity",
"flowdependencies",
"http",
"graphql",
"postgresql",
"noop",
"appdependencies",
"deploymentcallback",
"singlestepflow",
"flowscript",
"flownode",
"appscript",
"aiagent",
"unassigned_script",
"unassigned_flow",
"unassigned_singlestepflow"
]
}
}
}
}
],
"parameters": {
"Left": [
"Text",
{
"Custom": {
"name": "job_trigger_kind",
"kind": {
"Enum": [
"webhook",
"http",
"websocket",
"kafka",
"email",
"nats",
"schedule",
"app",
"ui",
"postgres",
"sqs",
"gcp",
"mqtt",
"nextcloud",
"google",
"ci_test",
"github",
"azure",
"asset",
"freshness",
"amqp"
]
}
}
},
"Text",
"UuidArray"
]
},
"nullable": [
false,
true,
false,
false
]
},
"hash": "2e0d69d27edb7a13c6055edcb4b277100bf02c6c19a5e1d19b969812722c98e3"
}
@@ -0,0 +1,15 @@
{
"db_name": "PostgreSQL",
"query": "INSERT INTO workspace_job_pause (workspace_id, paused_until, paused_by, paused_at, reason)\n SELECT $1, paused_until, paused_by, paused_at, reason\n FROM workspace_job_pause WHERE workspace_id = $2\n ON CONFLICT (workspace_id) DO NOTHING",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Varchar",
"Text"
]
},
"nullable": []
},
"hash": "3d2fe43b089638369a77d4eaf1eb62c021127f603c54d1190a6898e7749f5105"
}
@@ -0,0 +1,46 @@
{
"db_name": "PostgreSQL",
"query": "SELECT paused_until, paused_by, paused_at, reason,\n (SELECT count(*) FROM workspace_held_job h WHERE h.workspace_id = p.workspace_id) AS \"held_count!\"\n FROM workspace_job_pause p\n WHERE workspace_id = $1 AND paused_until > now()",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "paused_until",
"type_info": "Timestamptz"
},
{
"ordinal": 1,
"name": "paused_by",
"type_info": "Varchar"
},
{
"ordinal": 2,
"name": "paused_at",
"type_info": "Timestamptz"
},
{
"ordinal": 3,
"name": "reason",
"type_info": "Text"
},
{
"ordinal": 4,
"name": "held_count!",
"type_info": "Int8"
}
],
"parameters": {
"Left": [
"Text"
]
},
"nullable": [
false,
false,
false,
true,
null
]
},
"hash": "5c4441bc1d689be1ae4ad87dd47702a1d7f89abc4823716083fae209c7c38f38"
}
@@ -0,0 +1,22 @@
{
"db_name": "PostgreSQL",
"query": "WITH held AS (\n DELETE FROM workspace_held_job WHERE workspace_id = $1\n RETURNING job_id, scheduled_for\n ),\n queued AS (\n UPDATE v2_job_queue q SET scheduled_for = GREATEST(h.scheduled_for, now())\n FROM held h\n WHERE q.id = h.job_id AND NOT q.running\n RETURNING q.id\n ),\n kinds AS (\n UPDATE v2_job j SET kind = CASE j.kind\n WHEN 'unassigned_script' THEN 'script'::JOB_KIND\n WHEN 'unassigned_flow' THEN 'flow'::JOB_KIND\n WHEN 'unassigned_singlestepflow' THEN 'singlestepflow'::JOB_KIND\n ELSE j.kind\n END\n FROM queued q WHERE j.id = q.id\n )\n SELECT count(*) AS \"count!\" FROM queued",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "count!",
"type_info": "Int8"
}
],
"parameters": {
"Left": [
"Text"
]
},
"nullable": [
null
]
},
"hash": "70aad8f4b2ff1cf780f215751b50a7a2714f534ccb75a04fd6280b0898c217e8"
}
@@ -0,0 +1,54 @@
{
"db_name": "PostgreSQL",
"query": "SELECT id FROM v2_job\n WHERE workspace_id = $1\n AND (kind = 'unassigned_script'::JOB_KIND OR kind = 'unassigned_flow'::JOB_KIND OR kind = 'unassigned_singlestepflow'::JOB_KIND)\n AND trigger_kind = $2\n AND trigger = $3\n AND NOT EXISTS (SELECT 1 FROM workspace_held_job h WHERE h.job_id = v2_job.id)\n AND id = ANY($4)",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Uuid"
}
],
"parameters": {
"Left": [
"Text",
{
"Custom": {
"name": "job_trigger_kind",
"kind": {
"Enum": [
"webhook",
"http",
"websocket",
"kafka",
"email",
"nats",
"schedule",
"app",
"ui",
"postgres",
"sqs",
"gcp",
"mqtt",
"nextcloud",
"google",
"ci_test",
"github",
"azure",
"asset",
"freshness",
"amqp"
]
}
}
},
"Text",
"UuidArray"
]
},
"nullable": [
false
]
},
"hash": "72cf330524f618ec25aa404bea9b484d94e5232681f1e2405dcf41b210f1d7dd"
}
@@ -0,0 +1,101 @@
{
"db_name": "PostgreSQL",
"query": "\n SELECT\n id,\n args as \"args: _\",\n created_at,\n kind AS \"kind: _\"\n FROM v2_job\n WHERE workspace_id = $1\n AND (\n kind = 'unassigned_script'::JOB_KIND OR\n kind = 'unassigned_flow'::JOB_KIND OR\n kind = 'unassigned_singlestepflow'::JOB_KIND\n )\n AND trigger_kind = $2\n AND trigger = $3\n AND NOT EXISTS (SELECT 1 FROM workspace_held_job h WHERE h.job_id = v2_job.id)\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Uuid"
},
{
"ordinal": 1,
"name": "args: _",
"type_info": "Jsonb"
},
{
"ordinal": 2,
"name": "created_at",
"type_info": "Timestamptz"
},
{
"ordinal": 3,
"name": "kind: _",
"type_info": {
"Custom": {
"name": "job_kind",
"kind": {
"Enum": [
"script",
"preview",
"flow",
"dependencies",
"flowpreview",
"script_hub",
"identity",
"flowdependencies",
"http",
"graphql",
"postgresql",
"noop",
"appdependencies",
"deploymentcallback",
"singlestepflow",
"flowscript",
"flownode",
"appscript",
"aiagent",
"unassigned_script",
"unassigned_flow",
"unassigned_singlestepflow"
]
}
}
}
}
],
"parameters": {
"Left": [
"Text",
{
"Custom": {
"name": "job_trigger_kind",
"kind": {
"Enum": [
"webhook",
"http",
"websocket",
"kafka",
"email",
"nats",
"schedule",
"app",
"ui",
"postgres",
"sqs",
"gcp",
"mqtt",
"nextcloud",
"google",
"ci_test",
"github",
"azure",
"asset",
"freshness",
"amqp"
]
}
}
},
"Text"
]
},
"nullable": [
false,
true,
false,
false
]
},
"hash": "7a5263f5c9b11b7b506d994247c657b279af8db3ac9769f9c2e241f90eda6d3e"
}
@@ -0,0 +1,16 @@
{
"db_name": "PostgreSQL",
"query": "INSERT INTO workspace_held_job (job_id, workspace_id, scheduled_for) VALUES ($1, $2, $3)",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Uuid",
"Varchar",
"Timestamptz"
]
},
"nullable": []
},
"hash": "a3753022fb0d88a3f8cb851de8bcaa5c8513bfab2d000f3531aec9456d5be020"
}
@@ -0,0 +1,14 @@
{
"db_name": "PostgreSQL",
"query": "DELETE FROM workspace_job_pause WHERE workspace_id = $1",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Text"
]
},
"nullable": []
},
"hash": "a67a6416939ef5001e0941c54ddfd786749c6b3580cf46a2ab7ed8ff754c4f1b"
}
@@ -0,0 +1,14 @@
{
"db_name": "PostgreSQL",
"query": "UPDATE workspace_held_job SET workspace_id = $1\n WHERE job_id IN (SELECT id FROM v2_job WHERE workspace_id = $1)",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Text"
]
},
"nullable": []
},
"hash": "c3dad628ba70d35c7255edfce64a3061f3bf3bf3bbb14a60dc3179a3f1788c05"
}
@@ -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 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"
}
@@ -0,0 +1,14 @@
{
"db_name": "PostgreSQL",
"query": "DELETE FROM workspace_job_pause WHERE workspace_id = $1 AND paused_until <= now()",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Text"
]
},
"nullable": []
},
"hash": "ce165e198c0fe474d3610c2a6bde63c867a1d4a16633b1645d77413aa4ecf002"
}
@@ -0,0 +1,20 @@
{
"db_name": "PostgreSQL",
"query": "SELECT workspace_id AS \"workspace_id!\" FROM workspace_job_pause WHERE paused_until <= now()\n UNION\n SELECT DISTINCT workspace_id FROM workspace_held_job h\n WHERE NOT EXISTS (SELECT 1 FROM workspace_job_pause p WHERE p.workspace_id = h.workspace_id)",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "workspace_id!",
"type_info": "Varchar"
}
],
"parameters": {
"Left": []
},
"nullable": [
null
]
},
"hash": "df40a8d02af6cf9857c033b25748eb0b7dbb70ae1f5bd31b8b05c5d9792d30c5"
}
@@ -0,0 +1,17 @@
{
"db_name": "PostgreSQL",
"query": "INSERT INTO workspace_job_pause (workspace_id, paused_until, paused_by, reason)\n VALUES ($1, $2, $3, $4)\n ON CONFLICT (workspace_id) DO UPDATE\n SET paused_until = EXCLUDED.paused_until, paused_by = EXCLUDED.paused_by,\n paused_at = now(), reason = EXCLUDED.reason",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Varchar",
"Timestamptz",
"Varchar",
"Text"
]
},
"nullable": []
},
"hash": "fc50d1b966f71f9c59d6faf44e1c2fa9b835042b9d31de0af87a48bb25804299"
}
+1 -1
View File
@@ -1 +1 @@
5cfc0dc6760ea7f631fc98ea1edd39adfc55bf11
b01587dedb195d0cafaa96514d152b0fce36fe1f
@@ -0,0 +1,4 @@
DROP TRIGGER IF EXISTS workspace_job_pause_change_trigger ON workspace_job_pause;
DROP FUNCTION IF EXISTS notify_workspace_job_pause_change();
DROP TABLE IF EXISTS workspace_held_job;
DROP TABLE IF EXISTS workspace_job_pause;
@@ -0,0 +1,41 @@
-- New top-level jobs of a workspace are held until `paused_until`. Runtime state, kept out of
-- workspace_settings so a settings push cannot clear it mid-deploy and a fork never starts paused.
-- A row past its deadline reads as not paused; the monitor deletes it and releases its jobs.
CREATE TABLE IF NOT EXISTS workspace_job_pause (
workspace_id VARCHAR(50) PRIMARY KEY REFERENCES workspace(id) ON DELETE CASCADE,
paused_until TIMESTAMPTZ NOT NULL,
paused_by VARCHAR(255) NOT NULL,
paused_at TIMESTAMPTZ NOT NULL DEFAULT now(),
reason TEXT
);
-- The jobs a workspace pause holds, as opposed to those a suspended trigger holds: both are queued
-- as `unassigned_*`. No foreign key to the queue, so completing or cancelling a job pays nothing
-- for it; a row whose job is gone is dropped when the jobs are released.
CREATE TABLE IF NOT EXISTS workspace_held_job (
job_id UUID PRIMARY KEY,
workspace_id VARCHAR(50) NOT NULL,
-- When the job was due before it was held: a schedule tick queued ahead of time keeps its time.
scheduled_for TIMESTAMPTZ NOT NULL
);
CREATE INDEX IF NOT EXISTS workspace_held_job_workspace_id_idx ON workspace_held_job (workspace_id);
GRANT ALL ON workspace_job_pause TO windmill_user;
GRANT ALL ON workspace_job_pause TO windmill_admin;
GRANT ALL ON workspace_held_job TO windmill_user;
GRANT ALL ON workspace_held_job TO windmill_admin;
CREATE OR REPLACE FUNCTION notify_workspace_job_pause_change()
RETURNS TRIGGER AS $$
BEGIN
INSERT INTO notify_event (channel, payload)
VALUES ('notify_workspace_job_pause_change', COALESCE(NEW.workspace_id, OLD.workspace_id));
RETURN NULL;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
DROP TRIGGER IF EXISTS workspace_job_pause_change_trigger ON workspace_job_pause;
CREATE TRIGGER workspace_job_pause_change_trigger
AFTER INSERT OR UPDATE OR DELETE ON workspace_job_pause
FOR EACH ROW
EXECUTE FUNCTION notify_workspace_job_pause_change();
+3
View File
@@ -1724,6 +1724,9 @@ async fn process_notify_event(
);
windmill_common::workspaces::TEAM_PLAN_CACHE.remove(payload);
}
windmill_common::job_pause::JOB_PAUSE_CHANGE_CHANNEL => {
windmill_common::job_pause::evict(payload);
}
"notify_workspace_rate_limit_change" => {
tracing::info!(
"Workspace rate limit change detected, invalidating rate limit cache: {}",
+11
View File
@@ -4467,6 +4467,16 @@ pub async fn monitor_db(
}
};
let resume_expired_job_pauses_f = async {
if server_mode && !initial_load {
if let Some(db) = conn.as_sql() {
if let Err(e) = windmill_common::job_pause::resume_expired(&db).await {
tracing::error!("Error resuming expired workspace job pauses: {e:#}");
}
}
}
};
// run every 30 iterations (~5min at the default LISTEN_NEW_EVENTS_INTERVAL_SEC).
let reconcile_unarmed_schedules_f = async {
if server_mode && iteration.is_some() && iteration.as_ref().unwrap().should_run(30) {
@@ -4629,6 +4639,7 @@ pub async fn monitor_db(
pipeline_freshness_watchdog_f,
reconcile_unarmed_schedules_f,
stranded_jobs_f,
resume_expired_job_pauses_f,
);
}
+128
View File
@@ -0,0 +1,128 @@
//! A workspace job pause holds new top-level jobs and the queued ones that have not started, and
//! resume releases exactly those: each when it was due, and not the jobs a suspended trigger holds.
use serde_json::json;
use sqlx::{Pool, Postgres};
use uuid::Uuid;
use windmill_test_utils::*;
const ADMIN: &str = "SECRET_TOKEN";
const MEMBER: &str = "SECRET_TOKEN_2";
async fn kind_and_due(db: &Pool<Postgres>, id: Uuid) -> (String, chrono::DateTime<chrono::Utc>) {
sqlx::query_as(
"SELECT j.kind::text, q.scheduled_for FROM v2_job j JOIN v2_job_queue q USING (id)
WHERE j.id = $1",
)
.bind(id)
.fetch_one(db)
.await
.unwrap()
}
#[sqlx::test(fixtures("base"))]
async fn pause_holds_and_resume_releases(db: Pool<Postgres>) -> anyhow::Result<()> {
initialize_tracing().await;
let server = ApiServer::start(db.clone()).await?;
let ws = format!(
"http://localhost:{}/api/w/test-workspace",
server.addr.port()
);
let http = reqwest::Client::new();
let post = |url: String, token: &str| http.post(url).bearer_auth(token);
let resp = post(format!("{ws}/scripts/create"), MEMBER)
.json(&json!({
"path": "u/test-user-2/s", "summary": "", "description": "",
"content": "echo hi", "language": "bash",
"schema": {"type": "object", "properties": {}, "required": []}
}))
.send()
.await?;
assert_eq!(resp.status(), 201, "{}", 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()
};
// Queued before the pause, due later: the pause holds it and resume keeps its time.
let due = chrono::Utc::now() + chrono::Duration::hours(1);
let scheduled = job_id(
run(
MEMBER,
&format!(
"?scheduled_for={}",
due.to_rfc3339_opts(chrono::SecondsFormat::Secs, true)
),
)
.send()
.await?,
)
.await;
// Held by a suspended trigger, not by the pause.
let suspended = job_id(run(MEMBER, "?suspended_mode=true").send().await?).await;
let resp = post(format!("{ws}/workspaces/pause_jobs"), MEMBER)
.json(&json!({"duration_s": 600}))
.send()
.await?;
assert_eq!(resp.status(), 403, "pausing is admin only");
let resp = post(format!("{ws}/workspaces/pause_jobs"), ADMIN)
.json(&json!({"duration_s": 600}))
.send()
.await?;
assert_eq!(resp.status(), 200, "{}", resp.text().await?);
assert_eq!(kind_and_due(&db, scheduled).await.0, "unassigned_script");
let held = job_id(run(MEMBER, "").send().await?).await;
assert_eq!(kind_and_due(&db, held).await.0, "unassigned_script");
// A member cannot step around the pause by naming a parent it does not own.
let forged = job_id(
run(MEMBER, &format!("?parent_job={}", Uuid::new_v4()))
.send()
.await?,
)
.await;
assert_eq!(kind_and_due(&db, forged).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");
// A caller waiting for the result is refused rather than left waiting.
let resp = post(
format!("{ws}/jobs/run_wait_result/p/u/test-user-2/s"),
MEMBER,
)
.json(&json!({}))
.send()
.await?;
assert_eq!(resp.status(), 503);
assert!(resp.headers().contains_key("retry-after"));
let resp = post(format!("{ws}/workspaces/resume_jobs"), ADMIN)
.send()
.await?;
assert_eq!(resp.status(), 200);
assert_eq!(resp.json::<i64>().await?, 3);
for id in [held, forged] {
let (kind, at) = kind_and_due(&db, id).await;
assert_eq!(kind, "script");
assert!(at <= chrono::Utc::now());
}
let (kind, at) = kind_and_due(&db, scheduled).await;
assert_eq!(kind, "script");
assert_eq!(
at.timestamp(),
due.timestamp(),
"a released job keeps when it was due"
);
assert_eq!(kind_and_due(&db, suspended).await.0, "unassigned_script");
Ok(())
}
+14 -11
View File
@@ -1174,17 +1174,20 @@ pub async fn run_flow_and_wait_result(
args: PushArgsOwned,
trigger: Option<TriggerMetadata>,
) -> error::Result<Response> {
let (uuid, early_return, has_failure_module, _) = run_flow(
authed,
db,
None,
user_db,
w_id,
flow_path,
flow_version_info,
run_query,
args,
trigger,
let (uuid, early_return, has_failure_module, _) = windmill_common::job_pause::with_policy(
windmill_common::job_pause::PausePolicy::Refuse,
run_flow(
authed,
db,
None,
user_db,
w_id,
flow_path,
flow_version_info,
run_query,
args,
trigger,
),
)
.await?;
@@ -37,6 +37,7 @@ use windmill_audit::ActionKind;
use windmill_common::datatable_roles::ADMIN_DATATABLE_ROLE;
use windmill_common::db::UserDB;
use windmill_common::error::{pg_error_message, Error, JsonResult, Result};
use windmill_common::job_pause::{with_policy, PausePolicy};
use windmill_common::jobs::{JobPayload, RawCode};
use windmill_common::query_builders::{render_db_quoted_identifier, DbType};
use windmill_common::runnable_settings::{ConcurrencySettingsWithCustom, DebouncingSettings};
@@ -258,50 +259,54 @@ async fn run_datatable_migration_job(
let push_args = PushArgs { extra: None, args: &args };
let scope_ceiling = windmill_api_auth::caller_scope_ceiling(db, authed).await?;
let (uuid, mut tx) = push(
db,
PushIsolationLevel::Isolated(user_db.clone(), authed.clone().into()),
w_id,
JobPayload::Code(RawCode {
content: sql.to_string(),
path: Some("datatable_migration".to_string()),
hash: None,
language: ScriptLang::Postgresql,
lock: None,
cache_ttl: None,
cache_ignore_s3_path: None,
dedicated_worker: None,
tag: None,
concurrency_settings: ConcurrencySettingsWithCustom::default(),
debouncing_settings: DebouncingSettings::default(),
modules: None,
}),
push_args,
authed.display_username(),
&authed.email,
username_to_permissioned_as(&authed.username),
authed.token_prefix.as_deref(),
authed.username_override.as_deref(),
None,
None,
None,
None,
None,
None,
false,
false,
None,
true,
None,
None,
None,
None,
Some(&authed.clone().into()),
false,
None,
None,
None,
scope_ceiling.as_deref(),
// Migrations are what a deploy pauses jobs for: they run while jobs are paused.
let (uuid, mut tx) = with_policy(
PausePolicy::Exempt,
push(
db,
PushIsolationLevel::Isolated(user_db.clone(), authed.clone().into()),
w_id,
JobPayload::Code(RawCode {
content: sql.to_string(),
path: Some("datatable_migration".to_string()),
hash: None,
language: ScriptLang::Postgresql,
lock: None,
cache_ttl: None,
cache_ignore_s3_path: None,
dedicated_worker: None,
tag: None,
concurrency_settings: ConcurrencySettingsWithCustom::default(),
debouncing_settings: DebouncingSettings::default(),
modules: None,
}),
push_args,
authed.display_username(),
&authed.email,
username_to_permissioned_as(&authed.username),
authed.token_prefix.as_deref(),
authed.username_override.as_deref(),
None,
None,
None,
None,
None,
None,
false,
false,
None,
true,
None,
None,
None,
None,
Some(&authed.clone().into()),
false,
None,
None,
None,
scope_ceiling.as_deref(),
),
)
.await?;
@@ -0,0 +1,171 @@
/*
* Author: Ruben Fiszel
* Copyright: Windmill Labs, Inc 2026
* This file and its contents are licensed under the AGPLv3 License.
* Please see the included NOTICE for copyright information and
* LICENSE-AGPL for a copy of the license.
*/
use axum::{
extract::{Extension, Path},
routing::{get, post},
Json, Router,
};
use chrono::{DateTime, Duration, Utc};
use serde::{Deserialize, Serialize};
use windmill_api_auth::ApiAuthed;
use windmill_audit::audit_oss::audit_log;
use windmill_audit::ActionKind;
use windmill_common::error::{Error, JsonResult};
use windmill_common::feature_usage::log_feature_usage;
use windmill_common::job_pause::{self, MAX_PAUSE_DAYS};
use windmill_common::utils::require_admin;
use windmill_common::DB;
pub(crate) fn routes() -> Router {
Router::new()
.route("/jobs_paused", get(get_jobs_paused))
.route("/pause_jobs", post(pause_jobs))
.route("/resume_jobs", post(resume_jobs))
}
#[derive(Serialize)]
struct JobsPaused {
paused_until: DateTime<Utc>,
paused_by: String,
paused_at: DateTime<Utc>,
reason: Option<String>,
held_count: i64,
}
async fn read_pause(db: &DB, w_id: &str) -> windmill_common::error::Result<Option<JobsPaused>> {
Ok(sqlx::query_as!(
JobsPaused,
r#"SELECT paused_until, paused_by, paused_at, reason,
(SELECT count(*) FROM workspace_held_job h WHERE h.workspace_id = p.workspace_id) AS "held_count!"
FROM workspace_job_pause p
WHERE workspace_id = $1 AND paused_until > now()"#,
w_id
)
.fetch_optional(db)
.await?)
}
async fn get_jobs_paused(
_authed: ApiAuthed,
Extension(db): Extension<DB>,
Path(w_id): Path<String>,
) -> JsonResult<Option<JobsPaused>> {
Ok(Json(read_pause(&db, &w_id).await?))
}
#[derive(Deserialize)]
struct PauseJobsRequest {
until: Option<DateTime<Utc>>,
duration_s: Option<i64>,
reason: Option<String>,
/// Where the pause was asked from, for telemetry only.
source: Option<String>,
}
async fn pause_jobs(
authed: ApiAuthed,
Extension(db): Extension<DB>,
Path(w_id): Path<String>,
Json(req): Json<PauseJobsRequest>,
) -> JsonResult<Option<JobsPaused>> {
require_admin(authed.is_admin, &authed.username)?;
let now = Utc::now();
let until = match (req.until, req.duration_s) {
(Some(until), None) => until,
(None, Some(secs)) if secs > 0 => now + Duration::seconds(secs),
_ => {
return Err(Error::BadRequest(
"give either `until` or a positive `duration_s`".to_string(),
))
}
};
if until <= now {
return Err(Error::BadRequest(
"`until` must be in the future".to_string(),
));
}
if until > now + Duration::days(MAX_PAUSE_DAYS) {
return Err(Error::BadRequest(format!(
"jobs cannot be paused for more than {MAX_PAUSE_DAYS} days"
)));
}
let mut tx = db.begin().await?;
sqlx::query!(
"INSERT INTO workspace_job_pause (workspace_id, paused_until, paused_by, reason)
VALUES ($1, $2, $3, $4)
ON CONFLICT (workspace_id) DO UPDATE
SET paused_until = EXCLUDED.paused_until, paused_by = EXCLUDED.paused_by,
paused_at = now(), reason = EXCLUDED.reason",
&w_id,
until,
&authed.username,
req.reason,
)
.execute(&mut *tx)
.await?;
let held = job_pause::hold_queued_jobs(&mut tx, &w_id).await?;
let until_s = until.to_rfc3339();
let held_s = held.to_string();
audit_log(
&mut *tx,
&authed,
"workspaces.pause_jobs",
ActionKind::Update,
&w_id,
None,
Some(
[
("until", until_s.as_str()),
("held_queued", held_s.as_str()),
]
.into(),
),
)
.await?;
tx.commit().await?;
job_pause::evict(&w_id);
let source = match req.source.as_deref() {
Some(s @ ("cli" | "ui" | "sdk")) => s,
_ => "api",
};
log_feature_usage("workspace_job_pause", "paused", source);
Ok(Json(read_pause(&db, &w_id).await?))
}
async fn resume_jobs(
authed: ApiAuthed,
Extension(db): Extension<DB>,
Path(w_id): Path<String>,
) -> JsonResult<i64> {
require_admin(authed.is_admin, &authed.username)?;
let mut tx = db.begin().await?;
let released = job_pause::resume(&mut tx, &w_id).await?;
let released_s = released.to_string();
audit_log(
&mut *tx,
&authed,
"workspaces.resume_jobs",
ActionKind::Update,
&w_id,
None,
Some([("released", released_s.as_str())].into()),
)
.await?;
tx.commit().await?;
job_pause::evict(&w_id);
log_feature_usage("workspace_job_pause", "resumed", "manual");
Ok(Json(released))
}
@@ -10,6 +10,7 @@ pub mod datatable_permissions;
pub mod datatable_permissions_oss;
pub mod datatable_replay_oss;
pub mod deployment_requests;
pub mod job_pause;
pub mod remote_deploy;
pub mod workspace_roles;
pub mod workspaces;
@@ -147,6 +147,7 @@ pub fn workspaced_service() -> Router {
get(test_datatable_connection),
)
.merge(crate::datatable_migrations::routes())
.merge(crate::job_pause::routes())
.merge(crate::datatable_permissions::routes())
.merge(crate::datatable_acl::routes())
.route("/git_sync_enabled", get(get_git_sync_enabled))
@@ -767,6 +767,25 @@ pub(crate) async fn change_workspace_id(
.execute(&mut *tx)
.await?;
info!("Moving the job pause and the jobs it holds");
sqlx::query!(
"INSERT INTO workspace_job_pause (workspace_id, paused_until, paused_by, paused_at, reason)
SELECT $1, paused_until, paused_by, paused_at, reason
FROM workspace_job_pause WHERE workspace_id = $2
ON CONFLICT (workspace_id) DO NOTHING",
&rw.new_id,
&old_id
)
.execute(&mut *tx)
.await?;
sqlx::query!(
"UPDATE workspace_held_job SET workspace_id = $1
WHERE job_id IN (SELECT id FROM v2_job WHERE workspace_id = $1)",
&rw.new_id
)
.execute(&mut *tx)
.await?;
info!("Updating raw_app table");
sqlx::query!(
"UPDATE raw_app SET workspace_id = $1 WHERE workspace_id = $2",
+99
View File
@@ -8688,6 +8688,82 @@ paths:
type: string
example: "Updated public app rate limit for workspace: workspace_id"
/w/{workspace}/workspaces/jobs_paused:
get:
summary: get whether new jobs of this workspace are paused
description: Returns null when new jobs are not paused.
operationId: getJobsPaused
tags:
- workspace
parameters:
- $ref: "#/components/parameters/WorkspaceId"
responses:
"200":
description: the current job pause, or null
content:
application/json:
schema:
$ref: "#/components/schemas/JobsPaused"
/w/{workspace}/workspaces/pause_jobs:
post:
summary: pause new jobs of this workspace
description: |
Until the deadline, new top-level jobs from triggers, schedules and async runs are held,
and queued jobs that have not started are held too. Callers waiting for a result (run and
wait, sync HTTP routes, apps) get a 503 with Retry-After. Dependency, git sync and
datatable migration jobs, steps of flows already running, and runs started directly by an
admin are not held. Pausing again moves the deadline. Admin only.
operationId: pauseJobs
tags:
- workspace
parameters:
- $ref: "#/components/parameters/WorkspaceId"
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
until:
type: string
format: date-time
description: when the pause ends. Give either this or duration_s, at most 7 days ahead.
duration_s:
type: integer
description: how long the pause lasts, in seconds
reason:
type: string
source:
type: string
enum: [cli, ui, sdk, api]
description: where the pause was asked from, for usage telemetry only
responses:
"200":
description: the job pause now in effect
content:
application/json:
schema:
$ref: "#/components/schemas/JobsPaused"
/w/{workspace}/workspaces/resume_jobs:
post:
summary: resume new jobs of this workspace
description: Ends the job pause and releases the jobs it held. Admin only.
operationId: resumeJobs
tags:
- workspace
parameters:
- $ref: "#/components/parameters/WorkspaceId"
responses:
"200":
description: the number of held jobs released
content:
application/json:
schema:
type: integer
/oauth/login_callback/{client_name}:
post:
security: []
@@ -37181,6 +37257,29 @@ components:
- imported_path
- count
JobsPaused:
type: object
nullable: true
properties:
paused_until:
type: string
format: date-time
paused_by:
type: string
paused_at:
type: string
format: date-time
reason:
type: string
held_count:
type: integer
description: jobs held by the pause, waiting to be released
required:
- paused_until
- paused_by
- paused_at
- held_count
WorkspaceInvite:
type: object
properties:
+40 -36
View File
@@ -5109,42 +5109,46 @@ async fn execute_component(
None => None,
};
let preview_obo_author = preview_obo.as_ref().and(opt_authed.clone());
let (uuid, mut tx) = push(
&db,
tx,
&w_id,
job_payload,
push_args,
&username,
email,
permissioned_as,
opt_authed
.and_then(|a| a.token_prefix)
.or_else(|| tokened.token.map(|t| t[0..TOKEN_PREFIX_LEN].to_string()))
.as_deref(),
// The caller of an app run is whoever used the app, which `push` already derives from
// `username` here — the app identity took `permissioned_as`.
None,
None,
None,
None,
None,
None,
job_id,
false,
false,
None,
true,
tag,
None,
None,
None,
None,
false,
end_user_email,
app_trigger,
None,
scope_ceiling.as_deref(),
// The app's viewer is waiting on the result: refuse rather than hold while jobs are paused.
let (uuid, mut tx) = windmill_common::job_pause::with_policy(
windmill_common::job_pause::PausePolicy::Refuse,
push(
&db,
tx,
&w_id,
job_payload,
push_args,
&username,
email,
permissioned_as,
opt_authed
.and_then(|a| a.token_prefix)
.or_else(|| tokened.token.map(|t| t[0..TOKEN_PREFIX_LEN].to_string()))
.as_deref(),
// The caller of an app run is whoever used the app, which `push` already derives from
// `username` here — the app identity took `permissioned_as`.
None,
None,
None,
None,
None,
None,
job_id,
false,
false,
None,
true,
tag,
None,
None,
None,
None,
false,
end_user_email,
app_trigger,
None,
scope_ceiling.as_deref(),
),
)
.await?;
+48 -44
View File
@@ -149,50 +149,54 @@ pub(crate) async fn bundle_raw_app_sources(
let tx = PushIsolationLevel::Isolated(user_db.clone(), authed.clone().into());
let scope_ceiling = windmill_api_auth::caller_scope_ceiling(db, authed).await?;
let (uuid, tx) = push(
db,
tx,
w_id,
JobPayload::Code(RawCode {
hash: None,
content: bundle_job_script(),
path: Some("bundle raw app".to_string()),
language: ScriptLang::Bun,
lock: None,
concurrency_settings: Default::default(),
debouncing_settings: Default::default(),
cache_ttl: None,
cache_ignore_s3_path: None,
dedicated_worker: None,
modules: None,
tag: None,
}),
PushArgs { args: &args, extra: None },
authed.display_username(),
&authed.email,
windmill_common::users::username_to_permissioned_as(&authed.username),
authed.token_prefix.as_deref(),
authed.username_override.as_deref(),
None,
None,
None,
None,
None,
None,
false,
false,
None,
true,
None,
Some(BUNDLE_TIMEOUT_SECS),
None,
None,
Some(&authed.clone().into()),
false,
None,
authed.trigger_or_fallback(None),
None,
scope_ceiling.as_deref(),
// Rebuilding a raw app is part of its deploy, which may be what jobs are paused for.
let (uuid, tx) = windmill_common::job_pause::with_policy(
windmill_common::job_pause::PausePolicy::Exempt,
push(
db,
tx,
w_id,
JobPayload::Code(RawCode {
hash: None,
content: bundle_job_script(),
path: Some("bundle raw app".to_string()),
language: ScriptLang::Bun,
lock: None,
concurrency_settings: Default::default(),
debouncing_settings: Default::default(),
cache_ttl: None,
cache_ignore_s3_path: None,
dedicated_worker: None,
modules: None,
tag: None,
}),
PushArgs { args: &args, extra: None },
authed.display_username(),
&authed.email,
windmill_common::users::username_to_permissioned_as(&authed.username),
authed.token_prefix.as_deref(),
authed.username_override.as_deref(),
None,
None,
None,
None,
None,
None,
false,
false,
None,
true,
None,
Some(BUNDLE_TIMEOUT_SECS),
None,
None,
Some(&authed.clone().into()),
false,
None,
authed.trigger_or_fallback(None),
None,
scope_ceiling.as_deref(),
),
)
.await?;
tx.commit().await?;
+195 -178
View File
@@ -34,6 +34,7 @@ use windmill_common::client::AuthedClient;
use windmill_common::db::UserDbWithAuthed;
use windmill_common::error::JsonResult;
use windmill_common::flow_status::{JobResult, RestartedFrom};
use windmill_common::job_pause::{with_policy, PausePolicy};
use windmill_common::jobs::{
format_completed_job_result, format_result, is_safe_log_file_path, is_valid_entrypoint_name,
DynamicInput, ENTRYPOINT_OVERRIDE,
@@ -8217,37 +8218,40 @@ pub async fn run_wait_result_job_by_path_get(
let end_user_email = run_end_user_email(&db, &w_id, &authed, None).await?;
let scope_ceiling = windmill_api_auth::caller_scope_ceiling(&db, &authed).await?;
let (uuid, tx) = push(
&db,
tx,
&w_id,
job_payload,
push_args,
authed.display_username(),
email,
permissioned_as,
authed.token_prefix.as_deref(),
authed.username_override.as_deref(),
None,
None,
run_query.parent_job,
None,
run_query.root_job,
run_query.job_id,
false,
false,
None,
!run_query.invisible_to_owner.unwrap_or(false),
tag,
timeout,
None,
None,
push_authed.as_ref(),
false,
end_user_email,
authed.trigger_or_fallback(None),
run_query.suspended_mode,
scope_ceiling.as_deref(),
let (uuid, tx) = with_policy(
PausePolicy::Refuse,
push(
&db,
tx,
&w_id,
job_payload,
push_args,
authed.display_username(),
email,
permissioned_as,
authed.token_prefix.as_deref(),
authed.username_override.as_deref(),
None,
None,
run_query.parent_job,
None,
run_query.root_job,
run_query.job_id,
false,
false,
None,
!run_query.invisible_to_owner.unwrap_or(false),
tag,
timeout,
None,
None,
push_authed.as_ref(),
false,
end_user_email,
authed.trigger_or_fallback(None),
run_query.suspended_mode,
scope_ceiling.as_deref(),
),
)
.await?;
tx.commit().await?;
@@ -8368,37 +8372,40 @@ pub async fn run_wait_result_script_by_path_internal(
let end_user_email = run_end_user_email(&db, &w_id, &authed, None).await?;
let scope_ceiling = windmill_api_auth::caller_scope_ceiling(&db, &authed).await?;
let (uuid, tx) = push(
&db,
tx,
&w_id,
job_payload,
push_args,
authed.display_username(),
email,
permissioned_as,
authed.token_prefix.as_deref(),
authed.username_override.as_deref(),
None,
None,
run_query.parent_job,
None,
run_query.root_job,
run_query.job_id,
false,
false,
None,
!run_query.invisible_to_owner.unwrap_or(false),
tag,
timeout,
None,
None,
push_authed.as_ref(),
false,
end_user_email,
authed.trigger_or_fallback(None),
run_query.suspended_mode,
scope_ceiling.as_deref(),
let (uuid, tx) = with_policy(
PausePolicy::Refuse,
push(
&db,
tx,
&w_id,
job_payload,
push_args,
authed.display_username(),
email,
permissioned_as,
authed.token_prefix.as_deref(),
authed.username_override.as_deref(),
None,
None,
run_query.parent_job,
None,
run_query.root_job,
run_query.job_id,
false,
false,
None,
!run_query.invisible_to_owner.unwrap_or(false),
tag,
timeout,
None,
None,
push_authed.as_ref(),
false,
end_user_email,
authed.trigger_or_fallback(None),
run_query.suspended_mode,
scope_ceiling.as_deref(),
),
)
.await?;
tx.commit().await?;
@@ -8487,51 +8494,54 @@ pub async fn run_wait_result_script_by_hash(
let end_user_email = run_end_user_email(&db, &w_id, &authed, None).await?;
let scope_ceiling = windmill_api_auth::caller_scope_ceiling(&db, &authed).await?;
let (uuid, tx) = push(
&db,
tx,
&w_id,
JobPayload::ScriptHash {
hash: ScriptHash(hash),
path: path,
concurrency_settings,
debouncing_settings,
cache_ttl,
cache_ignore_s3_path,
language,
dedicated_worker,
priority,
apply_preprocessor: !run_query.skip_preprocessor.unwrap_or(false)
&& has_preprocessor.unwrap_or(false),
labels,
job_token_scopes,
},
push_args,
authed.display_username(),
email,
permissioned_as,
authed.token_prefix.as_deref(),
authed.username_override.as_deref(),
None,
None,
run_query.parent_job,
None,
run_query.root_job,
run_query.job_id,
false,
false,
None,
!run_query.invisible_to_owner.unwrap_or(false),
tag,
timeout,
None,
None,
push_authed.as_ref(),
false,
end_user_email,
authed.trigger_or_fallback(None),
run_query.suspended_mode,
scope_ceiling.as_deref(),
let (uuid, tx) = with_policy(
PausePolicy::Refuse,
push(
&db,
tx,
&w_id,
JobPayload::ScriptHash {
hash: ScriptHash(hash),
path: path,
concurrency_settings,
debouncing_settings,
cache_ttl,
cache_ignore_s3_path,
language,
dedicated_worker,
priority,
apply_preprocessor: !run_query.skip_preprocessor.unwrap_or(false)
&& has_preprocessor.unwrap_or(false),
labels,
job_token_scopes,
},
push_args,
authed.display_username(),
email,
permissioned_as,
authed.token_prefix.as_deref(),
authed.username_override.as_deref(),
None,
None,
run_query.parent_job,
None,
run_query.root_job,
run_query.job_id,
false,
false,
None,
!run_query.invisible_to_owner.unwrap_or(false),
tag,
timeout,
None,
None,
push_authed.as_ref(),
false,
end_user_email,
authed.trigger_or_fallback(None),
run_query.suspended_mode,
scope_ceiling.as_deref(),
),
)
.await?;
tx.commit().await?;
@@ -8696,67 +8706,71 @@ pub async fn stream_job(
};
let poll_delay_ms = run_query.poll_delay_ms;
let (uuid, early_return, has_failure_module) = match runnable_id {
RunnableId::ScriptId(ScriptId::ScriptPath(script_path))
| RunnableId::HubScript(script_path) => {
let (uuid, _, _) = push_script_job_by_path_into_queue(
authed.clone(),
db.clone(),
None,
user_db,
w_id.clone(),
StripPath(script_path),
run_query,
args,
None,
)
.await?;
(uuid, None, false)
}
RunnableId::ScriptId(ScriptId::ScriptHash(script_hash)) => {
let (uuid, _, _) = run_job_by_hash_inner(
authed.clone(),
db.clone(),
user_db,
w_id.clone(),
script_hash,
run_query,
args,
None,
)
.await?;
(uuid, None, false)
}
RunnableId::FlowId(FlowId::FlowPath(flow_path)) => {
let (uuid, early_return, has_failure_module, _) = push_flow_job_by_path_into_queue(
authed.clone(),
db.clone(),
None,
user_db,
w_id.clone(),
StripPath(flow_path),
run_query,
args,
None,
)
.await?;
(uuid, early_return, has_failure_module)
}
RunnableId::FlowId(FlowId::FlowVersion(version)) => {
let (uuid, early_return, has_failure_module) = run_flow_by_version_inner(
authed.clone(),
db.clone(),
user_db,
w_id.clone(),
version,
run_query,
args,
None,
)
.await?;
(uuid, early_return, has_failure_module)
}
};
let (uuid, early_return, has_failure_module) = with_policy(PausePolicy::Refuse, async {
let pushed = match runnable_id {
RunnableId::ScriptId(ScriptId::ScriptPath(script_path))
| RunnableId::HubScript(script_path) => {
let (uuid, _, _) = push_script_job_by_path_into_queue(
authed.clone(),
db.clone(),
None,
user_db,
w_id.clone(),
StripPath(script_path),
run_query,
args,
None,
)
.await?;
(uuid, None, false)
}
RunnableId::ScriptId(ScriptId::ScriptHash(script_hash)) => {
let (uuid, _, _) = run_job_by_hash_inner(
authed.clone(),
db.clone(),
user_db,
w_id.clone(),
script_hash,
run_query,
args,
None,
)
.await?;
(uuid, None, false)
}
RunnableId::FlowId(FlowId::FlowPath(flow_path)) => {
let (uuid, early_return, has_failure_module, _) = push_flow_job_by_path_into_queue(
authed.clone(),
db.clone(),
None,
user_db,
w_id.clone(),
StripPath(flow_path),
run_query,
args,
None,
)
.await?;
(uuid, early_return, has_failure_module)
}
RunnableId::FlowId(FlowId::FlowVersion(version)) => {
let (uuid, early_return, has_failure_module) = run_flow_by_version_inner(
authed.clone(),
db.clone(),
user_db,
w_id.clone(),
version,
run_query,
args,
None,
)
.await?;
(uuid, early_return, has_failure_module)
}
};
Ok::<_, Error>(pushed)
})
.await?;
let opt_authed = Some(authed.clone());
let opt_tokened = OptTokened { token: None }; // ignored when authed is some
@@ -10528,16 +10542,19 @@ async fn run_dynamic_select(
);
let push_args = PushArgsOwned { extra: None, args: script_args };
let (uuid, _, _) = push_script_job_by_path_into_queue(
authed.clone(),
db.clone(),
None,
user_db.clone(),
w_id.clone(),
StripPath(path),
run_query.clone(),
push_args,
None,
let (uuid, _, _) = with_policy(
PausePolicy::Refuse,
push_script_job_by_path_into_queue(
authed.clone(),
db.clone(),
None,
user_db.clone(),
w_id.clone(),
StripPath(path),
run_query.clone(),
push_args,
None,
),
)
.await?;
@@ -22,6 +22,7 @@ use axum::{
use futures::StreamExt;
use http::{HeaderMap, StatusCode};
use std::{collections::HashMap, sync::Arc};
use windmill_common::job_pause::{with_policy, PausePolicy};
use windmill_common::{
db::UserDB,
error::{Error, Result},
@@ -798,22 +799,25 @@ async fn route_job(
match trigger.request_type {
RequestType::SyncSse => {
// Trigger the job (always async when streaming)
let (uuid, _, early_return, has_failure_module, _) = trigger_runnable_inner(
&db,
None,
Some(user_db.clone()),
authed.clone(),
&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),
None,
trigger_info,
None,
let (uuid, _, early_return, has_failure_module, _) = with_policy(
PausePolicy::Refuse,
trigger_runnable_inner(
&db,
None,
Some(user_db.clone()),
authed.clone(),
&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),
None,
trigger_info,
None,
),
)
.await
.map_err(|e| e.into_response())?;
@@ -880,19 +884,22 @@ async fn route_job(
)
.await
.map_err(|e| e.into_response()),
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,
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,
),
)
.await
.map_err(|e| e.into_response()),
+13 -4
View File
@@ -94,6 +94,8 @@ pub enum Error {
MigrationNeeded { version: String, feature: String, guide_url: url::Url },
#[error("{0} is unavailable. It is possible for this worker to be behind.")]
FeatureUnavailable(String),
#[error("New jobs of this workspace are paused until {}", .until.to_rfc3339())]
JobsPaused { until: chrono::DateTime<chrono::Utc> },
}
impl Error {
@@ -130,6 +132,7 @@ impl Error {
Self::NotAuthorized(_) => "NotAuthorized",
Self::MetricNotFound(_) => "MetricNotFound",
Self::PermissionDenied(_) => "PermissionDenied",
Self::JobsPaused { .. } => "JobsPaused",
_ => "InternalErr",
}
}
@@ -302,6 +305,7 @@ impl Error {
| Self::QuotaExceeded(_) => axum::http::StatusCode::BAD_REQUEST,
Self::BadGateway(_) => axum::http::StatusCode::BAD_GATEWAY,
Self::Generic(status_code, _) => *status_code,
Self::JobsPaused { .. } => axum::http::StatusCode::SERVICE_UNAVAILABLE,
_ => axum::http::StatusCode::INTERNAL_SERVER_ERROR,
}
}
@@ -319,17 +323,22 @@ impl IntoResponse for Error {
axum::http::StatusCode::NOT_FOUND | axum::http::StatusCode::CONFLICT
) {
tracing::warn!(message = e.to_string());
} else if matches!(e, Self::JobsPaused { .. }) {
tracing::info!(message = e.to_string());
} else {
tracing::error!(message = e.to_string(), error = ?e);
};
let body = Body::from(e.to_string());
axum::response::Response::builder()
let mut builder = axum::response::Response::builder()
.header("Content-Type", "text/plain")
.status(status)
.body(body)
.unwrap()
.status(status);
if let Self::JobsPaused { until } = e {
let secs = (*until - chrono::Utc::now()).num_seconds().max(1);
builder = builder.header("Retry-After", secs.to_string());
}
builder.body(body).unwrap()
}
}
+339
View File
@@ -0,0 +1,339 @@
/*
* Author: Ruben Fiszel
* Copyright: Windmill Labs, Inc 2026
* This file and its contents are licensed under the AGPLv3 License.
* Please see the included NOTICE for copyright information and
* LICENSE-AGPL for a copy of the license.
*/
//! Workspace job pause: while `workspace_job_pause.paused_until` is in the future, new top-level
//! jobs of the workspace are held as `unassigned_*` (recorded in `workspace_held_job`) or, when
//! their caller waits for the result, refused with [`Error::JobsPaused`].
use chrono::{DateTime, Utc};
use quick_cache::sync::Cache;
use sqlx::{Postgres, Transaction};
use crate::{
error::{Error, Result},
jobs::{JobKind, JobTriggerKind},
DB,
};
/// Longest pause accepted. Held jobs are queued 30 days out, and a worker fails an `unassigned_*`
/// job it reaches, so a pause must always end, and its jobs be released, well before that.
pub const MAX_PAUSE_DAYS: i64 = 7;
/// Short because agent workers push jobs and do not see `notify_event` evictions.
const CACHE_TTL_SECS: i64 = 10;
lazy_static::lazy_static! {
// Value: (paused_until, cached_at timestamp)
pub static ref JOB_PAUSE_CACHE: Cache<String, (Option<DateTime<Utc>>, i64)> = Cache::new(5000);
}
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>> {
let now = Utc::now();
let cached = JOB_PAUSE_CACHE
.get(w_id)
.filter(|(_, cached_at)| now.timestamp() - cached_at < CACHE_TTL_SECS);
let until = match cached {
Some((until, _)) => until,
None => match sqlx::query_scalar!(
"SELECT paused_until FROM workspace_job_pause WHERE workspace_id = $1",
w_id
)
.fetch_optional(db)
.await
{
Ok(until) => {
JOB_PAUSE_CACHE.insert(w_id.to_string(), (until, now.timestamp()));
until
}
Err(e) => {
tracing::error!("could not read the job pause of workspace {w_id}: {e:#}");
None
}
},
};
until.filter(|until| *until > now)
}
pub fn evict(w_id: &str) {
JOB_PAUSE_CACHE.remove(w_id);
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PauseDecision {
Run,
Hold,
Reject,
}
/// What a pause does to a job pushed with no parent. A job with a parent (flow step, a running
/// job's child, an error handler) always runs: the work it belongs to already started.
///
/// A direct run carries no trigger path: `trigger_or_fallback` stamps nothing for a session and
/// `webhook` for any token, while every trigger and schedule names itself. An admin's direct run
/// is not held, so an admin can run migrations and smoke tests during a deploy. An admin token
/// used by an external webhook looks the same and is not held either.
pub fn pause_decision(
kind: JobKind,
trigger_kind: Option<&JobTriggerKind>,
trigger_path: Option<&str>,
is_admin: bool,
) -> PauseDecision {
match kind {
JobKind::Dependencies
| JobKind::FlowDependencies
| JobKind::AppDependencies
| JobKind::DeploymentCallback
| JobKind::Identity
| JobKind::Noop
| JobKind::FlowScript
| JobKind::FlowNode
| JobKind::AIAgent
| JobKind::UnassignedScript
| JobKind::UnassignedFlow
| JobKind::UnassignedSinglestepFlow => return PauseDecision::Run,
_ => (),
}
let direct =
trigger_path.is_none() && matches!(trigger_kind, None | Some(JobTriggerKind::Webhook));
if direct && is_admin {
return PauseDecision::Run;
}
match kind {
JobKind::Script | JobKind::Flow | JobKind::SingleStepFlow => PauseDecision::Hold,
_ => PauseDecision::Reject,
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PausePolicy {
/// Part of a deploy or a migration: runs while paused.
Exempt,
/// The caller waits for the result, so a job that would be held is refused instead.
Refuse,
}
tokio::task_local! {
static PAUSE_POLICY: PausePolicy;
}
/// Run `f` with every job it pushes under `policy`. Task-locals do not cross `tokio::spawn`: the
/// push must happen on the task that entered the scope.
pub async fn with_policy<F: std::future::Future>(policy: PausePolicy, f: F) -> F::Output {
PAUSE_POLICY.scope(policy, f).await
}
pub fn current_policy() -> Option<PausePolicy> {
PAUSE_POLICY.try_with(|p| *p).ok()
}
/// 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,
w_id: &str,
kind: JobKind,
trigger_kind: Option<&JobTriggerKind>,
trigger_path: Option<&str>,
is_admin: bool,
) -> Result<Option<DateTime<Utc>>> {
let policy = current_policy();
if policy == Some(PausePolicy::Exempt) {
return Ok(None);
}
let Some(until) = jobs_paused_until(db, w_id).await else {
return Ok(None);
};
match pause_decision(kind, trigger_kind, trigger_path, is_admin) {
PauseDecision::Run => Ok(None),
PauseDecision::Hold if policy != Some(PausePolicy::Refuse) => Ok(Some(until)),
PauseDecision::Hold | PauseDecision::Reject => Err(Error::JobsPaused { until }),
}
}
/// 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.
pub async fn hold_queued_jobs(tx: &mut Transaction<'_, Postgres>, w_id: &str) -> Result<i64> {
let held = sqlx::query_scalar!(
r#"WITH candidates AS (
SELECT q.id, q.scheduled_for
FROM v2_job_queue q
JOIN v2_job j ON j.id = q.id
LEFT JOIN job_perms p ON p.job_id = q.id
WHERE q.workspace_id = $1
AND NOT q.running
AND j.parent_job IS NULL
AND j.kind IN ('script', 'flow', 'singlestepflow')
AND NOT (
COALESCE(p.is_admin, false)
AND j.trigger IS NULL
AND (j.trigger_kind IS NULL OR j.trigger_kind = 'webhook')
)
FOR UPDATE OF q SKIP LOCKED
),
held AS (
INSERT INTO workspace_held_job (job_id, workspace_id, scheduled_for)
SELECT id, $1, scheduled_for FROM candidates
ON CONFLICT (job_id) DO NOTHING
),
queued AS (
UPDATE v2_job_queue q SET scheduled_for = now() + interval '30 days'
FROM candidates c WHERE q.id = c.id
),
kinds AS (
UPDATE v2_job j SET kind = CASE j.kind
WHEN 'script' THEN 'unassigned_script'::JOB_KIND
WHEN 'flow' THEN 'unassigned_flow'::JOB_KIND
ELSE 'unassigned_singlestepflow'::JOB_KIND
END
FROM candidates c WHERE j.id = c.id
)
SELECT count(*) AS "count!" FROM candidates"#,
w_id
)
.fetch_one(&mut **tx)
.await?;
Ok(held)
}
/// 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> {
let released = sqlx::query_scalar!(
r#"WITH held AS (
DELETE FROM workspace_held_job WHERE workspace_id = $1
RETURNING job_id, scheduled_for
),
queued AS (
UPDATE v2_job_queue q SET scheduled_for = GREATEST(h.scheduled_for, now())
FROM held h
WHERE q.id = h.job_id AND NOT q.running
RETURNING q.id
),
kinds AS (
UPDATE v2_job j SET kind = CASE j.kind
WHEN 'unassigned_script' THEN 'script'::JOB_KIND
WHEN 'unassigned_flow' THEN 'flow'::JOB_KIND
WHEN 'unassigned_singlestepflow' THEN 'singlestepflow'::JOB_KIND
ELSE j.kind
END
FROM queued q WHERE j.id = q.id
)
SELECT count(*) AS "count!" FROM queued"#,
w_id
)
.fetch_one(&mut **tx)
.await?;
Ok(released)
}
/// Ends the pause of `w_id` and releases its jobs.
pub async fn resume(tx: &mut Transaction<'_, Postgres>, w_id: &str) -> Result<i64> {
sqlx::query!(
"DELETE FROM workspace_job_pause WHERE workspace_id = $1",
w_id
)
.execute(&mut **tx)
.await?;
release_held_jobs(tx, w_id).await
}
/// Ends every pause past its deadline and releases the jobs of workspaces that are no longer
/// paused. Safe to run on every server at once: each release deletes the rows it acts on.
pub async fn resume_expired(db: &DB) -> Result<()> {
let workspaces = sqlx::query_scalar!(
r#"SELECT workspace_id AS "workspace_id!" FROM workspace_job_pause WHERE paused_until <= now()
UNION
SELECT DISTINCT workspace_id FROM workspace_held_job h
WHERE NOT EXISTS (SELECT 1 FROM workspace_job_pause p WHERE p.workspace_id = h.workspace_id)"#
)
.fetch_all(db)
.await?;
for w_id in workspaces {
let mut tx = db.begin().await?;
let ended = sqlx::query!(
"DELETE FROM workspace_job_pause WHERE workspace_id = $1 AND paused_until <= now()",
&w_id
)
.execute(&mut *tx)
.await?
.rows_affected()
> 0;
let still_paused = sqlx::query_scalar!(
r#"SELECT EXISTS (SELECT 1 FROM workspace_job_pause WHERE workspace_id = $1) AS "exists!""#,
&w_id
)
.fetch_one(&mut *tx)
.await?;
if still_paused {
continue;
}
let released = release_held_jobs(&mut tx, &w_id).await?;
tx.commit().await?;
evict(&w_id);
if ended {
tracing::info!(
"job pause of workspace {w_id} reached its deadline, released {released} jobs"
);
crate::feature_usage::log_feature_usage("workspace_job_pause", "resumed", "deadline");
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn decisions() {
use PauseDecision::*;
let http = Some(&JobTriggerKind::Http);
let webhook = Some(&JobTriggerKind::Webhook);
let schedule = Some(&JobTriggerKind::Schedule);
assert_eq!(
pause_decision(JobKind::Dependencies, None, None, false),
Run
);
assert_eq!(
pause_decision(JobKind::DeploymentCallback, None, None, false),
Run
);
assert_eq!(pause_decision(JobKind::Script, None, None, true), Run);
assert_eq!(pause_decision(JobKind::Flow, webhook, None, true), Run);
assert_eq!(pause_decision(JobKind::Preview, None, None, true), Run);
// Triggers and schedules run as their owner, who may be an admin.
assert_eq!(
pause_decision(JobKind::Script, http, Some("f/h"), true),
Hold
);
assert_eq!(
pause_decision(JobKind::Flow, schedule, Some("f/s"), true),
Hold
);
assert_eq!(pause_decision(JobKind::Script, webhook, None, false), Hold);
assert_eq!(
pause_decision(JobKind::SingleStepFlow, http, Some("f/h"), false),
Hold
);
assert_eq!(pause_decision(JobKind::Preview, None, None, false), Reject);
assert_eq!(
pause_decision(
JobKind::AppScript,
Some(&JobTriggerKind::App),
Some("f/a"),
true
),
Reject
);
}
}
+1
View File
@@ -82,6 +82,7 @@ pub mod hub_resource_types;
pub mod indexer;
pub mod instance_config;
pub mod job_metrics;
pub mod job_pause;
pub mod log_context;
pub mod materialization;
pub mod min_version;
+32
View File
@@ -7669,6 +7669,27 @@ async fn push_inner<'c, 'd>(
root_job
};
// 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,
workspace_id,
job_kind,
trigger_kind.as_ref(),
trigger_path.as_ref().and_then(|p| p.as_deref()),
job_authed.is_admin,
)
.await?
.map(|_| scheduled_for_o.unwrap_or_else(Utc::now))
} else {
None
};
let suspended_mode = if held_by_pause.is_some() {
Some(true)
} else {
suspended_mode
};
let (job_kind, scheduled_for_o) = if suspended_mode.unwrap_or(false) {
let unassigned_job_kind = match job_kind {
JobKind::Script => JobKind::UnassignedScript,
@@ -7816,6 +7837,17 @@ async fn push_inner<'c, 'd>(
.warn_after_seconds(1)
.await?;
if let Some(due) = held_by_pause {
sqlx::query!(
"INSERT INTO workspace_held_job (job_id, workspace_id, scheduled_for) VALUES ($1, $2, $3)",
job_id,
workspace_id,
due,
)
.execute(&mut *tx)
.await?;
}
// RunnableSettings::insert(RunnableType::Job)
// tracing::debug!("Pushing job {job_id} with tag {tag}, schedule_path {schedule_path:?}, script_path: {script_path:?}, email {email}, workspace_id {workspace_id}");
@@ -132,6 +132,7 @@ pub async fn resume_suspended_trigger_jobs(
)
AND trigger_kind = $2
AND trigger = $3
AND NOT EXISTS (SELECT 1 FROM workspace_held_job h WHERE h.job_id = v2_job.id)
AND id = ANY($4)
"#,
w_id,
@@ -160,6 +161,7 @@ pub async fn resume_suspended_trigger_jobs(
)
AND trigger_kind = $2
AND trigger = $3
AND NOT EXISTS (SELECT 1 FROM workspace_held_job h WHERE h.job_id = v2_job.id)
"#,
w_id,
trigger_kind as _,
@@ -310,6 +312,7 @@ pub async fn cancel_suspended_trigger_jobs(
AND (kind = 'unassigned_script'::JOB_KIND OR kind = 'unassigned_flow'::JOB_KIND OR kind = 'unassigned_singlestepflow'::JOB_KIND)
AND trigger_kind = $2
AND trigger = $3
AND NOT EXISTS (SELECT 1 FROM workspace_held_job h WHERE h.job_id = v2_job.id)
AND id = ANY($4)",
w_id,
trigger_kind as _,
@@ -325,7 +328,8 @@ pub async fn cancel_suspended_trigger_jobs(
WHERE workspace_id = $1
AND (kind = 'unassigned_script'::JOB_KIND OR kind = 'unassigned_flow'::JOB_KIND OR kind = 'unassigned_singlestepflow'::JOB_KIND)
AND trigger_kind = $2
AND trigger = $3",
AND trigger = $3
AND NOT EXISTS (SELECT 1 FROM workspace_held_job h WHERE h.job_id = v2_job.id)",
w_id,
trigger_kind as _,
trigger_path,
+1 -1
View File
@@ -4898,7 +4898,7 @@ pub async fn handle_queued_job(
match job.kind {
JobKind::UnassignedScript | JobKind::UnassignedFlow | JobKind::UnassignedSinglestepFlow => {
return Err(Error::ExecutionErr("Suspended job was not handled by the user within 30 days, job will not be executed.".to_string()));
return Err(Error::ExecutionErr("Suspended job (held by a suspended trigger or a workspace job pause) was not released within 30 days, job will not be executed.".to_string()));
}
_ => {}
}
+56
View File
@@ -64,6 +64,13 @@ import {
} from "../script/script.ts";
import { DbtPathCollisionError, handleFile } from "../script/script.ts";
import {
DEFAULT_PAUSE_DURATION,
parseDuration,
pauseWorkspaceJobs,
resumeWorkspaceJobs,
waitForDependencyJobs,
} from "../workspace/jobsPause.ts";
import {
deepEqual,
fetchRemoteVersion,
@@ -4876,6 +4883,8 @@ export async function push(
branch?: string;
keepDeleted?: boolean;
acceptOverridingPermissionedAsWithSelf?: boolean;
pauseJobs?: boolean | string;
keepPaused?: boolean;
},
) {
if ((opts as any).jsonOutput) log.setSilent(true);
@@ -5830,6 +5839,15 @@ export async function push(
const start = performance.now();
const pushStartedAt = new Date().toISOString();
const jobsPause = opts.pauseJobs
? await pauseWorkspaceJobs(
workspace.workspaceId,
parseDuration(
opts.pauseJobs === true ? DEFAULT_PAUSE_DURATION : opts.pauseJobs,
),
"wmill sync push",
)
: undefined;
log.info(colors.gray(`Applying changes to files ...`));
let stateful = opts.stateful;
@@ -6784,11 +6802,40 @@ export async function push(
);
}
}
let jobsResumed = false;
if (jobsPause) {
const depsDone = await waitForDependencyJobs(
workspace.workspaceId,
pushStartedAt,
new Date(jobsPause.paused_until),
);
if (opts.keepPaused) {
log.info(
colors.yellow(
`Jobs stay paused until ${jobsPause.paused_until} (--keep-paused). Run 'wmill workspace resume-jobs' when ready.`,
),
);
} else if (failedChanges.length > 0 || !depsDone) {
log.warn(
`Jobs stay paused until ${jobsPause.paused_until} because ` +
(failedChanges.length > 0
? "some changes failed to push"
: "dependency jobs are still running") +
". Run 'wmill workspace resume-jobs' once the workspace is consistent.",
);
} else {
await resumeWorkspaceJobs(workspace.workspaceId);
jobsResumed = true;
}
}
const pushedCount = changes.length - failedChanges.length;
if (opts.jsonOutput) {
const result = {
success: failedChanges.length === 0,
lock_jobs: lockJobs,
...(jobsPause
? { jobs_paused_until: jobsResumed ? null : jobsPause.paused_until }
: {}),
...(failedChanges.length > 0 ? { failed: failedChanges } : {}),
message:
failedChanges.length > 0
@@ -7030,6 +7077,15 @@ const command = new Command()
"Include a message that will be added to all scripts/flows/apps updated during this push",
)
.option("--parallel <number>", "Number of changes to process in parallel")
.option(
"--pause-jobs [duration:string]",
"Pause new jobs of the workspace while pushing (default 30m, at most 7d): triggers, schedules and async runs are held, then released once the dependency jobs of the push finish. Admin only",
)
.option(
"--keep-paused",
"With --pause-jobs, leave jobs paused after the push (e.g. to run migrations first); resume with 'wmill workspace resume-jobs'",
{ depends: ["pause-jobs"] },
)
.option(
"--repository <repo:string>",
"Specify repository path (e.g., u/user/repo) when multiple repositories exist",
+121
View File
@@ -0,0 +1,121 @@
import { colors } from "@cliffy/ansi/colors";
import { GlobalOptions } from "../../types.ts";
import * as log from "../../core/log.ts";
import { requireLogin } from "../../core/auth.ts";
import { resolveWorkspace } from "../../core/context.ts";
import { getHeaders } from "../../utils/utils.ts";
import * as wmill from "../../../gen/services.gen.ts";
export const DEFAULT_PAUSE_DURATION = "30m";
const UNIT_SECONDS: Record<string, number> = { s: 1, m: 60, h: 3600, d: 86400 };
/** `90s`, `30m`, `2h`, `1d` or a bare number of seconds. */
export function parseDuration(value: string): number {
const m = /^\s*(\d+)\s*([smhd]?)\s*$/.exec(value);
if (!m || Number(m[1]) <= 0) {
throw new Error(
`Invalid duration "${value}": expected a positive number followed by s, m, h or d (e.g. 30m)`,
);
}
return Number(m[1]) * UNIT_SECONDS[m[2] || "s"];
}
export async function pauseWorkspaceJobs(
workspaceId: string,
durationS: number,
reason?: string,
) {
const pause = await wmill.pauseJobs({
workspace: workspaceId,
requestBody: { duration_s: durationS, reason, source: "cli" },
});
log.info(
colors.yellow(
`New jobs of ${workspaceId} are paused until ${pause?.paused_until}` +
(pause?.held_count ? ` (${pause.held_count} queued jobs held)` : ""),
),
);
return pause;
}
export async function resumeWorkspaceJobs(workspaceId: string) {
const released = await wmill.resumeJobs({ workspace: workspaceId });
log.info(
colors.green(
`Jobs of ${workspaceId} resumed, ${released} held job${released === 1 ? "" : "s"} released`,
),
);
return released;
}
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.
*/
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.
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, {
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;
if (!announced) {
log.info(
colors.gray(
`Waiting for ${queued.length} dependency job(s) to finish before resuming jobs ...`,
),
);
announced = true;
}
await new Promise((r) => setTimeout(r, 2000));
}
}
export async function pauseJobsCommand(
opts: GlobalOptions & { for?: string; reason?: string },
) {
await requireLogin(opts);
const workspace = await resolveWorkspace(opts);
await pauseWorkspaceJobs(
workspace.workspaceId,
parseDuration(opts.for ?? DEFAULT_PAUSE_DURATION),
opts.reason,
);
}
export async function resumeJobsCommand(opts: GlobalOptions) {
await requireLogin(opts);
const workspace = await resolveWorkspace(opts);
await resumeWorkspaceJobs(workspace.workspaceId);
}
export async function jobsPausedCommand(opts: GlobalOptions & { json?: boolean }) {
await requireLogin(opts);
const workspace = await resolveWorkspace(opts);
const pause = await wmill.getJobsPaused({ workspace: workspace.workspaceId });
if (opts.json) {
console.log(JSON.stringify(pause, null, 2));
} else if (!pause) {
log.info("New jobs are not paused");
} else {
log.info(
`New jobs are paused until ${pause.paused_until} by ${pause.paused_by}, ${pause.held_count} held` +
(pause.reason ? ` (${pause.reason})` : ""),
);
}
}
+21 -1
View File
@@ -19,6 +19,12 @@ import { createWorkspaceFork, deleteWorkspaceFork } from "./fork.ts";
import { mergeWorkspaces } from "./merge.ts";
import { connectSlack, disconnectSlack } from "./slack.ts";
import { applySettings, getSettings } from "./settings.ts";
import {
DEFAULT_PAUSE_DURATION,
jobsPausedCommand,
pauseJobsCommand,
resumeJobsCommand,
} from "./jobsPause.ts";
import * as wmill from "../../../gen/services.gen.ts";
@@ -922,6 +928,20 @@ Arguments (omit both to be prompted interactively):
.option("--dry-run", "Only show the changes")
.option("--replace", "Also clear the settings the file omits, as 'wmill sync push' does")
.option("-y --yes", "Apply without asking")
.action(applySettings as any);
.action(applySettings as any)
.command("pause-jobs")
.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("--reason <reason:string>", "Shown to users of the workspace while paused")
.action(pauseJobsCommand as any)
.command("resume-jobs")
.description("Resume new jobs of the active workspace and release the jobs the pause held. Admin only.")
.action(resumeJobsCommand as any)
.command("jobs-paused")
.description("Show whether new jobs of the active workspace are paused")
.option("--json", "Output as JSON")
.action(jobsPausedCommand as any);
export default command;
+82
View File
@@ -705,6 +705,24 @@ async getResource(path?: string, undefinedIfEmpty?: boolean): Promise<any>
*/
async getRootJobId(jobId?: string): Promise<string>
/**
* Pause new jobs of the current workspace, e.g. while a flow runs migrations. Jobs from triggers,
* schedules and async runs are held until {@link resumeWorkspaceJobs} or the end of the pause;
* callers waiting for a result get a 503. The steps of the calling flow, and runs started directly
* by an admin, keep running. Requires the job to run as a workspace admin.
* @param durationS how long the pause lasts at most, in seconds (at most 7 days)
* @param reason shown to users of the workspace while paused
* @returns the pause now in effect
*/
async pauseWorkspaceJobs(durationS: number, reason?: string): Promise<JobsPaused>
/**
* Resume new jobs of the current workspace and release the jobs the pause held.
* Requires the job to run as a workspace admin.
* @returns the number of held jobs released
*/
async resumeWorkspaceJobs(): Promise<number>
/**
* Run a script synchronously by its path and wait for the result
* @param path - Script path in Windmill
@@ -1554,6 +1572,24 @@ async getResource(path?: string, undefinedIfEmpty?: boolean): Promise<any>
*/
async getRootJobId(jobId?: string): Promise<string>
/**
* Pause new jobs of the current workspace, e.g. while a flow runs migrations. Jobs from triggers,
* schedules and async runs are held until {@link resumeWorkspaceJobs} or the end of the pause;
* callers waiting for a result get a 503. The steps of the calling flow, and runs started directly
* by an admin, keep running. Requires the job to run as a workspace admin.
* @param durationS how long the pause lasts at most, in seconds (at most 7 days)
* @param reason shown to users of the workspace while paused
* @returns the pause now in effect
*/
async pauseWorkspaceJobs(durationS: number, reason?: string): Promise<JobsPaused>
/**
* Resume new jobs of the current workspace and release the jobs the pause held.
* Requires the job to run as a workspace admin.
* @returns the number of held jobs released
*/
async resumeWorkspaceJobs(): Promise<number>
/**
* Run a script synchronously by its path and wait for the result
* @param path - Script path in Windmill
@@ -2512,6 +2548,24 @@ async getResource(path?: string, undefinedIfEmpty?: boolean): Promise<any>
*/
async getRootJobId(jobId?: string): Promise<string>
/**
* Pause new jobs of the current workspace, e.g. while a flow runs migrations. Jobs from triggers,
* schedules and async runs are held until {@link resumeWorkspaceJobs} or the end of the pause;
* callers waiting for a result get a 503. The steps of the calling flow, and runs started directly
* by an admin, keep running. Requires the job to run as a workspace admin.
* @param durationS how long the pause lasts at most, in seconds (at most 7 days)
* @param reason shown to users of the workspace while paused
* @returns the pause now in effect
*/
async pauseWorkspaceJobs(durationS: number, reason?: string): Promise<JobsPaused>
/**
* Resume new jobs of the current workspace and release the jobs the pause held.
* Requires the job to run as a workspace admin.
* @returns the number of held jobs released
*/
async resumeWorkspaceJobs(): Promise<number>
/**
* Run a script synchronously by its path and wait for the result
* @param path - Script path in Windmill
@@ -4598,6 +4652,26 @@ def get_job(job_id: str) -> dict
# Root job ID
def get_root_job_id(job_id: str | None = None) -> dict
# Pause new jobs of the workspace, e.g. while a flow runs migrations.
#
# Jobs from triggers, schedules and async runs are held until resume_workspace_jobs or
# the end of the pause; callers waiting for a result get a 503. The steps of the calling
# flow, and runs started directly by an admin, keep running. Requires a workspace admin.
#
# Args:
# duration_s: How long the pause lasts at most, in seconds (at most 7 days)
# reason: Shown to users of the workspace while paused
#
# Returns:
# The pause now in effect
def pause_workspace_jobs(duration_s: int, reason: str | None = None) -> dict
# Resume new jobs of the workspace and release the jobs the pause held.
#
# Returns:
# The number of held jobs released
def resume_workspace_jobs() -> int
# Get an OIDC JWT token for authentication to external services.
#
# Args:
@@ -9073,6 +9147,8 @@ sync local with a remote workspaces or the opposite (push or pull)
- \`--extra-includes <patterns:file[]>\` - Comma separated patterns to specify which file to take into account (among files that are compatible with windmill). Patterns can include * (any string until '/') and ** (any string). Useful to still take wmill.yaml into account and act as a second pattern to satisfy
- \`--message <message:string>\` - Include a message that will be added to all scripts/flows/apps updated during this push
- \`--parallel <number>\` - Number of changes to process in parallel
- \`--pause-jobs [duration:string]\` - Pause new jobs of the workspace while pushing (default 30m, at most 7d): triggers, schedules and async runs are held, then released once the dependency jobs of the push finish. Admin only
- \`--keep-paused\` - With --pause-jobs, leave jobs paused after the push (e.g. to run migrations first); resume with 'wmill workspace resume-jobs'
- \`--repository <repo:string>\` - Specify repository path (e.g., u/user/repo) when multiple repositories exist
- \`--branch, --env <branch:string>\` - [Deprecated: use --workspace] Override the current git branch/environment
- \`--lint\` - Run lint validation before pushing
@@ -9263,6 +9339,12 @@ Arguments (omit both to be prompted interactively):
- \`--dry-run\` - Only show the changes
- \`--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)
- \`--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
- \`--json\` - Output as JSON
+42
View File
@@ -0,0 +1,42 @@
# Workspace job pause
A workspace admin can pause new jobs of a workspace until a deadline (`workspace_job_pause`),
typically around a deploy: `wmill sync push --pause-jobs`, `wmill workspace pause-jobs`, the
General tab of workspace settings, or `pauseWorkspaceJobs` / `pause_workspace_jobs` from a flow.
## What a pause does to a pushed job
`push_inner` asks `windmill_common::job_pause::check_push` about every job pushed with no parent:
- **Runs**: dependency, flow/app dependency, git sync (`deploymentcallback`) jobs; runs started
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.
- **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.
- **Refused** (`Error::JobsPaused`, 503 + `Retry-After`): any other kind (previews, app inline
scripts), and anything pushed under `PausePolicy::Refuse`.
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
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.
## Invariants
- `workspace_held_job` is what tells a pause-held job from one a suspended trigger holds; both are
`unassigned_*` with the same trigger columns. Trigger resume/cancel exclude the held rows, and
pause resume releases only them.
- Pausing also holds the workspace's queued jobs that have not started (`hold_queued_jobs`): a
schedule's next run is queued ahead of time and would otherwise run mid-deploy. Release sets
`scheduled_for = GREATEST(held due time, now())`, so that run keeps its slot.
- The pause is runtime state: it is not in the settings document (a settings push must not clear
it, a fork must not start paused) and is read through a 10s cache evicted by `notify_event`.
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.
- Held jobs run the version they were pushed with; resume does not re-resolve them to the latest
deployed version.
@@ -0,0 +1,66 @@
<script lang="ts">
import { Button } from '$lib/components/common'
import { classes as alertClasses, icons as alertIcons } from '$lib/components/common/alert/model'
import { WorkspaceService } from '$lib/gen'
import { userStore, workspaceStore } from '$lib/stores'
import { sendUserToast } from '$lib/toast'
import { displayDate } from '$lib/utils'
import { jobsPause } from './jobsPause.svelte'
import { untrack } from 'svelte'
// A pause can be started from the CLI or a flow, so the banner polls rather than waiting
// for this tab to change it.
const POLL_MS = 30_000
$effect(() => {
const workspace = $workspaceStore
if (!workspace) return
// `load` reads and writes the shared state; only the workspace should re-run this effect.
untrack(() => jobsPause.load(workspace))
const interval = setInterval(() => jobsPause.load(workspace), POLL_MS)
return () => clearInterval(interval)
})
let resuming = $state(false)
async function resume() {
const workspace = $workspaceStore
if (!workspace) return
resuming = true
try {
const released = await WorkspaceService.resumeJobs({ workspace })
jobsPause.set(workspace, null)
sendUserToast(`Jobs resumed, ${released} held job${released === 1 ? '' : 's'} released`)
} catch (e) {
sendUserToast(`Could not resume jobs: ${e?.body ?? e}`, true)
} finally {
resuming = false
}
}
let pause = $derived(jobsPause.workspace === $workspaceStore ? jobsPause.pause : null)
const palette = alertClasses.warning
const Icon = alertIcons.warning
</script>
{#if pause}
<div
class="shrink-0 px-4 py-1.5 flex items-center justify-center gap-x-3 gap-y-1 flex-wrap {palette.bgClass}"
role="status"
>
<Icon size={16} class="shrink-0 {palette.iconClass}" />
<span class="text-xs font-medium {palette.titleClass}">
New jobs are paused until {displayDate(pause.paused_until)}
{#if pause.held_count > 0}
· {pause.held_count} held
{/if}
{#if pause.reason}
· {pause.reason}
{/if}
</span>
{#if $userStore?.is_admin || $userStore?.is_super_admin}
<Button variant="subtle" unifiedSize="xs" loading={resuming} onclick={resume}>
Resume jobs
</Button>
{/if}
</div>
{/if}
@@ -0,0 +1,95 @@
<script lang="ts">
import { workspaceStore } from '$lib/stores'
import Button from '../common/button/Button.svelte'
import TextInput from '../text_input/TextInput.svelte'
import Select from '../select/Select.svelte'
import { sendUserToast } from '$lib/toast'
import { WorkspaceService } from '$lib/gen'
import { displayDate } from '$lib/utils'
import { jobsPause } from './jobsPause.svelte'
const durations = [
{ label: '15 minutes', value: 15 * 60 },
{ label: '30 minutes', value: 30 * 60 },
{ label: '1 hour', value: 60 * 60 },
{ label: '2 hours', value: 2 * 60 * 60 },
{ label: '6 hours', value: 6 * 60 * 60 },
{ label: '1 day', value: 24 * 60 * 60 },
{ label: '7 days', value: 7 * 24 * 60 * 60 }
]
let durationS = $state(30 * 60)
let reason = $state('')
let busy = $state(false)
let pause = $derived(jobsPause.workspace === $workspaceStore ? jobsPause.pause : null)
async function pauseJobs() {
const workspace = $workspaceStore
if (!workspace) return
busy = true
try {
const p = await WorkspaceService.pauseJobs({
workspace,
requestBody: { duration_s: durationS, reason: reason || undefined, source: 'ui' }
})
jobsPause.set(workspace, p)
sendUserToast('New jobs are paused')
} catch (e) {
sendUserToast(`Could not pause jobs: ${e?.body ?? e}`, true)
} finally {
busy = false
}
}
async function resumeJobs() {
const workspace = $workspaceStore
if (!workspace) return
busy = true
try {
const released = await WorkspaceService.resumeJobs({ workspace })
jobsPause.set(workspace, null)
sendUserToast(`Jobs resumed, ${released} held job${released === 1 ? '' : 's'} released`)
} catch (e) {
sendUserToast(`Could not resume jobs: ${e?.body ?? e}`, true)
} finally {
busy = false
}
}
</script>
<div class="flex flex-col gap-1">
<p class="font-semibold text-xs text-emphasis">Pause new jobs</p>
<p class="text-xs text-secondary font-normal max-w-2xl">
Hold the jobs that triggers, schedules and webhooks start, for example while a deploy installs
dependencies or migrations are pending. Held jobs run when jobs resume, at the latest when the
pause ends. Callers waiting for a result, such as apps and synchronous routes, get an error
instead. Dependency and git sync jobs, steps of flows already running and runs started by an
admin are not held.
</p>
{#if pause}
<div class="flex flex-row gap-2 items-center mt-1">
<span class="text-xs text-primary">
Paused until {displayDate(pause.paused_until)} by {pause.paused_by}, {pause.held_count}
held job{pause.held_count === 1 ? '' : 's'}
{#if pause.reason}({pause.reason}){/if}
</span>
<Button variant="accent" unifiedSize="sm" loading={busy} onclick={resumeJobs}>
Resume jobs
</Button>
</div>
{:else}
<div class="flex flex-row gap-2 items-center mt-1 flex-wrap">
<Select items={durations} bind:value={durationS} size="sm" class="w-36" />
<TextInput
bind:value={reason}
size="sm"
class="max-w-xs"
inputProps={{ placeholder: 'Reason (optional)', 'aria-label': 'Pause reason' }}
/>
<Button variant="default" unifiedSize="sm" loading={busy} onclick={pauseJobs}>
Pause jobs
</Button>
</div>
{/if}
</div>
@@ -0,0 +1,30 @@
import { WorkspaceService, type JobsPaused } from '$lib/gen'
/** The job pause of the workspace in view, shared by the banner and the workspace settings. */
class JobsPauseState {
pause = $state<JobsPaused>(null)
workspace = $state<string | undefined>(undefined)
async load(workspace: string) {
if (this.workspace !== workspace) {
this.workspace = workspace
this.pause = null
}
try {
const pause = await WorkspaceService.getJobsPaused({ workspace })
// A reply for a workspace the user already left must not overwrite the current one.
if (this.workspace === workspace) {
this.pause = pause
}
} catch (e) {
console.error('Could not read whether jobs are paused', e)
}
}
set(workspace: string, pause: JobsPaused) {
this.workspace = workspace
this.pause = pause
}
}
export const jobsPause = new JobsPauseState()
@@ -105,6 +105,7 @@
import { pruneMeaninglessDrafts } from '$lib/userDraftPrune'
import DraftMigrationErrorModal from '$lib/components/DraftMigrationErrorModal.svelte'
import InstanceBanner from '$lib/components/InstanceBanner.svelte'
import JobsPausedBanner from '$lib/components/jobsPause/JobsPausedBanner.svelte'
import InstanceUiSync from '$lib/components/InstanceUiSync.svelte'
import { onDestroy, setContext, untrack } from 'svelte'
import { cubicOut } from 'svelte/easing'
@@ -1542,6 +1543,9 @@ outside this layout, and their shortcut must reopen the URL that is their creden
where the announcement would land inside someone else's page. -->
<InstanceBanner />
{/if}
{#if !menuHidden}
<JobsPausedBanner />
{/if}
{#if $userStore?.is_service_account}
<div
class="bg-yellow-100 dark:bg-yellow-900/50 border-b border-yellow-300 dark:border-yellow-700 px-4 py-2 text-sm text-yellow-800 dark:text-yellow-200 flex items-center justify-center gap-4 shrink-0"
@@ -65,6 +65,7 @@
import ChangeWorkspaceName from '$lib/components/settings/ChangeWorkspaceName.svelte'
import ChangeWorkspaceId from '$lib/components/settings/ChangeWorkspaceId.svelte'
import ChangeWorkspaceColor from '$lib/components/settings/ChangeWorkspaceColor.svelte'
import PauseJobsSection from '$lib/components/jobsPause/PauseJobsSection.svelte'
import CloudQuotas from '$lib/components/settings/CloudQuotas.svelte'
import {
convertBackendSettingsToFrontendSettings,
@@ -1871,7 +1872,9 @@
onclick={saveSlackSigningSecret}
disabled={!slackSigningSecret.trim() && !slackSigningSecretSet}
>
{slackSigningSecret.trim() || !slackSigningSecretSet ? 'Save' : 'Remove'}
{slackSigningSecret.trim() || !slackSigningSecretSet
? 'Save'
: 'Remove'}
</Button>
</div>
<div class="text-2xs text-hint"
@@ -2008,6 +2011,7 @@
<ChangeWorkspaceName />
<ChangeWorkspaceId />
<ChangeWorkspaceColor />
<PauseJobsSection />
</div>
<div class="text-xs font-semibold text-emphasis mt-6 mb-1">Export workspace</div>
+55
View File
@@ -533,6 +533,33 @@ class Windmill:
job_id = job_id or os.environ.get("WM_JOB_ID")
return self.get(f"/w/{self.workspace}/jobs_u/get_root_job_id/{job_id}").json()
def pause_workspace_jobs(self, duration_s: int, reason: str | None = None) -> dict:
"""Pause new jobs of the workspace, e.g. while a flow runs migrations.
Jobs from triggers, schedules and async runs are held until resume_workspace_jobs or
the end of the pause; callers waiting for a result get a 503. The steps of the calling
flow, and runs started directly by an admin, keep running. Requires a workspace admin.
Args:
duration_s: How long the pause lasts at most, in seconds (at most 7 days)
reason: Shown to users of the workspace while paused
Returns:
The pause now in effect
"""
return self.post(
f"/w/{self.workspace}/workspaces/pause_jobs",
json={"duration_s": duration_s, "reason": reason, "source": "sdk"},
).json()
def resume_workspace_jobs(self) -> int:
"""Resume new jobs of the workspace and release the jobs the pause held.
Returns:
The number of held jobs released
"""
return self.post(f"/w/{self.workspace}/workspaces/resume_jobs").json()
def get_id_token(self, audience: str, expires_in: int | None = None) -> str:
"""Get an OIDC JWT token for authentication to external services.
@@ -1653,6 +1680,34 @@ def get_root_job_id(job_id: str | None = None) -> str:
return _client.get_root_job_id(job_id)
@init_global_client
def pause_workspace_jobs(duration_s: int, reason: str | None = None) -> dict:
"""Pause new jobs of the workspace, e.g. while a flow runs migrations.
Jobs from triggers, schedules and async runs are held until resume_workspace_jobs or the
end of the pause; callers waiting for a result get a 503. The steps of the calling flow,
and runs started directly by an admin, keep running. Requires a workspace admin.
Args:
duration_s: How long the pause lasts at most, in seconds (at most 7 days)
reason: Shown to users of the workspace while paused
Returns:
The pause now in effect
"""
return _client.pause_workspace_jobs(duration_s, reason)
@init_global_client
def resume_workspace_jobs() -> int:
"""Resume new jobs of the workspace and release the jobs the pause held.
Returns:
The number of held jobs released
"""
return _client.resume_workspace_jobs()
@init_global_client
@deprecate("Windmill().version")
def get_version() -> str:
@@ -663,6 +663,8 @@ sync local with a remote workspaces or the opposite (push or pull)
- `--extra-includes <patterns:file[]>` - Comma separated patterns to specify which file to take into account (among files that are compatible with windmill). Patterns can include * (any string until '/') and ** (any string). Useful to still take wmill.yaml into account and act as a second pattern to satisfy
- `--message <message:string>` - Include a message that will be added to all scripts/flows/apps updated during this push
- `--parallel <number>` - Number of changes to process in parallel
- `--pause-jobs [duration:string]` - Pause new jobs of the workspace while pushing (default 30m, at most 7d): triggers, schedules and async runs are held, then released once the dependency jobs of the push finish. Admin only
- `--keep-paused` - With --pause-jobs, leave jobs paused after the push (e.g. to run migrations first); resume with 'wmill workspace resume-jobs'
- `--repository <repo:string>` - Specify repository path (e.g., u/user/repo) when multiple repositories exist
- `--branch, --env <branch:string>` - [Deprecated: use --workspace] Override the current git branch/environment
- `--lint` - Run lint validation before pushing
@@ -853,6 +855,12 @@ Arguments (omit both to be prompted interactively):
- `--dry-run` - Only show the changes
- `--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)
- `--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
- `--json` - Output as JSON
+46
View File
@@ -1785,6 +1785,24 @@ async getResource(path?: string, undefinedIfEmpty?: boolean): Promise<any>
*/
async getRootJobId(jobId?: string): Promise<string>
/**
* Pause new jobs of the current workspace, e.g. while a flow runs migrations. Jobs from triggers,
* schedules and async runs are held until {@link resumeWorkspaceJobs} or the end of the pause;
* callers waiting for a result get a 503. The steps of the calling flow, and runs started directly
* by an admin, keep running. Requires the job to run as a workspace admin.
* @param durationS how long the pause lasts at most, in seconds (at most 7 days)
* @param reason shown to users of the workspace while paused
* @returns the pause now in effect
*/
async pauseWorkspaceJobs(durationS: number, reason?: string): Promise<JobsPaused>
/**
* Resume new jobs of the current workspace and release the jobs the pause held.
* Requires the job to run as a workspace admin.
* @returns the number of held jobs released
*/
async resumeWorkspaceJobs(): Promise<number>
/**
* Run a script synchronously by its path and wait for the result
* @param path - Script path in Windmill
@@ -2508,6 +2526,26 @@ def get_job(job_id: str) -> dict
# Root job ID
def get_root_job_id(job_id: str | None = None) -> dict
# Pause new jobs of the workspace, e.g. while a flow runs migrations.
#
# Jobs from triggers, schedules and async runs are held until resume_workspace_jobs or
# the end of the pause; callers waiting for a result get a 503. The steps of the calling
# flow, and runs started directly by an admin, keep running. Requires a workspace admin.
#
# Args:
# duration_s: How long the pause lasts at most, in seconds (at most 7 days)
# reason: Shown to users of the workspace while paused
#
# Returns:
# The pause now in effect
def pause_workspace_jobs(duration_s: int, reason: str | None = None) -> dict
# Resume new jobs of the workspace and release the jobs the pause held.
#
# Returns:
# The number of held jobs released
def resume_workspace_jobs() -> int
# Get an OIDC JWT token for authentication to external services.
#
# Args:
@@ -4414,6 +4452,8 @@ sync local with a remote workspaces or the opposite (push or pull)
- \`--extra-includes <patterns:file[]>\` - Comma separated patterns to specify which file to take into account (among files that are compatible with windmill). Patterns can include * (any string until '/') and ** (any string). Useful to still take wmill.yaml into account and act as a second pattern to satisfy
- \`--message <message:string>\` - Include a message that will be added to all scripts/flows/apps updated during this push
- \`--parallel <number>\` - Number of changes to process in parallel
- \`--pause-jobs [duration:string]\` - Pause new jobs of the workspace while pushing (default 30m, at most 7d): triggers, schedules and async runs are held, then released once the dependency jobs of the push finish. Admin only
- \`--keep-paused\` - With --pause-jobs, leave jobs paused after the push (e.g. to run migrations first); resume with 'wmill workspace resume-jobs'
- \`--repository <repo:string>\` - Specify repository path (e.g., u/user/repo) when multiple repositories exist
- \`--branch, --env <branch:string>\` - [Deprecated: use --workspace] Override the current git branch/environment
- \`--lint\` - Run lint validation before pushing
@@ -4604,6 +4644,12 @@ Arguments (omit both to be prompted interactively):
- \`--dry-run\` - Only show the changes
- \`--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)
- \`--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
- \`--json\` - Output as JSON
+38
View File
@@ -1514,6 +1514,24 @@ async getResource(path?: string, undefinedIfEmpty?: boolean): Promise<any>
*/
async getRootJobId(jobId?: string): Promise<string>
/**
* Pause new jobs of the current workspace, e.g. while a flow runs migrations. Jobs from triggers,
* schedules and async runs are held until {@link resumeWorkspaceJobs} or the end of the pause;
* callers waiting for a result get a 503. The steps of the calling flow, and runs started directly
* by an admin, keep running. Requires the job to run as a workspace admin.
* @param durationS how long the pause lasts at most, in seconds (at most 7 days)
* @param reason shown to users of the workspace while paused
* @returns the pause now in effect
*/
async pauseWorkspaceJobs(durationS: number, reason?: string): Promise<JobsPaused>
/**
* Resume new jobs of the current workspace and release the jobs the pause held.
* Requires the job to run as a workspace admin.
* @returns the number of held jobs released
*/
async resumeWorkspaceJobs(): Promise<number>
/**
* Run a script synchronously by its path and wait for the result
* @param path - Script path in Windmill
@@ -2237,6 +2255,26 @@ def get_job(job_id: str) -> dict
# Root job ID
def get_root_job_id(job_id: str | None = None) -> dict
# Pause new jobs of the workspace, e.g. while a flow runs migrations.
#
# Jobs from triggers, schedules and async runs are held until resume_workspace_jobs or
# the end of the pause; callers waiting for a result get a 503. The steps of the calling
# flow, and runs started directly by an admin, keep running. Requires a workspace admin.
#
# Args:
# duration_s: How long the pause lasts at most, in seconds (at most 7 days)
# reason: Shown to users of the workspace while paused
#
# Returns:
# The pause now in effect
def pause_workspace_jobs(duration_s: int, reason: str | None = None) -> dict
# Resume new jobs of the workspace and release the jobs the pause held.
#
# Returns:
# The number of held jobs released
def resume_workspace_jobs() -> int
# Get an OIDC JWT token for authentication to external services.
#
# Args:
@@ -132,6 +132,26 @@ def get_job(job_id: str) -> dict
# Root job ID
def get_root_job_id(job_id: str | None = None) -> dict
# Pause new jobs of the workspace, e.g. while a flow runs migrations.
#
# Jobs from triggers, schedules and async runs are held until resume_workspace_jobs or
# the end of the pause; callers waiting for a result get a 503. The steps of the calling
# flow, and runs started directly by an admin, keep running. Requires a workspace admin.
#
# Args:
# duration_s: How long the pause lasts at most, in seconds (at most 7 days)
# reason: Shown to users of the workspace while paused
#
# Returns:
# The pause now in effect
def pause_workspace_jobs(duration_s: int, reason: str | None = None) -> dict
# Resume new jobs of the workspace and release the jobs the pause held.
#
# Returns:
# The number of held jobs released
def resume_workspace_jobs() -> int
# Get an OIDC JWT token for authentication to external services.
#
# Args:
@@ -48,6 +48,24 @@ async getResource(path?: string, undefinedIfEmpty?: boolean): Promise<any>
*/
async getRootJobId(jobId?: string): Promise<string>
/**
* Pause new jobs of the current workspace, e.g. while a flow runs migrations. Jobs from triggers,
* schedules and async runs are held until {@link resumeWorkspaceJobs} or the end of the pause;
* callers waiting for a result get a 503. The steps of the calling flow, and runs started directly
* by an admin, keep running. Requires the job to run as a workspace admin.
* @param durationS how long the pause lasts at most, in seconds (at most 7 days)
* @param reason shown to users of the workspace while paused
* @returns the pause now in effect
*/
async pauseWorkspaceJobs(durationS: number, reason?: string): Promise<JobsPaused>
/**
* Resume new jobs of the current workspace and release the jobs the pause held.
* Requires the job to run as a workspace admin.
* @returns the number of held jobs released
*/
async resumeWorkspaceJobs(): Promise<number>
/**
* Run a script synchronously by its path and wait for the result
* @param path - Script path in Windmill
@@ -668,6 +668,8 @@ sync local with a remote workspaces or the opposite (push or pull)
- `--extra-includes <patterns:file[]>` - Comma separated patterns to specify which file to take into account (among files that are compatible with windmill). Patterns can include * (any string until '/') and ** (any string). Useful to still take wmill.yaml into account and act as a second pattern to satisfy
- `--message <message:string>` - Include a message that will be added to all scripts/flows/apps updated during this push
- `--parallel <number>` - Number of changes to process in parallel
- `--pause-jobs [duration:string]` - Pause new jobs of the workspace while pushing (default 30m, at most 7d): triggers, schedules and async runs are held, then released once the dependency jobs of the push finish. Admin only
- `--keep-paused` - With --pause-jobs, leave jobs paused after the push (e.g. to run migrations first); resume with 'wmill workspace resume-jobs'
- `--repository <repo:string>` - Specify repository path (e.g., u/user/repo) when multiple repositories exist
- `--branch, --env <branch:string>` - [Deprecated: use --workspace] Override the current git branch/environment
- `--lint` - Run lint validation before pushing
@@ -858,6 +860,12 @@ Arguments (omit both to be prompted interactively):
- `--dry-run` - Only show the changes
- `--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)
- `--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
- `--json` - Output as JSON
@@ -247,6 +247,24 @@ async getResource(path?: string, undefinedIfEmpty?: boolean): Promise<any>
*/
async getRootJobId(jobId?: string): Promise<string>
/**
* Pause new jobs of the current workspace, e.g. while a flow runs migrations. Jobs from triggers,
* schedules and async runs are held until {@link resumeWorkspaceJobs} or the end of the pause;
* callers waiting for a result get a 503. The steps of the calling flow, and runs started directly
* by an admin, keep running. Requires the job to run as a workspace admin.
* @param durationS how long the pause lasts at most, in seconds (at most 7 days)
* @param reason shown to users of the workspace while paused
* @returns the pause now in effect
*/
async pauseWorkspaceJobs(durationS: number, reason?: string): Promise<JobsPaused>
/**
* Resume new jobs of the current workspace and release the jobs the pause held.
* Requires the job to run as a workspace admin.
* @returns the number of held jobs released
*/
async resumeWorkspaceJobs(): Promise<number>
/**
* Run a script synchronously by its path and wait for the result
* @param path - Script path in Windmill
@@ -259,6 +259,24 @@ async getResource(path?: string, undefinedIfEmpty?: boolean): Promise<any>
*/
async getRootJobId(jobId?: string): Promise<string>
/**
* Pause new jobs of the current workspace, e.g. while a flow runs migrations. Jobs from triggers,
* schedules and async runs are held until {@link resumeWorkspaceJobs} or the end of the pause;
* callers waiting for a result get a 503. The steps of the calling flow, and runs started directly
* by an admin, keep running. Requires the job to run as a workspace admin.
* @param durationS how long the pause lasts at most, in seconds (at most 7 days)
* @param reason shown to users of the workspace while paused
* @returns the pause now in effect
*/
async pauseWorkspaceJobs(durationS: number, reason?: string): Promise<JobsPaused>
/**
* Resume new jobs of the current workspace and release the jobs the pause held.
* Requires the job to run as a workspace admin.
* @returns the number of held jobs released
*/
async resumeWorkspaceJobs(): Promise<number>
/**
* Run a script synchronously by its path and wait for the result
* @param path - Script path in Windmill
@@ -249,6 +249,24 @@ async getResource(path?: string, undefinedIfEmpty?: boolean): Promise<any>
*/
async getRootJobId(jobId?: string): Promise<string>
/**
* Pause new jobs of the current workspace, e.g. while a flow runs migrations. Jobs from triggers,
* schedules and async runs are held until {@link resumeWorkspaceJobs} or the end of the pause;
* callers waiting for a result get a 503. The steps of the calling flow, and runs started directly
* by an admin, keep running. Requires the job to run as a workspace admin.
* @param durationS how long the pause lasts at most, in seconds (at most 7 days)
* @param reason shown to users of the workspace while paused
* @returns the pause now in effect
*/
async pauseWorkspaceJobs(durationS: number, reason?: string): Promise<JobsPaused>
/**
* Resume new jobs of the current workspace and release the jobs the pause held.
* Requires the job to run as a workspace admin.
* @returns the number of held jobs released
*/
async resumeWorkspaceJobs(): Promise<number>
/**
* Run a script synchronously by its path and wait for the result
* @param path - Script path in Windmill
@@ -343,6 +343,26 @@ def get_job(job_id: str) -> dict
# Root job ID
def get_root_job_id(job_id: str | None = None) -> dict
# Pause new jobs of the workspace, e.g. while a flow runs migrations.
#
# Jobs from triggers, schedules and async runs are held until resume_workspace_jobs or
# the end of the pause; callers waiting for a result get a 503. The steps of the calling
# flow, and runs started directly by an admin, keep running. Requires a workspace admin.
#
# Args:
# duration_s: How long the pause lasts at most, in seconds (at most 7 days)
# reason: Shown to users of the workspace while paused
#
# Returns:
# The pause now in effect
def pause_workspace_jobs(duration_s: int, reason: str | None = None) -> dict
# Resume new jobs of the workspace and release the jobs the pause held.
#
# Returns:
# The number of held jobs released
def resume_workspace_jobs() -> int
# Get an OIDC JWT token for authentication to external services.
#
# Args:
+5 -1
View File
@@ -46,7 +46,7 @@ cp "${script_dirpath}/sqlUtils.ts" "${script_dirpath}/src/"
echo "" >> "${script_dirpath}/src/index.ts"
echo 'export type { DenoS3LightClientSettings } from "./s3Types";' >> "${script_dirpath}/src/index.ts"
echo "" >> "${script_dirpath}/src/index.ts"
echo 'export { type Base64, setClient, getWorkspace, workerHasInternalServer, SHARED_FOLDER, getStatePath, getInternalState, setInternalState, getResumeEndpoints, getResult, getResultMaybe, resolveDefaultResource, databaseUrlFromResource, base64ToUint8Array, uint8ArrayToBase64, getVariable, setVariable, getResource, setResource, getResumeUrls, setState, setProgress, getProgress, workerIsDraining, getState, getIdToken, denoS3LightClientSettings, cancelJob, loadS3FileStream, loadS3File, writeS3File, deleteS3File, signS3Objects, signS3Object, getPresignedS3PublicUrls, getPresignedS3PublicUrl, task, taskScript, taskFlow, workflow, step, sleep, parallel, waitForApproval, getApprovalUrls, type TaskOptions, type TaskRetry, type Jsonified, type JsonifiedFn, WorkflowCtx, _workflowCtx, setWorkflowCtx, StepSuspend, runScript, runScriptAsync, runScriptByPath, runScriptByHash, runScriptByPathAsync, runScriptByHashAsync, type RunScriptAsyncOptions, runFlow, runFlowAsync, waitJob, getRootJobId, setFlowUserState, getFlowUserState, usernameToEmail, requestInteractiveSlackApproval, type Sql, requestInteractiveTeamsApproval, appendToResultStream, streamResult, datatable, ducklake, upsertPartition, appendPartition, type DucklakeMaterializeOptions, type SqlStatement, type DatatableSqlTemplateFunction, type SqlTemplateFunction, type S3Object, type S3ObjectRecord, type S3ObjectURI, commitKafkaOffsets } from "./client";' >> "${script_dirpath}/src/index.ts"
echo 'export { type Base64, setClient, getWorkspace, workerHasInternalServer, SHARED_FOLDER, getStatePath, getInternalState, setInternalState, getResumeEndpoints, getResult, getResultMaybe, resolveDefaultResource, databaseUrlFromResource, base64ToUint8Array, uint8ArrayToBase64, getVariable, setVariable, getResource, setResource, getResumeUrls, setState, setProgress, getProgress, workerIsDraining, getState, getIdToken, denoS3LightClientSettings, cancelJob, loadS3FileStream, loadS3File, writeS3File, deleteS3File, signS3Objects, signS3Object, getPresignedS3PublicUrls, getPresignedS3PublicUrl, task, taskScript, taskFlow, workflow, step, sleep, parallel, waitForApproval, getApprovalUrls, type TaskOptions, type TaskRetry, type Jsonified, type JsonifiedFn, WorkflowCtx, _workflowCtx, setWorkflowCtx, StepSuspend, runScript, runScriptAsync, runScriptByPath, runScriptByHash, runScriptByPathAsync, runScriptByHashAsync, type RunScriptAsyncOptions, runFlow, runFlowAsync, waitJob, getRootJobId, pauseWorkspaceJobs, resumeWorkspaceJobs, setFlowUserState, getFlowUserState, usernameToEmail, requestInteractiveSlackApproval, type Sql, requestInteractiveTeamsApproval, appendToResultStream, streamResult, datatable, ducklake, upsertPartition, appendPartition, type DucklakeMaterializeOptions, type SqlStatement, type DatatableSqlTemplateFunction, type SqlTemplateFunction, type S3Object, type S3ObjectRecord, type S3ObjectURI, commitKafkaOffsets } from "./client";' >> "${script_dirpath}/src/index.ts"
# Build default export by combining client utilities + services
# This preserves backward compatibility for `import wmill from "windmill-client"`
@@ -99,6 +99,8 @@ import {
runFlowAsync,
waitJob,
getRootJobId,
pauseWorkspaceJobs,
resumeWorkspaceJobs,
setFlowUserState,
getFlowUserState,
usernameToEmail,
@@ -190,6 +192,8 @@ const wmill = {
runFlowAsync,
waitJob,
getRootJobId,
pauseWorkspaceJobs,
resumeWorkspaceJobs,
setFlowUserState,
getFlowUserState,
usernameToEmail,
+30 -1
View File
@@ -10,8 +10,9 @@ import {
OidcService,
UserService,
KafkaTriggerService,
WorkspaceService,
} from "./services.gen";
import type { Retry } from "./types.gen";
import type { JobsPaused, Retry } from "./types.gen";
import { OpenAPI } from "./core/OpenAPI";
import { isSuspendSignal, stepErrorMarker, taskErrorFromMarker } from "./wacError";
// import type { DenoS3LightClientSettings } from "./index";
@@ -159,6 +160,34 @@ export async function getRootJobId(jobId?: string): Promise<string> {
return await JobService.getRootJobId({ workspace, id: jobId });
}
/**
* Pause new jobs of the current workspace, e.g. while a flow runs migrations. Jobs from triggers,
* schedules and async runs are held until {@link resumeWorkspaceJobs} or the end of the pause;
* callers waiting for a result get a 503. The steps of the calling flow, and runs started directly
* by an admin, keep running. Requires the job to run as a workspace admin.
* @param durationS how long the pause lasts at most, in seconds (at most 7 days)
* @param reason shown to users of the workspace while paused
* @returns the pause now in effect
*/
export async function pauseWorkspaceJobs(
durationS: number,
reason?: string
): Promise<JobsPaused> {
return await WorkspaceService.pauseJobs({
workspace: getWorkspace(),
requestBody: { duration_s: durationS, reason, source: "sdk" },
});
}
/**
* Resume new jobs of the current workspace and release the jobs the pause held.
* Requires the job to run as a workspace admin.
* @returns the number of held jobs released
*/
export async function resumeWorkspaceJobs(): Promise<number> {
return await WorkspaceService.resumeJobs({ workspace: getWorkspace() });
}
/**
* @deprecated Use runScriptByPath or runScriptByHash instead
*/