diff --git a/AGENTS.md b/AGENTS.md index c2aae7159d..f83ccd65f9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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 diff --git a/backend/.sqlx/query-015adf2239a34462212dd927281adbc370a0bc35a7a7dc5bbba80ac2432c6360.json b/backend/.sqlx/query-015adf2239a34462212dd927281adbc370a0bc35a7a7dc5bbba80ac2432c6360.json new file mode 100644 index 0000000000..3d0f1164fe --- /dev/null +++ b/backend/.sqlx/query-015adf2239a34462212dd927281adbc370a0bc35a7a7dc5bbba80ac2432c6360.json @@ -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" +} diff --git a/backend/.sqlx/query-111ce9bef31798a72024704087556b9ddaf9d39c0749c0f1fc022233ee0bab1f.json b/backend/.sqlx/query-111ce9bef31798a72024704087556b9ddaf9d39c0749c0f1fc022233ee0bab1f.json new file mode 100644 index 0000000000..1b99c9045b --- /dev/null +++ b/backend/.sqlx/query-111ce9bef31798a72024704087556b9ddaf9d39c0749c0f1fc022233ee0bab1f.json @@ -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" +} diff --git a/backend/.sqlx/query-22bca2f5ed54a016d79063361430d2c561e3fe57c8ed36cfc32b390e704add39.json b/backend/.sqlx/query-22bca2f5ed54a016d79063361430d2c561e3fe57c8ed36cfc32b390e704add39.json new file mode 100644 index 0000000000..7e83def0f4 --- /dev/null +++ b/backend/.sqlx/query-22bca2f5ed54a016d79063361430d2c561e3fe57c8ed36cfc32b390e704add39.json @@ -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" +} diff --git a/backend/.sqlx/query-2e0d69d27edb7a13c6055edcb4b277100bf02c6c19a5e1d19b969812722c98e3.json b/backend/.sqlx/query-2e0d69d27edb7a13c6055edcb4b277100bf02c6c19a5e1d19b969812722c98e3.json new file mode 100644 index 0000000000..ea5feadd96 --- /dev/null +++ b/backend/.sqlx/query-2e0d69d27edb7a13c6055edcb4b277100bf02c6c19a5e1d19b969812722c98e3.json @@ -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" +} diff --git a/backend/.sqlx/query-3d2fe43b089638369a77d4eaf1eb62c021127f603c54d1190a6898e7749f5105.json b/backend/.sqlx/query-3d2fe43b089638369a77d4eaf1eb62c021127f603c54d1190a6898e7749f5105.json new file mode 100644 index 0000000000..3d18288dd5 --- /dev/null +++ b/backend/.sqlx/query-3d2fe43b089638369a77d4eaf1eb62c021127f603c54d1190a6898e7749f5105.json @@ -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" +} diff --git a/backend/.sqlx/query-5c4441bc1d689be1ae4ad87dd47702a1d7f89abc4823716083fae209c7c38f38.json b/backend/.sqlx/query-5c4441bc1d689be1ae4ad87dd47702a1d7f89abc4823716083fae209c7c38f38.json new file mode 100644 index 0000000000..cd33b6dbed --- /dev/null +++ b/backend/.sqlx/query-5c4441bc1d689be1ae4ad87dd47702a1d7f89abc4823716083fae209c7c38f38.json @@ -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" +} diff --git a/backend/.sqlx/query-70aad8f4b2ff1cf780f215751b50a7a2714f534ccb75a04fd6280b0898c217e8.json b/backend/.sqlx/query-70aad8f4b2ff1cf780f215751b50a7a2714f534ccb75a04fd6280b0898c217e8.json new file mode 100644 index 0000000000..24de50c1d2 --- /dev/null +++ b/backend/.sqlx/query-70aad8f4b2ff1cf780f215751b50a7a2714f534ccb75a04fd6280b0898c217e8.json @@ -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" +} diff --git a/backend/.sqlx/query-72cf330524f618ec25aa404bea9b484d94e5232681f1e2405dcf41b210f1d7dd.json b/backend/.sqlx/query-72cf330524f618ec25aa404bea9b484d94e5232681f1e2405dcf41b210f1d7dd.json new file mode 100644 index 0000000000..9abe878a45 --- /dev/null +++ b/backend/.sqlx/query-72cf330524f618ec25aa404bea9b484d94e5232681f1e2405dcf41b210f1d7dd.json @@ -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" +} diff --git a/backend/.sqlx/query-7a5263f5c9b11b7b506d994247c657b279af8db3ac9769f9c2e241f90eda6d3e.json b/backend/.sqlx/query-7a5263f5c9b11b7b506d994247c657b279af8db3ac9769f9c2e241f90eda6d3e.json new file mode 100644 index 0000000000..d82674459c --- /dev/null +++ b/backend/.sqlx/query-7a5263f5c9b11b7b506d994247c657b279af8db3ac9769f9c2e241f90eda6d3e.json @@ -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" +} diff --git a/backend/.sqlx/query-a3753022fb0d88a3f8cb851de8bcaa5c8513bfab2d000f3531aec9456d5be020.json b/backend/.sqlx/query-a3753022fb0d88a3f8cb851de8bcaa5c8513bfab2d000f3531aec9456d5be020.json new file mode 100644 index 0000000000..05540cb684 --- /dev/null +++ b/backend/.sqlx/query-a3753022fb0d88a3f8cb851de8bcaa5c8513bfab2d000f3531aec9456d5be020.json @@ -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" +} diff --git a/backend/.sqlx/query-a67a6416939ef5001e0941c54ddfd786749c6b3580cf46a2ab7ed8ff754c4f1b.json b/backend/.sqlx/query-a67a6416939ef5001e0941c54ddfd786749c6b3580cf46a2ab7ed8ff754c4f1b.json new file mode 100644 index 0000000000..933980a8db --- /dev/null +++ b/backend/.sqlx/query-a67a6416939ef5001e0941c54ddfd786749c6b3580cf46a2ab7ed8ff754c4f1b.json @@ -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" +} diff --git a/backend/.sqlx/query-c3dad628ba70d35c7255edfce64a3061f3bf3bf3bbb14a60dc3179a3f1788c05.json b/backend/.sqlx/query-c3dad628ba70d35c7255edfce64a3061f3bf3bf3bbb14a60dc3179a3f1788c05.json new file mode 100644 index 0000000000..2129ca7c18 --- /dev/null +++ b/backend/.sqlx/query-c3dad628ba70d35c7255edfce64a3061f3bf3bf3bbb14a60dc3179a3f1788c05.json @@ -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" +} diff --git a/backend/.sqlx/query-cc1797618f9633bb884b24d3c4523a5ad824a6bac86c3efd640fe7999069ce93.json b/backend/.sqlx/query-cc1797618f9633bb884b24d3c4523a5ad824a6bac86c3efd640fe7999069ce93.json new file mode 100644 index 0000000000..8005fd9d38 --- /dev/null +++ b/backend/.sqlx/query-cc1797618f9633bb884b24d3c4523a5ad824a6bac86c3efd640fe7999069ce93.json @@ -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" +} diff --git a/backend/.sqlx/query-ce165e198c0fe474d3610c2a6bde63c867a1d4a16633b1645d77413aa4ecf002.json b/backend/.sqlx/query-ce165e198c0fe474d3610c2a6bde63c867a1d4a16633b1645d77413aa4ecf002.json new file mode 100644 index 0000000000..799f2e4c7a --- /dev/null +++ b/backend/.sqlx/query-ce165e198c0fe474d3610c2a6bde63c867a1d4a16633b1645d77413aa4ecf002.json @@ -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" +} diff --git a/backend/.sqlx/query-df40a8d02af6cf9857c033b25748eb0b7dbb70ae1f5bd31b8b05c5d9792d30c5.json b/backend/.sqlx/query-df40a8d02af6cf9857c033b25748eb0b7dbb70ae1f5bd31b8b05c5d9792d30c5.json new file mode 100644 index 0000000000..5136cdac9a --- /dev/null +++ b/backend/.sqlx/query-df40a8d02af6cf9857c033b25748eb0b7dbb70ae1f5bd31b8b05c5d9792d30c5.json @@ -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" +} diff --git a/backend/.sqlx/query-fc50d1b966f71f9c59d6faf44e1c2fa9b835042b9d31de0af87a48bb25804299.json b/backend/.sqlx/query-fc50d1b966f71f9c59d6faf44e1c2fa9b835042b9d31de0af87a48bb25804299.json new file mode 100644 index 0000000000..78a3af574c --- /dev/null +++ b/backend/.sqlx/query-fc50d1b966f71f9c59d6faf44e1c2fa9b835042b9d31de0af87a48bb25804299.json @@ -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" +} diff --git a/backend/ee-repo-ref.txt b/backend/ee-repo-ref.txt index f8c8a245eb..c9c7abe047 100644 --- a/backend/ee-repo-ref.txt +++ b/backend/ee-repo-ref.txt @@ -1 +1 @@ -5cfc0dc6760ea7f631fc98ea1edd39adfc55bf11 +b01587dedb195d0cafaa96514d152b0fce36fe1f diff --git a/backend/migrations/20261023123955_workspace_pause_jobs.down.sql b/backend/migrations/20261023123955_workspace_pause_jobs.down.sql new file mode 100644 index 0000000000..93f4c5ed2a --- /dev/null +++ b/backend/migrations/20261023123955_workspace_pause_jobs.down.sql @@ -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; diff --git a/backend/migrations/20261023123955_workspace_pause_jobs.up.sql b/backend/migrations/20261023123955_workspace_pause_jobs.up.sql new file mode 100644 index 0000000000..66b3b009db --- /dev/null +++ b/backend/migrations/20261023123955_workspace_pause_jobs.up.sql @@ -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(); diff --git a/backend/src/main.rs b/backend/src/main.rs index 1035a0549f..a9dc191727 100644 --- a/backend/src/main.rs +++ b/backend/src/main.rs @@ -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: {}", diff --git a/backend/src/monitor.rs b/backend/src/monitor.rs index fbadfa4269..e206c907d3 100644 --- a/backend/src/monitor.rs +++ b/backend/src/monitor.rs @@ -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, ); } diff --git a/backend/tests/workspace_job_pause.rs b/backend/tests/workspace_job_pause.rs new file mode 100644 index 0000000000..0976938bfd --- /dev/null +++ b/backend/tests/workspace_job_pause.rs @@ -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, id: Uuid) -> (String, chrono::DateTime) { + 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) -> 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::().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::().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(()) +} diff --git a/backend/windmill-api-jobs/src/execution.rs b/backend/windmill-api-jobs/src/execution.rs index 53c318b70d..ef8d46c6b4 100644 --- a/backend/windmill-api-jobs/src/execution.rs +++ b/backend/windmill-api-jobs/src/execution.rs @@ -1174,17 +1174,20 @@ pub async fn run_flow_and_wait_result( args: PushArgsOwned, trigger: Option, ) -> error::Result { - 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?; diff --git a/backend/windmill-api-workspaces/src/datatable_migrations.rs b/backend/windmill-api-workspaces/src/datatable_migrations.rs index 35ea6210dd..1c7a048eb0 100644 --- a/backend/windmill-api-workspaces/src/datatable_migrations.rs +++ b/backend/windmill-api-workspaces/src/datatable_migrations.rs @@ -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?; diff --git a/backend/windmill-api-workspaces/src/job_pause.rs b/backend/windmill-api-workspaces/src/job_pause.rs new file mode 100644 index 0000000000..b72cbf27a0 --- /dev/null +++ b/backend/windmill-api-workspaces/src/job_pause.rs @@ -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, + paused_by: String, + paused_at: DateTime, + reason: Option, + held_count: i64, +} + +async fn read_pause(db: &DB, w_id: &str) -> windmill_common::error::Result> { + 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, + Path(w_id): Path, +) -> JsonResult> { + Ok(Json(read_pause(&db, &w_id).await?)) +} + +#[derive(Deserialize)] +struct PauseJobsRequest { + until: Option>, + duration_s: Option, + reason: Option, + /// Where the pause was asked from, for telemetry only. + source: Option, +} + +async fn pause_jobs( + authed: ApiAuthed, + Extension(db): Extension, + Path(w_id): Path, + Json(req): Json, +) -> JsonResult> { + 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, + Path(w_id): Path, +) -> JsonResult { + 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)) +} diff --git a/backend/windmill-api-workspaces/src/lib.rs b/backend/windmill-api-workspaces/src/lib.rs index cc5a7b9ab0..718f60ee68 100644 --- a/backend/windmill-api-workspaces/src/lib.rs +++ b/backend/windmill-api-workspaces/src/lib.rs @@ -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; diff --git a/backend/windmill-api-workspaces/src/workspaces.rs b/backend/windmill-api-workspaces/src/workspaces.rs index e2027c3e9b..633a519c4f 100644 --- a/backend/windmill-api-workspaces/src/workspaces.rs +++ b/backend/windmill-api-workspaces/src/workspaces.rs @@ -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)) diff --git a/backend/windmill-api-workspaces/src/workspaces_extra.rs b/backend/windmill-api-workspaces/src/workspaces_extra.rs index 64aa5c6a08..f2e58c3d00 100644 --- a/backend/windmill-api-workspaces/src/workspaces_extra.rs +++ b/backend/windmill-api-workspaces/src/workspaces_extra.rs @@ -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", diff --git a/backend/windmill-api/openapi.yaml b/backend/windmill-api/openapi.yaml index fd5e02bed4..f1bd901e32 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -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: diff --git a/backend/windmill-api/src/apps.rs b/backend/windmill-api/src/apps.rs index bc0124b685..166c1ddcf6 100644 --- a/backend/windmill-api/src/apps.rs +++ b/backend/windmill-api/src/apps.rs @@ -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?; diff --git a/backend/windmill-api/src/apps_raw_bundle.rs b/backend/windmill-api/src/apps_raw_bundle.rs index 61dc4b861d..db27cb1188 100644 --- a/backend/windmill-api/src/apps_raw_bundle.rs +++ b/backend/windmill-api/src/apps_raw_bundle.rs @@ -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?; diff --git a/backend/windmill-api/src/jobs.rs b/backend/windmill-api/src/jobs.rs index c5dd374c7a..37085af13a 100644 --- a/backend/windmill-api/src/jobs.rs +++ b/backend/windmill-api/src/jobs.rs @@ -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?; diff --git a/backend/windmill-api/src/triggers/http/handler.rs b/backend/windmill-api/src/triggers/http/handler.rs index 5db6bf303d..48087dfb9c 100644 --- a/backend/windmill-api/src/triggers/http/handler.rs +++ b/backend/windmill-api/src/triggers/http/handler.rs @@ -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()), diff --git a/backend/windmill-common/src/error.rs b/backend/windmill-common/src/error.rs index dd8ec49f92..3fb27300c5 100644 --- a/backend/windmill-common/src/error.rs +++ b/backend/windmill-common/src/error.rs @@ -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 }, } 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() } } diff --git a/backend/windmill-common/src/job_pause.rs b/backend/windmill-common/src/job_pause.rs new file mode 100644 index 0000000000..fa97e8a609 --- /dev/null +++ b/backend/windmill-common/src/job_pause.rs @@ -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>, 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> { + 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(policy: PausePolicy, f: F) -> F::Output { + PAUSE_POLICY.scope(policy, f).await +} + +pub fn current_policy() -> Option { + 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>> { + 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 { + 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 { + 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 { + 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 + ); + } +} diff --git a/backend/windmill-common/src/lib.rs b/backend/windmill-common/src/lib.rs index 1fdfe72de7..a953a1c301 100644 --- a/backend/windmill-common/src/lib.rs +++ b/backend/windmill-common/src/lib.rs @@ -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; diff --git a/backend/windmill-queue/src/jobs.rs b/backend/windmill-queue/src/jobs.rs index c51f057f16..9e4cc88815 100644 --- a/backend/windmill-queue/src/jobs.rs +++ b/backend/windmill-queue/src/jobs.rs @@ -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}"); diff --git a/backend/windmill-trigger/src/global_handler.rs b/backend/windmill-trigger/src/global_handler.rs index 64ad693a10..eb75d12c39 100644 --- a/backend/windmill-trigger/src/global_handler.rs +++ b/backend/windmill-trigger/src/global_handler.rs @@ -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, diff --git a/backend/windmill-worker/src/worker.rs b/backend/windmill-worker/src/worker.rs index aa742bfdf5..b0b25cfbc1 100644 --- a/backend/windmill-worker/src/worker.rs +++ b/backend/windmill-worker/src/worker.rs @@ -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())); } _ => {} } diff --git a/cli/src/commands/sync/sync.ts b/cli/src/commands/sync/sync.ts index 43bba850ed..a07fab2785 100644 --- a/cli/src/commands/sync/sync.ts +++ b/cli/src/commands/sync/sync.ts @@ -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 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 ", "Specify repository path (e.g., u/user/repo) when multiple repositories exist", diff --git a/cli/src/commands/workspace/jobsPause.ts b/cli/src/commands/workspace/jobsPause.ts new file mode 100644 index 0000000000..eb78e3e948 --- /dev/null +++ b/cli/src/commands/workspace/jobsPause.ts @@ -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 = { 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 { + // 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})` : ""), + ); + } +} diff --git a/cli/src/commands/workspace/workspace.ts b/cli/src/commands/workspace/workspace.ts index caac17136a..9e4090c7fd 100644 --- a/cli/src/commands/workspace/workspace.ts +++ b/cli/src/commands/workspace/workspace.ts @@ -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 ", "How long the pause lasts at most (e.g. 30m, 2h, 1d; at most 7d)", { default: DEFAULT_PAUSE_DURATION }) + .option("--reason ", "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; diff --git a/cli/src/guidance/skills.gen.ts b/cli/src/guidance/skills.gen.ts index d932957a20..8ba4a88030 100644 --- a/cli/src/guidance/skills.gen.ts +++ b/cli/src/guidance/skills.gen.ts @@ -705,6 +705,24 @@ async getResource(path?: string, undefinedIfEmpty?: boolean): Promise */ async getRootJobId(jobId?: string): Promise +/** + * 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 + +/** + * 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 + /** * 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 */ async getRootJobId(jobId?: string): Promise +/** + * 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 + +/** + * 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 + /** * 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 */ async getRootJobId(jobId?: string): Promise +/** + * 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 + +/** + * 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 + /** * 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 \` - 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 \` - Include a message that will be added to all scripts/flows/apps updated during this push - \`--parallel \` - 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 \` - Specify repository path (e.g., u/user/repo) when multiple repositories exist - \`--branch, --env \` - [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 \` - How long the pause lasts at most (e.g. 30m, 2h, 1d; at most 7d) + - \`--reason \` - 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 diff --git a/docs/workspace-job-pause.md b/docs/workspace-job-pause.md new file mode 100644 index 0000000000..b41ea7b19c --- /dev/null +++ b/docs/workspace-job-pause.md @@ -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. diff --git a/frontend/src/lib/components/jobsPause/JobsPausedBanner.svelte b/frontend/src/lib/components/jobsPause/JobsPausedBanner.svelte new file mode 100644 index 0000000000..36a6750b58 --- /dev/null +++ b/frontend/src/lib/components/jobsPause/JobsPausedBanner.svelte @@ -0,0 +1,66 @@ + + +{#if pause} +
+ + + 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} + + {#if $userStore?.is_admin || $userStore?.is_super_admin} + + {/if} +
+{/if} diff --git a/frontend/src/lib/components/jobsPause/PauseJobsSection.svelte b/frontend/src/lib/components/jobsPause/PauseJobsSection.svelte new file mode 100644 index 0000000000..9f0f5bb92f --- /dev/null +++ b/frontend/src/lib/components/jobsPause/PauseJobsSection.svelte @@ -0,0 +1,95 @@ + + +
+

Pause new jobs

+

+ 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. +

+ {#if pause} +
+ + 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} + + +
+ {:else} +
+