diff --git a/backend/.sqlx/query-2c70b10578338d5722e5fa4f43b92ab3384f62ae44824b3ba15a4d7921435ca7.json b/backend/.sqlx/query-2c70b10578338d5722e5fa4f43b92ab3384f62ae44824b3ba15a4d7921435ca7.json
deleted file mode 100644
index 0704b15557..0000000000
--- a/backend/.sqlx/query-2c70b10578338d5722e5fa4f43b92ab3384f62ae44824b3ba15a4d7921435ca7.json
+++ /dev/null
@@ -1,19 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "INSERT INTO token\n (token_hash, token_prefix, token, label, super_admin, email, admin)\n VALUES ($1, $2, $3, $4, $5, $6, true)",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Varchar",
- "Varchar",
- "Varchar",
- "Varchar",
- "Bool",
- "Varchar"
- ]
- },
- "nullable": []
- },
- "hash": "2c70b10578338d5722e5fa4f43b92ab3384f62ae44824b3ba15a4d7921435ca7"
-}
diff --git a/backend/.sqlx/query-91a13927f7e0577e52755fd8463a4fc58818c109deda6678c79474bf45428966.json b/backend/.sqlx/query-91a13927f7e0577e52755fd8463a4fc58818c109deda6678c79474bf45428966.json
new file mode 100644
index 0000000000..d41b7811ee
--- /dev/null
+++ b/backend/.sqlx/query-91a13927f7e0577e52755fd8463a4fc58818c109deda6678c79474bf45428966.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT running FROM v2_job_queue WHERE id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "running",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "91a13927f7e0577e52755fd8463a4fc58818c109deda6678c79474bf45428966"
+}
diff --git a/backend/.sqlx/query-997338328a15fd1bfd7cb779e7b02e374235f36f51a37362d3789daf5de39d2b.json b/backend/.sqlx/query-997338328a15fd1bfd7cb779e7b02e374235f36f51a37362d3789daf5de39d2b.json
new file mode 100644
index 0000000000..90732f4169
--- /dev/null
+++ b/backend/.sqlx/query-997338328a15fd1bfd7cb779e7b02e374235f36f51a37362d3789daf5de39d2b.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT EXISTS (SELECT 1 FROM (\n SELECT DISTINCT ON (path) dedicated_worker FROM script\n WHERE workspace_id = $1 AND path = ANY($2) AND archived = false\n ORDER BY path, created_at DESC\n ) s WHERE s.dedicated_worker IS TRUE) AS \"e!\"",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "e!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "TextArray"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "997338328a15fd1bfd7cb779e7b02e374235f36f51a37362d3789daf5de39d2b"
+}
diff --git a/backend/.sqlx/query-9c18d50a5efbf986621b0b56107d0d2df192a8ac63372190187039af5a7ac491.json b/backend/.sqlx/query-9c18d50a5efbf986621b0b56107d0d2df192a8ac63372190187039af5a7ac491.json
new file mode 100644
index 0000000000..d08ece8a5a
--- /dev/null
+++ b/backend/.sqlx/query-9c18d50a5efbf986621b0b56107d0d2df192a8ac63372190187039af5a7ac491.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT path FROM script WHERE hash = $1 AND workspace_id = $2",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "path",
+ "type_info": "Varchar"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Int8",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "9c18d50a5efbf986621b0b56107d0d2df192a8ac63372190187039af5a7ac491"
+}
diff --git a/backend/.sqlx/query-c224b00ecb13c0a8b83e081dbd1599ad52b73c220420bebb82d2cc77c467dd43.json b/backend/.sqlx/query-c224b00ecb13c0a8b83e081dbd1599ad52b73c220420bebb82d2cc77c467dd43.json
new file mode 100644
index 0000000000..2ac8996171
--- /dev/null
+++ b/backend/.sqlx/query-c224b00ecb13c0a8b83e081dbd1599ad52b73c220420bebb82d2cc77c467dd43.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT on_behalf_of IS NOT NULL OR on_behalf_of_email IS NOT NULL AS \"o!\" FROM script WHERE hash = $1 AND workspace_id = $2",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "o!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Int8",
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "c224b00ecb13c0a8b83e081dbd1599ad52b73c220420bebb82d2cc77c467dd43"
+}
diff --git a/backend/.sqlx/query-de7673ea7d10ed5e59d4a9455e996171643833ced99f5d72d322d0905850acf3.json b/backend/.sqlx/query-de7673ea7d10ed5e59d4a9455e996171643833ced99f5d72d322d0905850acf3.json
new file mode 100644
index 0000000000..1e5cd1822d
--- /dev/null
+++ b/backend/.sqlx/query-de7673ea7d10ed5e59d4a9455e996171643833ced99f5d72d322d0905850acf3.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT EXISTS (SELECT 1 FROM flow WHERE workspace_id = $1 AND path = ANY($2)\n AND dedicated_worker IS TRUE) AS \"dedicated!\"",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "dedicated!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "TextArray"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "de7673ea7d10ed5e59d4a9455e996171643833ced99f5d72d322d0905850acf3"
+}
diff --git a/backend/ee-repo-ref.txt b/backend/ee-repo-ref.txt
index aa8778b178..0ced85faad 100644
--- a/backend/ee-repo-ref.txt
+++ b/backend/ee-repo-ref.txt
@@ -1 +1 @@
-4a19159ab6f634de29673aa530b76d9a9710ab78
+7444cbcf74797689d2b7835581b2db27ef8ec86c
diff --git a/backend/src/monitor.rs b/backend/src/monitor.rs
index 49a4a590e6..13d97c7ca0 100644
--- a/backend/src/monitor.rs
+++ b/backend/src/monitor.rs
@@ -2052,6 +2052,10 @@ async fn delete_expired_otel_traces(db: &DB, retention_secs: i64) -> u64 {
deleted
}
+/// Set once no token is left for the cleanup to delete.
+static DEDICATED_WORKER_TOKENS_DELETED: std::sync::atomic::AtomicBool =
+ std::sync::atomic::AtomicBool::new(false);
+
pub async fn delete_expired_items(db: &DB) -> () {
let expired_tokens_r = sqlx::query_as!(
TokenRow,
@@ -4493,6 +4497,32 @@ pub async fn monitor_db(
}
};
+ // run every 40 minutes or more: 240 iterations of at least 10s
+ let dedicated_worker_tokens_f = async {
+ if server_mode
+ && !DEDICATED_WORKER_TOKENS_DELETED.load(std::sync::atomic::Ordering::Relaxed)
+ && iteration.is_some()
+ && iteration.as_ref().unwrap().should_run(240)
+ && windmill_common::min_version::MIN_VERSION_SUPPORTS_DEDICATED_JOB_TOKENS
+ .met_conservatively()
+ {
+ if let Some(db) = conn.as_sql() {
+ match windmill_worker::delete_dedicated_worker_tokens(db).await {
+ Ok((deleted, left)) => {
+ if deleted > 0 {
+ tracing::info!("deleted {deleted} unused dedicated worker tokens");
+ }
+ if !left {
+ DEDICATED_WORKER_TOKENS_DELETED
+ .store(true, std::sync::atomic::Ordering::Relaxed);
+ }
+ }
+ Err(e) => tracing::error!("Error deleting dedicated worker tokens: {e:#}"),
+ }
+ }
+ }
+ };
+
// Not gated on server_mode: feature-usage counters accumulate wherever an
// instrumented call site runs, and a worker that never flushed would lose
// its counts on shutdown.
@@ -4887,6 +4917,7 @@ pub async fn monitor_db(
join!(
expired_items_f,
+ dedicated_worker_tokens_f,
feature_usage_f,
zombie_jobs_f,
stale_jobs_f,
diff --git a/backend/tests/dedicated_workers.rs b/backend/tests/dedicated_workers.rs
index c69bcc4563..0b4954c0ea 100644
--- a/backend/tests/dedicated_workers.rs
+++ b/backend/tests/dedicated_workers.rs
@@ -123,6 +123,51 @@ mod dedicated_worker_tests {
Ok(())
}
+ /// A flow named in a worker's config that does not enable dedicated_worker gets no
+ /// subprocesses: only admins can enable it, and its steps would start with an admin token.
+ #[sqlx::test(fixtures("base", "dedicated_flows"))]
+ #[serial]
+ async fn test_dedicated_flow_requires_flag(db: Pool) -> anyhow::Result<()> {
+ initialize_tracing().await;
+ let server = ApiServer::start(db.clone()).await?;
+ let port = server.addr.port();
+ let path = "f/system/dedicated_rawscript_flow";
+ sqlx::query("UPDATE flow SET dedicated_worker = NULL WHERE path = $1")
+ .bind(path)
+ .execute(&db)
+ .await?;
+ let uuid = RunJob::from(JobPayload::Flow {
+ path: path.to_string(),
+ dedicated_worker: Some(true),
+ apply_preprocessor: false,
+ labels: None,
+ version: 3000000000000001,
+ job_token_scopes: None,
+ })
+ .arg("x", json!(5))
+ .push(&db)
+ .await;
+ let listener = listen_for_completed_jobs(&db).await;
+ in_test_worker_dedicated(
+ db.clone(),
+ listener.find(&uuid),
+ port,
+ vec![wp("test-workspace", &format!("flow/{path}"))],
+ )
+ .await;
+ let job = completed_job(uuid, &db).await;
+ assert_eq!(job.json_result().unwrap(), json!(15));
+ let on_dedicated: bool = sqlx::query_scalar(
+ "SELECT EXISTS (SELECT 1 FROM job_logs l JOIN v2_job j ON j.id = l.job_id
+ WHERE j.parent_job = $1 AND l.logs LIKE '%dedicated worker bun:%')",
+ )
+ .bind(uuid)
+ .fetch_one(&db)
+ .await?;
+ assert!(!on_dedicated);
+ Ok(())
+ }
+
/// Test a dedicated flow with a Script step referencing an external workspace script.
#[sqlx::test(fixtures("base", "dedicated_flows"))]
#[serial]
@@ -313,10 +358,10 @@ mod dedicated_worker_tests {
Ok(())
}
- /// A squashed for-loop runs each iteration as a regular job, not in a shared subprocess.
+ /// Test flow runners: a squashed for-loop spawns dedicated subprocesses.
#[sqlx::test(fixtures("base", "dedicated_flows"))]
#[serial]
- async fn test_squashed_loop_runs_iterations_as_jobs(db: Pool) -> anyhow::Result<()> {
+ async fn test_dedicated_flow_runners(db: Pool) -> anyhow::Result<()> {
initialize_tracing().await;
// Reset dedicated_workers in WORKER_CONFIG to avoid pollution from previous tests.
{
@@ -355,17 +400,8 @@ mod dedicated_worker_tests {
// for-loop over [1, 2, 3], each * 10 = [10, 20, 30]
assert_eq!(job.json_result().unwrap(), json!([10, 20, 30]));
- let in_subprocess: i64 = sqlx::query_scalar(
- "WITH RECURSIVE t(id) AS (
- SELECT $1::uuid UNION SELECT j.id FROM v2_job j JOIN t ON j.parent_job = t.id
- )
- SELECT count(*) FROM job_logs l JOIN t ON l.job_id = t.id
- WHERE l.logs LIKE '%dedicated worker%'",
- )
- .bind(job.id)
- .fetch_one(&db)
- .await?;
- assert_eq!(in_subprocess, 0);
+ // Verify the loop iterations ran on dedicated worker subprocesses
+ assert_ran_on_dedicated_worker(&db, job.id, "bun").await;
Ok(())
}
@@ -741,7 +777,8 @@ mod dedicated_worker_tests {
Ok(())
}
- /// Test a squashed for-loop with a bash step.
+ /// Test a squashed for-loop with a bash step (unsupported for flow runners).
+ /// The bash step can't spawn a flow runner, so each iteration falls back to normal execution.
#[sqlx::test(fixtures("base", "dedicated_flows"))]
#[serial]
async fn test_dedicated_flow_runners_unsupported_lang(
@@ -1353,6 +1390,65 @@ mod dedicated_worker_tests {
Ok(())
}
+ /// Code outside of main runs with the process's workspace admin token; each job still runs
+ /// main with its caller's.
+ #[sqlx::test(fixtures("base", "dedicated_flows"))]
+ #[serial]
+ async fn test_dedicated_module_level_call(db: Pool) -> anyhow::Result<()> {
+ initialize_tracing().await;
+ let server = ApiServer::start(db.clone()).await?;
+ let port = server.addr.port();
+ let code = r#"
+const get = () => fetch(
+ `${process.env.BASE_URL}/api/w/test-workspace/variables/get_value/u/test-user/private`,
+ { headers: { Authorization: "Bearer " + process.env.WM_TOKEN } },
+);
+const atStart = await (await get()).json();
+export async function main() {
+ return [atStart, (await get()).ok, process.env.WM_EMAIL];
+}"#;
+ insert_dedicated_script(&db, 300913, "bun", code).await;
+ sqlx::query(
+ "INSERT INTO variable(workspace_id, path, value, is_secret)
+ VALUES ('test-workspace', 'u/test-user/private', 'of-test-user', false)",
+ )
+ .execute(&db)
+ .await?;
+ let path = "f/system/identity_bun";
+ let uuid = RunJob::from(JobPayload::ScriptHash {
+ hash: windmill_common::scripts::ScriptHash(300913),
+ path: path.to_string(),
+ cache_ttl: None,
+ cache_ignore_s3_path: None,
+ dedicated_worker: Some(true),
+ language: windmill_common::scripts::ScriptLang::Bun,
+ priority: None,
+ apply_preprocessor: false,
+ labels: None,
+ concurrency_settings: Default::default(),
+ debouncing_settings: Default::default(),
+ job_token_scopes: None,
+ })
+ .as_user("test-user-2", "test2@windmill.dev")
+ .push(&db)
+ .await;
+ let listener = listen_for_completed_jobs(&db).await;
+ in_test_worker_dedicated(
+ db.clone(),
+ listener.find(&uuid),
+ port,
+ vec![wp("test-workspace", path)],
+ )
+ .await;
+ let job = completed_job(uuid, &db).await;
+ assert_eq!(
+ job.json_result().unwrap(),
+ json!(["of-test-user", false, "test2@windmill.dev"])
+ );
+ assert_ran_on_dedicated_worker(&db, uuid, "bun").await;
+ Ok(())
+ }
+
/// Test a dedicated Python worker script that uses a relative import.
/// Verifies that the Python loader resolves relative imports correctly.
#[cfg(feature = "python")]
@@ -1594,4 +1690,414 @@ mod dedicated_worker_tests {
assert_ran_on_dedicated_worker(&db, uuid, "bun").await;
Ok(())
}
+
+ /// What a script of this shape returns: `[WM_EMAIL, whoami's email, whether it read the
+ /// admin-only settings, x]`, the whoami sent with a token cached at import as SDK clients do.
+ const IDENTITY_TS: &str = r#"
+const cached = "Bearer " + process.env.WM_TOKEN;
+let cachedInJob: string | undefined;
+const get = (path: string, auth: string) =>
+ fetch(`${process.env.BASE_URL ?? process.env.BASE_INTERNAL_URL}/api/w/test-workspace/${path}`, { headers: { Authorization: auth } });
+export async function main(x: any) {
+ cachedInJob ??= "Bearer " + process.env.WM_TOKEN;
+ const who = await get("users/whoami", cached);
+ const whoInJob = await get("users/whoami", cachedInJob);
+ const settings = await get("workspaces/get_settings", "Bearer " + process.env.WM_TOKEN);
+ const emails = new Set([(await who.json()).email, (await whoInJob.json()).email]);
+ return [process.env.WM_EMAIL, [...emails].join(), settings.ok, x ?? null];
+}"#;
+ #[cfg(feature = "python")]
+ const IDENTITY_PY: &str = r#"
+import json, os, urllib.request, urllib.error
+def get(path):
+ req = urllib.request.Request(os.environ["BASE_INTERNAL_URL"] + "/api/w/test-workspace/" + path,
+ headers={"Authorization": "Bearer " + os.environ["WM_TOKEN"]})
+ try:
+ return json.load(urllib.request.urlopen(req))
+ except urllib.error.HTTPError:
+ return None
+def main(x = None):
+ # The job of x = 1 cannot read this script; the next one, of x = 2, can.
+ if x in (1, 2):
+ from u.someone.helper import value
+ assert x == 1 or value == 7
+ return [os.environ["WM_EMAIL"], get("users/whoami")["email"], get("workspaces/get_settings") is not None, x]
+"#;
+
+ async fn insert_dedicated_script(db: &Pool, hash: i64, lang: &str, content: &str) {
+ let lock = if lang == "python3" || lang == "deno" {
+ ""
+ } else {
+ "{}\n//bun.lock\n"
+ };
+ sqlx::query(
+ "INSERT INTO script(workspace_id, created_by, content, schema, summary, description,
+ path, hash, language, lock, dedicated_worker)
+ VALUES ('test-workspace', 'test-user', $1, '{}', '', '', $2, $3, $4::text::script_lang, $5, true)",
+ )
+ .bind(content)
+ .bind(format!("f/system/identity_{lang}"))
+ .bind(hash)
+ .bind(lang)
+ .bind(lock)
+ .execute(db)
+ .await
+ .unwrap();
+ }
+
+ /// Jobs of different users share one process, each with its own token, for its variables,
+ /// its API calls and the references in its arguments.
+ async fn check_job_identity(
+ db: Pool,
+ lang: windmill_common::scripts::ScriptLang,
+ mode: &str,
+ content: &str,
+ ) -> anyhow::Result<()> {
+ initialize_tracing().await;
+ let server = ApiServer::start(db.clone()).await?;
+ let port = server.addr.port();
+ let name = lang.as_str();
+ insert_dedicated_script(&db, 300900, name, content).await;
+ sqlx::query(
+ "INSERT INTO variable(workspace_id, path, value, is_secret)
+ VALUES ('test-workspace', 'u/test-user/private', 'of-test-user', false)",
+ )
+ .execute(&db)
+ .await?;
+
+ let admin = ("test-user", "test@windmill.dev");
+ let other = ("test-user-2", "test2@windmill.dev");
+ let path = format!("f/system/identity_{name}");
+ let mut jobs = vec![];
+ for (user, arg) in [
+ (admin, json!("$var:u/test-user/private")),
+ (other, json!("$var:u/test-user/private")),
+ (other, json!(1)),
+ (admin, json!(2)),
+ (other, json!(3)),
+ ] {
+ jobs.push(
+ RunJob::from(JobPayload::ScriptHash {
+ hash: windmill_common::scripts::ScriptHash(300900),
+ path: path.clone(),
+ cache_ttl: None,
+ cache_ignore_s3_path: None,
+ dedicated_worker: Some(true),
+ language: lang,
+ priority: None,
+ apply_preprocessor: false,
+ labels: None,
+ concurrency_settings: Default::default(),
+ debouncing_settings: Default::default(),
+ job_token_scopes: None,
+ })
+ .arg("x", arg)
+ .as_user(user.0, user.1)
+ .push(&db)
+ .await,
+ );
+ }
+ let listener = listen_for_completed_jobs(&db).await;
+ in_test_worker_dedicated(
+ db.clone(),
+ wait_for_all(listener, &jobs),
+ port,
+ vec![wp("test-workspace", &path)],
+ )
+ .await;
+
+ let (a, o) = (admin.1, other.1);
+ let expected = [
+ Some(json!([a, a, true, "of-test-user"])),
+ // Its argument names a variable it cannot read: it alone fails.
+ None,
+ Some(json!([o, o, false, 1])),
+ Some(json!([a, a, true, 2])),
+ Some(json!([o, o, false, 3])),
+ ];
+ for (id, expected) in jobs.iter().zip(expected) {
+ let job = completed_job(*id, &db).await;
+ match expected {
+ Some(expected) => assert_eq!(job.json_result().unwrap(), expected),
+ None => assert!(!job.success),
+ }
+ assert_ran_on_dedicated_worker(&db, *id, mode).await;
+ }
+ let minted: i64 =
+ sqlx::query_scalar("SELECT count(*) FROM token WHERE label NOT LIKE 'test token%'")
+ .fetch_one(&db)
+ .await?;
+ assert_eq!(minted, 0);
+ Ok(())
+ }
+
+ #[sqlx::test(fixtures("base"))]
+ #[serial]
+ async fn test_dedicated_job_identity_bun(db: Pool) -> anyhow::Result<()> {
+ use windmill_common::scripts::ScriptLang;
+ check_job_identity(db, ScriptLang::Bun, "bun", IDENTITY_TS).await
+ }
+
+ #[sqlx::test(fixtures("base"))]
+ #[serial]
+ async fn test_dedicated_job_identity_nodejs(db: Pool) -> anyhow::Result<()> {
+ use windmill_common::scripts::ScriptLang;
+ let content = format!("//nodejs\n{IDENTITY_TS}");
+ check_job_identity(db, ScriptLang::Bun, "nodejs", &content).await
+ }
+
+ #[sqlx::test(fixtures("base"))]
+ #[serial]
+ async fn test_dedicated_job_identity_deno(db: Pool) -> anyhow::Result<()> {
+ use windmill_common::scripts::ScriptLang;
+ check_job_identity(db, ScriptLang::Deno, "deno", IDENTITY_TS).await
+ }
+
+ #[cfg(feature = "deno_core")]
+ #[sqlx::test(fixtures("base"))]
+ #[serial]
+ async fn test_dedicated_job_identity_native(db: Pool) -> anyhow::Result<()> {
+ use windmill_common::scripts::ScriptLang;
+ let content = format!("//native\n{IDENTITY_TS}");
+ check_job_identity(db, ScriptLang::Bunnative, "nativets", &content).await
+ }
+
+ #[cfg(feature = "python")]
+ #[sqlx::test(fixtures("base"))]
+ #[serial]
+ async fn test_dedicated_job_identity_python(db: Pool) -> anyhow::Result<()> {
+ use windmill_common::scripts::ScriptLang;
+ sqlx::query(
+ "INSERT INTO script(workspace_id, created_by, content, schema, summary, description,
+ path, hash, language, lock)
+ VALUES ('test-workspace', 'system', 'value = 7', '{}', '', '', 'u/someone/helper',
+ 300901, 'python3', '')",
+ )
+ .execute(&db)
+ .await?;
+ check_job_identity(db, ScriptLang::Python3, "python", IDENTITY_PY).await
+ }
+
+ /// A process that ends before completing its job fails it, instead of leaving it running.
+ #[sqlx::test(fixtures("base", "dedicated_flows"))]
+ #[serial]
+ async fn test_flow_runner_exits_at_import(db: Pool) -> anyhow::Result<()> {
+ initialize_tracing().await;
+ let server = ApiServer::start(db.clone()).await?;
+ let port = server.addr.port();
+ // The job is handed over while the process is still importing the script.
+ sqlx::query(
+ "INSERT INTO flow_version(id, workspace_id, path, schema, value, created_by)
+ SELECT 3000000000000099, workspace_id, path, schema, replace(value::text,
+ 'export function main', 'await new Promise((r) => setTimeout(r, 2000)); process.exit(1); export function main'
+ )::jsonb, created_by FROM flow_version WHERE id = 3000000000000004",
+ )
+ .execute(&db)
+ .await?;
+ let run = RunJob::from(JobPayload::Flow {
+ path: "f/system/dedicated_flow_runners".to_string(),
+ dedicated_worker: None,
+ apply_preprocessor: false,
+ labels: None,
+ version: 3000000000000099,
+ job_token_scopes: None,
+ });
+ let job = tokio::time::timeout(
+ std::time::Duration::from_secs(60),
+ run.run_until_complete(&db, false, port),
+ )
+ .await?;
+ assert!(job.json_result().unwrap().to_string().contains("exited before completing"));
+ assert!(!job.success);
+ Ok(())
+ }
+
+ /// A flow the loop calls has step ids of its own: its jobs run its code, as its identity, and
+ /// not the runner of the loop's step of that id.
+ #[sqlx::test(fixtures("base"))]
+ #[serial]
+ async fn test_flow_runner_called_flow(db: Pool) -> anyhow::Result<()> {
+ initialize_tracing().await;
+ let server = ApiServer::start(db.clone()).await?;
+ let port = server.addr.port();
+ let step = |content: &str, inputs: serde_json::Value| {
+ json!({ "id": "b", "value": {
+ "type": "rawscript", "language": "bun", "content": content,
+ "lock": "{}\n//bun.lock\n", "input_transforms": inputs,
+ }})
+ };
+ let called = json!({ "modules": [step(
+ "export function main() { return ['called', process.env.WM_EMAIL]; }", json!({}),
+ )]});
+ let outer = json!({ "modules": [{ "id": "a", "value": {
+ "type": "forloopflow", "squash": true, "parallel": false, "skip_failures": false,
+ "iterator": { "type": "javascript", "expr": "[1, 2]" },
+ "modules": [
+ { "id": "c", "value": {
+ "type": "flow", "path": "f/system/called", "input_transforms": {},
+ }},
+ step(
+ r#"
+const base = `${process.env.BASE_URL}/api/w/test-workspace/users/whoami`;
+const who = await fetch(base, { headers: { Authorization: "Bearer " + process.env.WM_TOKEN } });
+const atImport = (await who.json()).email;
+export function main(c: any) {
+ const { WM_EMAIL, WM_FLOW_STEP_ID, WM_FLOW_PATH, WM_FLOW_JOB_ID } = process.env;
+ return [c, atImport, WM_EMAIL, WM_FLOW_STEP_ID, !!WM_FLOW_PATH, !!WM_FLOW_JOB_ID];
+}"#,
+ json!({ "c": { "type": "javascript", "expr": "results.c" } }),
+ ),
+ ],
+ }}]});
+ for (version, path, value, on_behalf_of) in [
+ (3000000000000201i64, "f/system/called", &called, Some("u/test-user")),
+ (3000000000000202, "f/system/outer", &outer, None),
+ ] {
+ sqlx::query(
+ "INSERT INTO flow(workspace_id, summary, description, path, versions, schema,
+ value, edited_by, on_behalf_of, on_behalf_of_email)
+ VALUES ('test-workspace', '', '', $1, ARRAY[$2], '{}', $3, 'system', $4,
+ CASE WHEN $4 IS NOT NULL THEN 'test@windmill.dev' END)",
+ )
+ .bind(path)
+ .bind(version)
+ .bind(value)
+ .bind(on_behalf_of)
+ .execute(&db)
+ .await?;
+ sqlx::query(
+ "INSERT INTO flow_version(id, workspace_id, path, schema, value, created_by)
+ VALUES ($1, 'test-workspace', $2, '{}', $3, 'system')",
+ )
+ .bind(version)
+ .bind(path)
+ .bind(value)
+ .execute(&db)
+ .await?;
+ }
+ let job = RunJob::from(JobPayload::Flow {
+ path: "f/system/outer".to_string(),
+ dedicated_worker: None,
+ apply_preprocessor: false,
+ labels: None,
+ version: 3000000000000202,
+ job_token_scopes: None,
+ })
+ .as_user("test-user-2", "test2@windmill.dev")
+ .run_until_complete(&db, false, port)
+ .await;
+ let (called, caller) = (json!(["called", "test@windmill.dev"]), "test2@windmill.dev");
+ let iteration = json!([called, caller, caller, "b", true, true]);
+ assert_eq!(job.json_result().unwrap(), json!([iteration, iteration]));
+ assert_ran_on_dedicated_worker(&db, job.id, "bun").await;
+ Ok(())
+ }
+
+ /// A step that runs as someone else, asks for a sandbox or is a hub script is not run by a
+ /// loop's runners, whose directories are removed with them.
+ #[sqlx::test(fixtures("base"))]
+ #[serial]
+ async fn test_flow_runner_excluded_steps(db: Pool) -> anyhow::Result<()> {
+ initialize_tracing().await;
+ let server = ApiServer::start(db.clone()).await?;
+ let port = server.addr.port();
+ let content = "export function main() { return [process.env.WM_EMAIL, process.cwd()]; }";
+ let sandboxed = format!("//sandbox\n{content}");
+ for (hash, name, content, on_behalf_of) in [
+ (300901i64, "plain", content, None),
+ (300902, "as_other", content, Some("u/test-user")),
+ (300903, "sandboxed", &sandboxed, None),
+ ] {
+ sqlx::query(
+ "INSERT INTO script(workspace_id, created_by, content, schema, summary, description,
+ path, hash, language, lock, on_behalf_of, on_behalf_of_email)
+ VALUES ('test-workspace', 'test-user', $1, '{}', '', '', $2, $3, 'bun', $4, $5,
+ CASE WHEN $5 IS NOT NULL THEN 'test@windmill.dev' END)",
+ )
+ .bind(content)
+ .bind(format!("f/system/{name}"))
+ .bind(hash)
+ .bind("{}\n//bun.lock\n")
+ .bind(on_behalf_of)
+ .execute(&db)
+ .await?;
+ }
+ let step = |name: &str| {
+ json!({ "id": name, "value": {
+ "type": "script", "path": format!("f/system/{name}"), "input_transforms": {},
+ }})
+ };
+ // A sandboxed job fails on a host without nsjail, so the hub step never runs there.
+ let value = json!({ "modules": [{ "id": "a", "value": {
+ "type": "forloopflow", "squash": true, "parallel": false, "skip_failures": false,
+ "iterator": { "type": "javascript", "expr": "[1]" },
+ "modules": [step("plain"), step("as_other"), step("sandboxed"),
+ { "id": "hub", "value": { "type": "script", "path": "hub/1/none/none", "input_transforms": {} } }],
+ }}]});
+ sqlx::query(
+ "INSERT INTO flow(workspace_id, summary, description, path, versions, schema, value, edited_by)
+ VALUES ('test-workspace', '', '', 'f/system/excluded', ARRAY[3000000000000301], '{}', $1, 'system')",
+ )
+ .bind(&value)
+ .execute(&db)
+ .await?;
+ sqlx::query(
+ "INSERT INTO flow_version(id, workspace_id, path, schema, value, created_by)
+ VALUES (3000000000000301, 'test-workspace', 'f/system/excluded', '{}', $1, 'system')",
+ )
+ .bind(&value)
+ .execute(&db)
+ .await?;
+ RunJob::from(JobPayload::Flow {
+ path: "f/system/excluded".to_string(),
+ dedicated_worker: None,
+ apply_preprocessor: false,
+ labels: None,
+ version: 3000000000000301,
+ job_token_scopes: None,
+ })
+ .as_user("test-user-2", "test2@windmill.dev")
+ .run_until_complete(&db, false, port)
+ .await;
+ let steps: Vec<(String, bool, Option)> = sqlx::query_as(
+ "SELECT j.flow_step_id, COALESCE(l.logs, '') LIKE '%dedicated worker bun:%', c.result
+ FROM v2_job j JOIN v2_job_completed c USING (id) LEFT JOIN job_logs l ON l.job_id = j.id
+ WHERE j.kind = 'script' ORDER BY j.created_at",
+ )
+ .fetch_all(&db)
+ .await?;
+ assert_eq!(steps.len(), 3, "{steps:?}");
+ let ran = |i: usize| {
+ let (step, on_runner, result) = &steps[i];
+ (
+ step.as_str(),
+ *on_runner,
+ result.as_ref().unwrap()[0].as_str().unwrap().to_string(),
+ )
+ };
+ assert_eq!(ran(0), ("plain", true, "test2@windmill.dev".to_string()));
+ assert_eq!(ran(1), ("as_other", false, "test@windmill.dev".to_string()));
+ assert_eq!(
+ (steps[2].0.as_str(), steps[2].1),
+ ("sandboxed", false),
+ "{steps:?}"
+ );
+
+ let runner_dir = steps[0].2.as_ref().unwrap()[1]
+ .as_str()
+ .unwrap()
+ .to_string();
+ assert!(runner_dir.contains("dedicated-"), "{runner_dir}");
+ for _ in 0..100 {
+ if !std::path::Path::new(&runner_dir).exists() {
+ break;
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(100)).await;
+ }
+ assert!(
+ !std::path::Path::new(&runner_dir).exists(),
+ "{runner_dir} was left"
+ );
+ Ok(())
+ }
}
diff --git a/backend/tests/fixtures/dedicated_flows.sql b/backend/tests/fixtures/dedicated_flows.sql
index e81cd32556..0ff6ae5caa 100644
--- a/backend/tests/fixtures/dedicated_flows.sql
+++ b/backend/tests/fixtures/dedicated_flows.sql
@@ -326,7 +326,7 @@ E'{"modules":[{"id":"a","value":{"type":"forloopflow","iterator":{"type":"javasc
-- ============================================================
INSERT INTO public.script(workspace_id, created_by, content, schema, summary, description, path, hash, language, lock, dedicated_worker) VALUES (
'test-workspace',
-'system',
+'test-user',
E'# extra_requirements: f/system/dedicated_double\nfrom .py_dedicated_helper import helper\n\ndef main(x: int):\n return helper(x) + 100',
'{"$schema":"https://json-schema.org/draft/2020-12/schema","properties":{"x":{"type":"number","description":""}},"required":["x"],"type":"object"}',
'', '',
@@ -456,7 +456,7 @@ E'export function helper(x: number) { return x * 10; }',
INSERT INTO public.script(workspace_id, created_by, content, schema, summary, description, path, hash, language, lock, dedicated_worker) VALUES (
'test-workspace',
-'system',
+'test-user',
E'import { helper } from "./dedicated_helper.ts";\n\nexport function main(x: number) { return helper(x) + 1; }',
'{"$schema":"https://json-schema.org/draft/2020-12/schema","properties":{"x":{"type":"number","description":""}},"required":["x"],"type":"object"}',
'', '',
@@ -477,7 +477,7 @@ E'def helper(x: int):\n return x * 10',
INSERT INTO public.script(workspace_id, created_by, content, schema, summary, description, path, hash, language, lock, dedicated_worker) VALUES (
'test-workspace',
-'system',
+'test-user',
E'from .py_dedicated_helper import helper\n\ndef main(x: int):\n return helper(x) + 1',
'{"$schema":"https://json-schema.org/draft/2020-12/schema","properties":{"x":{"type":"number","description":""}},"required":["x"],"type":"object"}',
'', '',
@@ -598,3 +598,7 @@ E'{"modules":[{"id":"a","value":{"type":"forloopflow","iterator":{"type":"javasc
'system'
);
+-- Only a flow that enables dedicated_worker gets dedicated subprocesses. The squashed-loop flows
+-- are not dedicated: regular workers run them, and start their loops' runners.
+UPDATE public.flow SET dedicated_worker = true
+WHERE path NOT IN ('f/system/dedicated_flow_runners', 'f/system/dedicated_flow_runners_bash');
diff --git a/backend/windmill-api-flows/src/flows.rs b/backend/windmill-api-flows/src/flows.rs
index 01cdfd155d..a6961d4ea0 100644
--- a/backend/windmill-api-flows/src/flows.rs
+++ b/backend/windmill-api-flows/src/flows.rs
@@ -659,6 +659,38 @@ pub async fn validate_operator_composed_flow(
Ok(())
}
+/// A dedicated flow's steps load in a process that starts with a workspace admin token, so only
+/// admins enable `dedicated_worker` on a flow or deploy one that has it.
+async fn require_admin_for_dedicated_flow(
+ authed: &ApiAuthed,
+ db: &DB,
+ w_id: &str,
+ dedicated_worker: Option,
+ paths: &[&str],
+) -> Result<()> {
+ if authed.is_admin {
+ return Ok(());
+ }
+ let paths: Vec = paths.iter().map(|p| p.to_string()).collect();
+ let dedicated = dedicated_worker == Some(true)
+ || sqlx::query_scalar!(
+ r#"SELECT EXISTS (SELECT 1 FROM flow WHERE workspace_id = $1 AND path = ANY($2)
+ AND dedicated_worker IS TRUE) AS "dedicated!""#,
+ w_id,
+ &paths
+ )
+ .fetch_one(db)
+ .await?;
+ if dedicated {
+ return Err(Error::PermissionDenied(format!(
+ "only workspace admins can deploy {}: it runs on dedicated workers. Ask a workspace \
+ admin to deploy it.",
+ paths.last().map(String::as_str).unwrap_or_default()
+ )));
+ }
+ Ok(())
+}
+
async fn create_flow(
authed: ApiAuthed,
Extension(db): Extension,
@@ -671,6 +703,7 @@ async fn create_flow(
let flows_level =
check_operator_can_build(&db, &w_id, &authed, BuilderKind::Flows, "create flows").await?;
check_scopes(&authed, || format!("flows:write:{}", nf.path))?;
+ require_admin_for_dedicated_flow(&authed, &db, &w_id, nf.dedicated_worker, &[&nf.path]).await?;
// A `<= 0` flow timeout is "unset", not a 0-second limit that kills every run instantly.
// (The concurrency settings inside the flow value are normalized on deserialization; see
@@ -1300,6 +1333,14 @@ async fn update_flow(
if nf.path != flow_path {
check_scopes(&authed, || format!("flows:write:{}", nf.path))?;
}
+ require_admin_for_dedicated_flow(
+ &authed,
+ &db,
+ &w_id,
+ nf.dedicated_worker,
+ &[flow_path, &nf.path],
+ )
+ .await?;
if let RuleCheckResult::Blocked(msg) = check_deploy_rules(
&w_id,
diff --git a/backend/windmill-api-integration-tests/tests/scripts.rs b/backend/windmill-api-integration-tests/tests/scripts.rs
index d6afc9f302..d5be3e7a7f 100644
--- a/backend/windmill-api-integration-tests/tests/scripts.rs
+++ b/backend/windmill-api-integration-tests/tests/scripts.rs
@@ -1034,3 +1034,92 @@ async fn test_list_search_scope_filtering(db: Pool) -> anyhow::Result<
Ok(())
}
+
+async fn deploy_as(
+ db: &Pool,
+ base: &str,
+ token: &str,
+ path: String,
+ dedicated: bool,
+) -> reqwest::StatusCode {
+ let mut body = new_script(&path, "", "export async function main() { return 1; }");
+ body["dedicated_worker"] = json!(dedicated);
+ let deployed: bool = sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM script WHERE path = $1)")
+ .bind(&path)
+ .fetch_one(db)
+ .await
+ .unwrap();
+ let url = if deployed {
+ format!("{base}/scripts/update/{path}")
+ } else {
+ format!("{base}/scripts/create")
+ };
+ client()
+ .post(url)
+ .bearer_auth(token)
+ .json(&body)
+ .send()
+ .await
+ .unwrap()
+ .status()
+}
+
+/// A dedicated worker's process starts with a workspace admin token, so only admins deploy a
+/// script or flow that runs on dedicated workers.
+#[sqlx::test(migrations = "../migrations", fixtures("base"))]
+async fn test_dedicated_code_is_admin_only(db: Pool) -> anyhow::Result<()> {
+ initialize_tracing().await;
+ let server = ApiServer::start(db.clone()).await?;
+ let base = format!(
+ "http://localhost:{}/api/w/test-workspace",
+ server.addr.port()
+ );
+ let deploy = |token: &'static str, path: String, dedicated: bool| {
+ deploy_as(&db, &base, token, path, dedicated)
+ };
+ let (admin, user) = ("SECRET_TOKEN", "SECRET_TOKEN_2");
+ let p = |name: &str| format!("u/test-user-2/{name}");
+
+ assert_eq!(deploy(user, p("dedicated"), true).await, 403);
+ assert_eq!(deploy(admin, p("dedicated"), true).await, 201);
+ assert_eq!(deploy(user, p("dedicated"), false).await, 403);
+ assert_eq!(deploy(user, p("other"), false).await, 201);
+
+ let new_flow = |path: &str| {
+ json!({ "path": path, "summary": "", "description": "", "dedicated_worker": true,
+ "value": { "modules": [] }, "schema": {} })
+ };
+ let resp = client()
+ .post(format!("{base}/flows/create"))
+ .bearer_auth(user)
+ .json(&new_flow("u/test-user-2/flow"))
+ .send()
+ .await?;
+ assert_eq!(resp.status(), 403);
+ let resp = client()
+ .post(format!("{base}/flows/create"))
+ .bearer_auth(admin)
+ .json(&new_flow("u/test-user-2/flow"))
+ .send()
+ .await?;
+ assert_eq!(resp.status(), 201, "{}", resp.text().await?);
+ let mut plain = new_flow("u/test-user-2/plain_flow");
+ plain["dedicated_worker"] = json!(false);
+ let resp = client()
+ .post(format!("{base}/flows/create"))
+ .bearer_auth(user)
+ .json(&plain)
+ .send()
+ .await?;
+ assert_eq!(resp.status(), 201, "{}", resp.text().await?);
+ let mut edit = new_flow("u/test-user-2/flow");
+ edit["dedicated_worker"] = json!(false);
+ let resp = client()
+ .post(format!("{base}/flows/update/u/test-user-2/flow"))
+ .bearer_auth(user)
+ .json(&edit)
+ .send()
+ .await?;
+ assert_eq!(resp.status(), 403);
+ Ok(())
+}
diff --git a/backend/windmill-api-scripts/src/scripts.rs b/backend/windmill-api-scripts/src/scripts.rs
index 1102db5fe1..689dbdc299 100644
--- a/backend/windmill-api-scripts/src/scripts.rs
+++ b/backend/windmill-api-scripts/src/scripts.rs
@@ -1382,6 +1382,46 @@ async fn create_script_internal<'c>(
)> {
windmill_common::workspaces::check_role_can_code(&db, &w_id, &authed, "create scripts").await?;
check_scopes(&authed, || format!("scripts:write:{}", ns.path))?;
+ if !authed.is_admin {
+ let mut paths = vec![ns.path.clone()];
+ paths.extend(supersede_head_at.clone());
+ if let Some(parent) = &ns.parent_hash {
+ paths.extend(
+ sqlx::query_scalar!(
+ "SELECT path FROM script WHERE hash = $1 AND workspace_id = $2",
+ parent.0,
+ &w_id
+ )
+ .fetch_optional(&db)
+ .await?,
+ );
+ }
+ // The process of a dedicated script starts with a workspace admin token.
+ let runs_dedicated = sqlx::query_scalar!(
+ r#"SELECT EXISTS (SELECT 1 FROM (
+ SELECT DISTINCT ON (path) dedicated_worker FROM script
+ WHERE workspace_id = $1 AND path = ANY($2) AND archived = false
+ ORDER BY path, created_at DESC
+ ) s WHERE s.dedicated_worker IS TRUE) AS "e!""#,
+ &w_id,
+ &paths
+ )
+ .fetch_one(&db)
+ .await?;
+ let reason = if ns.dedicated_worker == Some(true) {
+ "it would run on dedicated workers"
+ } else if runs_dedicated {
+ "it runs on dedicated workers"
+ } else {
+ ""
+ };
+ if !reason.is_empty() {
+ return Err(Error::PermissionDenied(format!(
+ "only workspace admins can deploy {}: {reason}. Ask a workspace admin to deploy it.",
+ ns.path
+ )));
+ }
+ }
// Normalize positive-only settings so a `<= 0` value (e.g. a CLI-pushed `0`) persists as
// disabled rather than as a zero-slot concurrency cap or a 0-second timeout. Deserialization
diff --git a/backend/windmill-common/src/min_version.rs b/backend/windmill-common/src/min_version.rs
index f5ec9b00db..84a59fbbdf 100644
--- a/backend/windmill-common/src/min_version.rs
+++ b/backend/windmill-common/src/min_version.rs
@@ -53,6 +53,12 @@ pub const MIN_VERSION_SUPPORTS_FAILED_ONLY_RESTART: VC =
// so a step the test mocks would run for real. Must name the release this ships in.
pub const MIN_VERSION_SUPPORTS_FLOW_TEST_SUBFLOWS: VC =
vc(1, 879, 0, "Overriding steps inside subflows in flow tests");
+// A dedicated worker that predates per-job tokens uses one `token` row for as long as it runs,
+// so the rows left behind are only deleted once no such worker is live. Must name the release
+// this ships in or a later one. When the keep-alive minimum passes it, the deletion can become
+// a migration.
+pub const MIN_VERSION_SUPPORTS_DEDICATED_JOB_TOKENS: VC =
+ vc(1, 897, 0, "Per-job tokens on dedicated workers");
// A worker before this release decodes `trigger_kind` strictly and cannot read `ui`, so a job
// stamped with it would fail on every pull of that worker.
pub const MIN_VERSION_SUPPORTS_UI_TRIGGER_KIND: VC = vc(1, 776, 0, "ui trigger kind");
diff --git a/backend/windmill-queue/src/jobs.rs b/backend/windmill-queue/src/jobs.rs
index ea03341dce..adf4d2cb67 100644
--- a/backend/windmill-queue/src/jobs.rs
+++ b/backend/windmill-queue/src/jobs.rs
@@ -9478,6 +9478,8 @@ async fn restarted_flows_resolution(
// Wrapper struct to send both job and optional flow_runners to dedicated workers
pub struct DedicatedWorkerJob {
pub job: Arc,
+ /// The job's own token.
+ pub token: String,
pub flow_runners: Option>,
pub done_tx: Option>,
}
@@ -9487,6 +9489,22 @@ pub struct FlowRunners {
pub runners: HashMap>,
pub handles: Vec>,
pub job_id: Uuid,
+ /// What the jobs of the flow's own steps have as `flow_innermost_root_job`.
+ pub root_job: Uuid,
+ pub permissioned_as: String,
+}
+
+impl FlowRunners {
+ /// The runner of a job's step. Step ids are unique within a flow only, and the jobs of a
+ /// flow the loop calls also come with the loop's runners.
+ pub fn for_job(&self, job: &MiniPulledJob) -> Option<&Sender> {
+ if job.flow_innermost_root_job != Some(self.root_job)
+ || job.permissioned_as != self.permissioned_as
+ {
+ return None;
+ }
+ self.runners.get(job.flow_step_id.as_ref()?)
+ }
}
impl Drop for FlowRunners {
diff --git a/backend/windmill-runtime-nativets/src/dedicated.rs b/backend/windmill-runtime-nativets/src/dedicated.rs
index 5838456de9..94a35d38dd 100644
--- a/backend/windmill-runtime-nativets/src/dedicated.rs
+++ b/backend/windmill-runtime-nativets/src/dedicated.rs
@@ -31,7 +31,7 @@ impl ExecutingIsolate {
}
pub struct PrewarmedIsolate {
- args_tx: Option>,
+ args_tx: Option)>>,
result_rx: Option>,
ready_rx: Option>,
handle: Option>>,
@@ -58,7 +58,7 @@ impl PrewarmedIsolate {
arg_names: Vec,
entrypoint: Option,
) -> Self {
- let (args_tx, args_rx) = tokio::sync::oneshot::channel::();
+ let (args_tx, args_rx) = tokio::sync::oneshot::channel::<(String, Option)>();
let (result_tx, result_rx) = tokio::sync::oneshot::channel::();
let (ready_tx, ready_rx) = tokio::sync::oneshot::channel::<()>();
@@ -76,11 +76,21 @@ impl PrewarmedIsolate {
let _ = ready_tx.send(());
- let args_json = match args_rx.await {
+ let (args_json, job_env) = match args_rx.await {
Ok(a) => a,
Err(_) => return Ok(()),
};
+ if let Some(job_env) = job_env {
+ let set = js_runtime
+ .execute_script("", format!("globalThis.__wmJobEnv = {job_env};"));
+ if set.is_err() {
+ let result = Err("could not set the job's variables".to_string());
+ let _ = result_tx.send(PrewarmedResult { result, logs: String::new() });
+ return Ok(());
+ }
+ }
+
let positional = args_to_positional(&args_json, &arg_names);
{
let op_state = js_runtime.op_state();
@@ -145,9 +155,19 @@ impl PrewarmedIsolate {
/// Send args and start execution. Returns an `ExecutingIsolate` that
/// can be awaited independently, allowing the caller to pre-warm
/// the next isolate in parallel.
- pub fn start_execution(mut self, args: String) -> ExecutingIsolate {
+ pub fn start_execution(self, args: String) -> ExecutingIsolate {
+ self.start(args, None)
+ }
+
+ /// [`Self::start_execution`] with variables only this job has, as a JSON object. `env_code`
+ /// reads them from `globalThis.__wmJobEnv`: the modules are loaded but not yet evaluated.
+ pub fn start_execution_with_env(self, args: String, job_env: &str) -> ExecutingIsolate {
+ self.start(args, Some(job_env.to_string()))
+ }
+
+ fn start(mut self, args: String, job_env: Option) -> ExecutingIsolate {
let args_tx = self.args_tx.take().expect("start_execution called twice");
- let _ = args_tx.send(args);
+ let _ = args_tx.send((args, job_env));
ExecutingIsolate {
result_rx: self.result_rx.take().expect("result_rx missing"),
handle: self.handle.take().expect("handle missing"),
diff --git a/backend/windmill-worker/src/bun_executor.rs b/backend/windmill-worker/src/bun_executor.rs
index f6e7ee2f68..49caf3cd24 100644
--- a/backend/windmill-worker/src/bun_executor.rs
+++ b/backend/windmill-worker/src/bun_executor.rs
@@ -212,9 +212,12 @@ pub struct TsScriptEntry<'a> {
/// execd_preprocess: -> preprocess + execute the single registered script
/// exec:: -> execute script by path (runner groups with multiple scripts)
/// exec_preprocess:: -> preprocess + execute script by path
+/// env: -> set the variables of the next job, or clear the last one's
/// end -> exit
#[cfg(any(feature = "private", test))]
pub fn generate_multi_script_wrapper(scripts: &[TsScriptEntry<'_>], ext: &str) -> String {
+ use crate::common::JOB_ENV_JS;
+
let is_debug = std::env::var("RUST_LOG").is_ok_and(|x| x == "windmill=debug");
let print_lines = if is_debug {
r#"console.log("[debug] " + line);"#
@@ -279,7 +282,7 @@ function getPreArgs_{i}(line) {{
r#"
{imports}
import * as Readline from "node:readline"
-
+{JOB_ENV_JS}
BigInt.prototype.toJSON = function () {{
return this.toString();
}};
@@ -307,6 +310,11 @@ const scripts = new Map();
console.log('start');
for await (const line of Readline.createInterface({{ input: process.stdin }})) {{
+ if (line.startsWith("env:")) {{
+ _wmSetJobEnv(line.slice("env:".length));
+ continue;
+ }}
+
{print_lines}
if (line === "end") {{
@@ -4787,7 +4795,7 @@ async fn handle_dedicated_bunnative(
inner_content: &str,
js_code: &str,
env_code: &str,
- token: &str,
+ base_internal_url: &str,
worker_name: &str,
_w_id: &str,
script_path: &str,
@@ -4795,7 +4803,6 @@ async fn handle_dedicated_bunnative(
jobs_rx: &mut Receiver,
killpill_rx: tokio::sync::broadcast::Receiver<()>,
job_completed_tx: JobCompletedSender,
- client: &windmill_common::client::AuthedClient,
) -> Result<()> {
#[cfg(not(feature = "deno_core"))]
{
@@ -4803,14 +4810,13 @@ async fn handle_dedicated_bunnative(
inner_content,
js_code,
env_code,
- token,
+ base_internal_url,
worker_name,
script_path,
db,
jobs_rx,
killpill_rx,
job_completed_tx,
- client,
);
return Err(error::Error::internal_err(
"deno_core feature is not activated but native dedicated worker was started"
@@ -4822,7 +4828,6 @@ async fn handle_dedicated_bunnative(
{
use std::sync::Arc;
- use crate::common::transform_json;
use windmill_common::worker::to_raw_value;
use windmill_queue::{append_logs, JobCompleted, MiniCompletedJob};
use windmill_runtime_nativets::PrewarmedIsolate;
@@ -4832,7 +4837,7 @@ async fn handle_dedicated_bunnative(
windmill_parser_ts::parse_deno_signature(inner_content, true, false, None)?.args;
let arg_names: Vec = parsed_args.into_iter().map(|x| x.name).collect();
- let env_code = env_code.to_string();
+ let env_code = format!("{env_code}{}", crate::common::JOB_ENV_NATIVE_JS);
let js_code = js_code.to_string();
let pre_arg_names: Option> = windmill_parser_ts::parse_deno_signature(
@@ -4886,29 +4891,34 @@ async fn handle_dedicated_bunnative(
break;
},
job = jobs_rx.recv(), if alive => {
- if let Some(DedicatedWorkerJob { job, flow_runners, done_tx }) = job {
+ if let Some(DedicatedWorkerJob { job, token, flow_runners, done_tx }) = job {
let id = job.id;
+ let _masks = crate::worker::RunningJobMasks::register(id, &token);
+ let mut masker = windmill_common::sensitive_log_masks::JobMasker::new(id);
tracing::info!(
"received job on nativets dedicated worker for {script_path}: {id}"
);
- let args = if let Some(args) = job.args.as_ref() {
- if let Some(x) = transform_json(
- client, &job.workspace_id, &args.0, &job, &db.into(),
- ).await? {
- serde_json::to_string(&x)
- .unwrap_or_else(|_| "{}".to_string())
- } else {
- serde_json::to_string(&args)
- .unwrap_or_else(|_| "{}".to_string())
- }
- } else {
- "{}".to_string()
- };
+ let args = crate::common::dedicated_job_args(
+ &job, &token, base_internal_url, db,
+ ).await;
+ let mut job_env = crate::common::dedicated_job_env(&job, &token, flow_runners.is_some(), db).await;
+ if ann.no_network {
+ job_env.remove("WM_TOKEN");
+ }
+ let job_env = serde_json::to_string(&job_env)
+ .unwrap_or_else(|_| "{}".to_string());
// Run the job: preprocess if needed, then execute main.
// Uses a labeled block to unify error handling with a single JobCompleted send.
let (result, success, preprocessed_args, logs) = 'job: {
+ let args = match args {
+ Ok(args) => args,
+ Err(e) => break 'job (
+ Arc::new(to_raw_value(&serde_json::json!({"message": e.to_string(), "name": "Error"}))),
+ false, None, init_log.clone(),
+ ),
+ };
let ready = match init_err.take() {
Some(e) => Err(e),
None => warm.wait_ready().await,
@@ -4946,7 +4956,7 @@ async fn handle_dedicated_bunnative(
);
}
- let pre_executing = pre_isolate.start_execution(args.clone());
+ let pre_executing = pre_isolate.start_execution_with_env(args.clone(), &job_env);
// Pipeline: start pre-warming the next preprocessor isolate
pre_warm = Some(PrewarmedIsolate::spawn(
env_code.clone(),
@@ -4964,7 +4974,7 @@ async fn handle_dedicated_bunnative(
),
};
if !pre_result.logs.is_empty() {
- append_logs(&id, &job.workspace_id, pre_result.logs, &db.into()).await;
+ append_logs(&id, &job.workspace_id, masker.mask(&pre_result.logs).into_owned(), &db.into()).await;
}
let raw = match pre_result.result {
Ok(r) => r,
@@ -4988,7 +4998,7 @@ async fn handle_dedicated_bunnative(
(args, None)
};
- let executing = warm.start_execution(main_args);
+ let executing = warm.start_execution_with_env(main_args, &job_env);
// Pipeline: start pre-warming the next main isolate
warm = PrewarmedIsolate::spawn(
env_code.clone(),
@@ -5044,7 +5054,7 @@ async fn handle_dedicated_bunnative(
.unwrap_or(result)
};
- append_logs(&id, &job.workspace_id, logs, &db.into()).await;
+ append_logs(&id, &job.workspace_id, masker.mask(&logs).into_owned(), &db.into()).await;
job_completed_tx.send_job(JobCompleted {
job: MiniCompletedJob::from(job),
result,
@@ -5054,7 +5064,7 @@ async fn handle_dedicated_bunnative(
canceled_by: None,
success,
cached_res_path: None,
- token: token.to_string(),
+ token,
duration: None,
preprocessed_args,
has_stream: Some(false),
@@ -5090,7 +5100,6 @@ pub async fn start_worker(
job_completed_tx: JobCompletedSender,
jobs_rx: &mut Receiver,
killpill_rx: tokio::sync::broadcast::Receiver<()>,
- client: windmill_common::client::AuthedClient,
concurrency_semaphore: Option>,
) -> Result<()> {
let mut logs = "".to_string();
@@ -5197,7 +5206,7 @@ pub async fn start_worker(
inner_content,
&js_code,
&env_code,
- token,
+ base_internal_url,
worker_name,
w_id,
script_path,
@@ -5205,7 +5214,6 @@ pub async fn start_worker(
jobs_rx,
killpill_rx,
job_completed_tx,
- &client,
)
.await;
}
@@ -5356,13 +5364,12 @@ pub async fn start_worker(
vec![&wrapper_path],
killpill_rx,
job_completed_tx,
- token,
+ base_internal_url,
jobs_rx,
worker_name,
db,
script_path,
"nodejs",
- client,
false,
concurrency_semaphore,
)
@@ -5386,13 +5393,12 @@ pub async fn start_worker(
],
killpill_rx,
job_completed_tx,
- token,
+ base_internal_url,
jobs_rx,
worker_name,
db,
script_path,
"bun",
- client,
false,
concurrency_semaphore,
)
diff --git a/backend/windmill-worker/src/common.rs b/backend/windmill-worker/src/common.rs
index 381b004ca1..defb01a5e5 100644
--- a/backend/windmill-worker/src/common.rs
+++ b/backend/windmill-worker/src/common.rs
@@ -648,6 +648,136 @@ async fn get_job_variables(
Ok(build_envs_map(variables).await)
}
+#[cfg(feature = "private")]
+pub(crate) const DEDICATED_JOB_VARS: [&str; 11] = [
+ "WM_TOKEN",
+ "WM_EMAIL",
+ "WM_USERNAME",
+ "WM_PERMISSIONED_AS",
+ "WM_JOB_ID",
+ "WM_END_USER_EMAIL",
+ "WM_FLOW_JOB_ID",
+ "WM_ROOT_FLOW_JOB_ID",
+ "WM_ROOT_JOB_ID",
+ "WM_FLOW_STEP_ID",
+ "WM_FLOW_PATH",
+];
+
+/// The variables of one job that a dedicated process is given along with it: the
+/// [`DEDICATED_JOB_VARS`]. The flow's path takes a query, so only a flow runner's jobs have it.
+#[cfg(feature = "private")]
+pub(crate) async fn dedicated_job_env(
+ job: &MiniPulledJob,
+ token: &str,
+ flow_runner: bool,
+ db: &DB,
+) -> HashMap<&'static str, String> {
+ let flow_path = if flow_runner {
+ parent_flow_path(job.parent_job, &db.into())
+ .await
+ .unwrap_or_else(|e| {
+ tracing::error!("Error reading the flow path of job {}: {e:#}", job.id);
+ None
+ })
+ } else {
+ None
+ };
+ let id = |x: Option| x.map(|x| x.to_string()).unwrap_or_default();
+ HashMap::from([
+ ("WM_FLOW_JOB_ID", id(job.parent_job)),
+ ("WM_ROOT_FLOW_JOB_ID", id(job.flow_innermost_root_job)),
+ ("WM_ROOT_JOB_ID", get_root_job_id(job).to_string()),
+ ("WM_FLOW_STEP_ID", job.flow_step_id.clone().unwrap_or_default()),
+ ("WM_FLOW_PATH", flow_path.unwrap_or_default()),
+ ("WM_TOKEN", token.to_string()),
+ ("WM_EMAIL", job.permissioned_as_email.clone()),
+ ("WM_USERNAME", job.created_by.clone()),
+ ("WM_PERMISSIONED_AS", job.permissioned_as.clone()),
+ ("WM_JOB_ID", job.id.to_string()),
+ (
+ "WM_END_USER_EMAIL",
+ job.permissioned_as_end_user_email
+ .clone()
+ .unwrap_or_default(),
+ ),
+ ])
+}
+
+/// A job's arguments as JSON, its references resolved with its own token.
+#[cfg(feature = "private")]
+pub(crate) async fn dedicated_job_args(
+ job: &MiniPulledJob,
+ token: &str,
+ base_internal_url: &str,
+ db: &DB,
+) -> error::Result {
+ let Some(args) = job.args.as_ref() else {
+ return Ok("{}".to_string());
+ };
+ let client = AuthedClient::new(
+ base_internal_url.to_string(),
+ job.workspace_id.clone(),
+ token.to_string(),
+ None,
+ );
+ let resolved = transform_json(&client, &job.workspace_id, &args.0, job, &db.into()).await?;
+ Ok(match resolved {
+ Some(x) => serde_json::to_string(&x),
+ None => serde_json::to_string(args),
+ }
+ .unwrap_or_else(|_| "{}".to_string()))
+}
+
+/// Sets a job's variables in a JS wrapper. `windmill-client`, possibly a copy bundled in the
+/// script, keeps the token it read at import or in `setClient`: a request to this instance
+/// carrying a token the process was given is sent with the job's. The token follows the job's
+/// async context, so a call it left running never goes out with the next job's.
+#[cfg(any(feature = "private", test))]
+pub(crate) const JOB_ENV_JS: &str = r#"
+import { AsyncLocalStorage as _WmAsyncLocalStorage } from "node:async_hooks";
+import _wmProcess from "node:process";
+
+const _wmJobToken = new _WmAsyncLocalStorage();
+const _wmSpawnAuth = "Bearer " + _wmProcess.env.WM_TOKEN;
+const _wmOrigins = new Set();
+for (const name of ["BASE_INTERNAL_URL", "BASE_URL", "WM_BASE_URL"]) {
+ try { _wmOrigins.add(new URL(_wmProcess.env[name]).origin); } catch {}
+}
+// Any job token, rather than the ones seen: a process runs too many jobs to remember them.
+const _wmStale = (auth, input) => auth === _wmSpawnAuth
+ || /^Bearer jwt_(?!ext_)/.test(auth ?? "")
+ && _wmOrigins.has(new URL(input instanceof Request ? input.url : input).origin);
+
+globalThis.fetch = new Proxy(globalThis.fetch, {
+ apply(target, thisArg, args) {
+ const token = _wmJobToken.getStore();
+ if (token) {
+ try {
+ const [input, init] = args;
+ const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : undefined));
+ if (_wmStale(headers.get("authorization"), input)) {
+ headers.set("authorization", "Bearer " + token);
+ args = [input, { ...init, headers }];
+ }
+ } catch {}
+ }
+ return Reflect.apply(target, thisArg, args);
+ },
+});
+
+function _wmSetJobEnv(json) {
+ const env = JSON.parse(json);
+ Object.assign(_wmProcess.env, env);
+ _wmJobToken.enterWith(env.WM_TOKEN);
+}
+"#;
+
+/// Takes the variables of [`start_execution_with_env`], set before the script is evaluated.
+///
+/// [`start_execution_with_env`]: windmill_runtime_nativets::PrewarmedIsolate::start_execution_with_env
+#[cfg(all(feature = "private", feature = "deno_core"))]
+pub(crate) const JOB_ENV_NATIVE_JS: &str = "\nObject.assign(process.env, globalThis.__wmJobEnv);\n";
+
pub async fn build_envs_map(context: Vec) -> HashMap {
let mut r: HashMap =
context.into_iter().map(|rv| (rv.name, rv.value)).collect();
diff --git a/backend/windmill-worker/src/dedicated_worker_oss.rs b/backend/windmill-worker/src/dedicated_worker_oss.rs
index 09e86193e0..b1be466344 100644
--- a/backend/windmill-worker/src/dedicated_worker_oss.rs
+++ b/backend/windmill-worker/src/dedicated_worker_oss.rs
@@ -24,3 +24,10 @@ pub async fn spawn_flow_module_runners(
"Squashing flow loops is not available in OSS".to_string(),
))
}
+
+#[cfg(not(feature = "private"))]
+pub async fn delete_dedicated_worker_tokens(
+ _db: &windmill_common::db::DB,
+) -> windmill_common::error::Result<(u64, bool)> {
+ Ok((0, false))
+}
diff --git a/backend/windmill-worker/src/deno_executor.rs b/backend/windmill-worker/src/deno_executor.rs
index 9f673710b8..ec2b0a2f69 100644
--- a/backend/windmill-worker/src/deno_executor.rs
+++ b/backend/windmill-worker/src/deno_executor.rs
@@ -754,6 +754,8 @@ use crate::{dedicated_worker_oss::handle_dedicated_process, JobCompletedSender};
/// and preprocessor logic. Uses the `execd:` protocol (single-script, no path needed).
#[cfg(any(feature = "private", test))]
pub fn generate_dedicated_worker_wrapper(inner_content: &str) -> Result {
+ use crate::common::JOB_ENV_JS;
+
let args = windmill_parser_ts::parse_deno_signature(inner_content, true, false, None)?.args;
let dates = args
.iter()
@@ -819,7 +821,7 @@ pub fn generate_dedicated_worker_wrapper(inner_content: &str) -> Result
r#"
import {{ main }} from "./main.ts";
{preprocessor_import}
-
+{JOB_ENV_JS}
BigInt.prototype.toJSON = function () {{
return this.toString();
}};
@@ -840,6 +842,10 @@ for await (const chunk of Deno.stdin.readable) {{
exit = true;
break;
}}
+ if (line.startsWith("env:")) {{
+ _wmSetJobEnv(line.slice("env:".length));
+ continue;
+ }}
{preprocessor_logic}
if (line.startsWith("execd:")) {{
const argsJson = line.slice("execd:".length);
@@ -882,7 +888,6 @@ pub async fn start_worker(
jobs_rx: &mut Receiver,
killpill_rx: tokio::sync::broadcast::Receiver<()>,
db: &sqlx::Pool,
- client: windmill_common::client::AuthedClient,
concurrency_semaphore: Option>,
) -> Result<()> {
use windmill_common::variables;
@@ -948,13 +953,12 @@ pub async fn start_worker(
deno_args,
killpill_rx,
job_completed_tx,
- token,
+ base_internal_url,
jobs_rx,
worker_name,
db,
script_path,
"deno",
- client,
false,
concurrency_semaphore,
)
diff --git a/backend/windmill-worker/src/lib.rs b/backend/windmill-worker/src/lib.rs
index 685d0bc011..92755aa9fd 100644
--- a/backend/windmill-worker/src/lib.rs
+++ b/backend/windmill-worker/src/lib.rs
@@ -42,6 +42,7 @@ mod dbt_state;
#[cfg(feature = "private")]
mod dedicated_worker_ee;
mod dedicated_worker_oss;
+pub use dedicated_worker_oss::delete_dedicated_worker_tokens;
mod deno_executor;
mod docker_v2;
#[cfg(feature = "duckdb")]
diff --git a/backend/windmill-worker/src/python_executor.rs b/backend/windmill-worker/src/python_executor.rs
index 5aefaed01c..1b978f569a 100644
--- a/backend/windmill-worker/src/python_executor.rs
+++ b/backend/windmill-worker/src/python_executor.rs
@@ -1544,6 +1544,7 @@ pub struct PyScriptEntry<'a> {
/// Protocol:
/// execd: -> execute the single registered script (non-runner-group)
/// exec:: -> execute script by path (runner groups)
+/// env: -> set the variables of the next job, or clear the last one's
/// end -> exit
#[cfg(any(feature = "private", test))]
pub fn generate_multi_script_wrapper(
@@ -1631,6 +1632,7 @@ def pre_transform_{i}(kwargs):
format!(
r#"
import json
+import os
import sys
import traceback
import re
@@ -1680,6 +1682,24 @@ def res_to_json(res, typ):
{functions}
{registrations}
+# `loader` leaves an empty module for a script the running job cannot read, which the next job may.
+def forget_unresolved_imports():
+ loader = sys.modules.get('loader')
+ if loader is None:
+ return
+ names = [n for n in sys.modules if n.startswith(('f.', 'u.'))]
+ for n in sorted(names, key=len, reverse=True):
+ spec = getattr(sys.modules[n], '__spec__', None)
+ if n.count('.') < 2 or not isinstance(getattr(spec, 'loader', None), loader.WindmillLoader):
+ continue
+ if any(m.startswith(n + '.') for m in sys.modules):
+ continue
+ mod = sys.modules.pop(n)
+ parent, _, name = n.rpartition('.')
+ parent = sys.modules.get(parent)
+ if getattr(parent, name, None) is mod:
+ delattr(parent, name)
+
sys.stdout.write('start\n')
sys.stdout.flush()
@@ -1688,6 +1708,15 @@ for line in sys.stdin:
if line == 'end':
break
+ if line.startswith('env:'):
+ os.environ.update(json.loads(line[len('env:'):]))
+ # `wmill` keeps the first client it builds, along with the token it was built with.
+ wmill_client = sys.modules.get('wmill.client')
+ if wmill_client is not None:
+ wmill_client._client = None
+ forget_unresolved_imports()
+ continue
+
if line.startswith('exec_preprocess:'):
try:
rest = line[len('exec_preprocess:'):]
@@ -3705,7 +3734,6 @@ pub async fn start_worker(
job_completed_tx: JobCompletedSender,
jobs_rx: &mut tokio::sync::mpsc::Receiver,
killpill_rx: tokio::sync::broadcast::Receiver<()>,
- client: windmill_common::client::AuthedClient,
concurrency_semaphore: Option>,
) -> error::Result<()> {
use crate::PyV;
@@ -3848,13 +3876,12 @@ pub async fn start_worker(
["-u", "-m", "wrapper"].to_vec(),
killpill_rx,
job_completed_tx,
- token,
+ base_internal_url,
jobs_rx,
worker_name,
db,
script_path,
"python",
- client,
false,
concurrency_semaphore,
)
diff --git a/backend/windmill-worker/src/worker.rs b/backend/windmill-worker/src/worker.rs
index eb0d6df8c5..548660366d 100644
--- a/backend/windmill-worker/src/worker.rs
+++ b/backend/windmill-worker/src/worker.rs
@@ -1192,6 +1192,16 @@ pub fn runs_no_network_in_jail(language: Option, content: &str) -> b
}
}
+/// Whether a script asks to be jailed wherever it runs.
+pub fn asks_for_sandbox(language: Option, content: &str) -> bool {
+ match language {
+ Some(ScriptLang::Python3) => {
+ windmill_common::worker::PythonAnnotations::parse(content).sandbox
+ }
+ _ => windmill_common::worker::TypeScriptAnnotations::parse(content).sandbox,
+ }
+}
+
/// Refuses a `no_network` job that imports another workspace script its run step would fetch
/// from the API, which it cannot reach. Without this the fetch fails inside the script, where
/// Python's loader falls back to an empty namespace module and the error names something else.
@@ -4090,9 +4100,8 @@ pub async fn run_worker(
// dispatch by path and return before that check, so a job sent down them
// would run with whatever arguments survived the failure.
let fails_before_running = job.pre_run_error.is_some();
- // A dedicated worker or flow runner runs every job it gets with its own
- // unscoped worker token, so a job with a restricted token runs here, with the
- // token minted for it, whichever tag brought it.
+ // A dedicated worker or flow runner shares its process between jobs, so a job
+ // with a restricted token runs here, in its own, whichever tag brought it.
let restricted = job.job_token_scopes.is_some();
if !dedicated_workers.is_empty() && !fails_before_running && !restricted {
@@ -4124,8 +4133,11 @@ pub async fn run_worker(
});
if let Some(dedicated_worker_tx) = dedicated_worker_tx {
let job_id = job.id;
+ let JobAndPerms { job, token, .. } =
+ extract_job_and_perms(job, &conn).await;
let dedicated_job = DedicatedWorkerJob {
- job: Arc::new(job.job()),
+ job: Arc::new(job),
+ token,
flow_runners: None,
done_tx: None,
};
@@ -4163,71 +4175,92 @@ pub async fn run_worker(
if let Some(flow_runners) =
flow_runners.filter(|_| !fails_before_running && !restricted)
{
- let key_o = job.flow_step_id.as_ref().map(|x| x.to_string());
- if let Some(key) = key_o {
- if let Some(flow_runner_tx) = flow_runners.runners.get(&key) {
- tracing::info!(
- "sending job {} to flow runner step {}",
- job.id,
- key
- );
- let (done_tx, done_rx) = tokio::sync::oneshot::channel::<()>();
- let flow_runners = flow_runners.clone();
+ if let Some(flow_runner_tx) = flow_runners.for_job(&job) {
+ tracing::info!(
+ "sending job {} to flow runner step {}",
+ job.id,
+ job.flow_step_id.as_deref().unwrap_or_default()
+ );
+ let (done_tx, done_rx) = tokio::sync::oneshot::channel::<()>();
+ let flow_runners = flow_runners.clone();
- let job = job.job();
+ let JobAndPerms { job, token, .. } =
+ extract_job_and_perms(job, &conn).await;
- let dedicated_job = DedicatedWorkerJob {
- job: Arc::new(job.clone()),
- flow_runners: Some(flow_runners),
- done_tx: Some(done_tx),
- };
+ let dedicated_job = DedicatedWorkerJob {
+ job: Arc::new(job.clone()),
+ token: token.clone(),
+ flow_runners: Some(flow_runners),
+ done_tx: Some(done_tx),
+ };
- if let Err(e) = flow_runner_tx.send(dedicated_job).await {
- let token = match &conn {
- Connection::Sql(db) => {
- windmill_queue::jobs::create_token(db, &job, None).await
- }
- _ => "".to_string(),
- };
- handle_all_job_kind_error(
- &conn,
- &AuthedClient::new(
- base_internal_url.to_owned(),
- job.workspace_id.clone(),
- token,
- None,
- ),
- MiniCompletedJob::from(job),
- error::Error::InternalErr(format!(
- "failed to send jobs to flow runners: {e:?}"
- )),
- false,
- Some(&same_worker_tx),
- &worker_dir,
- &worker_name,
- job_completed_tx.clone(),
- &killpill_rx,
- #[cfg(feature = "benchmark")]
- &mut bench,
- )
- .await;
- } else {
- if let Err(err) = done_rx.await {
- tracing::error!("Flow runner done channel has been dropped without being received: {err:?}");
+ if let Err(e) = flow_runner_tx.send(dedicated_job).await {
+ handle_all_job_kind_error(
+ &conn,
+ &AuthedClient::new(
+ base_internal_url.to_owned(),
+ job.workspace_id.clone(),
+ token,
+ None,
+ ),
+ MiniCompletedJob::from(job),
+ error::Error::InternalErr(format!(
+ "failed to send jobs to flow runners: {e:?}"
+ )),
+ false,
+ Some(&same_worker_tx),
+ &worker_dir,
+ &worker_name,
+ job_completed_tx.clone(),
+ &killpill_rx,
+ #[cfg(feature = "benchmark")]
+ &mut bench,
+ )
+ .await;
+ } else {
+ if let Err(err) = done_rx.await {
+ tracing::error!("Flow runner done channel has been dropped without being received: {err:?}");
+ // Nothing restarts a flow runner. On shutdown the job is
+ // left for another worker to recover.
+ let stopping = killed_but_draining_same_worker_jobs
+ || !killpill_rx.is_empty();
+ if !stopping && is_running(&conn, &job.id).await {
+ handle_all_job_kind_error(
+ &conn,
+ &AuthedClient::new(
+ base_internal_url.to_owned(),
+ job.workspace_id.clone(),
+ token,
+ None,
+ ),
+ MiniCompletedJob::from(job),
+ error::Error::ExecutionErr(
+ "the process of this step exited before completing the job".to_string(),
+ ),
+ false,
+ Some(&same_worker_tx),
+ &worker_dir,
+ &worker_name,
+ job_completed_tx.clone(),
+ &killpill_rx,
+ #[cfg(feature = "benchmark")]
+ &mut bench,
+ )
+ .await;
}
}
-
- #[cfg(feature = "benchmark")]
- {
- add_time!(bench, "sent to flow runner");
- if let Some(db) = conn.as_sql() {
- infos.sample_pool(db.size(), db.num_idle() as u32);
- }
- infos.add_iter(bench, bench_job_id, is_top_level_job);
- }
-
- continue;
}
+
+ #[cfg(feature = "benchmark")]
+ {
+ add_time!(bench, "sent to flow runner");
+ if let Some(db) = conn.as_sql() {
+ infos.sample_pool(db.size(), db.num_idle() as u32);
+ }
+ infos.add_iter(bench, bench_job_id, is_top_level_job);
+ }
+
+ continue;
}
}
}
@@ -5026,6 +5059,20 @@ pub struct PreviousResult<'a> {
pub previous_result: Option<&'a RawValue>,
}
+async fn is_running(conn: &Connection, job_id: &Uuid) -> bool {
+ let Connection::Sql(db) = conn else {
+ return false;
+ };
+ sqlx::query_scalar!("SELECT running FROM v2_job_queue WHERE id = $1", job_id)
+ .fetch_optional(db)
+ .await
+ .unwrap_or_else(|e| {
+ tracing::error!("Error reading whether job {job_id} is running: {e:#}");
+ None
+ })
+ .unwrap_or(false)
+}
+
/// Detects and stores runtime assets from job arguments.
/// This function is called when a job starts executing to track which assets
/// are passed as inputs to the job at runtime.
@@ -5069,10 +5116,10 @@ async fn detect_and_store_runtime_assets_from_job_args(
/// Lives here rather than at the call sites so that every way of running a job —
/// the poller, the interactive worker shell, an inline AI agent tool — is covered
/// by construction.
-struct RunningJobMasks(Uuid);
+pub(crate) struct RunningJobMasks(Uuid);
impl RunningJobMasks {
- fn register(job_id: Uuid, token: &str) -> Self {
+ pub(crate) fn register(job_id: Uuid, token: &str) -> Self {
windmill_common::sensitive_log_masks::register_running_job(job_id);
windmill_common::sensitive_log_masks::register_secret_for_job(job_id, token);
RunningJobMasks(job_id)
@@ -7761,7 +7808,7 @@ pub async fn parse_sig_of_lang(
/// resolves to `/`, shared by every concurrent run and unwritable to a non-root server.
/// Removed on drop: no job loop owns it, and the run's future is dropped mid-await when the
/// HTTP client disconnects.
-struct InlineJobDir(String);
+pub(crate) struct InlineJobDir(pub(crate) String);
impl Drop for InlineJobDir {
fn drop(&mut self) {
diff --git a/backend/windmill-worker/src/worker_flow.rs b/backend/windmill-worker/src/worker_flow.rs
index 28920820fd..f73074c4f7 100644
--- a/backend/windmill-worker/src/worker_flow.rs
+++ b/backend/windmill-worker/src/worker_flow.rs
@@ -5025,15 +5025,33 @@ async fn push_next_flow_job(
};
// only start runners if we're not already in a squash for loop
- // Runners would run its steps with their own unscoped token: a restricted flow, or a loop
- // that restricts itself or any step in it, runs them as regular jobs.
- let start_runners = flow_runners.is_none()
+ // A restricted flow, or a loop that restricts itself or any step in it, runs its steps as
+ // regular jobs rather than in a shared process.
+ let start_runners = cfg!(feature = "private")
+ && flow_runners.is_none()
&& flow_job.job_token_scopes.is_none()
&& matches!(
next_status,
NextStatus::NextLoopIteration { start_runners: true, .. }
)
&& !restricts_any_step(module);
+ // A runner's process starts outside nsjail.
+ let start_runners = if start_runners && crate::is_sandboxing_enabled() {
+ let log = format!(
+ "Squash is ignored for step {}: this worker runs jobs in nsjail, so each iteration runs as a regular job\n",
+ module.id
+ );
+ append_logs(
+ &root_flow_id_for(&flow_job),
+ &flow_job.workspace_id,
+ log,
+ &db.into(),
+ )
+ .await;
+ false
+ } else {
+ start_runners
+ };
let do_not_pass_runners = matches!(next_status, NextStatus::NextStep { .. })
&& flow_runners
@@ -6023,6 +6041,8 @@ async fn push_next_flow_job(
runners: new_flow_runners,
handles: new_flow_runner_handles,
job_id: flow_job.id,
+ root_job: root_flow_id_for(&flow_job),
+ permissioned_as: flow_job.permissioned_as.clone(),
};
Some(Arc::new(flow_runners))
} else if !do_not_pass_runners {
@@ -6500,6 +6520,7 @@ async fn compute_next_flow_transform(
FlowModuleValue::WhileloopFlow {
modules,
modules_node,
+ squash,
skip_failures,
failure_threshold,
..
@@ -6535,7 +6556,7 @@ async fn compute_next_flow_transform(
};
let next_loop_idx = flow_jobs.len();
- let start_runners = false;
+ let start_runners = next_loop_idx == 0 && squash.unwrap_or(false);
next_loop_iteration(
flow,
status,
@@ -6572,6 +6593,7 @@ async fn compute_next_flow_transform(
modules_node,
iterator,
parallel,
+ squash,
iteration_label,
skip_failures,
failure_threshold,
@@ -6657,8 +6679,7 @@ async fn compute_next_flow_transform(
ForLoopStatus::NextIteration(mut ns) => {
ns.iteration_label = iteration_label;
ns.failure_threshold = failure_threshold;
- // A squashed loop runs each iteration as a regular job, like any other loop.
- let start_runners = false;
+ let start_runners = ns.index == 0 && squash.unwrap_or(false);
next_loop_iteration(
flow,
status,
@@ -6785,7 +6806,7 @@ async fn compute_next_flow_transform(
if let Err(e) = &pred_res {
append_predicate_error_to_root_logs(
db,
- root_flow_id_for(flow_job),
+ root_flow_id_for(&flow_job),
&flow_job.workspace_id,
Some(&module.id),
&format!("branchone branch {i}"),
diff --git a/docs/auth-surface.md b/docs/auth-surface.md
index 3f95de02b2..40d51b5608 100644
--- a/docs/auth-surface.md
+++ b/docs/auth-surface.md
@@ -210,8 +210,8 @@ Symbols, not line numbers, are cited: they drift less.
trusted, so a restricted job token, even an admin's, can only place a job it starts in its own
run (`unclaimable_run_lineage`); a route that
authenticates a token itself instead of through the route layer must call
- `check_job_token_scope`. A restricted job never runs on a dedicated worker, which uses its own
- unscoped token for every job. `$var:`/`$res:` args are resolved through the API with the job's
+ `check_job_token_scope`. A restricted job never runs on a dedicated worker, which shares its
+ process between jobs. `$var:`/`$res:` args are resolved through the API with the job's
own token, so they need read scopes. A deploy that omits the setting keeps the deployed value
and `null` clears it, so an unaware client cannot drop a restriction; setting one is refused
until every worker supports it, since an older worker mints without it. The OIDC
@@ -221,6 +221,13 @@ Symbols, not line numbers, are cited: they drift less.
the deployed version: an older script hash run by hash runs with that version's setting (a
restricted caller still caps it). Write scopes on scripts, flows, schedules or triggers let a
job escape its restriction.
+- **A dedicated worker's process runs code outside `main` with a workspace admin token** (a JWT
+ for the `dedicated_worker` identity, never super admin); each job then gets its own job token.
+ So only admins deploy a script or flow with `dedicated_worker`. The scripts it imports and a
+ flow's steps run there too, but anyone who can write them may still deploy them, as for any
+ script an admin runs: the editor warns that they should live where only admins write. A flow
+ without the flag gets no dedicated process even when a worker group names it. Squashed loops
+ start with the flow caller's own job token instead.
- **A remote deploy token is a credential for another instance**, held per account and workspace
(`remote_deploy_token`, encrypted under the workspace key, re-keyed by `set_encryption_key`).
Its `email` references `password(email)` with `ON DELETE/UPDATE CASCADE`, so whatever deletes or
diff --git a/frontend/src/lib/components/Dev.svelte b/frontend/src/lib/components/Dev.svelte
index 6515807dde..63b53a2e18 100644
--- a/frontend/src/lib/components/Dev.svelte
+++ b/frontend/src/lib/components/Dev.svelte
@@ -1113,7 +1113,7 @@
/>
{:else if currentScript?.language == 'python3'}
relative imports detected
workspace imports detectedBeware that when using relative imports, the code used in preview for those is
the one that is already deployed. If you make update to the common logic, you will
need to `wmill sync push` to see it reflected in the preview runs.
diff --git a/frontend/src/lib/components/flows/content/FlowLoop.svelte b/frontend/src/lib/components/flows/content/FlowLoop.svelte
index b0bcbea290..b0630bd653 100644
--- a/frontend/src/lib/components/flows/content/FlowLoop.svelte
+++ b/frontend/src/lib/components/flows/content/FlowLoop.svelte
@@ -363,7 +363,7 @@
title: mod.value.parallel ? SQUASH_PARALLEL_CONFLICT : undefined,
right: 'Squash',
rightTooltip:
- 'Squashing a for loop runs all iterations on the same worker, using a single runner per step for the entire loop. This eliminates cold starts between iterations for supported languages (Bun, Deno, and Python).',
+ 'Squashing a for loop runs all iterations on the same worker, using a single runner per step for the entire loop. This eliminates cold starts between iterations for supported languages (Bun, Deno, and Python). It is ignored on workers that run jobs in nsjail, and when the flow, the loop or one of its steps restricts its job token: each iteration then runs as a regular job.',
rightDocumentationLink: 'https://www.windmill.dev/docs/flows/flow_loops'
}}
/>
diff --git a/frontend/src/lib/components/flows/content/FlowSettings.svelte b/frontend/src/lib/components/flows/content/FlowSettings.svelte
index 7028a5e962..f15b1047d6 100644
--- a/frontend/src/lib/components/flows/content/FlowSettings.svelte
+++ b/frontend/src/lib/components/flows/content/FlowSettings.svelte
@@ -23,6 +23,7 @@
import CacheSetting from '$lib/components/itemSettings/CacheSetting.svelte'
import PrioritySetting from '$lib/components/itemSettings/PrioritySetting.svelte'
import DedicatedWorkersSetting from '$lib/components/itemSettings/DedicatedWorkersSetting.svelte'
+ import { flowUsesWorkspaceScripts } from '$lib/workspaceImports'
import DeleteAfterUseSetting from '$lib/components/itemSettings/DeleteAfterUseSetting.svelte'
import RunOnBehalfOfSetting from '$lib/components/itemSettings/RunOnBehalfOfSetting.svelte'
import InvisibleRunsSetting from '$lib/components/itemSettings/InvisibleRunsSetting.svelte'
@@ -386,6 +387,9 @@
{#if customUi?.settingsTabs?.sharedDiretory != false}
diff --git a/frontend/src/lib/components/flows/content/ScriptEditorDrawer.svelte b/frontend/src/lib/components/flows/content/ScriptEditorDrawer.svelte
index 955eff7ac5..2ae29cea1b 100644
--- a/frontend/src/lib/components/flows/content/ScriptEditorDrawer.svelte
+++ b/frontend/src/lib/components/flows/content/ScriptEditorDrawer.svelte
@@ -7,6 +7,7 @@
import { inferArgs } from '$lib/infer'
import { Loader2, Save, DiffIcon, Settings } from 'lucide-svelte'
import ScriptRuntimeSettings from '$lib/components/itemSettings/ScriptRuntimeSettings.svelte'
+ import { importsWorkspaceScripts, warnAfterDedicatedDeploy } from '$lib/workspaceImports'
import ScriptSettingsBadges from '$lib/components/ScriptSettingsBadges.svelte'
import Popover from '$lib/components/Popover.svelte'
import {
@@ -146,6 +147,13 @@
lock: undefined
}
})
+ if (script.dedicated_worker) {
+ warnAfterDedicatedDeploy(
+ 'script',
+ script.path,
+ importsWorkspaceScripts(script.language, script.content)
+ )
+ }
savedScript = structuredClone($state.snapshot(script))
callback?.()
} catch (error) {
@@ -356,7 +364,13 @@
These runtime settings are saved together with the script when you press Save.
-
+
{/if}
{#snippet actions()}
diff --git a/frontend/src/lib/components/flows/content/WorkspaceScriptSettingsDrawer.svelte b/frontend/src/lib/components/flows/content/WorkspaceScriptSettingsDrawer.svelte
index 9f644fb960..8f79c1b38d 100644
--- a/frontend/src/lib/components/flows/content/WorkspaceScriptSettingsDrawer.svelte
+++ b/frontend/src/lib/components/flows/content/WorkspaceScriptSettingsDrawer.svelte
@@ -2,6 +2,7 @@
import { Button, Drawer, DrawerContent } from '$lib/components/common'
import Alert from '$lib/components/common/alert/Alert.svelte'
import ScriptRuntimeSettings from '$lib/components/itemSettings/ScriptRuntimeSettings.svelte'
+ import { importsWorkspaceScripts, warnAfterDedicatedDeploy } from '$lib/workspaceImports'
import ScriptSettingsBadges from '$lib/components/ScriptSettingsBadges.svelte'
import { ScriptService, type Script } from '$lib/gen'
import { emptyString, sendUserToast } from '$lib/utils'
@@ -69,6 +70,7 @@
// user. The captured callback still fires — it refreshes the script it belongs to.
const seq = openSeq
const cb = callback
+ const saved = script
saving = true
try {
// Spread the full loaded script so fields we don't edit here (codebase,
@@ -94,6 +96,13 @@
}
})
sendUserToast('Script settings saved')
+ if (saved.dedicated_worker) {
+ warnAfterDedicatedDeploy(
+ 'script',
+ saved.path,
+ importsWorkspaceScripts(saved.language, saved.content)
+ )
+ }
cb?.()
if (seq === openSeq) drawer?.closeDrawer()
} catch (e) {
@@ -136,7 +145,13 @@
Saving creates a new version of the workspace script with these runtime settings. The code
is left unchanged.
-
+
{/if}
{#snippet actions()}
diff --git a/frontend/src/lib/components/itemSettings/DedicatedImportsWarning.svelte b/frontend/src/lib/components/itemSettings/DedicatedImportsWarning.svelte
new file mode 100644
index 0000000000..668f66d884
--- /dev/null
+++ b/frontend/src/lib/components/itemSettings/DedicatedImportsWarning.svelte
@@ -0,0 +1,10 @@
+
+
+
+ {dedicatedImportsNotice(kind)}
+
diff --git a/frontend/src/lib/components/itemSettings/DedicatedWorkersSetting.svelte b/frontend/src/lib/components/itemSettings/DedicatedWorkersSetting.svelte
index 592a8e21a3..14de141307 100644
--- a/frontend/src/lib/components/itemSettings/DedicatedWorkersSetting.svelte
+++ b/frontend/src/lib/components/itemSettings/DedicatedWorkersSetting.svelte
@@ -2,40 +2,73 @@
import Alert from '$lib/components/common/alert/Alert.svelte'
import { isCloudHosted } from '$lib/cloud'
import { enterpriseLicense } from '$lib/stores'
+ import { useOperatingUser } from '$lib/components/operatingWorkspace.svelte'
import SettingToggle from './SettingToggle.svelte'
+ import DedicatedImportsWarning from './DedicatedImportsWarning.svelte'
+ import { resource } from 'runed'
interface Props {
kind: 'flow' | 'script'
dedicatedWorker: boolean | undefined
/** Why this item cannot run on dedicated workers, e.g. its language. */
unsupportedReason?: string
+ /** Whether its code uses other workspace scripts, which run in the same process. */
+ usesWorkspaceScripts?: Promise
}
- let { kind, dedicatedWorker = $bindable(), unsupportedReason }: Props = $props()
+ let {
+ kind,
+ dedicatedWorker = $bindable(),
+ unsupportedReason,
+ usesWorkspaceScripts
+ }: Props = $props()
+
+ const operatingUser = useOperatingUser()
+ const isAdmin = $derived(
+ !!operatingUser.current?.is_admin || !!operatingUser.current?.is_super_admin
+ )
+
+ // Keeps the last answer while the next one is computed, so the warning does not flicker on edits.
+ const uses = resource(
+ () => usesWorkspaceScripts,
+ async (pending) => (await pending) ?? false
+ )
{#snippet reason()}
{unsupportedReason}
{/snippet}
+{#snippet adminOnly()}
+ Only workspace admins can deploy a {kind} that runs on dedicated workers.
+{/snippet}
+
{#if !isCloudHosted()}
(dedicatedWorker = on || undefined)}
- hint={unsupportedReason ? reason : undefined}
+ hint={unsupportedReason
+ ? reason
+ : $enterpriseLicense && !isAdmin && dedicatedWorker
+ ? adminOnly
+ : undefined}
>
A worker group must listen to this {kind}. Select it in the dedicated workers section of the
worker group configuration.
+ {#if uses.current && usesWorkspaceScripts}
+
+ {/if}
{/if}
diff --git a/frontend/src/lib/components/itemSettings/ScriptRuntimeSettings.svelte b/frontend/src/lib/components/itemSettings/ScriptRuntimeSettings.svelte
index f385d2c8d6..7674500bc1 100644
--- a/frontend/src/lib/components/itemSettings/ScriptRuntimeSettings.svelte
+++ b/frontend/src/lib/components/itemSettings/ScriptRuntimeSettings.svelte
@@ -22,9 +22,17 @@
tagPlaceholder?: string
/** Seeded when the custom timeout is turned on. */
defaultTimeout?: number
+ /** Whether the script imports other workspace scripts. */
+ usesWorkspaceScripts?: Promise
}
- let { script = $bindable(), workspaceId, tagPlaceholder, defaultTimeout = 300 }: Props = $props()
+ let {
+ script = $bindable(),
+ workspaceId,
+ tagPlaceholder,
+ defaultTimeout = 300,
+ usesWorkspaceScripts
+ }: Props = $props()
const DEDICATED_WORKER_LANGUAGES = ['bun', 'bunnative', 'python3', 'deno']
@@ -88,6 +96,7 @@
{
+ it('sees Python relative and workspace imports, not packages', async () => {
+ expect(await importsWorkspaceScripts('python3', 'from .helper import a')).toBe(true)
+ expect(await importsWorkspaceScripts('python3', 'from f.lib.helper import a')).toBe(true)
+ expect(await importsWorkspaceScripts('python3', 'import f.lib.helper as h')).toBe(true)
+ expect(await importsWorkspaceScripts('python3', 'import wmill\nfrom requests import get')).toBe(
+ false
+ )
+ })
+})
+
+describe('flowUsesWorkspaceScripts', () => {
+ it('sees script steps at any depth and inline imports, not hub steps', async () => {
+ const loop = (modules: unknown[]) => ({
+ modules: [{ value: { type: 'forloopflow', modules } }]
+ })
+ expect(
+ await flowUsesWorkspaceScripts(loop([{ value: { type: 'script', path: 'f/x/a' } }]))
+ ).toBe(true)
+ expect(
+ await flowUsesWorkspaceScripts(loop([{ value: { type: 'script', path: 'hub/1/x' } }]))
+ ).toBe(false)
+ const inline = (content: string) => ({
+ modules: [{ value: { type: 'rawscript', language: 'python3', content } }]
+ })
+ expect(await flowUsesWorkspaceScripts(inline('from .helper import a'))).toBe(true)
+ expect(await flowUsesWorkspaceScripts(inline('def main(): pass'))).toBe(false)
+ })
+})
diff --git a/frontend/src/lib/workspaceImports.ts b/frontend/src/lib/workspaceImports.ts
new file mode 100644
index 0000000000..4543a6b5f0
--- /dev/null
+++ b/frontend/src/lib/workspaceImports.ts
@@ -0,0 +1,63 @@
+import { initWasmTs } from '$lib/infer'
+import { sendUserToast } from '$lib/toast'
+import {
+ approximateFindPythonRelativePath,
+ isTypescriptRelativePath,
+ parseTypescriptDeps
+} from '$lib/relative_imports'
+
+/** Whether `code` imports other workspace scripts, relatively or by path. */
+export async function importsWorkspaceScripts(
+ language: string | undefined,
+ code: string | undefined
+): Promise {
+ if (!code) return false
+ if (language === 'python3') return approximateFindPythonRelativePath(code).length > 0
+ if (['bun', 'bunnative', 'deno', 'nativets'].includes(language ?? '')) {
+ await initWasmTs()
+ return parseTypescriptDeps(code).some(isTypescriptRelativePath)
+ }
+ return false
+}
+
+/** Whether a flow's steps use workspace scripts, by path or through an inline step's imports. */
+export async function flowUsesWorkspaceScripts(value: unknown): Promise {
+ const inline: Promise[] = []
+ const byPath = (v: unknown): boolean => {
+ if (Array.isArray(v)) return v.some(byPath)
+ if (!v || typeof v !== 'object') return false
+ const o = v as Record
+ if (o.type === 'script' && typeof o.path === 'string' && !o.path.startsWith('hub/')) return true
+ if (o.type === 'rawscript')
+ inline.push(importsWorkspaceScripts(o.language as string, o.content as string))
+ return Object.values(o).some(byPath)
+ }
+ return byPath(value) || (await Promise.all(inline)).some(Boolean)
+}
+
+/** Why a dedicated script or flow that uses workspace scripts should keep them admin-only. */
+export function dedicatedImportsNotice(kind: 'flow' | 'script') {
+ return (
+ (kind === 'flow'
+ ? 'Its steps use workspace scripts, which run in its dedicated processes.'
+ : 'It imports workspace scripts, which run in its dedicated process.') +
+ ' Code outside of main runs there with workspace admin rights, so keep these scripts where only workspace admins can edit them.'
+ )
+}
+
+/** Shown once after a deploy, when the deployed script or flow is dedicated and uses workspace scripts. */
+export function warnAfterDedicatedDeploy(
+ kind: 'flow' | 'script',
+ path: string,
+ uses: Promise
+) {
+ const what = kind === 'flow' ? 'uses workspace scripts in its steps' : 'imports workspace scripts'
+ void uses
+ .catch(() => false)
+ .then((uses) => {
+ if (uses) {
+ const msg = `${path} runs on dedicated workers and ${what}: keep them where only workspace admins can edit them.`
+ sendUserToast(msg, 'warning', [], undefined, 15000)
+ }
+ })
+}