diff --git a/backend/.sqlx/query-0361abb4ab7e9a9cf28f0e0551892334eda482fea471e77b6febcd061feba08f.json b/backend/.sqlx/query-0361abb4ab7e9a9cf28f0e0551892334eda482fea471e77b6febcd061feba08f.json new file mode 100644 index 0000000000..6405fdd4fb --- /dev/null +++ b/backend/.sqlx/query-0361abb4ab7e9a9cf28f0e0551892334eda482fea471e77b6febcd061feba08f.json @@ -0,0 +1,28 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT key, original_scheduled_for IS NOT NULL AND released_at IS NULL AS \"held!\"\n FROM concurrency_key WHERE job_id = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "key", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "held!", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false, + null + ] + }, + "hash": "0361abb4ab7e9a9cf28f0e0551892334eda482fea471e77b6febcd061feba08f" +} diff --git a/backend/.sqlx/query-79ad082adcef4e3dd4745bff5f498889cdd0f5365bd43442ac745997f1a4173c.json b/backend/.sqlx/query-79ad082adcef4e3dd4745bff5f498889cdd0f5365bd43442ac745997f1a4173c.json new file mode 100644 index 0000000000..960a40a9cd --- /dev/null +++ b/backend/.sqlx/query-79ad082adcef4e3dd4745bff5f498889cdd0f5365bd43442ac745997f1a4173c.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE concurrency_key SET released_at = $2 WHERE job_id = $1 AND released_at IS NULL", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Timestamptz" + ] + }, + "nullable": [] + }, + "hash": "79ad082adcef4e3dd4745bff5f498889cdd0f5365bd43442ac745997f1a4173c" +} diff --git a/backend/.sqlx/query-eaf0a5853b3550a4706d2aff6587b750ce7392ac6d7406403ce84127c5d978e3.json b/backend/.sqlx/query-eaf0a5853b3550a4706d2aff6587b750ce7392ac6d7406403ce84127c5d978e3.json new file mode 100644 index 0000000000..2ed99ef3d8 --- /dev/null +++ b/backend/.sqlx/query-eaf0a5853b3550a4706d2aff6587b750ce7392ac6d7406403ce84127c5d978e3.json @@ -0,0 +1,34 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT key, original_scheduled_for AS deferred_from, released_at FROM concurrency_key WHERE job_id = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "key", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "deferred_from", + "type_info": "Timestamptz" + }, + { + "ordinal": 2, + "name": "released_at", + "type_info": "Timestamptz" + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false, + true, + true + ] + }, + "hash": "eaf0a5853b3550a4706d2aff6587b750ce7392ac6d7406403ce84127c5d978e3" +} diff --git a/backend/ee-repo-ref.txt b/backend/ee-repo-ref.txt index 6b19aeeb50..01f7a1b754 100644 --- a/backend/ee-repo-ref.txt +++ b/backend/ee-repo-ref.txt @@ -1 +1 @@ -6302def89634fcf38db8c71122f1a4bdfe60f937 +302da0e8e3817d5cbda5cf1053a9fe89019d7c27 diff --git a/backend/migrations/20261124161107_concurrency_key_released_at.down.sql b/backend/migrations/20261124161107_concurrency_key_released_at.down.sql new file mode 100644 index 0000000000..fea8b63fd5 --- /dev/null +++ b/backend/migrations/20261124161107_concurrency_key_released_at.down.sql @@ -0,0 +1 @@ +ALTER TABLE concurrency_key DROP COLUMN IF EXISTS released_at; diff --git a/backend/migrations/20261124161107_concurrency_key_released_at.up.sql b/backend/migrations/20261124161107_concurrency_key_released_at.up.sql new file mode 100644 index 0000000000..46eb8a4664 --- /dev/null +++ b/backend/migrations/20261124161107_concurrency_key_released_at.up.sql @@ -0,0 +1,2 @@ +-- When the concurrency limit let in a job it had held back: the time the job was last due. +ALTER TABLE concurrency_key ADD COLUMN IF NOT EXISTS released_at TIMESTAMPTZ; diff --git a/backend/windmill-api/openapi.yaml b/backend/windmill-api/openapi.yaml index 880a24dfc1..7a95bab790 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -27977,6 +27977,38 @@ paths: application/json: schema: type: string + /concurrency_groups/{id}/key_status: + get: + summary: Get a job's concurrency key and whether its limit held it back + description: Requires read access to the job, the same as reading the run itself. Returns null when the job has no concurrency key. + operationId: getConcurrencyKeyStatus + tags: + - concurrencyGroups + parameters: + - $ref: "#/components/parameters/JobId" + responses: + "200": + description: concurrency key and deferral of the given job + content: + application/json: + schema: + type: object + nullable: true + properties: + key: + type: string + deferred_from: + type: string + format: date-time + nullable: true + description: When the job was first due. Set the first time its concurrency limit held it back, and kept after it ran. + released_at: + type: string + format: date-time + nullable: true + description: When the concurrency limit let in a job it had held back, as the time the job was last due. The rest until it started is queue time. + required: + - key /w/{workspace}/concurrency_groups/list_jobs: get: summary: Get intervals of job runtime concurrency diff --git a/backend/windmill-api/src/concurrency_groups.rs b/backend/windmill-api/src/concurrency_groups.rs index aab73c81d9..3e0a136b30 100644 --- a/backend/windmill-api/src/concurrency_groups.rs +++ b/backend/windmill-api/src/concurrency_groups.rs @@ -1,6 +1,8 @@ use std::sync::Arc; use axum::{extract::Path, routing::get, Extension, Json, Router}; +use chrono::{DateTime, Utc}; +use serde::Serialize; use uuid::Uuid; use windmill_common::{ db::UserDB, @@ -18,6 +20,7 @@ use crate::{ pub fn global_service() -> Router { windmill_api_jobs::concurrency_groups::global_service() .route("/{job_id}/key", get(get_concurrency_key)) + .route("/{job_id}/key_status", get(get_concurrency_key_status)) } /// A concurrency key embeds the job's workspace, its runnable path and any @@ -31,6 +34,44 @@ pub fn global_service() -> Router { /// job's own workspace before evaluating access — that also rejects non-members, for whom /// the job does not exist. Members reaching [`require_job_read_access`] get its 403, which /// discloses existence only inside a workspace they belong to. +async fn require_concurrency_key_read( + token: &str, + cache: &AuthCache, + db: &DB, + user_db: &UserDB, + view_token: Option<&str>, + job_id: Uuid, +) -> Result<(), Error> { + let not_found = || Error::NotFound(format!("Job {job_id} not found")); + + // A caller who cannot reach the job must not be able to tell it apart from a job + // that does not exist, so both answer with the same 404. + let job = sqlx::query!( + "SELECT workspace_id, created_by FROM v2_job WHERE id = $1", + job_id + ) + .fetch_optional(db) + .await? + .ok_or_else(not_found)?; + + let authed_in_workspace = cache + .get_authed(Some(job.workspace_id.clone()), token) + .await + .ok_or_else(not_found)?; + windmill_api_auth::check_job_token_scope(&authed_in_workspace, || "jobs:read".to_string())?; + + require_job_read_access( + db, + user_db, + &authed_in_workspace, + &job.workspace_id, + &job_id, + &job.created_by, + view_token, + ) + .await +} + async fn get_concurrency_key( _authed: ApiAuthed, Tokened { token }: Tokened, @@ -40,37 +81,42 @@ async fn get_concurrency_key( OptViewToken(view_token): OptViewToken, Path(job_id): Path, ) -> JsonResult> { - let not_found = || Error::NotFound(format!("Job {job_id} not found")); - - // A caller who cannot reach the job must not be able to tell it apart from a job - // that does not exist, so both answer with the same 404. - let job = sqlx::query!( - "SELECT workspace_id, created_by FROM v2_job WHERE id = $1", - job_id - ) - .fetch_optional(&db) - .await? - .ok_or_else(not_found)?; - - let authed_in_workspace = cache - .get_authed(Some(job.workspace_id.clone()), &token) - .await - .ok_or_else(not_found)?; - windmill_api_auth::check_job_token_scope(&authed_in_workspace, || "jobs:read".to_string())?; - - require_job_read_access( - &db, - &user_db, - &authed_in_workspace, - &job.workspace_id, - &job_id, - &job.created_by, - view_token.as_deref(), - ) - .await?; - + require_concurrency_key_read(&token, &cache, &db, &user_db, view_token.as_deref(), job_id) + .await?; let key = sqlx::query_scalar!("SELECT key FROM concurrency_key WHERE job_id = $1", job_id) .fetch_optional(&db) .await?; Ok(Json(key)) } + +#[derive(Serialize)] +struct ConcurrencyKeyStatus { + key: String, + /// When the job was first due. Set the first time its limit held it back, and kept + /// after it ran. + deferred_from: Option>, + /// When the limit let the job in: the time it was last due. The rest until it started + /// is queue time. + released_at: Option>, +} + +async fn get_concurrency_key_status( + _authed: ApiAuthed, + Tokened { token }: Tokened, + Extension(cache): Extension>, + Extension(db): Extension, + Extension(user_db): Extension, + OptViewToken(view_token): OptViewToken, + Path(job_id): Path, +) -> JsonResult> { + require_concurrency_key_read(&token, &cache, &db, &user_db, view_token.as_deref(), job_id) + .await?; + let status = sqlx::query_as!( + ConcurrencyKeyStatus, + "SELECT key, original_scheduled_for AS deferred_from, released_at FROM concurrency_key WHERE job_id = $1", + job_id + ) + .fetch_optional(&db) + .await?; + Ok(Json(status)) +} diff --git a/backend/windmill-queue/src/jobs.rs b/backend/windmill-queue/src/jobs.rs index e3d488bbea..ef9ae9b068 100644 --- a/backend/windmill-queue/src/jobs.rs +++ b/backend/windmill-queue/src/jobs.rs @@ -5619,6 +5619,40 @@ pub async fn custom_concurrency_key( .await } +/// A job's concurrency key, and whether its limit has held it back without letting it in yet. +pub async fn concurrency_key_and_hold( + db: &Pool, + job_id: &Uuid, +) -> windmill_common::error::Result> { + let fut = async || { + sqlx::query!( + "SELECT key, original_scheduled_for IS NOT NULL AND released_at IS NULL AS \"held!\" + FROM concurrency_key WHERE job_id = $1", + job_id + ) + .fetch_optional(db) + .await + }; + fut.retry( + ConstantBuilder::default() + .with_delay(std::time::Duration::from_secs(3)) + .with_max_times(5) + .build(), + ) + .notify(|err, dur| { + tracing::error!( + "Could not get concurrency key for job {job_id}, retrying in {dur:#?}, err: {err:#?}" + ); + }) + .await + .map(|r| r.map(|r| (r.key, r.held))) + .map_err(|e| { + Error::internal_err(format!( + "Could not get concurrency key for job {job_id}: {e:#}" + )) + }) +} + pub async fn concurrency_key( db: &Pool, id: &Uuid, diff --git a/frontend/src/lib/components/FlowPreviewContent.svelte b/frontend/src/lib/components/FlowPreviewContent.svelte index 8f2add6e08..6f7ff1296f 100644 --- a/frontend/src/lib/components/FlowPreviewContent.svelte +++ b/frontend/src/lib/components/FlowPreviewContent.svelte @@ -638,6 +638,7 @@ slim textPosition="bottom" showStepId + stepStates={localModuleStates} waitingNested={Object.keys(suspendStatus?.val ?? {}).length > 0} /> {/if} diff --git a/frontend/src/lib/components/FlowStatusViewer.svelte b/frontend/src/lib/components/FlowStatusViewer.svelte index 59ffbcde18..e0ba599727 100644 --- a/frontend/src/lib/components/FlowStatusViewer.svelte +++ b/frontend/src/lib/components/FlowStatusViewer.svelte @@ -97,13 +97,11 @@ let lastJobId: string = untrack(() => jobId) - let retryStatus = $state({ val: {} }) let globalRefreshes: Record Promise)[]> = $state({}) setContext('FlowStatusViewer', { flowState, suspendStatus, - retryStatus, hideDownloadInGraph: untrack(() => hideDownloadInGraph), hideNodeDefinition: untrack(() => hideNodeDefinition), hideTimeline: untrack(() => hideTimeline), @@ -119,7 +117,6 @@ if (jobId !== lastJobId) { console.log('updateJobId 3', jobId) lastJobId = jobId - retryStatus.val = {} suspendStatus.val = {} globalRefreshes = {} for (let key in localModuleStates) delete flowState[key] diff --git a/frontend/src/lib/components/FlowStatusViewerInner.svelte b/frontend/src/lib/components/FlowStatusViewerInner.svelte index 3c1a064b65..aab0b5c801 100644 --- a/frontend/src/lib/components/FlowStatusViewerInner.svelte +++ b/frontend/src/lib/components/FlowStatusViewerInner.svelte @@ -13,8 +13,10 @@ type CompletedJob, type WorkflowStatus, type FlowNote, - type FlowValue + type FlowValue, + ConcurrencyGroupsService } from '$lib/gen' + import { getDbClockNow } from '$lib/forLater' import FlowJobResult from './FlowJobResult.svelte' import WorkflowTimeline from './WorkflowTimeline.svelte' import DisplayResult from './DisplayResult.svelte' @@ -84,7 +86,6 @@ let { flowState: flowStateStore, - retryStatus, suspendStatus, hideDownloadInGraph, hideTimeline, @@ -631,17 +632,6 @@ } updateInnerModules(status) - // The preprocessor (step -1) and the error handler (past the steps) retry outside `modules`. - const outsideSteps = status.step < 0 || status.step >= status.modules.length - let count = - job?.type === 'CompletedJob' || (retryingStepId == undefined && !outsideSteps) - ? undefined - : status.retry?.fail_count - if (count) { - retryStatus.val[jobId ?? ''] = count - } else if (retryStatus.val[jobId ?? ''] != undefined) { - delete retryStatus.val[jobId ?? ''] - } let jobStatus = job?.flow_status?.modules?.[job?.flow_status.step] if (jobStatus && jobStatus.count != undefined) { @@ -725,6 +715,94 @@ /** The step waiting for or running its next attempt, if any. */ let retryingStepId: string | undefined = undefined + + // A concurrency limit moves a waiting step's due time each time it holds it back, often by + // only a few seconds, so a step still waiting once that time has passed is read again, at + // most every 5s. The parent flow does not change meanwhile, hence the timer below. + const waitingStepChecks = new Map() + // A step's concurrency key is written as it is queued: one without can never be held, so + // past the end of its sleep only a change of the parent flow can change what it waits for. + const unlimitedSteps = new Set() + function waitingStepDue(mod: FlowStatusModule): boolean { + const last = waitingStepChecks.get(mod.job ?? '') + if (last != undefined && Date.now() - last < 5000) return false + const scheduledFor = localModuleStates[mod.id ?? '']?.scheduled_for + return scheduledFor == undefined || new Date(scheduledFor) <= getDbClockNow() + } + + function loadWaitingStep(mod: FlowStatusModule, retrying: boolean) { + waitingStepChecks.set(mod.job ?? '', Date.now()) + const workspace = workspaceId ?? $operatingWorkspace ?? '' + Promise.all([ + JobService.getJob({ workspace, id: mod.job ?? '', noLogs: true, noCode: true }), + ConcurrencyGroupsService.getConcurrencyKeyStatus({ id: mod.job ?? '' }).catch(() => undefined) + ]) + .then(([job, held]) => { + // The step may have started or ended while this was in flight. + const now = innerModules?.find((m) => m.id === mod.id) + if (now?.type !== 'WaitingForExecutor' || now.job !== mod.job) return + if (held === null) unlimitedSteps.add(mod.job ?? '') + const scheduledFor: string | undefined = job?.['scheduled_for'] + // Once let in, a held job only waits for a worker. + const waiting_reason: GraphModuleState['waiting_reason'] = + held?.deferred_from && !held.released_at + ? 'concurrency' + : scheduledFor && + new Date(scheduledFor) > getDbClockNow() && + !retrying && + sleepsBefore(mod.id) + ? 'sleep' + : undefined + setModuleState(mod.id ?? '', { + type: mod.type, + scheduled_for: job?.['scheduled_for'], + waiting_reason, + concurrency_key: waiting_reason === 'concurrency' ? held?.key : undefined, + held_since: + waiting_reason === 'concurrency' ? (held?.deferred_from ?? undefined) : undefined, + job_id: job?.id, + parent_module: failedStepOf(mod), + args: job?.args, + tag: job?.tag, + script_hash: job?.script_hash + }) + // So the timeline draws the wait while it lasts. + if (waiting_reason && job?.created_at) + setDurationStatusByJob( + mod.id ?? '', + job.id, + { created_at: new Date(job.created_at).getTime() }, + true + ) + }) + .catch((e) => { + console.error(`Could not load inner module for job ${mod.job}`, e) + }) + } + + $effect(() => { + if (job?.type !== 'QueuedJob' || isReplay) return + const id = setInterval(() => { + innerModules?.forEach((mod) => { + if ( + mod.type === 'WaitingForExecutor' && + (!unlimitedSteps.has(mod.job ?? '') || + localModuleStates[mod.id ?? '']?.waiting_reason === 'sleep') && + waitingStepDue(mod) + ) { + loadWaitingStep(mod, mod.id === retryingStepId) + } + }) + }, 5000) + return () => clearInterval(id) + }) + + /** Whether the step before `id` sleeps once done, which pushes `id` back by that long. */ + function sleepsBefore(id: string | undefined): boolean { + const raw = job?.raw_flow?.modules ?? [] + const i = raw.findIndex((m) => m.id === id) + return i > 0 && !!raw[i - 1].sleep + } function updateInnerModules(status: FlowStatus) { const found = findDeniedApproval(status) const denied = found?.approval @@ -750,6 +828,24 @@ if (mod.type === 'Failure' && localModuleStates[mod.id ?? '']?.type === 'Success') { setModuleState(mod.id ?? '', { type: 'Failure' }) } + // The step after an approval step is the one that waits for it. + const approvalStep = innerModules?.[i - 1] + const approvalWait = + mod.id && + job?.id && + approvalStep?.id && + approvalStep.type === 'Success' && + mod.type === 'WaitingForEvents' + ? { + job: job.id, + workspace: job.workspace_id, + step: approvalStep.id, + required: mod.count ?? 1 + } + : undefined + if (mod.id && !deepEqual(approvalWait, localModuleStates[mod.id]?.approval_wait)) { + setModuleState(mod.id, { approval_wait: approvalWait }) + } if (mod.type === 'WaitingForEvents' && innerModules?.[i - 1]?.type === 'Success') { setModuleState(mod.id ?? '', { type: mod.type, @@ -757,33 +853,9 @@ tag: job?.tag, script_hash: job?.script_hash }) - } else if ( - mod.type === 'WaitingForExecutor' && - localModuleStates[mod.id ?? '']?.scheduled_for == undefined - ) { + } else if (mod.type === 'WaitingForExecutor' && waitingStepDue(mod)) { if (!isReplay) { - JobService.getJob({ - workspace: workspaceId ?? $operatingWorkspace ?? '', - id: mod.job ?? '', - noLogs: true, - noCode: true - }) - .then((job) => { - const newState = { - type: mod.type, - scheduled_for: job?.['scheduled_for'], - job_id: job?.id, - parent_module: failedStepOf(mod), - args: job?.args, - tag: job?.tag, - script_hash: job?.script_hash - } - - setModuleState(mod.id ?? '', newState) - }) - .catch((e) => { - console.error(`Could not load inner module for job ${mod.job}`, e) - }) + loadWaitingStep(mod, mod.id === retryingId) } } else if ( (mod.flow_jobs || mod.branch_chosen) && @@ -1415,8 +1487,6 @@ let wrapperHeight: number = $state(0) - let retryStatusHeight: number = $state(0) - function removeFailureNode(id: string, parent_module: any) { if (id?.startsWith('failure-') && parent_module) { ;[...globalModuleStates, localModuleStates].forEach((stateMap) => { @@ -1437,12 +1507,33 @@ suspend?: boolean /** Shown in place of the id. */ label?: string + /** The fixed sleep of the step before it, in seconds. */ + sleepBefore?: number + /** An inline script with a concurrency limit, which can be held back. */ + limited?: boolean + } + + // Sleeps in branches and loop bodies are not looked at. + function timelineExtras( + modules: FlowModule[] + ): Map { + const extras = new Map() + modules.forEach((m, i) => { + const sleep = modules[i - 1]?.sleep + const v = m.value + extras.set(m.id, { + sleepBefore: sleep?.type === 'static' ? Number(sleep.value) || undefined : undefined, + limited: v.type === 'rawscript' && (v.concurrent_limit ?? 0) > 0 + }) + }) + return extras } function allModulesForTimeline( modules: FlowModule[], expandedSubflows: Record ): FlowModuleForTimeline[] { + const topExtras = timelineExtras(modules) const ids = dfs( modules, (x) => @@ -1450,7 +1541,8 @@ id: x.id, type: x.value.type, suspend: x.suspend != undefined, - label: x.id === AGENT_STEP_ID ? agentStepLabel(job?.script_path) : undefined + label: x.id === AGENT_STEP_ID ? agentStepLabel(job?.script_path) : undefined, + ...topExtras.get(x.id) }) as FlowModuleForTimeline, { skipToolNodes: true @@ -1469,6 +1561,7 @@ return [] } let nprefix = buildPrefix(prefix, oid) + const extras = fms ? timelineExtras(fms) : undefined return fms ? rec( dfs( @@ -1476,7 +1569,8 @@ (x) => ({ id: x.id.startsWith('subflow:') ? x.id : buildSubflowKey(x.id, nprefix), type: x.value.type, - suspend: x.suspend != undefined + suspend: x.suspend != undefined, + ...extras?.get(x.id) }), { skipToolNodes: true } ), @@ -2133,6 +2227,10 @@ {/if} @@ -2206,21 +2304,12 @@
-
- {#each Object.values(retryStatus?.val ?? {}) as count} - {#if count} - - Retry in progress, # of failed attempts: {count} - - {/if} - {/each} -
{#if node.duration_ms} diff --git a/frontend/src/lib/components/FlowTimeline.svelte b/frontend/src/lib/components/FlowTimeline.svelte index fd44399e30..a1d7ca44eb 100644 --- a/frontend/src/lib/components/FlowTimeline.svelte +++ b/frontend/src/lib/components/FlowTimeline.svelte @@ -1,5 +1,6 @@
Execution + {#if hasSleep} +
+
+ Sleep +
+ {/if} + {#if hasHold} +
+
+ Concurrency limit +
+ {/if} {#if hasApprovalWait}
@@ -184,8 +274,11 @@ />
{/if} - {#each flowModules as { id: k, type: typ, suspend: isSuspend, label } (k)} - {@const subItems = items?.[k]?.filter((x) => x.created_at && x.started_at)} + {#each flowModules as m (m.id)} + {@const { id: k, type: typ, suspend: isSuspend, label } = m} + {@const subItems = items?.[k]?.filter( + (x) => x.created_at && (x.started_at || localModuleStates[k]?.waiting_reason) + )}
- + {#if segments.length <= 1} + + {:else} + {#each segments as seg, i (i)} + 0} + colorClass={segmentStyle[seg.kind].colorClass} + tooltip="{segmentStyle[seg.kind].label} · {msToCompactDuration( + seg.len, + 1 + )}" + followedByBar + spacerClass="bg-gray-100 dark:bg-gray-800/50 rounded-l-md" + started_at={seg.start} + len={i === segments.length - 1 ? Math.max(seg.len - 100, 0) : seg.len} + running={b?.started_at == undefined} + /> + {/each} + {/if} {#if b.started_at} @@ -90,6 +94,12 @@ {/if}
+{:else if job && 'running' in job && job.running && stepWaiting} +
+ + {stepWaiting === 'sleep' ? 'Sleeping' : 'Step held by concurrency limit'} + +
{:else if job && 'running' in job && job.running}
@@ -100,6 +110,12 @@ {@render continuedOnErrorBadge()}
+{:else if job && 'running' in job && heldByConcurrency} +
+ + Held by concurrency limit + +
{:else if job && 'running' in job && 'scheduled_for' in job && job.scheduled_for && forLater(job.scheduled_for)}
diff --git a/frontend/src/lib/components/ModuleStatus.svelte b/frontend/src/lib/components/ModuleStatus.svelte index 351b3e0d03..3615d8d29f 100644 --- a/frontend/src/lib/components/ModuleStatus.svelte +++ b/frontend/src/lib/components/ModuleStatus.svelte @@ -1,32 +1,73 @@ {#if type == 'WaitingForEvents'} - - - Waiting to be resumed by resume events such as approvals + + + {approval_wait ? approval.label : 'Waiting to be resumed by resume events such as approvals'} {:else if type == 'WaitingForPriorSteps'} Waiting for prior steps to complete +{:else if type == 'WaitingForExecutor' && waiting_reason === 'sleep'} + + + Sleeping until {displayDate(scheduled_for, true)} · {msToCompactDuration(sleepLeft, 0)} left + +{:else if type == 'WaitingForExecutor' && waiting_reason === 'concurrency'} + + + Held by concurrency limit{heldFor != undefined + ? ` · ${msToCompactDuration(heldFor, 0)}` + : ''}{concurrency_key ? ` (key ${concurrency_key})` : ''}, next check by {displayDate( + scheduled_for, + true + )} + {:else if type == 'WaitingForExecutor'} - + {#if scheduled_for && forLater(scheduled_for.toString())} Job is scheduled to be executed at {displayDate(scheduled_for, true)} {:else} diff --git a/frontend/src/lib/components/TimelineBar.svelte b/frontend/src/lib/components/TimelineBar.svelte index 43c72a9c8b..a76a1e17e5 100644 --- a/frontend/src/lib/components/TimelineBar.svelte +++ b/frontend/src/lib/components/TimelineBar.svelte @@ -4,7 +4,8 @@ import Popover from './Popover.svelte' interface Props { - position?: 'center' | 'left' | 'right' + /** `none`: a middle piece of a bar split in several. */ + position?: 'center' | 'left' | 'right' | 'none' total: number min: number | undefined started_at: number | undefined @@ -61,7 +62,9 @@ ? 'rounded-l-md' : position == 'right' ? 'rounded-r-md' - : 'rounded-md'} center-center text-white text-2xs whitespace-nowrap hover:outline outline-1 outline-black" + : position == 'none' + ? '' + : 'rounded-md'} center-center text-white text-2xs whitespace-nowrap hover:outline outline-1 outline-black" > {#snippet text()} {#if tooltip} diff --git a/frontend/src/lib/components/flows/FlowProgressBar.svelte b/frontend/src/lib/components/flows/FlowProgressBar.svelte index 30b0f958ca..61c320ac53 100644 --- a/frontend/src/lib/components/flows/FlowProgressBar.svelte +++ b/frontend/src/lib/components/flows/FlowProgressBar.svelte @@ -4,6 +4,8 @@ import { forLater } from '$lib/forLater' import { waitingRequest } from '../agentRequest' import type { Snippet } from 'svelte' + import type { GraphModuleState } from '../graph' + import { displayDate } from '$lib/utils' interface Props { job?: Job | undefined @@ -13,6 +15,8 @@ textPosition?: 'top' | 'bottom' // Prefer step ID over step index when both are available showStepId?: boolean + /** The run graph's step states, which say why a step that has not started is waiting. */ + stepStates?: Record errorAction?: Snippet /** A run nested under this one waits on an approval, which its own steps don't show. */ waitingNested?: boolean @@ -25,10 +29,42 @@ slim = false, textPosition = 'top', showStepId = false, + stepStates = undefined, errorAction, waitingNested = false }: Props = $props() + // The current step, or a step waiting inside it when it is a subflow. + let waitingText = $derived.by(() => { + const current = job?.flow_status?.modules?.[job.flow_status.step]?.id + if (!current || !stepStates) return undefined + const inside = `subflow:${current}:` + const retrying = Object.entries(stepStates).find( + ([key, s]) => + (key === current || key.startsWith(inside)) && + (s.type === 'WaitingForExecutor' || s.type === 'InProgress') && + (s.retries ?? 0) > 0 + ) + if (retrying) { + const [key, s] = retrying + const n = s.retries ?? 0 + return `Retrying step '${key.split(':').pop()}', ${n} failed attempt${n === 1 ? '' : 's'}` + } + const found = Object.entries(stepStates).find( + ([key, s]) => + (key === current || key.startsWith(inside)) && + s.type === 'WaitingForExecutor' && + s.waiting_reason + ) + if (!found) return undefined + const [key, s] = found + const step = key.split(':').pop() + const until = displayDate(s.scheduled_for, true) + return s.waiting_reason === 'sleep' + ? `Sleeping before step '${step}' until ${until}` + : `Step '${step}' held by concurrency limit, next check by ${until}` + }) + let error: number | undefined = $state(undefined) let index = $state(0) let subIndex: number | undefined = $state(undefined) @@ -196,5 +232,6 @@ {isCanceled} {isScheduled} {isSkipped} + {waitingText} {errorAction} /> diff --git a/frontend/src/lib/components/flows/map/FlowModuleSchemaItem.svelte b/frontend/src/lib/components/flows/map/FlowModuleSchemaItem.svelte index 2c468d9773..5e960ad82d 100644 --- a/frontend/src/lib/components/flows/map/FlowModuleSchemaItem.svelte +++ b/frontend/src/lib/components/flows/map/FlowModuleSchemaItem.svelte @@ -66,6 +66,8 @@ pathHref?: string nodeState?: FlowNodeState retries?: number | undefined + /** In a run, while its concurrency limit holds the step back. */ + held?: { since?: string; nextCheck?: Date | string } /** In a run, the attempts the retry badge picks from. */ attempts?: RetryAttempts | undefined warningMessage?: string | undefined @@ -101,6 +103,7 @@ pathHref = undefined, nodeState, retries = undefined, + held = undefined, attempts = undefined, warningMessage = undefined, editMode = false, @@ -311,6 +314,7 @@ (settingsMenuOpen = o)} onOpenSetting={editMode && id diff --git a/frontend/src/lib/components/flows/map/MapItem.svelte b/frontend/src/lib/components/flows/map/MapItem.svelte index e957665a6b..c847f89fee 100644 --- a/frontend/src/lib/components/flows/map/MapItem.svelte +++ b/frontend/src/lib/components/flows/map/MapItem.svelte @@ -32,6 +32,8 @@ nodeState?: FlowNodeState duration_ms?: number | undefined retries?: number | undefined + /** In a run, while its concurrency limit holds the step back. */ + held?: { since?: string; nextCheck?: Date | string } flowJobs: | { flowJobs: string[] @@ -83,6 +85,7 @@ nodeState, duration_ms = undefined, retries = undefined, + held = undefined, flowJobs, attempts = undefined, editMode = false, @@ -283,6 +286,7 @@ {:else} void onOpenChange?: (open: boolean) => void @@ -34,6 +36,7 @@ settings, retries = undefined, attempts = undefined, + held = undefined, onOpenSetting, onOpenChange }: Props = $props() @@ -87,9 +90,26 @@ // With nothing else to list, the menu is the attempt list itself, one hover fewer. let attemptsOnly = $derived(!!pickerProps && settings.length === 1) + // Read as the menu opens: the held time it shows does not tick. + let heldDetail = $derived( + held?.since && open + ? ` · held ${msToCompactDuration(Math.max(Date.now() - new Date(held.since).getTime(), 0), 0)}` + : held + ? ' · held' + : undefined + ) + let items: Item[] = $derived( ordered.map((s) => { const action = onOpenSetting && (() => onOpenSetting(s.key)) + if (s.key === 'concurrency' && heldDetail) + return { + displayName: s.label, + icon: s.icon, + iconColor: '#f97316', + detail: s.summary.text + heldDetail, + action + } if (s.key !== 'retries') return { displayName: s.label, icon: s.icon, detail: s.summary.text, action } if (pickerProps) { @@ -143,13 +163,14 @@ unifiedSize="2xs" wrapperClasses="bg-surface rounded-md" btnClasses="px-2" - title="Step settings" + title={held ? 'Step settings: held by its concurrency limit' : 'Step settings'} > {#each shown as s (s.key)} {@const Icon = s.icon} diff --git a/frontend/src/lib/components/graph/approvalCount.svelte.ts b/frontend/src/lib/components/graph/approvalCount.svelte.ts new file mode 100644 index 0000000000..1600bbc1e5 --- /dev/null +++ b/frontend/src/lib/components/graph/approvalCount.svelte.ts @@ -0,0 +1,28 @@ +import { JobService } from '$lib/gen' +import type { GraphModuleState } from './model' + +/** How many approvals a waiting step has received so far. Approvals coming in do not change the + * run until the last one, so the count is read on its own, and only when there is more than one + * to count. */ +export function useApprovalCount(wait: () => GraphModuleState['approval_wait']) { + let count = $state(undefined) + $effect(() => { + const w = wait() + if (!w || w.required <= 1 || !w.workspace) return + const args = { workspace: w.workspace, jobId: w.job, stepId: w.step } + const read = () => + JobService.getApprovalStepDetail(args) + .then((d) => (count = d.approvals.length)) + .catch(() => {}) + read() + const id = setInterval(read, 10000) + return () => clearInterval(id) + }) + return { + /** "Waiting for approval", with "· 1 of 2" once some are in. */ + get label() { + const w = wait() + return `Waiting for approval${count && w ? ` · ${count} of ${w.required}` : ''}` + } + } +} diff --git a/frontend/src/lib/components/graph/flowRunStatus.svelte.ts b/frontend/src/lib/components/graph/flowRunStatus.svelte.ts index 39886c5737..8233713c2b 100644 --- a/frontend/src/lib/components/graph/flowRunStatus.svelte.ts +++ b/frontend/src/lib/components/graph/flowRunStatus.svelte.ts @@ -44,6 +44,20 @@ export class FlowRunStatus { return count } + /** Steps inside the subflow step `id`, at any depth, waiting for an approval, waiting out a + * sleep or held by their concurrency limit. */ + waitingStepsInside(id: string): { approval: number; sleep: number; concurrency: number } { + const prefix = (id.startsWith('subflow:') ? id : 'subflow:' + id) + ':' + const count = { approval: 0, sleep: 0, concurrency: 0 } + for (const [key, state] of this.#moduleStates) { + if (!key.startsWith(prefix)) continue + if (state.approval_wait) count.approval++ + else if (state.type === 'WaitingForExecutor' && state.waiting_reason) + count[state.waiting_reason]++ + } + return count + } + setModuleStates(next: Record | undefined) { const incoming = next ?? {} for (const id of [...this.#moduleStates.keys()]) { diff --git a/frontend/src/lib/components/graph/model.ts b/frontend/src/lib/components/graph/model.ts index c8d7aac34e..1468973644 100644 --- a/frontend/src/lib/components/graph/model.ts +++ b/frontend/src/lib/components/graph/model.ts @@ -29,7 +29,6 @@ export type DurationStatus = { export type FlowStatusViewerContext = { flowState?: FlowState - retryStatus: StateStore> /** `prefix`: the subflow step ids leading to the run, as `buildPrefix` chains them. */ suspendStatus: StateStore> hideDownloadInGraph?: boolean @@ -48,6 +47,15 @@ export type GraphModuleState = { result?: any tag?: string scheduled_for?: Date + /** Why a `WaitingForExecutor` step is due later: the previous step's sleep, or its own + * concurrency limit holding it back (`concurrency_key`). */ + waiting_reason?: 'sleep' | 'concurrency' + /** On the step waiting for the approval step `step` before it: their run, and how many + * approvals it needs. */ + approval_wait?: { job: string; workspace?: string; step: string; required: number } + /** When its concurrency limit first held the step back. */ + held_since?: string + concurrency_key?: string job_id?: string parent_module?: string selectedForloop?: string diff --git a/frontend/src/lib/components/graph/renderers/nodes/ModuleNode.svelte b/frontend/src/lib/components/graph/renderers/nodes/ModuleNode.svelte index 2e2539fa8d..34db0d4e02 100644 --- a/frontend/src/lib/components/graph/renderers/nodes/ModuleNode.svelte +++ b/frontend/src/lib/components/graph/renderers/nodes/ModuleNode.svelte @@ -8,10 +8,14 @@ StickyNote, PictureInPicture2, Bug, - RefreshCw + RefreshCw, + Gauge, + Hourglass, + Moon } from 'lucide-svelte' import DropdownV2 from '$lib/components/DropdownV2.svelte' import NodeWrapper from './NodeWrapper.svelte' + import WaitingMark from './WaitingMark.svelte' import AiDecisionNodeBranch from './AiDecisionNodeBranch.svelte' import type { ModuleN } from '../../graphBuilder.svelte' import { jobToGraphModuleState } from '$lib/components/modulesTest.svelte' @@ -219,6 +223,24 @@ : undefined }) + // Live, so it takes the slot of the retried and error handler counts while it lasts. + let waitingInside = $derived.by(() => { + if (!flowRunStatus?.showsRun || data.editMode || data.module?.value?.type !== 'flow') return + const { approval, sleep, concurrency } = flowRunStatus.waitingStepsInside(data.id) + if (approval > 0) + return { + reason: 'approval' as const, + label: `${approval === 1 ? 'Approval' : `${approval} approvals`} waiting inside` + } + if (concurrency > 0) + return { + reason: 'concurrency' as const, + label: `${concurrency} step${concurrency === 1 ? '' : 's'} held by concurrency limit` + } + if (sleep > 0) + return { reason: 'sleep' as const, label: `${sleep} step${sleep === 1 ? '' : 's'} sleeping` } + }) + let type = $derived.by(() => { let typ = state?.type if (!typ && flowJobs) { @@ -319,6 +341,9 @@ nodeState={state?.skipped ? '_Skipped' : type} duration_ms={state?.duration_ms} retries={state?.retries} + held={type === 'WaitingForExecutor' && state?.waiting_reason === 'concurrency' + ? { since: state.held_since, nextCheck: state.scheduled_for } + : undefined} {flowJobs} {attempts} on:delete={(e) => { @@ -352,11 +377,61 @@ : undefined} /> - {#await hiddenErrorHandlers} - {@render insideBar(retriedInside, undefined)} - {:then handlers} - {@render insideBar(retriedInside, handlers)} - {/await} + {#if type === 'WaitingForExecutor' && state?.waiting_reason} + data.module && data.eventHandlers.select(data.module.id)} + /> + {:else if state?.approval_wait} + data.module && data.eventHandlers.select(data.module.id)} + /> + {/if} + {#if waitingInside} + +
e.stopPropagation()} + > + +
+ {:else} + {#await hiddenErrorHandlers} + {@render insideBar(retriedInside, undefined)} + {:then handlers} + {@render insideBar(retriedInside, handlers)} + {/await} + {/if} {#if (data.module?.value?.type === 'branchall' || data.module?.value?.type === 'branchone') && data.insertable}
diff --git a/frontend/src/lib/components/graph/renderers/nodes/WaitingMark.svelte b/frontend/src/lib/components/graph/renderers/nodes/WaitingMark.svelte new file mode 100644 index 0000000000..871505e92a --- /dev/null +++ b/frontend/src/lib/components/graph/renderers/nodes/WaitingMark.svelte @@ -0,0 +1,79 @@ + + + + +
e.stopPropagation()} +> + +
diff --git a/frontend/src/lib/components/progressBar/ProgressBar.svelte b/frontend/src/lib/components/progressBar/ProgressBar.svelte index 60f59ae880..c2c7d7ed85 100644 --- a/frontend/src/lib/components/progressBar/ProgressBar.svelte +++ b/frontend/src/lib/components/progressBar/ProgressBar.svelte @@ -37,6 +37,8 @@ isScheduled?: boolean // Whether the job was skipped (early-stop labelled as skipped) isSkipped?: boolean + /** Why the next step has not started yet, e.g. a sleep or a concurrency limit. */ + waitingText?: string /** Rendered after "Error occurred" when the bar is in its error state. */ errorAction?: Snippet } @@ -60,6 +62,7 @@ isCanceled = false, isScheduled = false, isSkipped = false, + waitingText = undefined, errorAction }: Props = $props() let duration = 200 @@ -166,7 +169,7 @@ {:else if status == 'running' && !isCanceled && !isScheduled && !isSkipped} {/if} - {#key status + isWaitingForEvents + stepId + isCanceled + isScheduled + isSkipped} + {#key status + isWaitingForEvents + stepId + isCanceled + isScheduled + isSkipped + waitingText} {#if status == 'error'} Error occurred @@ -180,9 +183,11 @@ Waiting to be resumed {:else if isScheduled} (not started) + {:else if waitingText} + {waitingText} {:else if showStepId} {stepId - ? `${isCanceled ? 'Canceled at' : 'Running'} step ${stepId}` + ? `${isCanceled ? 'Canceled at' : 'Running'} step '${stepId}'` : `${isCanceled ? 'Canceled' : ''}`} {:else if hideStepTitle} {isCanceled ? 'Canceled' : 'Running'} diff --git a/frontend/src/lib/components/runs/JobDetailHeader.svelte b/frontend/src/lib/components/runs/JobDetailHeader.svelte index a2b19a54bf..75be13f4f5 100644 --- a/frontend/src/lib/components/runs/JobDetailHeader.svelte +++ b/frontend/src/lib/components/runs/JobDetailHeader.svelte @@ -52,6 +52,12 @@ displayPersistentScriptDefinition?: boolean openPersistentScriptDrawer?: () => void concurrencyKey?: string + /** When the job was first due, if its concurrency limit held it back. */ + concurrencyDeferredFrom?: string + /** When its concurrency limit let in the job it had held back. */ + concurrencyReleasedAt?: string + /** Why the step the flow is at has not started. */ + stepWaiting?: 'sleep' | 'concurrency' compact?: boolean extraCompact?: boolean onFilterByConcurrencyKey?: (key: string) => void @@ -67,6 +73,9 @@ displayPersistentScriptDefinition = false, openPersistentScriptDrawer, concurrencyKey, + concurrencyDeferredFrom, + concurrencyReleasedAt, + stepWaiting, compact = false, extraCompact = false, onFilterByConcurrencyKey, @@ -75,6 +84,8 @@ onResolutionChanged }: Props = $props() + let heldByConcurrency = $derived(!!concurrencyDeferredFrom && !concurrencyReleasedAt) + let togglingResolution = $state(false) let resolutionNote = $state('') @@ -386,7 +397,7 @@
{#if job} - +
Job ID @@ -473,7 +484,7 @@
- +
@@ -511,13 +522,15 @@
- + - import { ConcurrencyGroupsService, type Job, type WorkflowStatus } from '../../gen' + import { type Job, type WorkflowStatus } from '../../gen' + import { useConcurrencyKeyStatus } from './useConcurrencyKeyStatus.svelte' import JobLoader from '../JobLoader.svelte' import DisplayResult from '../DisplayResult.svelte' import JobArgs from '../JobArgs.svelte' @@ -34,12 +35,7 @@ let loadError: string | undefined = $state(undefined) let isLoadingJobDetails: boolean = $state(false) - let lastJobId: string | undefined = $state(undefined) - let concurrencyKey: string | undefined = $state(undefined) - async function getConcurrencyKey(job: Job) { - lastJobId = job.id - concurrencyKey = await ConcurrencyGroupsService.getConcurrencyKey({ id: job.id }) - } + const concurrency = useConcurrencyKeyStatus(() => job) let viewTab = $state('logs') @@ -99,10 +95,6 @@ } }) - $effect(() => { - job?.id && lastJobId !== job.id && untrack(() => job && getConcurrencyKey(job)) - }) - let jobLoader: JobLoader | undefined = $state(undefined) // Set all tabs content to the same height to prevent layout jumps @@ -153,7 +145,9 @@
@@ -65,10 +77,32 @@ + {:else if 'running' in job && job.running && stepWaiting === 'sleep'} + + + + {:else if 'running' in job && job.running && stepWaiting === 'concurrency'} + + + {:else if 'running' in job && job.running} + {:else if 'running' in job && heldByConcurrency} + + + {:else if job && 'running' in job && job.scheduled_for && forLater(job.scheduled_for)} diff --git a/frontend/src/lib/components/runs/RunBadges.svelte b/frontend/src/lib/components/runs/RunBadges.svelte index 2c31ed852c..90f807858b 100644 --- a/frontend/src/lib/components/runs/RunBadges.svelte +++ b/frontend/src/lib/components/runs/RunBadges.svelte @@ -1,11 +1,11 @@ {#if job.script_hash && showScriptHash && job.job_kind !== 'aiagent'} @@ -110,10 +156,23 @@
{/each} {/if} +{#snippet held()} + {#if heldMs != undefined && heldMs > 0} + + {msToCompactDuration(heldMs, 0)} + + {/if} +{/snippet} + {#if concurrencyKey}
{#snippet text()} + {#if heldMs != undefined} + Held by its concurrency limit for {msToCompactDuration(heldMs, 0)}{queuedAfterMs + ? `, then queued ${msToCompactDuration(queuedAfterMs, 0)}` + : ''}. + {/if} This job has concurrency limits enabled with the key: {#if onFilterByConcurrencyKey} {:else} - Concurrency: {truncateRev(concurrencyKey, 20)} + Concurrency: {truncateRev(concurrencyKey, 20)}{@render held()} {/if} diff --git a/frontend/src/lib/components/runs/RunDetail.svelte b/frontend/src/lib/components/runs/RunDetail.svelte index 9e9962d564..0e381047a1 100644 --- a/frontend/src/lib/components/runs/RunDetail.svelte +++ b/frontend/src/lib/components/runs/RunDetail.svelte @@ -6,7 +6,6 @@ type Script, type WorkflowStatus, type NewScript, - ConcurrencyGroupsService, MetricsService, WorkerService, type ScriptArgs @@ -74,6 +73,7 @@ import PageHeaderContent from '$lib/components/PageHeaderContent.svelte' import { pageHeader } from '$lib/components/pageHeaderRegistry.svelte' import JobDetailHeader from '$lib/components/runs/JobDetailHeader.svelte' + import { useConcurrencyKeyStatus } from '$lib/components/runs/useConcurrencyKeyStatus.svelte' import ScriptRetryChain from '$lib/components/runs/ScriptRetryChain.svelte' import FlowApprovals from '$lib/components/runs/FlowApprovals.svelte' import JobArgs from '$lib/components/JobArgs.svelte' @@ -270,20 +270,13 @@ (localStorage.getItem('hideExplicitProgressTip') ?? 'false') == 'false' ) - let lastJobId: string | undefined = $state(undefined) - let concurrencyKey: string | undefined = $state(undefined) + const concurrency = useConcurrencyKeyStatus(() => job) setContext( 'FlowGraphAssetContext', initFlowGraphAssetsCtx({ getModules: () => job?.raw_flow?.modules ?? [] }) ) - async function getConcurrencyKey(job: Job | undefined) { - if (!job) return - lastJobId = job.id - concurrencyKey = await ConcurrencyGroupsService.getConcurrencyKey({ id: job.id }) - } - // Share read link: if the URL carries a `view_token`, install it so every job // read on this page (incl. flow steps, args, logs, SSE) is authorized by it. // Set eagerly at init (before JobLoader mounts and fires its first fetch), and @@ -710,9 +703,6 @@ return openEditInFork(kind, itemPath, workspaceId) } - $effect(() => { - job?.id && lastJobId !== job.id && untrack(() => getConcurrencyKey(job)) - }) $effect(() => { workspaceId && runId && untrack(() => onRunsPageChange()) }) @@ -1432,7 +1422,14 @@ openPersistentScriptDrawer={() => { persistentScriptDrawer?.open?.(persistentScriptDefinition) }} - {concurrencyKey} + concurrencyKey={concurrency.key} + concurrencyDeferredFrom={concurrency.deferredFrom} + concurrencyReleasedAt={concurrency.releasedAt} + stepWaiting={job.type === 'QueuedJob' + ? Object.values(graphModuleStates).find( + (s) => s.type === 'WaitingForExecutor' && s.waiting_reason + )?.waiting_reason + : undefined} /> {/if}
@@ -1455,6 +1452,7 @@ textPosition="bottom" slim showStepId + stepStates={graphModuleStates} waitingNested={Object.keys(suspendStatus?.val ?? {}).length > 0} > {#snippet errorAction()} diff --git a/frontend/src/lib/components/runs/useConcurrencyKeyStatus.svelte.ts b/frontend/src/lib/components/runs/useConcurrencyKeyStatus.svelte.ts new file mode 100644 index 0000000000..42b7f0224f --- /dev/null +++ b/frontend/src/lib/components/runs/useConcurrencyKeyStatus.svelte.ts @@ -0,0 +1,67 @@ +import { ConcurrencyGroupsService, type Job } from '$lib/gen' +import { getDbClockNow } from '$lib/forLater' + +/** A job's concurrency key and, if its limit held it back, when it was first due and when it was + * let in. */ +export function useConcurrencyKeyStatus(getJob: () => Job | undefined) { + type Status = { key: string; deferred_from?: string | null; released_at?: string | null } | null + let loaded = $state<{ jobId: string; status: Status } | undefined>(undefined) + + let id = $derived(getJob()?.id) + let phase = $derived.by(() => { + const job = getJob() + return job?.type === 'CompletedJob' ? 'done' : job?.['running'] ? 'running' : 'waiting' + }) + let scheduledFor = $derived(getJob()?.['scheduled_for'] as string | undefined) + + // Live updates do not carry a job's due time, so a limit holding it back is only seen by + // asking: once per phase (waiting, running, done), and every 5s while it waits once due. + $effect(() => { + const jobId = id + const waiting = phase === 'waiting' + const dueIn = scheduledFor ? new Date(scheduledFor).getTime() - getDbClockNow().getTime() : 0 + if (!jobId) return + let current = true + let stopped = false + let timer: ReturnType | undefined = undefined + const stop = () => { + stopped = true + clearTimeout(timer) + } + const load = () => + ConcurrencyGroupsService.getConcurrencyKeyStatus({ id: jobId }) + .then((status) => { + if (!current) return + loaded = { jobId, status } + // The key is written as the job is queued: none means it has no limit. + if (!status) stop() + }) + .catch(stop) + const poll = () => { + if (stopped) return + load() + timer = setTimeout(poll, 5000) + } + load() + // setTimeout fires at once past 2^31 - 1 ms. + if (waiting) timer = setTimeout(poll, Math.min(Math.max(dueIn, 5000), 2 ** 31 - 1)) + return () => { + current = false + stop() + } + }) + + let status = $derived(loaded?.jobId === id ? loaded?.status : undefined) + + return { + get key() { + return status?.key + }, + get deferredFrom() { + return status?.deferred_from ?? undefined + }, + get releasedAt() { + return status?.released_at ?? undefined + } + } +}