From 4e5fc300f3fbfd26c1f7ec1a55e11255e225e7b6 Mon Sep 17 00:00:00 2001 From: Ruben Fiszel Date: Sun, 22 Nov 2026 13:24:30 +0100 Subject: [PATCH] feat: add an instance setting for raw app versions to keep (#12577) * feat: add an instance setting for full-code app versions to keep `raw_app_versions_to_keep` makes the monitor delete each raw app's versions past the newest N, with their bundles. A version superseded less than an hour ago and a version a draft is based on are kept. Co-Authored-By: Claude Opus 5.5 * fix: validate the versions to keep in the UI as the server does Co-Authored-By: Claude Opus 5.5 * fix: read the drafts' bases per batch while pruning app versions A first pass over a long history runs for minutes, so a draft saved during it was not seen by the snapshot taken with the candidates. Co-Authored-By: Claude Opus 5.5 * fix: never date a version's supersession before the version itself `created_at` is when a deploy started, so a successor can carry the older one. Co-Authored-By: Claude Opus 5.5 * fix: keep pruned app versions' rows while object storage is down `get_object_store` answers `None` both for no storage and for storage that failed to build or refresh, and deleting the rows then orphans the bundles. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- ...e7fb1eb13fbf5e0c524460b447bbd7f054a58.json | 15 ++ ...b2031557d164a923e2aebeeb0bcc2995a42fb.json | 14 ++ ...a18af3cf6e3ac237b0eb864af026e4325757f.json | 15 ++ ...cc54afc12ff4a50d6103c3c5b622cfa5d9eb8.json | 34 ++++ ...d091f7f897627205c1a4dc1eea5ea1d7ad4e1.json | 23 +++ ...6d72341440080cc857ebb5ddd237ad638c5ec.json | 15 ++ backend/src/monitor.rs | 20 +++ backend/tests/raw_app_versions_retention.rs | 46 +++++ backend/windmill-api-settings/src/lib.rs | 4 + .../src/app_versions_retention.rs | 161 ++++++++++++++++++ backend/windmill-api/src/apps.rs | 9 +- backend/windmill-api/src/lib.rs | 2 + .../windmill-common/src/global_settings.rs | 36 +++- .../windmill-common/src/instance_config.rs | 4 + backend/windmill-object-store/src/lib.rs | 19 +++ .../src/lib/components/instanceSettings.ts | 20 +++ frontend/src/lib/parseCount.ts | 15 ++ frontend/src/lib/tokenExpiration.ts | 15 +- 18 files changed, 447 insertions(+), 20 deletions(-) create mode 100644 backend/.sqlx/query-36f37d5f288805a309986acff7ae7fb1eb13fbf5e0c524460b447bbd7f054a58.json create mode 100644 backend/.sqlx/query-58e6dfcea26f106238ea6f1139db2031557d164a923e2aebeeb0bcc2995a42fb.json create mode 100644 backend/.sqlx/query-89fb1f38292bd64e0b74f805e30a18af3cf6e3ac237b0eb864af026e4325757f.json create mode 100644 backend/.sqlx/query-8c7bb64ccca6faf2c367b23d42ccc54afc12ff4a50d6103c3c5b622cfa5d9eb8.json create mode 100644 backend/.sqlx/query-992d1ff51d9b2b8177adb15d34dd091f7f897627205c1a4dc1eea5ea1d7ad4e1.json create mode 100644 backend/.sqlx/query-b2dc52d4b21cc2e62ea3b8725be6d72341440080cc857ebb5ddd237ad638c5ec.json create mode 100644 backend/tests/raw_app_versions_retention.rs create mode 100644 backend/windmill-api/src/app_versions_retention.rs create mode 100644 frontend/src/lib/parseCount.ts diff --git a/backend/.sqlx/query-36f37d5f288805a309986acff7ae7fb1eb13fbf5e0c524460b447bbd7f054a58.json b/backend/.sqlx/query-36f37d5f288805a309986acff7ae7fb1eb13fbf5e0c524460b447bbd7f054a58.json new file mode 100644 index 0000000000..1e43697b33 --- /dev/null +++ b/backend/.sqlx/query-36f37d5f288805a309986acff7ae7fb1eb13fbf5e0c524460b447bbd7f054a58.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM deployment_metadata WHERE workspace_id = $1 AND app_version = ANY($2)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "Int8Array" + ] + }, + "nullable": [] + }, + "hash": "36f37d5f288805a309986acff7ae7fb1eb13fbf5e0c524460b447bbd7f054a58" +} diff --git a/backend/.sqlx/query-58e6dfcea26f106238ea6f1139db2031557d164a923e2aebeeb0bcc2995a42fb.json b/backend/.sqlx/query-58e6dfcea26f106238ea6f1139db2031557d164a923e2aebeeb0bcc2995a42fb.json new file mode 100644 index 0000000000..f965c96f38 --- /dev/null +++ b/backend/.sqlx/query-58e6dfcea26f106238ea6f1139db2031557d164a923e2aebeeb0bcc2995a42fb.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM app_bundles WHERE app_version_id = ANY($1)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Int8Array" + ] + }, + "nullable": [] + }, + "hash": "58e6dfcea26f106238ea6f1139db2031557d164a923e2aebeeb0bcc2995a42fb" +} diff --git a/backend/.sqlx/query-89fb1f38292bd64e0b74f805e30a18af3cf6e3ac237b0eb864af026e4325757f.json b/backend/.sqlx/query-89fb1f38292bd64e0b74f805e30a18af3cf6e3ac237b0eb864af026e4325757f.json new file mode 100644 index 0000000000..dee84dfa5d --- /dev/null +++ b/backend/.sqlx/query-89fb1f38292bd64e0b74f805e30a18af3cf6e3ac237b0eb864af026e4325757f.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM app_version WHERE app_id = $1 AND id = ANY($2)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Int8", + "Int8Array" + ] + }, + "nullable": [] + }, + "hash": "89fb1f38292bd64e0b74f805e30a18af3cf6e3ac237b0eb864af026e4325757f" +} diff --git a/backend/.sqlx/query-8c7bb64ccca6faf2c367b23d42ccc54afc12ff4a50d6103c3c5b622cfa5d9eb8.json b/backend/.sqlx/query-8c7bb64ccca6faf2c367b23d42ccc54afc12ff4a50d6103c3c5b622cfa5d9eb8.json new file mode 100644 index 0000000000..29da2c5f5f --- /dev/null +++ b/backend/.sqlx/query-8c7bb64ccca6faf2c367b23d42ccc54afc12ff4a50d6103c3c5b622cfa5d9eb8.json @@ -0,0 +1,34 @@ +{ + "db_name": "PostgreSQL", + "query": "WITH ranked AS (\n SELECT av.id, av.app_id,\n row_number() OVER newest_first AS rn,\n GREATEST(av.created_at, lag(av.created_at) OVER newest_first) AS superseded_at\n FROM app_version av\n LEFT JOIN (\n SELECT app.id AS app_id, v.id, v.ord\n FROM app, unnest(app.versions) WITH ORDINALITY AS v(id, ord)\n ) pos ON pos.app_id = av.app_id AND pos.id = av.id\n WHERE av.raw_app\n WINDOW newest_first AS (\n PARTITION BY av.app_id ORDER BY COALESCE(pos.ord, 0) DESC, av.id DESC\n )\n )\n SELECT a.id AS app_id, a.workspace_id, array_agg(r.id) AS \"versions!\"\n FROM ranked r\n JOIN app a ON a.id = r.app_id\n WHERE r.rn > $1\n AND r.superseded_at < now() - interval '1 hour'\n GROUP BY a.id", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "app_id", + "type_info": "Int8" + }, + { + "ordinal": 1, + "name": "workspace_id", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "versions!", + "type_info": "Int8Array" + } + ], + "parameters": { + "Left": [ + "Int8" + ] + }, + "nullable": [ + false, + false, + null + ] + }, + "hash": "8c7bb64ccca6faf2c367b23d42ccc54afc12ff4a50d6103c3c5b622cfa5d9eb8" +} diff --git a/backend/.sqlx/query-992d1ff51d9b2b8177adb15d34dd091f7f897627205c1a4dc1eea5ea1d7ad4e1.json b/backend/.sqlx/query-992d1ff51d9b2b8177adb15d34dd091f7f897627205c1a4dc1eea5ea1d7ad4e1.json new file mode 100644 index 0000000000..6eb9654562 --- /dev/null +++ b/backend/.sqlx/query-992d1ff51d9b2b8177adb15d34dd091f7f897627205c1a4dc1eea5ea1d7ad4e1.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT c.id AS \"id!\" FROM unnest($2::bigint[]) AS c(id)\n WHERE NOT EXISTS (\n SELECT 1 FROM draft d\n WHERE d.workspace_id = $1 AND d.typ IN ('app', 'raw_app') AND d.base = c.id::text\n )", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id!", + "type_info": "Int8" + } + ], + "parameters": { + "Left": [ + "Text", + "Int8Array" + ] + }, + "nullable": [ + null + ] + }, + "hash": "992d1ff51d9b2b8177adb15d34dd091f7f897627205c1a4dc1eea5ea1d7ad4e1" +} diff --git a/backend/.sqlx/query-b2dc52d4b21cc2e62ea3b8725be6d72341440080cc857ebb5ddd237ad638c5ec.json b/backend/.sqlx/query-b2dc52d4b21cc2e62ea3b8725be6d72341440080cc857ebb5ddd237ad638c5ec.json new file mode 100644 index 0000000000..f759b97878 --- /dev/null +++ b/backend/.sqlx/query-b2dc52d4b21cc2e62ea3b8725be6d72341440080cc857ebb5ddd237ad638c5ec.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE app SET versions = ARRAY(\n SELECT v.id FROM unnest(versions) WITH ORDINALITY AS v(id, ord)\n WHERE v.id <> ALL($2) ORDER BY v.ord\n ) WHERE id = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Int8", + "Int8Array" + ] + }, + "nullable": [] + }, + "hash": "b2dc52d4b21cc2e62ea3b8725be6d72341440080cc857ebb5ddd237ad638c5ec" +} diff --git a/backend/src/monitor.rs b/backend/src/monitor.rs index 09cb7680cc..7359e74b40 100644 --- a/backend/src/monitor.rs +++ b/backend/src/monitor.rs @@ -4751,6 +4751,25 @@ pub async fn monitor_db( } }; + // run every 120 iterations (~20min at the default LISTEN_NEW_EVENTS_INTERVAL_SEC). Spawned: + // a first pass over a long history would outlast the join's deadline. + let raw_app_versions_retention_f = async { + if server_mode && iteration.is_some() && iteration.as_ref().unwrap().should_run(120) { + if let Some(db) = conn.as_sql() { + let db = db.clone(); + tokio::spawn(async move { + match windmill_api::prune_raw_app_versions(&db).await { + Ok(0) => {} + Ok(pruned) => { + tracing::info!("pruned {pruned} raw app versions past the retention") + } + Err(e) => tracing::error!("Error pruning raw app versions: {e:#}"), + } + }); + } + } + }; + // run every 2 iterations (~20s at the default LISTEN_NEW_EVENTS_INTERVAL_SEC). // Enterprise feature: the active `// freshness` backstop lives in // windmill-queue's `freshness_watchdog` (`private`); OSS gets a no-op stub. @@ -4780,6 +4799,7 @@ pub async fn monitor_db( zombie_jobs_f, stale_jobs_f, trim_resource_versions_f, + raw_app_versions_retention_f, vacuum_queue_f, expose_queue_metrics_f, verify_license_key_f, diff --git a/backend/tests/raw_app_versions_retention.rs b/backend/tests/raw_app_versions_retention.rs new file mode 100644 index 0000000000..8568a62eab --- /dev/null +++ b/backend/tests/raw_app_versions_retention.rs @@ -0,0 +1,46 @@ +//! What `raw_app_versions_to_keep` may delete: never the deployed version, whatever its +//! timestamp, a version just superseded, a draft's base or a low-code app's version. + +use sqlx::{Pool, Postgres}; + +#[sqlx::test(fixtures("base"))] +async fn prune_keeps_head_recent_draft_base_and_low_code(db: Pool) -> anyhow::Result<()> { + // 106 is deployed yet has the oldest timestamp, so 104 and the 105 it replaced were both + // superseded minutes ago at the earliest. A draft is based on 102. + sqlx::raw_sql( + "INSERT INTO app (id, workspace_id, path, policy, versions) VALUES + (100, 'test-workspace', 'u/test-user/raw', '{}', '{101,102,103,105,104,106}'), + (200, 'test-workspace', 'u/test-user/low', '{}', '{201,202}'); + INSERT INTO app_version (id, app_id, value, created_by, created_at, raw_app) VALUES + (101, 100, '{}', 'test-user', now() - interval '6 days', true), + (102, 100, '{}', 'test-user', now() - interval '5 days', true), + (103, 100, '{}', 'test-user', now() - interval '4 days', true), + (105, 100, '{}', 'test-user', now() - interval '3 days', true), + (104, 100, '{}', 'test-user', now() - interval '5 minutes', true), + (106, 100, '{}', 'test-user', now() - interval '7 days', true), + (201, 200, '{}', 'test-user', now() - interval '6 days', false), + (202, 200, '{}', 'test-user', now() - interval '5 days', false); + INSERT INTO app_bundles (app_version_id, w_id, file_type, data) VALUES + (101, 'test-workspace', 'js', 'old'), (106, 'test-workspace', 'js', 'deployed'); + INSERT INTO draft (workspace_id, path, typ, value, base) + VALUES ('test-workspace', 'u/test-user/raw', 'raw_app', '{}', '102'); + INSERT INTO global_settings (name, value) VALUES ('raw_app_versions_to_keep', '1');", + ) + .execute(&db) + .await?; + + assert_eq!(windmill_api::prune_raw_app_versions(&db).await?, 2); + + let versions = |app: i64| { + sqlx::query_scalar::<_, Vec>("SELECT versions FROM app WHERE id = $1") + .bind(app) + .fetch_one(&db) + }; + assert_eq!(versions(100).await?, [102, 105, 104, 106]); + assert_eq!(versions(200).await?, [201, 202]); + let bundles: Vec = sqlx::query_scalar("SELECT app_version_id FROM app_bundles") + .fetch_all(&db) + .await?; + assert_eq!(bundles, [106]); + Ok(()) +} diff --git a/backend/windmill-api-settings/src/lib.rs b/backend/windmill-api-settings/src/lib.rs index ea9aa7aa5f..85d585c146 100644 --- a/backend/windmill-api-settings/src/lib.rs +++ b/backend/windmill-api-settings/src/lib.rs @@ -1310,6 +1310,10 @@ async fn run_setting_pre_write_hook( error::Error::BadRequest(format!("{MAX_TOKEN_EXPIRATION_DAYS_SETTING}: {e}")) })?; } + windmill_common::global_settings::RAW_APP_VERSIONS_TO_KEEP_SETTING => { + windmill_common::global_settings::parse_raw_app_versions_to_keep(Some(value)) + .map_err(|e| error::Error::BadRequest(format!("{key}: {e}")))?; + } INSTANCE_BANNER_SETTING => { match value { // Clearing (delete row) is handled by the caller; allow it through. diff --git a/backend/windmill-api/src/app_versions_retention.rs b/backend/windmill-api/src/app_versions_retention.rs new file mode 100644 index 0000000000..cabbb4308c --- /dev/null +++ b/backend/windmill-api/src/app_versions_retention.rs @@ -0,0 +1,161 @@ +//! Retention of raw app versions, per the `raw_app_versions_to_keep` instance setting. + +use windmill_common::{ + error::{Error, Result}, + global_settings::{ + load_value_from_global_settings, parse_raw_app_versions_to_keep, + RAW_APP_VERSIONS_TO_KEEP_SETTING, + }, + DB, +}; + +/// Versions deleted per transaction, which holds the app's row and so its deploys. +const DELETE_BATCH: usize = 100; + +/// Deletes the raw app versions past the `raw_app_versions_to_keep` newest of each app, with +/// their bundles, and returns how many went. Safe to run concurrently with itself and deploys. +/// +/// Checks no caller and spans every workspace: for the server's monitor, never for a route. +pub async fn prune_raw_app_versions(db: &DB) -> Result { + let setting = load_value_from_global_settings(db, RAW_APP_VERSIONS_TO_KEEP_SETTING).await?; + let Some(keep) = parse_raw_app_versions_to_keep(setting.as_ref()) + .map_err(|e| Error::internal_err(format!("{RAW_APP_VERSIONS_TO_KEEP_SETTING}: {e}")))? + else { + return Ok(0); + }; + + // Newest is last in `app.versions`, as in the history, not latest `created_at`, which is + // when the deploy started: a version was superseded no earlier than both its own and its + // successor's. The hour after that is for the dependency jobs and page loads still using it. + let apps = sqlx::query!( + r#"WITH ranked AS ( + SELECT av.id, av.app_id, + row_number() OVER newest_first AS rn, + GREATEST(av.created_at, lag(av.created_at) OVER newest_first) AS superseded_at + FROM app_version av + LEFT JOIN ( + SELECT app.id AS app_id, v.id, v.ord + FROM app, unnest(app.versions) WITH ORDINALITY AS v(id, ord) + ) pos ON pos.app_id = av.app_id AND pos.id = av.id + WHERE av.raw_app + WINDOW newest_first AS ( + PARTITION BY av.app_id ORDER BY COALESCE(pos.ord, 0) DESC, av.id DESC + ) + ) + SELECT a.id AS app_id, a.workspace_id, array_agg(r.id) AS "versions!" + FROM ranked r + JOIN app a ON a.id = r.app_id + WHERE r.rn > $1 + AND r.superseded_at < now() - interval '1 hour' + GROUP BY a.id"#, + keep, + ) + .fetch_all(db) + .await?; + + let mut pruned = 0; + for app in apps { + for candidates in app.versions.chunks(DELETE_BATCH) { + let versions = without_draft_bases(db, &app.workspace_id, candidates).await?; + if versions.is_empty() { + continue; + } + // Objects first: once the rows are gone nothing names them to a later pass. + #[cfg(all(feature = "enterprise", feature = "parquet"))] + delete_stored_bundles(db, &app.workspace_id, &versions).await?; + pruned += delete_versions(db, &app.workspace_id, app.app_id, &versions).await?; + } + } + Ok(pruned) +} + +/// A draft's base stays, for the diff against it. Read per batch, as a first pass over a long +/// history runs for minutes. Best effort, so no lock against draft saves: an editor can save a +/// draft on a version deleted long before, and a rebase then shows the whole draft as the diff. +async fn without_draft_bases(db: &DB, w_id: &str, versions: &[i64]) -> Result> { + Ok(sqlx::query_scalar!( + r#"SELECT c.id AS "id!" FROM unnest($2::bigint[]) AS c(id) + WHERE NOT EXISTS ( + SELECT 1 FROM draft d + WHERE d.workspace_id = $1 AND d.typ IN ('app', 'raw_app') AND d.base = c.id::text + )"#, + w_id, + versions, + ) + .fetch_all(db) + .await?) +} + +/// `app_script` rows stay: versions share them, and past jobs show their code from them. +async fn delete_versions(db: &DB, w_id: &str, app_id: i64, versions: &[i64]) -> Result { + let mut tx = db.begin().await?; + // The app row before its versions, the order deploys and relocks lock them in. The array is + // filtered inside the UPDATE so that a version appended while it waited is kept. + sqlx::query!( + "UPDATE app SET versions = ARRAY( + SELECT v.id FROM unnest(versions) WITH ORDINALITY AS v(id, ord) + WHERE v.id <> ALL($2) ORDER BY v.ord + ) WHERE id = $1", + app_id, + versions, + ) + .execute(&mut *tx) + .await?; + let deleted = sqlx::query!( + "DELETE FROM app_version WHERE app_id = $1 AND id = ANY($2)", + app_id, + versions, + ) + .execute(&mut *tx) + .await? + .rows_affected(); + sqlx::query!( + "DELETE FROM app_bundles WHERE app_version_id = ANY($1)", + versions, + ) + .execute(&mut *tx) + .await?; + sqlx::query!( + "DELETE FROM deployment_metadata WHERE workspace_id = $1 AND app_version = ANY($2)", + w_id, + versions, + ) + .execute(&mut *tx) + .await?; + tx.commit().await?; + Ok(deleted) +} + +#[cfg(all(feature = "enterprise", feature = "parquet"))] +async fn delete_stored_bundles(db: &DB, w_id: &str, versions: &[i64]) -> Result<()> { + use futures::StreamExt; + use windmill_object_store::object_store_reexports::{ObjectStoreError, Path}; + + let Some(store) = windmill_object_store::get_object_store().await else { + if windmill_object_store::instance_object_store_configured(db).await? { + return Err(Error::internal_err( + "instance object storage is unavailable, keeping the versions to retry", + )); + } + return Ok(()); + }; + let paths: Vec<_> = versions + .iter() + .flat_map(|id| { + ["js", "css"].map(|file_type| { + Ok(Path::from(crate::apps::app_bundle_object_path( + w_id, *id, file_type, + ))) + }) + }) + .collect(); + let mut results = store.delete_stream(futures::stream::iter(paths).boxed()); + while let Some(result) = results.next().await { + match result { + // An app without styles has no css, and a bundle may be in `app_bundles` instead. + Ok(_) | Err(ObjectStoreError::NotFound { .. }) => {} + Err(e) => return Err(windmill_object_store::object_store_error_to_error(e)), + } + } + Ok(()) +} diff --git a/backend/windmill-api/src/apps.rs b/backend/windmill-api/src/apps.rs index eeb41244b6..3e5067c202 100644 --- a/backend/windmill-api/src/apps.rs +++ b/backend/windmill-api/src/apps.rs @@ -945,7 +945,7 @@ async fn get_raw_app_data( let mut body: Option = None; #[cfg(all(feature = "enterprise", feature = "parquet"))] if let Some(os) = object_store { - let path = format!("/app_bundles/{}/{}.{}", w_id, id, file_type); + let path = app_bundle_object_path(&w_id, id, file_type); match os .get(&windmill_object_store::object_store_reexports::Path::from( path, @@ -2277,6 +2277,11 @@ async fn get_latest_version_secret_id( Ok(hx) } +#[cfg(all(feature = "enterprise", feature = "parquet"))] +pub(crate) fn app_bundle_object_path(w_id: &str, version: i64, file_type: &str) -> String { + format!("/app_bundles/{w_id}/{version}.{file_type}") +} + async fn store_raw_app_file<'a>( w_id: &str, id: &i64, @@ -2288,7 +2293,7 @@ async fn store_raw_app_file<'a>( { let object_store = windmill_object_store::get_object_store().await; - let path: String = format!("/app_bundles/{}/{}.{}", w_id, id, file_type); + let path = app_bundle_object_path(w_id, *id, file_type); if let Some(os) = object_store { if let Err(e) = os diff --git a/backend/windmill-api/src/lib.rs b/backend/windmill-api/src/lib.rs index a6855a810a..b1d3f60c76 100644 --- a/backend/windmill-api/src/lib.rs +++ b/backend/windmill-api/src/lib.rs @@ -76,6 +76,8 @@ mod ai_sessions; pub use ai_sessions::sweep_expired_ai_session_backups; mod ai_shared_artifacts; mod ai_shared_sessions; +mod app_versions_retention; +pub use app_versions_retention::prune_raw_app_versions; mod apps; mod apps_raw_bundle; pub use apps::invalidate_app_policy_cache; diff --git a/backend/windmill-common/src/global_settings.rs b/backend/windmill-common/src/global_settings.rs index 03d0edf8d6..e87dd17a76 100644 --- a/backend/windmill-common/src/global_settings.rs +++ b/backend/windmill-common/src/global_settings.rs @@ -139,7 +139,32 @@ pub const MAX_TOKEN_EXPIRATION_DAYS_BOUND: i64 = 1_000_000; pub fn parse_max_token_expiration_days( value: Option<&serde_json::Value>, ) -> Result, String> { - let days = match value { + parse_optional_count(value, MAX_TOKEN_EXPIRATION_DAYS_BOUND).map_err(|()| { + format!( + "must be a whole number of days from 1 to {MAX_TOKEN_EXPIRATION_DAYS_BOUND}, or empty for no limit" + ) + }) +} +/// How many versions of each raw app to keep. Unset keeps them all. +pub const RAW_APP_VERSIONS_TO_KEEP_SETTING: &str = "raw_app_versions_to_keep"; +pub const RAW_APP_VERSIONS_TO_KEEP_BOUND: i64 = 1_000_000; + +/// Reads a stored `raw_app_versions_to_keep`, `Ok(None)` when unset or cleared. Zero is an +/// error rather than "keep all" or "keep none": the deployed version always has to stay. +pub fn parse_raw_app_versions_to_keep( + value: Option<&serde_json::Value>, +) -> Result, String> { + parse_optional_count(value, RAW_APP_VERSIONS_TO_KEEP_BOUND).map_err(|()| { + format!( + "must be a whole number of versions from 1 to {RAW_APP_VERSIONS_TO_KEEP_BOUND}, or empty to keep them all" + ) + }) +} + +/// A whole number within `1..=max` stored as an integer, an integral float or a string of +/// digits, or `None` when null or empty. +fn parse_optional_count(value: Option<&serde_json::Value>, max: i64) -> Result, ()> { + let count = match value { None | Some(serde_json::Value::Null) => return Ok(None), Some(serde_json::Value::String(s)) if s.trim().is_empty() => return Ok(None), Some(serde_json::Value::Number(n)) => n @@ -148,13 +173,12 @@ pub fn parse_max_token_expiration_days( Some(serde_json::Value::String(s)) => s.trim().parse::().ok(), Some(_) => None, }; - match days { - Some(days) if (1..=MAX_TOKEN_EXPIRATION_DAYS_BOUND).contains(&days) => Ok(Some(days)), - _ => Err(format!( - "must be a whole number of days from 1 to {MAX_TOKEN_EXPIRATION_DAYS_BOUND}, or empty for no limit" - )), + match count { + Some(count) if (1..=max).contains(&count) => Ok(Some(count)), + _ => Err(()), } } + pub const AUTO_LOGIN_PROVIDER_SETTING: &str = "auto_login_provider"; /// Name of the SAML attribute or OIDC userinfo claim carrying the user's IdP groups. Unset or /// empty leaves instance-group membership entirely to SCIM. diff --git a/backend/windmill-common/src/instance_config.rs b/backend/windmill-common/src/instance_config.rs index 41317e41d8..1e92fe6372 100644 --- a/backend/windmill-common/src/instance_config.rs +++ b/backend/windmill-common/src/instance_config.rs @@ -1601,6 +1601,10 @@ pub async fn sync_global_settings_declarative( crate::global_settings::parse_max_token_expiration_days(desired.get(max_expiration_key)) .map_err(|e| anyhow::anyhow!("{max_expiration_key}: {e}"))?; + let versions_key = crate::global_settings::RAW_APP_VERSIONS_TO_KEEP_SETTING; + crate::global_settings::parse_raw_app_versions_to_keep(desired.get(versions_key)) + .map_err(|e| anyhow::anyhow!("{versions_key}: {e}"))?; + let idp_key = crate::global_settings::MCP_EXTERNAL_IDP_SETTING; crate::global_settings::parse_mcp_external_idp(desired.get(idp_key)) .map_err(|e| anyhow::anyhow!("{idp_key}: {e}"))?; diff --git a/backend/windmill-object-store/src/lib.rs b/backend/windmill-object-store/src/lib.rs index 4e40d6e313..160e3efdd9 100644 --- a/backend/windmill-object-store/src/lib.rs +++ b/backend/windmill-object-store/src/lib.rs @@ -397,6 +397,25 @@ pub enum ObjectStoreReload { Never, } +/// Whether the instance object store is set up, working or not, by the rules +/// [`reload_object_store_setting`] installs it with. [`get_object_store`] answers `None` both +/// when there is none and when it failed to build or to refresh its credentials. +#[cfg(feature = "parquet")] +pub async fn instance_object_store_configured(db: &windmill_common::DB) -> error::Result { + use windmill_common::{ + ee_oss::{get_license_plan, LicensePlan}, + global_settings::{load_value_from_global_settings, OBJECT_STORE_CONFIG_SETTING}, + }; + + if matches!(get_license_plan().await, LicensePlan::Pro) { + return Ok(false); + } + Ok(std::env::var("S3_CACHE_BUCKET").is_ok() + || load_value_from_global_settings(db, OBJECT_STORE_CONFIG_SETTING) + .await? + .is_some()) +} + #[cfg(feature = "parquet")] pub async fn reload_object_store_setting(db: &windmill_common::DB) -> ObjectStoreReload { use windmill_common::{ diff --git a/frontend/src/lib/components/instanceSettings.ts b/frontend/src/lib/components/instanceSettings.ts index e9254a814f..1ea315c0a5 100644 --- a/frontend/src/lib/components/instanceSettings.ts +++ b/frontend/src/lib/components/instanceSettings.ts @@ -4,6 +4,7 @@ import { z } from 'zod' import { instanceBannerFormError } from './instanceBanner' import { ACCENT_COLOR_SETTING, parseAccentColor } from '$lib/accentColor' import { parseMaxTokenExpirationDays } from '$lib/tokenExpiration' +import { parseCount } from '$lib/parseCount' import { writable } from 'svelte/store' import { OidcService } from '$lib/gen' import { workspaceRolesErrors } from '$lib/workspaceRoles' @@ -115,6 +116,9 @@ export interface Setting { export type SettingStorage = 'setting' +// Mirrors `RAW_APP_VERSIONS_TO_KEEP_BOUND` in windmill-common. +const RAW_APP_VERSIONS_TO_KEEP_BOUND = 1_000_000 + const positiveNumber = z.number().positive('Must be a positive number') const nonNegativeNumber = z.number().nonnegative('Must be zero or a positive number') @@ -344,6 +348,22 @@ export const settings: Record = { ee_only: '', hideInQuickSetup: true }, + { + label: 'Full-code app versions to keep', + key: 'raw_app_versions_to_keep', + description: + 'Number of versions to keep for each full-code app, counting the deployed one. Older versions and their bundles are permanently deleted within about 20 minutes, except versions replaced less than an hour ago and versions a draft is based on. Leave empty to keep every version.', + fieldType: 'number', + placeholder: 'all versions', + storage: 'setting', + hideInQuickSetup: true, + error: 'Must be a whole number of versions, from 1 to 1,000,000', + isValid: (value: unknown) => + value === undefined || + value === null || + value === '' || + parseCount(value, RAW_APP_VERSIONS_TO_KEEP_BOUND) !== undefined + }, { label: 'Maximum token expiration (days)', key: 'max_token_expiration_days', diff --git a/frontend/src/lib/parseCount.ts b/frontend/src/lib/parseCount.ts new file mode 100644 index 0000000000..b2e332343f --- /dev/null +++ b/frontend/src/lib/parseCount.ts @@ -0,0 +1,15 @@ +/** + * A whole number within `1..=max` stored as a JSON number or as a string of digits, `undefined` + * for anything else. Must accept exactly what `parse_optional_count` (windmill-common) does. + */ +export function parseCount(value: unknown, max: number): number | undefined { + const count = + typeof value === 'number' + ? value + : typeof value === 'string' && /^[+-]?\d+$/.test(value.trim()) + ? Number(value.trim()) + : undefined + return count !== undefined && Number.isInteger(count) && count >= 1 && count <= max + ? count + : undefined +} diff --git a/frontend/src/lib/tokenExpiration.ts b/frontend/src/lib/tokenExpiration.ts index a88ea1a9fd..11af0ea398 100644 --- a/frontend/src/lib/tokenExpiration.ts +++ b/frontend/src/lib/tokenExpiration.ts @@ -1,3 +1,5 @@ +import { parseCount } from '$lib/parseCount' + /** Largest `max_token_expiration_days` read as a ceiling, about 2,700 years. Mirrors * `MAX_TOKEN_EXPIRATION_DAYS_BOUND` in windmill-common. */ export const MAX_TOKEN_EXPIRATION_DAYS_BOUND = 1_000_000 @@ -10,16 +12,5 @@ export const MAX_TOKEN_EXPIRATION_DAYS_BOUND = 1_000_000 * looser and the token form hides "No expiration" on an instance whose server caps nothing. */ export function parseMaxTokenExpirationDays(value: unknown): number | undefined { - const days = - typeof value === 'number' - ? value - : typeof value === 'string' && /^[+-]?\d+$/.test(value.trim()) - ? Number(value.trim()) - : undefined - return days !== undefined && - Number.isInteger(days) && - days >= 1 && - days <= MAX_TOKEN_EXPIRATION_DAYS_BOUND - ? days - : undefined + return parseCount(value, MAX_TOKEN_EXPIRATION_DAYS_BOUND) }