Files
windmill/backend/windmill-api-configs/src/lib.rs
T
bffa61e33f fix: dedicated worker dispatch, cross-workspace deps, UI improvements (#8689)
* feat: restore bun as default runtime for dedicated workers

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* chore: add context comment for bun dedicated worker nodejs migration

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: dedicated worker dispatch for flows + add E2E tests

- Add workspace_id prefix to dedicated worker map lookup keys
- Update ee-repo-ref for dedicated worker path handling fix
- Add spawn_test_worker_dedicated/in_test_worker_dedicated test helpers
- Add 6 E2E tests for dedicated workers:
  - test_dedicated_flow_rawscript (regression for "Script not found" bug)
  - test_dedicated_flow_workspace_script
  - test_dedicated_flow_multiple_steps
  - test_dedicated_standalone_script
  - test_dedicated_runner_group
  - test_dedicated_flow_runners
- Add dedicated_flows.sql fixture with scripts, flows, and worker config

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: always run dependency job for dedicated worker scripts

When a script with dedicated_worker=true is deployed with a pre-computed
lock (e.g. via wmill sync push), no dependency job was created, so the
dedicated worker never detected the update and kept running the old version.

Now dedicated worker scripts always generate a dependency job regardless
of whether a lock is provided. The dependency job runs on the dedicated
worker and triggers a restart so it picks up the new script version.

Fixes #8638

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: use serial_test for dedicated worker tests to avoid WORKER_CONFIG races

Dedicated worker tests need non-default worker tags in the global
WORKER_CONFIG. When run in parallel (CI uses --test-threads=10),
multiple tests clobber each other's config. Use #[serial] to ensure
dedicated worker tests run sequentially.

Also load worker config from DB via load_worker_config() instead of
manually setting WORKER_CONFIG fields, ensuring consistency with the
monitor's reload path.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: nodejs dedicated worker script_path shadowing + add multi-language E2E tests

Fix script_path shadowing in bun_executor nodejs branch where the wrapper
file path was passed to handle_dedicated_process instead of the logical
path, causing "Script not found" for all //nodejs dedicated workers.

Add E2E tests for dedicated flows in all supported languages:
- test_dedicated_flow_deno
- test_dedicated_flow_python
- test_dedicated_flow_bunnative (V8 PrewarmedIsolate path)
- test_dedicated_flow_bun_nodejs (//nodejs annotation)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: simplify dedicated worker dispatch + add serialization and E2E tests

- Unified lookup: always use {workspace}:{runnable_path} for dedicated
  worker dispatch, replacing the flow_step_id iteration approach
- Added serialization_semaphore parameter to executor start_worker fns
- Added E2E tests: cross-workspace isolation, conflicting flow step IDs,
  preprocessor on dedicated worker
- Added workspace field to RunJob for cross-workspace test support

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat: cross-workspace workspace dependencies on workers page

Add two new instance-level endpoints to the configs router:
- GET /configs/list_all_workspace_dependencies
- GET /configs/list_all_dedicated_with_deps

Both require devops role and return data across all workspaces,
enabling the workers page to show a consistent view of which
workspace dependencies exist regardless of which workspace the
user is browsing.

Update DedicatedWorkersSelector to use the new cross-workspace
endpoints with fallback to per-workspace calls for non-devops users.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* chore: update ee-repo-ref to include dedicated worker lookup simplification

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* chore: use branch name for ee-repo-ref (CI can't fetch by SHA from non-default branch)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Update ee-repo-ref.txt with new reference

* sqlx

* fix: revert serialization semaphore, multi-workspace picker, dep conflict warnings

- Remove serialization_semaphore from executor start_worker signatures
- Remove serialization test and fixtures
- Fix DedicatedWorkersSelector to preserve tags from other workspaces
  when toggling in the picker
- Track workspace deps per-workspace for conflict detection
- Show warning when dep exists in another workspace but not the script's
- Group runner groups per-workspace to prevent cross-workspace merging
- Add workspace to dep badge link URL

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* chore: update ee-repo-ref

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: simplify exec protocol — execd: for single-script, exec: for runner groups

Add execd:/execd_preprocess: commands to bun/deno/python wrappers for
single-script dedicated workers (no path needed). Runner groups keep
exec:/exec_preprocess: with path for multi-script disambiguation.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* test: add unit tests for execd:/exec: wrapper protocol

Verify generate_multi_script_wrapper produces both execd: (single-script)
and exec: (runner group) protocol handlers, including preprocessor variants.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Update commit reference in ee-repo-ref.txt

* fix: remove beta badge from squash loop, keep tooltip

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: update protocol tests to use execd: for single-script wrappers

Deno and bun single-script protocol tests now send execd:{args} instead
of exec:{path}:{args}, matching the updated wrapper protocol. Multi-script
(runner group) tests continue to use exec:{path}:{args}.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: remove unused TEST_SCRIPT_PATH in deno protocol tests

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: review feedback — down migration, push_as workspace, UI improvements

- Use regexp_replace in down migration for positional accuracy
- Fix push_as() to use self.workspace_id instead of hardcoded value
- Remove per-workspace API fallbacks, use cross-workspace endpoints only
- Skip devops-only API calls when user is not devops (disabled prop)
- Fix duplicate key error for cross-workspace runner groups
- Add workspace to RunnerGroup for unique keying
- Reuse tagRow snippet for standalone items with expand/collapse
- Fix picker alignment: remove empty column for non-expandable items

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* test: comprehensive dedicated worker test coverage, fix Python execd_preprocess

- Add Python execd_preprocess: handler (was missing for single-script dedicated workers)
- Add 10 E2E tests: flow+standalone conflict, mixed lang fallback, unsupported lang
  flow runners, python runner group, bun/python/deno/bunnative preprocessors,
  runner group preprocessors, branchone flow
- Add 4 Python unit tests for execd:/execd_preprocess: protocol
- Update EE ref

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* chore: update ee-repo-ref

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: review feedback — migration escaping, deno try/catch, loadRunnables guard

- Down migration: use E'...' so \n matches actual newlines
- Up migration: anchor regex with ^ to avoid mid-content matches
- Deno execd_preprocess: move JSON.parse inside try/catch
- DedicatedWorkersSelector: skip devops-only API calls when disabled

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* chore: update ee-repo-ref

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* test: add dedicated worker relative import tests for bun and python

Verifies that build_loader's CURRENT_PATH correctly resolves workspace-
relative imports when running on a dedicated worker subprocess.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: dedicated worker dispatch for nested flow structures (branches/loops)

- Add extract_flow_root() to strip nesting segments from runnable_path
- Dispatch uses flow_root/flow_step_id for nested paths, runnable_path
  for flat paths — deterministic, O(1)
- Fix assert_ran_on_dedicated_worker to BFS all descendants
- Fix python mode labels (python vs python3 for runner groups)
- Add tests: simple forloop, multi-step forloop, whileloop, branchall,
  nested branch-in-loop, mixed lang fallback, unsupported lang runners

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* chore: fix ee-repo-ref SHA

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: hide picker and skip API calls for read-only users, hide empty runner badge

- Hide "Add more scripts/flows" section when disabled (read-only)
- Skip per-runnable API calls (getScriptByPath, getFlowByPath) for
  disabled users — just show path info
- Hide "0 runners" badge on flows with no eligible steps

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* chore: update ee-repo-ref to 9422b189762ae27edfc346541ae668a4ad728325

This commit updates the EE repository reference after PR #503 was merged in windmill-ee-private.

Previous ee-repo-ref: 4c6ba214bfc23fff05d1dc3200ac59e650af3f4f

New ee-repo-ref: 9422b189762ae27edfc346541ae668a4ad728325

Automated by sync-ee-ref workflow.

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-authored-by: windmill-internal-app[bot] <windmill-internal-app[bot]@users.noreply.github.com>
2026-04-03 17:50:07 +00:00

411 lines
13 KiB
Rust

/*
* Author: Ruben Fiszel
* Copyright: Windmill Labs, Inc 2022
* 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, Query},
routing::{get, post},
Json, Router,
};
use serde::{Deserialize, Serialize};
use sqlx::FromRow;
use windmill_audit::audit_oss::audit_log;
use windmill_audit::ActionKind;
use windmill_common::{
error::{self},
utils::Pagination,
worker::MIN_PERIODIC_SCRIPT_INTERVAL_SECONDS,
DB,
};
use windmill_api_auth::{require_devops_role, ApiAuthed};
pub fn global_service() -> Router {
Router::new()
.route("/list_worker_groups", get(list_worker_groups))
.route("/update/{name}", post(update_config).delete(delete_config))
.route("/get/{name}", get(get_config))
.route("/list", get(list_configs))
.route(
"/list_autoscaling_events/{worker_group}",
get(list_autoscaling_events),
)
.route(
"/native_kubernetes_autoscaling_healthcheck",
get(native_kubernetes_autoscaling_healthcheck),
)
.route(
"/list_available_python_versions",
get(list_available_python_versions),
)
.route(
"/list_all_workspace_dependencies",
get(list_all_workspace_dependencies),
)
.route(
"/list_all_dedicated_with_deps",
get(list_all_dedicated_with_deps),
)
}
#[derive(Serialize, Deserialize, FromRow)]
struct Config {
name: Option<String>,
config: serde_json::Value,
}
async fn list_worker_groups(
authed: ApiAuthed,
Extension(db): Extension<DB>,
) -> error::JsonResult<Vec<Config>> {
let mut configs_raw =
sqlx::query_as!(Config, "SELECT * FROM config WHERE name LIKE 'worker__%'")
.fetch_all(&db)
.await?;
// Remove the 'worker__' prefix from all config names
for config in configs_raw.iter_mut() {
if let Some(name) = &config.name {
if name.starts_with("worker__") {
config.name = Some(name.strip_prefix("worker__").unwrap().to_string());
}
}
}
let configs = if !authed.is_admin {
let mut obfuscated_configs: Vec<Config> = vec![];
for config in configs_raw {
let config_value_opt = config.config.as_object().map(|obj| obj.to_owned());
if let Some(mut config_value) = config_value_opt {
if let Some(env_var_map) = config_value
.get("env_vars_static")
.map(|obj| obj.as_object())
.flatten()
{
let mut new_env_var_map: serde_json::Map<String, serde_json::Value> =
serde_json::Map::new();
for (key, value) in env_var_map {
new_env_var_map.insert(
key.to_owned(),
// we know the value is a string here, so we to_string() it and take -2 to remove the quotes
serde_json::json!("*".repeat(value.to_string().len() - 2)),
);
}
config_value.insert(
"env_vars_static".to_string(),
serde_json::Value::Object(new_env_var_map),
);
}
obfuscated_configs.push(Config {
name: config.name,
config: serde_json::Value::Object(config_value),
})
}
}
obfuscated_configs
} else {
configs_raw
};
Ok(Json(configs))
}
async fn get_config(
authed: ApiAuthed,
Path(name): Path<String>,
Extension(db): Extension<DB>,
) -> error::JsonResult<Option<serde_json::Value>> {
require_devops_role(&db, &authed.email).await?;
let config = sqlx::query_as!(Config, "SELECT * FROM config WHERE name = $1", name)
.fetch_optional(&db)
.await?
.map(|c| c.config);
Ok(Json(config))
}
async fn update_config(
Path(name): Path<String>,
Extension(db): Extension<DB>,
authed: ApiAuthed,
Json(config): Json<serde_json::Value>,
) -> error::Result<String> {
require_devops_role(&db, &authed.email).await?;
#[cfg(not(feature = "enterprise"))]
let config = if name.starts_with("worker__") {
// In CE, only allow setting worker_tags, cache_clear, init_bash, and native_mode
serde_json::json!({
"worker_tags": config.get("worker_tags"),
"cache_clear": config.get("cache_clear"),
"init_bash": config.get("init_bash"),
"native_mode": config.get("native_mode")
})
} else {
config
};
if name.starts_with("worker__") {
let periodic_script_bash = config
.get("periodic_script_bash")
.filter(|v| !v.is_null())
.and_then(|v| v.as_str())
.filter(|s| !s.is_empty());
let periodic_script_interval = config
.get("periodic_script_interval_seconds")
.filter(|v| !v.is_null());
match (periodic_script_bash, periodic_script_interval) {
(Some(_), Some(interval_value)) => {
if let Some(interval) = interval_value.as_u64() {
if interval < MIN_PERIODIC_SCRIPT_INTERVAL_SECONDS {
return Err(error::Error::BadRequest(format!(
"Periodic script interval must be at least {} seconds, got {} seconds",
MIN_PERIODIC_SCRIPT_INTERVAL_SECONDS, interval
)));
}
} else {
return Err(error::Error::BadRequest(
"Periodic script interval must be a valid number".to_string(),
));
}
}
(Some(_), None) => {
return Err(error::Error::BadRequest(
"Periodic script interval must be specified when periodic script is configured"
.to_string(),
));
}
_ => {}
}
}
let mut tx = db.begin().await?;
sqlx::query!(
"INSERT INTO config (name, config) VALUES ($1, $2) ON CONFLICT (name) DO UPDATE SET config = EXCLUDED.config",
&name,
config
)
.execute(&mut *tx)
.await?;
audit_log(
&mut *tx,
&authed,
"worker_config.update",
ActionKind::Update,
"global",
Some(&name),
None,
)
.await?;
tx.commit().await?;
Ok(format!("Updated config {name}"))
}
async fn delete_config(
Path(name): Path<String>,
Extension(db): Extension<DB>,
authed: ApiAuthed,
) -> error::Result<String> {
require_devops_role(&db, &authed.email).await?;
let mut tx = db.begin().await?;
let deleted = sqlx::query!("DELETE FROM config WHERE name = $1 RETURNING name", name)
.fetch_all(&db)
.await?;
audit_log(
&mut *tx,
&authed,
"worker_config.delete",
ActionKind::Delete,
"global",
Some(&name),
None,
)
.await?;
tx.commit().await?;
if deleted.len() == 0 {
return Err(error::Error::NotFound(format!(
"Config {name} not found",
name = name
)));
}
Ok(format!("Deleted config {name}"))
}
#[derive(Serialize, Deserialize, FromRow)]
struct AutoscalingEvent {
id: i64,
worker_group: String,
event_type: Option<String>,
desired_workers: i32,
reason: Option<String>,
applied_at: chrono::NaiveDateTime,
}
async fn list_autoscaling_events(
Extension(db): Extension<DB>,
Path(worker_group): Path<String>,
Query(mut pagination): Query<Pagination>,
) -> error::JsonResult<Vec<AutoscalingEvent>> {
if pagination.per_page.is_none() {
pagination.per_page = Some(5);
}
let (per_page, offset) = windmill_common::utils::paginate(pagination);
let events = sqlx::query_as!(
AutoscalingEvent,
"SELECT id, worker_group, event_type::text, desired_workers, reason, applied_at FROM autoscaling_event WHERE worker_group = $1 ORDER BY applied_at DESC LIMIT $2 OFFSET $3",
worker_group,
per_page as i64,
offset as i64
)
.fetch_all(&db)
.await?;
Ok(Json(events))
}
#[cfg(all(feature = "enterprise", feature = "private"))]
async fn native_kubernetes_autoscaling_healthcheck(
authed: ApiAuthed,
Extension(db): Extension<DB>,
) -> Result<(), windmill_autoscaling::kubernetes_integration_ee::KubeError> {
require_devops_role(&db, &authed.email).await.map_err(|e| {
windmill_autoscaling::kubernetes_integration_ee::KubeError::Other(e.to_string())
})?;
windmill_autoscaling::kubernetes_integration_ee::kubernetes_healthcheck().await
}
#[cfg(not(all(feature = "enterprise", feature = "private")))]
async fn native_kubernetes_autoscaling_healthcheck() -> Result<(), error::Error> {
Err(error::Error::BadRequest(
"Native Kubernetes autoscaling available only in the enterprise version".to_string(),
))
}
async fn list_available_python_versions() -> error::JsonResult<Vec<String>> {
#[cfg(not(all(feature = "python", feature = "run_inline")))]
return Err(error::Error::BadRequest(
"Python listing available only with 'python' feature enabled".to_string(),
));
#[cfg(all(feature = "python", feature = "run_inline"))]
use itertools::Itertools;
#[cfg(all(feature = "python", feature = "run_inline"))]
return Ok(Json(
windmill_worker::PyV::list_available_python_versions()
.await
.iter()
.map(|v| v.to_string())
.collect_vec(),
));
}
#[cfg(feature = "enterprise")]
async fn list_configs(
authed: ApiAuthed,
Extension(db): Extension<DB>,
) -> error::JsonResult<Vec<Config>> {
require_devops_role(&db, &authed.email).await?;
let configs = sqlx::query_as!(Config, "SELECT name, config FROM config")
.fetch_all(&db)
.await?;
Ok(Json(configs))
}
#[cfg(not(feature = "enterprise"))]
async fn list_configs() -> error::JsonResult<String> {
Err(error::Error::BadRequest(
"Config listing available only in the enterprise version".to_string(),
))
}
#[derive(Serialize)]
struct WorkspaceDependencySummary {
workspace_id: String,
name: Option<String>,
language: windmill_common::scripts::ScriptLang,
}
async fn list_all_workspace_dependencies(
authed: ApiAuthed,
Extension(db): Extension<DB>,
) -> error::JsonResult<Vec<WorkspaceDependencySummary>> {
require_devops_role(&db, &authed.email).await?;
let deps = sqlx::query!(
r#"SELECT workspace_id, name, language AS "language: windmill_common::scripts::ScriptLang"
FROM workspace_dependencies
WHERE archived = false
ORDER BY workspace_id, name"#,
)
.fetch_all(&db)
.await?;
Ok(Json(
deps.into_iter()
.map(|r| WorkspaceDependencySummary {
workspace_id: r.workspace_id,
name: r.name,
language: r.language,
})
.collect(),
))
}
#[derive(Serialize)]
struct DedicatedScriptDepsWithWorkspace {
workspace_id: String,
path: String,
language: windmill_common::scripts::ScriptLang,
workspace_dep_names: Vec<String>,
}
async fn list_all_dedicated_with_deps(
authed: ApiAuthed,
Extension(db): Extension<DB>,
) -> error::JsonResult<Vec<DedicatedScriptDepsWithWorkspace>> {
require_devops_role(&db, &authed.email).await?;
let rows = sqlx::query!(
r#"SELECT DISTINCT ON (workspace_id, path)
workspace_id, path, language AS "language: windmill_common::scripts::ScriptLang", content
FROM script
WHERE archived = false
AND dedicated_worker = true
AND language = ANY($1::text[]::SCRIPT_LANG[])
ORDER BY workspace_id, path, created_at DESC"#,
&["python3", "bun", "bunnative", "deno"] as &[&str],
)
.fetch_all(&db)
.await?;
let result = rows
.into_iter()
.map(|row| {
let dep_names =
windmill_common::scripts::extract_workspace_dependencies_annotated_refs(
&row.language,
&row.content,
&row.path,
)
.map(|refs| refs.external)
.unwrap_or_default();
DedicatedScriptDepsWithWorkspace {
workspace_id: row.workspace_id,
path: row.path,
language: row.language,
workspace_dep_names: dep_names,
}
})
.collect();
Ok(Json(result))
}