Preset tables, latest workspace view, state logic improved

Signed-off-by: Danny Kopping <danny@coder.com>
This commit is contained in:
Danny Kopping
2025-01-23 14:09:58 +00:00
parent 281a76aad9
commit 4b5555e918
12 changed files with 191 additions and 64 deletions

View File

@ -1,28 +1,29 @@
-- name: GetTemplatePrebuildState :many
WITH latest_workspace_builds AS (SELECT wb.id,
wb.workspace_id,
wbmax.template_id,
wb.template_version_id
FROM (SELECT tv.template_id,
wbmax.workspace_id,
MAX(wbmax.build_number) as max_build_number
FROM workspace_builds wbmax
JOIN template_versions tv ON (tv.id = wbmax.template_version_id)
GROUP BY tv.template_id, wbmax.workspace_id) wbmax
JOIN workspace_builds wb ON (
wb.workspace_id = wbmax.workspace_id
AND wb.build_number = wbmax.max_build_number
))
-- TODO: need to store the desired instances & autoscaling schedules in db; use desired value here
SELECT CAST(1 AS integer) AS desired,
CAST(COUNT(wp.*) AS integer) AS actual,
CAST(0 AS integer) AS extraneous, -- TODO: calculate this by subtracting actual from count not matching template version
WITH
-- All prebuilds currently running
running_prebuilds AS (SELECT p.*, b.template_version_id
FROM workspace_prebuilds p
INNER JOIN workspace_latest_build b ON b.workspace_id = p.id
WHERE b.transition = 'start'::workspace_transition),
-- All templates which have been configured for prebuilds (any version)
templates_with_prebuilds AS (SELECT t.id AS template_id,
tv.id AS template_version_id,
tv.id = t.active_version_id AS using_active_version,
tvpp.desired_instances,
t.deleted,
t.deprecated != '' AS deprecated
FROM templates t
INNER JOIN template_versions tv ON tv.template_id = t.id
INNER JOIN template_version_presets tvp ON tvp.template_version_id = tv.id
INNER JOIN template_version_preset_prebuilds tvpp ON tvpp.preset_id = tvp.id
WHERE t.id = @template_id::uuid
GROUP BY t.id, tv.id, tvpp.id)
SELECT t.template_id,
COUNT(p.id) AS actual, -- running prebuilds for active version
MAX(CASE WHEN t.using_active_version THEN t.desired_instances ELSE 0 END) AS desired, -- we only care about the active version's desired instances
SUM(CASE WHEN t.using_active_version THEN 0 ELSE 1 END) AS extraneous, -- running prebuilds for inactive version
t.deleted,
t.deprecated,
tv.id AS template_version_id
FROM latest_workspace_builds lwb
JOIN template_versions tv ON lwb.template_version_id = tv.id
JOIN templates t ON t.id = lwb.template_id
LEFT JOIN workspace_prebuilds wp ON wp.id = lwb.workspace_id
WHERE t.id = @template_id::uuid
GROUP BY t.id, t.deleted, t.deprecated, tv.id;
t.deprecated
FROM templates_with_prebuilds t
LEFT JOIN running_prebuilds p ON p.template_version_id = t.template_version_id
GROUP BY t.template_id, p.id, t.deleted, t.deprecated;