@shipfox/api-workflows 12.6.0 → 13.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +8 -8
- package/CHANGELOG.md +23 -0
- package/dist/core/entities/workflow-run.d.ts +3 -0
- package/dist/core/entities/workflow-run.d.ts.map +1 -1
- package/dist/core/entities/workflow-run.js.map +1 -1
- package/dist/db/index.d.ts +1 -1
- package/dist/db/index.d.ts.map +1 -1
- package/dist/db/index.js +1 -1
- package/dist/db/index.js.map +1 -1
- package/dist/db/job-listeners.d.ts.map +1 -1
- package/dist/db/job-listeners.js +17 -1
- package/dist/db/job-listeners.js.map +1 -1
- package/dist/db/workflow-runs/job-executions.d.ts +2 -3
- package/dist/db/workflow-runs/job-executions.d.ts.map +1 -1
- package/dist/db/workflow-runs/job-executions.js +48 -20
- package/dist/db/workflow-runs/job-executions.js.map +1 -1
- package/dist/db/workflow-runs/outbox.d.ts +15 -0
- package/dist/db/workflow-runs/outbox.d.ts.map +1 -1
- package/dist/db/workflow-runs/outbox.js +35 -1
- package/dist/db/workflow-runs/outbox.js.map +1 -1
- package/dist/db/workflow-runs/queries.d.ts +5 -3
- package/dist/db/workflow-runs/queries.d.ts.map +1 -1
- package/dist/db/workflow-runs/queries.js +20 -6
- package/dist/db/workflow-runs/queries.js.map +1 -1
- package/dist/db/workflow-runs/run-graph.d.ts.map +1 -1
- package/dist/db/workflow-runs/run-graph.js +12 -0
- package/dist/db/workflow-runs/run-graph.js.map +1 -1
- package/dist/db/workflow-runs/run-status.d.ts.map +1 -1
- package/dist/db/workflow-runs/run-status.js +13 -1
- package/dist/db/workflow-runs/run-status.js.map +1 -1
- package/dist/db/workflow-runs.d.ts +2 -2
- package/dist/db/workflow-runs.d.ts.map +1 -1
- package/dist/db/workflow-runs.js +2 -2
- package/dist/db/workflow-runs.js.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -4
- package/dist/index.js.map +1 -1
- package/dist/presentation/dto/workflow-run.d.ts.map +1 -1
- package/dist/presentation/dto/workflow-run.js +4 -2
- package/dist/presentation/dto/workflow-run.js.map +1 -1
- package/dist/presentation/index.d.ts +1 -1
- package/dist/presentation/index.d.ts.map +1 -1
- package/dist/presentation/index.js +1 -1
- package/dist/presentation/index.js.map +1 -1
- package/dist/presentation/routes/get-run.d.ts.map +1 -1
- package/dist/presentation/routes/get-run.js +2 -1
- package/dist/presentation/routes/get-run.js.map +1 -1
- package/dist/presentation/subscribers/index.d.ts +0 -1
- package/dist/presentation/subscribers/index.d.ts.map +1 -1
- package/dist/presentation/subscribers/index.js +0 -1
- package/dist/presentation/subscribers/index.js.map +1 -1
- package/dist/temporal/activities/index.d.ts +2 -18
- package/dist/temporal/activities/index.d.ts.map +1 -1
- package/dist/temporal/activities/index.js +3 -5
- package/dist/temporal/activities/index.js.map +1 -1
- package/dist/temporal/activities/orchestration-activities.d.ts +5 -14
- package/dist/temporal/activities/orchestration-activities.d.ts.map +1 -1
- package/dist/temporal/activities/orchestration-activities.js +13 -34
- package/dist/temporal/activities/orchestration-activities.js.map +1 -1
- package/dist/temporal/workflows/index.bundle.js +20 -68
- package/dist/temporal/workflows/job-execution-orchestration.d.ts +0 -3
- package/dist/temporal/workflows/job-execution-orchestration.d.ts.map +1 -1
- package/dist/temporal/workflows/job-execution-orchestration.js +17 -41
- package/dist/temporal/workflows/job-execution-orchestration.js.map +1 -1
- package/dist/temporal/workflows/job-listener-orchestration.d.ts +0 -3
- package/dist/temporal/workflows/job-listener-orchestration.d.ts.map +1 -1
- package/dist/temporal/workflows/job-listener-orchestration.js +1 -9
- package/dist/temporal/workflows/job-listener-orchestration.js.map +1 -1
- package/dist/temporal/workflows/run-orchestration.d.ts.map +1 -1
- package/dist/temporal/workflows/run-orchestration.js +2 -18
- package/dist/temporal/workflows/run-orchestration.js.map +1 -1
- package/dist/temporal/workflows/test-env.d.ts +4 -6
- package/dist/temporal/workflows/test-env.d.ts.map +1 -1
- package/dist/temporal/workflows/test-env.js +13 -24
- package/dist/temporal/workflows/test-env.js.map +1 -1
- package/dist/tsconfig.test.tsbuildinfo +1 -1
- package/package.json +3 -3
- package/src/core/entities/workflow-run.ts +3 -0
- package/src/db/index.ts +1 -1
- package/src/db/job-listeners.test.ts +21 -0
- package/src/db/job-listeners.ts +18 -0
- package/src/db/workflow-runs/job-executions.test.ts +110 -12
- package/src/db/workflow-runs/job-executions.ts +54 -29
- package/src/db/workflow-runs/outbox.ts +63 -0
- package/src/db/workflow-runs/queries.test.ts +27 -0
- package/src/db/workflow-runs/queries.ts +31 -5
- package/src/db/workflow-runs/run-graph.ts +17 -0
- package/src/db/workflow-runs/run-status.test.ts +13 -0
- package/src/db/workflow-runs/run-status.ts +15 -1
- package/src/db/workflow-runs.ts +3 -1
- package/src/index.ts +1 -5
- package/src/presentation/dto/workflow-run.ts +7 -1
- package/src/presentation/index.ts +0 -1
- package/src/presentation/routes/get-run.test.ts +31 -0
- package/src/presentation/routes/get-run.ts +1 -0
- package/src/presentation/routes/list-runs.test.ts +5 -1
- package/src/presentation/subscribers/index.ts +0 -1
- package/src/temporal/activities/index.ts +2 -8
- package/src/temporal/activities/orchestration-activities.test.ts +17 -1
- package/src/temporal/activities/orchestration-activities.ts +13 -46
- package/src/temporal/workflows/job-execution-orchestration.test.ts +6 -25
- package/src/temporal/workflows/job-execution-orchestration.ts +17 -43
- package/src/temporal/workflows/job-listener-orchestration-continuation.test.ts +0 -3
- package/src/temporal/workflows/job-listener-orchestration.test.ts +9 -12
- package/src/temporal/workflows/job-listener-orchestration.ts +0 -8
- package/src/temporal/workflows/run-orchestration.test.ts +22 -33
- package/src/temporal/workflows/run-orchestration.ts +4 -28
- package/src/temporal/workflows/test-env.ts +14 -34
- package/test/fixtures/runners-inter-module.ts +0 -3
- package/test/helpers/workflow-runs.ts +25 -0
- package/tsconfig.build.tsbuildinfo +1 -1
- package/dist/presentation/subscribers/on-runner-job-queued.d.ts +0 -3
- package/dist/presentation/subscribers/on-runner-job-queued.d.ts.map +0 -1
- package/dist/presentation/subscribers/on-runner-job-queued.js +0 -20
- package/dist/presentation/subscribers/on-runner-job-queued.js.map +0 -1
- package/src/presentation/subscribers/on-runner-job-queued.test.ts +0 -57
- package/src/presentation/subscribers/on-runner-job-queued.ts +0 -23
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/db/workflow-runs/job-executions.ts"],"sourcesContent":["import {readPersistedWorkflowModel} from '@shipfox/api-definitions-dto';\nimport type {SecretsInterModuleClient} from '@shipfox/api-secrets-dto/inter-module';\nimport {WORKFLOWS_JOB_EXECUTION_TIMED_OUT} from '@shipfox/api-workflows-dto';\nimport {and, asc, desc, eq, isNull, notInArray, sql} from 'drizzle-orm';\nimport type {JobStatusReason} from '#core/entities/job.js';\nimport type {JobExecution, JobExecutionStatus} from '#core/entities/job-execution.js';\nimport {\n InterpolationUnresolvableError,\n JobNotFoundError,\n JobOutputNotJsonSafeError,\n JobOutputTooLargeError,\n JobOutputTooManyEntriesError,\n} from '#core/errors.js';\nimport {deriveJobExecutionOutputs} from '#core/job-transition/index.js';\nimport {deriveCompletion, isTerminal} from '#core/step-transition/decide-step-transition.js';\nimport type {RuntimeCompletionStatus} from '#core/workflow-scheduling/runtime-dag.js';\nimport {\n recordWorkflowJobExecutionLeaseExpiryResolved,\n recordWorkflowJobExecutionQueued,\n recordWorkflowJobExecutionStarted,\n recordWorkflowJobExecutionStatusChanged,\n recordWorkflowJobExecutionTimedOut,\n} from '#metrics/instance.js';\nimport {db, type Tx} from '../db.js';\nimport {writeWorkflowsOutboxEvent} from '../outbox-writes.js';\nimport {jobExecutions, toJobExecution} from '../schema/job-executions.js';\nimport {jobs, toJob} from '../schema/jobs.js';\nimport {stepAttempts, toStepAttempt} from '../schema/step-attempts.js';\nimport {steps, toStep} from '../schema/steps.js';\nimport {workflowRunAttempts} from '../schema/workflow-run-attempts.js';\nimport {toWorkflowRun, workflowRuns} from '../schema/workflow-runs.js';\nimport {getDirectDependencyJobContexts} from './jobs.js';\nimport {loadReferencedVariables} from './runs.js';\nimport {\n getWorkflowContextForJob,\n optimisticLockRetry,\n TERMINAL_EXECUTION_STATUSES,\n} from './shared.js';\nimport {bulkUpdateStepStatuses, getStepsByJobExecutionIdForUpdate} from './steps.js';\n\nasync function getJobExecutionFallbackName(tx: Tx, jobExecutionId: string): Promise<string> {\n const [row] = await tx\n .select({job: jobs})\n .from(jobExecutions)\n .innerJoin(jobs, eq(jobExecutions.jobId, jobs.id))\n .where(eq(jobExecutions.id, jobExecutionId))\n .limit(1);\n if (!row) throw new JobNotFoundError(jobExecutionId);\n return row.job.name ?? row.job.key;\n}\n\nexport async function getJobExecutionById(id: string, tx?: Tx): Promise<JobExecution | undefined> {\n const rows = await (tx ?? db())\n .select({jobExecution: jobExecutions, job: jobs})\n .from(jobExecutions)\n .innerJoin(jobs, eq(jobExecutions.jobId, jobs.id))\n .where(eq(jobExecutions.id, id))\n .limit(1);\n const row = rows[0];\n return row ? toJobExecution(row.jobExecution, row.job.name ?? row.job.key) : undefined;\n}\n\nexport async function getJobExecutionsByWorkflowRunAttemptId(\n workflowRunAttemptId: string,\n): Promise<JobExecution[]> {\n const rows = await db()\n .select({jobExecution: jobExecutions, job: jobs})\n .from(jobExecutions)\n .innerJoin(jobs, eq(jobExecutions.jobId, jobs.id))\n .where(eq(jobs.workflowRunAttemptId, workflowRunAttemptId))\n .orderBy(asc(jobExecutions.sequence), asc(jobExecutions.id));\n return rows.map((row) => toJobExecution(row.jobExecution, row.job.name ?? row.job.key));\n}\n\nexport async function getJobExecutionsByJobId(jobId: string): Promise<JobExecution[]> {\n const rows = await db()\n .select({jobExecution: jobExecutions, job: jobs})\n .from(jobExecutions)\n .innerJoin(jobs, eq(jobExecutions.jobId, jobs.id))\n .where(eq(jobExecutions.jobId, jobId))\n .orderBy(asc(jobExecutions.sequence), asc(jobExecutions.id));\n return rows.map((row) => toJobExecution(row.jobExecution, row.job.name ?? row.job.key));\n}\n\nexport async function getFirstJobExecutionByJobId(\n jobId: string,\n tx?: Tx,\n): Promise<JobExecution | undefined> {\n const rows = await (tx ?? db())\n .select({jobExecution: jobExecutions, job: jobs})\n .from(jobExecutions)\n .innerJoin(jobs, eq(jobExecutions.jobId, jobs.id))\n .where(eq(jobExecutions.jobId, jobId))\n .orderBy(asc(jobExecutions.sequence), asc(jobExecutions.id))\n .limit(1);\n const row = rows[0];\n return row ? toJobExecution(row.jobExecution, row.job.name ?? row.job.key) : undefined;\n}\n\nexport async function getLatestJobExecutionByJobId(\n jobId: string,\n tx?: Tx,\n): Promise<JobExecution | undefined> {\n const rows = await (tx ?? db())\n .select({jobExecution: jobExecutions, job: jobs})\n .from(jobExecutions)\n .innerJoin(jobs, eq(jobExecutions.jobId, jobs.id))\n .where(eq(jobExecutions.jobId, jobId))\n .orderBy(desc(jobExecutions.sequence), desc(jobExecutions.id))\n .limit(1);\n const row = rows[0];\n return row ? toJobExecution(row.jobExecution, row.job.name ?? row.job.key) : undefined;\n}\n\nexport interface UpdateJobExecutionStatusAtVersionParams {\n jobExecutionId: string;\n status: JobExecutionStatus;\n expectedVersion: number;\n statusReason?: JobStatusReason | null | undefined;\n statusReasonMessage?: string | null | undefined;\n markTimedOut?: boolean;\n secrets?: Pick<SecretsInterModuleClient, 'getVariablesByNamespace'> | undefined;\n}\n\nconst MAX_STATUS_REASON_MESSAGE_LENGTH = 2048;\n\nexport type JobOutputFailure = {\n statusReason: Extract<JobStatusReason, 'output_invalid' | 'output_too_large'>;\n statusReasonMessage: string;\n};\n\nexport function classifyJobOutputFailure(error: unknown): JobOutputFailure | null {\n if (error instanceof JobOutputTooLargeError) {\n return {\n statusReason: 'output_too_large',\n statusReasonMessage: boundedStatusReasonMessage(error.message),\n };\n }\n\n if (\n (error instanceof InterpolationUnresolvableError && error.field === 'job.outputs') ||\n error instanceof JobOutputNotJsonSafeError ||\n error instanceof JobOutputTooManyEntriesError\n ) {\n return {\n statusReason: 'output_invalid',\n statusReasonMessage: boundedStatusReasonMessage(error.message),\n };\n }\n\n return null;\n}\n\nfunction boundedStatusReasonMessage(message: string): string {\n return message.length <= MAX_STATUS_REASON_MESSAGE_LENGTH\n ? message\n : `${message.slice(0, MAX_STATUS_REASON_MESSAGE_LENGTH - 1)}…`;\n}\n\nasync function resolveJobExecutionOutputs(\n tx: Tx,\n params: {\n jobExecutionId: string;\n status: JobExecutionStatus;\n statusReason: JobStatusReason | null;\n secrets?: Pick<SecretsInterModuleClient, 'getVariablesByNamespace'> | undefined;\n },\n): Promise<Record<string, unknown> | null> {\n const [target] = await tx\n .select({execution: jobExecutions, job: jobs, attempt: workflowRunAttempts, run: workflowRuns})\n .from(jobExecutions)\n .innerJoin(jobs, eq(jobExecutions.jobId, jobs.id))\n .innerJoin(workflowRunAttempts, eq(jobs.workflowRunAttemptId, workflowRunAttempts.id))\n .innerJoin(workflowRuns, eq(workflowRunAttempts.workflowRunId, workflowRuns.id))\n .where(eq(jobExecutions.id, params.jobExecutionId))\n .limit(1);\n if (!target) throw new JobNotFoundError(params.jobExecutionId);\n const model =\n target.attempt.model === null ? null : readPersistedWorkflowModel(target.attempt.model);\n if (!model) return null;\n const modelJob = model.jobs.find((job) => job.key === target.job.key);\n if (!modelJob || modelJob.outputs === undefined) return null;\n\n const executionRows = await tx\n .select()\n .from(jobExecutions)\n .where(eq(jobExecutions.jobId, target.job.id))\n .orderBy(asc(jobExecutions.sequence), asc(jobExecutions.id));\n const fallbackName = target.job.name ?? target.job.key;\n const executions = executionRows.map((row) =>\n row.id === target.execution.id\n ? toJobExecution(\n {...row, status: params.status, statusReason: params.statusReason},\n fallbackName,\n )\n : toJobExecution(row, fallbackName),\n );\n const jobExecution = executions.find((execution) => execution.id === target.execution.id);\n if (!jobExecution) throw new JobNotFoundError(params.jobExecutionId);\n\n const stepRows = await tx\n .select()\n .from(steps)\n .where(eq(steps.jobExecutionId, params.jobExecutionId))\n .orderBy(asc(steps.position), asc(steps.id));\n const attemptRows = await tx\n .select()\n .from(stepAttempts)\n .where(eq(stepAttempts.jobExecutionId, params.jobExecutionId))\n .orderBy(asc(stepAttempts.executionOrder), asc(stepAttempts.id));\n const dependencyJobs = await getDirectDependencyJobContexts(target.job.id, tx);\n\n return deriveJobExecutionOutputs({\n run: toWorkflowRun(target.run),\n modelJob,\n job: toJob(target.job),\n jobExecution,\n executions,\n steps: stepRows.map(toStep),\n attempts: attemptRows.map(toStepAttempt),\n jobs: dependencyJobs,\n vars: await loadReferencedVariables({\n model,\n jobs: [modelJob],\n workspaceId: target.run.workspaceId,\n projectId: target.run.projectId,\n definitionId: target.run.definitionId,\n secrets: params.secrets,\n }),\n });\n}\n\nasync function updateJobExecutionStatusAtVersion(\n tx: Tx,\n params: UpdateJobExecutionStatusAtVersionParams,\n): Promise<{execution: JobExecution; changed: boolean} | null> {\n let status = params.status;\n let statusReason = params.statusReason ?? null;\n let statusReasonMessage = params.statusReasonMessage ?? null;\n let outputs: Record<string, unknown> | null | undefined;\n if (TERMINAL_EXECUTION_STATUSES.includes(status)) {\n outputs = null;\n }\n if (status === 'succeeded') {\n try {\n outputs = await resolveJobExecutionOutputs(tx, {\n jobExecutionId: params.jobExecutionId,\n status,\n statusReason,\n secrets: params.secrets,\n });\n } catch (error) {\n const outputFailure = classifyJobOutputFailure(error);\n if (outputFailure === null) throw error;\n status = 'failed';\n statusReason = outputFailure.statusReason;\n statusReasonMessage = outputFailure.statusReasonMessage;\n outputs = null;\n }\n }\n\n const rows = await tx\n .update(jobExecutions)\n .set({\n status,\n statusReason,\n statusReasonMessage,\n ...(outputs === undefined ? {} : {outputs}),\n version: sql`${jobExecutions.version} + 1`,\n updatedAt: new Date(),\n ...(params.markTimedOut ? {timedOutAt: new Date()} : {}),\n ...(TERMINAL_EXECUTION_STATUSES.includes(status) ? {finishedAt: sql`now()`} : {}),\n })\n .where(\n and(\n eq(jobExecutions.id, params.jobExecutionId),\n eq(jobExecutions.version, params.expectedVersion),\n notInArray(jobExecutions.status, TERMINAL_EXECUTION_STATUSES),\n ),\n )\n .returning();\n\n const row = rows[0];\n if (!row) return null;\n return {\n execution: toJobExecution(row, await getJobExecutionFallbackName(tx, row.id)),\n changed: true,\n };\n}\n\nexport interface UpdateJobExecutionStatusParams {\n jobExecutionId: string;\n status: JobExecutionStatus;\n expectedVersion: number;\n statusReason?: JobStatusReason | null | undefined;\n statusReasonMessage?: string | null | undefined;\n secrets?: Pick<SecretsInterModuleClient, 'getVariablesByNamespace'> | undefined;\n}\n\nexport async function updateJobExecutionStatus(\n params: UpdateJobExecutionStatusParams,\n): Promise<JobExecution> {\n const statusReason = params.statusReason ?? null;\n const result = await db().transaction(async (tx) => {\n return await optimisticLockRetry({\n updateFn: () =>\n updateJobExecutionStatusAtVersion(tx, {\n jobExecutionId: params.jobExecutionId,\n status: params.status,\n expectedVersion: params.expectedVersion,\n statusReason,\n statusReasonMessage: params.statusReasonMessage,\n secrets: params.secrets,\n }),\n fetchFn: async () => {\n const row = (\n await tx\n .select()\n .from(jobExecutions)\n .where(eq(jobExecutions.id, params.jobExecutionId))\n .limit(1)\n )[0];\n return row ? toJobExecution(row, await getJobExecutionFallbackName(tx, row.id)) : undefined;\n },\n matchFn: (execution) =>\n (execution.status === params.status && execution.statusReason === statusReason) ||\n TERMINAL_EXECUTION_STATUSES.includes(execution.status)\n ? {execution, changed: false}\n : null,\n failureMessage: `Optimistic lock failure: job execution ${params.jobExecutionId} version ${params.expectedVersion}`,\n });\n });\n\n if (result.changed) recordWorkflowJobExecutionStatusChanged(result.execution.status);\n\n return result.execution;\n}\n\nexport async function recordJobExecutionQueuedAt(params: {\n jobExecutionId: string;\n queuedAt: Date;\n}): Promise<void> {\n const updated = await db()\n .update(jobExecutions)\n .set({queuedAt: params.queuedAt})\n .where(and(eq(jobExecutions.id, params.jobExecutionId), isNull(jobExecutions.queuedAt)))\n .returning({id: jobExecutions.id});\n\n if (updated.length > 0) recordWorkflowJobExecutionQueued();\n}\n\nexport async function recordJobExecutionStartedAt(params: {\n jobExecutionId: string;\n startedAt: Date;\n}): Promise<void> {\n const updated = await db()\n .update(jobExecutions)\n .set({startedAt: params.startedAt})\n .where(and(eq(jobExecutions.id, params.jobExecutionId), isNull(jobExecutions.startedAt)))\n .returning({id: jobExecutions.id});\n\n if (updated.length > 0) recordWorkflowJobExecutionStarted();\n}\n\nexport async function failJobExecutionAsTimedOut(params: {\n jobExecutionId: string;\n workflowRunAttemptId: string;\n expectedVersion: number;\n secrets?: Pick<SecretsInterModuleClient, 'getVariablesByNamespace'> | undefined;\n}): Promise<JobExecution> {\n const result = await db().transaction(async (tx) => {\n const updated = await optimisticLockRetry({\n updateFn: () =>\n updateJobExecutionStatusAtVersion(tx, {\n jobExecutionId: params.jobExecutionId,\n status: 'failed',\n expectedVersion: params.expectedVersion,\n statusReason: 'timed_out',\n markTimedOut: true,\n secrets: params.secrets,\n }),\n fetchFn: async () => {\n const row = (\n await tx\n .select()\n .from(jobExecutions)\n .where(eq(jobExecutions.id, params.jobExecutionId))\n .limit(1)\n )[0];\n return row ? toJobExecution(row, await getJobExecutionFallbackName(tx, row.id)) : undefined;\n },\n matchFn: (execution) => (execution.timedOutAt !== null ? {execution, changed: false} : null),\n failureMessage: `Optimistic lock failure: job execution ${params.jobExecutionId} version ${params.expectedVersion}`,\n });\n\n if (updated.changed) {\n const identity = await getWorkflowContextForJob(updated.execution.jobId, tx);\n await writeWorkflowsOutboxEvent(tx, {\n type: WORKFLOWS_JOB_EXECUTION_TIMED_OUT,\n payload: {\n jobId: identity.jobId,\n jobExecutionId: params.jobExecutionId,\n workflowRunAttemptId: identity.workflowRunAttemptId,\n },\n });\n }\n\n return updated;\n });\n\n if (result.changed) {\n recordWorkflowJobExecutionStatusChanged(result.execution.status);\n recordWorkflowJobExecutionTimedOut();\n }\n\n return result.execution;\n}\n\nexport async function resolveJobExecutionAfterLeaseExpiry(params: {\n jobExecutionId: string;\n expectedVersion: number;\n secrets?: Pick<SecretsInterModuleClient, 'getVariablesByNamespace'> | undefined;\n}): Promise<{status: RuntimeCompletionStatus; executionVersion: number}> {\n const result = await db().transaction(async (tx) => {\n const jobExecutionSteps = await getStepsByJobExecutionIdForUpdate(params.jobExecutionId, tx);\n let changedJobExecution: JobExecution | null = null;\n\n if (jobExecutionSteps.length === 0) {\n throw new JobNotFoundError(params.jobExecutionId);\n }\n\n if (jobExecutionSteps.every((step) => isTerminal(step.status))) {\n const status = deriveCompletion(jobExecutionSteps);\n const updated = await updateJobExecutionStatusAtVersion(tx, {\n jobExecutionId: params.jobExecutionId,\n status,\n expectedVersion: params.expectedVersion,\n statusReason: statusReasonForStepCompletion(status),\n secrets: params.secrets,\n });\n changedJobExecution = updated?.changed ? updated.execution : null;\n } else {\n const updated = await updateJobExecutionStatusAtVersion(tx, {\n jobExecutionId: params.jobExecutionId,\n status: 'failed',\n expectedVersion: params.expectedVersion,\n statusReason: 'runner_lost',\n secrets: params.secrets,\n });\n if (updated?.changed) {\n changedJobExecution = updated.execution;\n await bulkUpdateStepStatuses(\n {jobExecutionId: params.jobExecutionId, status: 'cancelled'},\n tx,\n );\n }\n }\n\n const jobExecutionRow = (\n await tx\n .select()\n .from(jobExecutions)\n .where(eq(jobExecutions.id, params.jobExecutionId))\n .limit(1)\n )[0];\n if (!jobExecutionRow) {\n throw new Error(`Job execution not found resolving lease expiry: ${params.jobExecutionId}`);\n }\n const status: RuntimeCompletionStatus =\n jobExecutionRow.status === 'succeeded' ? 'succeeded' : 'failed';\n return {status, executionVersion: jobExecutionRow.version, changedJobExecution};\n });\n\n recordWorkflowJobExecutionLeaseExpiryResolved(result.status);\n if (result.changedJobExecution) {\n recordWorkflowJobExecutionStatusChanged(result.changedJobExecution.status);\n }\n\n return {status: result.status, executionVersion: result.executionVersion};\n}\n\nfunction statusReasonForStepCompletion(status: RuntimeCompletionStatus): JobStatusReason | null {\n return status === 'failed' ? 'step_failed' : null;\n}\n"],"names":["readPersistedWorkflowModel","WORKFLOWS_JOB_EXECUTION_TIMED_OUT","and","asc","desc","eq","isNull","notInArray","sql","InterpolationUnresolvableError","JobNotFoundError","JobOutputNotJsonSafeError","JobOutputTooLargeError","JobOutputTooManyEntriesError","deriveJobExecutionOutputs","deriveCompletion","isTerminal","recordWorkflowJobExecutionLeaseExpiryResolved","recordWorkflowJobExecutionQueued","recordWorkflowJobExecutionStarted","recordWorkflowJobExecutionStatusChanged","recordWorkflowJobExecutionTimedOut","db","writeWorkflowsOutboxEvent","jobExecutions","toJobExecution","jobs","toJob","stepAttempts","toStepAttempt","steps","toStep","workflowRunAttempts","toWorkflowRun","workflowRuns","getDirectDependencyJobContexts","loadReferencedVariables","getWorkflowContextForJob","optimisticLockRetry","TERMINAL_EXECUTION_STATUSES","bulkUpdateStepStatuses","getStepsByJobExecutionIdForUpdate","getJobExecutionFallbackName","tx","jobExecutionId","row","select","job","from","innerJoin","jobId","id","where","limit","name","key","getJobExecutionById","rows","jobExecution","undefined","getJobExecutionsByWorkflowRunAttemptId","workflowRunAttemptId","orderBy","sequence","map","getJobExecutionsByJobId","getFirstJobExecutionByJobId","getLatestJobExecutionByJobId","MAX_STATUS_REASON_MESSAGE_LENGTH","classifyJobOutputFailure","error","statusReason","statusReasonMessage","boundedStatusReasonMessage","message","field","length","slice","resolveJobExecutionOutputs","params","target","execution","attempt","run","workflowRunId","model","modelJob","find","outputs","executionRows","fallbackName","executions","status","stepRows","position","attemptRows","executionOrder","dependencyJobs","attempts","vars","workspaceId","projectId","definitionId","secrets","updateJobExecutionStatusAtVersion","includes","outputFailure","update","set","version","updatedAt","Date","markTimedOut","timedOutAt","finishedAt","expectedVersion","returning","changed","updateJobExecutionStatus","result","transaction","updateFn","fetchFn","matchFn","failureMessage","recordJobExecutionQueuedAt","updated","queuedAt","recordJobExecutionStartedAt","startedAt","failJobExecutionAsTimedOut","identity","type","payload","resolveJobExecutionAfterLeaseExpiry","jobExecutionSteps","changedJobExecution","every","step","statusReasonForStepCompletion","jobExecutionRow","Error","executionVersion"],"mappings":"AAAA,SAAQA,0BAA0B,QAAO,+BAA+B;AAEx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C,MAAMzC,uBACJ;oBAACI,gBAAgBmC,OAAOnC,cAAc;oBAAEgD,QAAQ;gBAAW,GAC3DjD;YAEJ;QACF;QAEA,MAAMiG,kBAAkB,AACtB,CAAA,MAAMjG,GACHG,MAAM,GACNE,IAAI,CAACxB,eACL4B,KAAK,CAAC/C,GAAGmB,cAAc2B,EAAE,EAAE4B,OAAOnC,cAAc,GAChDS,KAAK,CAAC,EAAC,CACX,CAAC,EAAE;QACJ,IAAI,CAACuF,iBAAiB;YACpB,MAAM,IAAIC,MAAM,CAAC,gDAAgD,EAAE9D,OAAOnC,cAAc,EAAE;QAC5F;QACA,MAAMgD,SACJgD,gBAAgBhD,MAAM,KAAK,cAAc,cAAc;QACzD,OAAO;YAACA;YAAQkD,kBAAkBF,gBAAgB/B,OAAO;YAAE2B;QAAmB;IAChF;IAEAvH,8CAA8CsG,OAAO3B,MAAM;IAC3D,IAAI2B,OAAOiB,mBAAmB,EAAE;QAC9BpH,wCAAwCmG,OAAOiB,mBAAmB,CAAC5C,MAAM;IAC3E;IAEA,OAAO;QAACA,QAAQ2B,OAAO3B,MAAM;QAAEkD,kBAAkBvB,OAAOuB,gBAAgB;IAAA;AAC1E;AAEA,SAASH,8BAA8B/C,MAA+B;IACpE,OAAOA,WAAW,WAAW,gBAAgB;AAC/C"}
|
|
1
|
+
{"version":3,"sources":["../../../src/db/workflow-runs/job-executions.ts"],"sourcesContent":["import {readPersistedWorkflowModel} from '@shipfox/api-definitions-dto';\nimport type {SecretsInterModuleClient} from '@shipfox/api-secrets-dto/inter-module';\nimport {canonicalizeLabels} from '@shipfox/runner-labels';\nimport {and, asc, desc, eq, isNull, notInArray, sql} from 'drizzle-orm';\nimport type {JobStatusReason} from '#core/entities/job.js';\nimport type {JobExecution, JobExecutionStatus} from '#core/entities/job-execution.js';\nimport {\n InterpolationUnresolvableError,\n JobNotFoundError,\n JobOutputNotJsonSafeError,\n JobOutputTooLargeError,\n JobOutputTooManyEntriesError,\n} from '#core/errors.js';\nimport {deriveJobExecutionOutputs} from '#core/job-transition/index.js';\nimport {deriveCompletion, isTerminal} from '#core/step-transition/decide-step-transition.js';\nimport type {RuntimeCompletionStatus} from '#core/workflow-scheduling/runtime-dag.js';\nimport {\n recordWorkflowJobExecutionLeaseExpiryResolved,\n recordWorkflowJobExecutionQueued,\n recordWorkflowJobExecutionStarted,\n recordWorkflowJobExecutionStatusChanged,\n recordWorkflowJobExecutionTimedOut,\n} from '#metrics/instance.js';\nimport {db, type Tx} from '../db.js';\nimport {jobExecutions, toJobExecution} from '../schema/job-executions.js';\nimport {jobs, toJob} from '../schema/jobs.js';\nimport {stepAttempts, toStepAttempt} from '../schema/step-attempts.js';\nimport {steps, toStep} from '../schema/steps.js';\nimport {workflowRunAttempts} from '../schema/workflow-run-attempts.js';\nimport {toWorkflowRun, workflowRuns} from '../schema/workflow-runs.js';\nimport {getDirectDependencyJobContexts} from './jobs.js';\nimport {writeJobExecutionQueuedOutbox, writeJobExecutionTerminatedOutbox} from './outbox.js';\nimport {loadReferencedVariables} from './runs.js';\nimport {optimisticLockRetry, TERMINAL_EXECUTION_STATUSES} from './shared.js';\nimport {bulkUpdateStepStatuses, getStepsByJobExecutionIdForUpdate} from './steps.js';\n\nasync function getJobExecutionFallbackName(tx: Tx, jobExecutionId: string): Promise<string> {\n const [row] = await tx\n .select({job: jobs})\n .from(jobExecutions)\n .innerJoin(jobs, eq(jobExecutions.jobId, jobs.id))\n .where(eq(jobExecutions.id, jobExecutionId))\n .limit(1);\n if (!row) throw new JobNotFoundError(jobExecutionId);\n return row.job.name ?? row.job.key;\n}\n\nexport async function getJobExecutionById(id: string, tx?: Tx): Promise<JobExecution | undefined> {\n const rows = await (tx ?? db())\n .select({jobExecution: jobExecutions, job: jobs})\n .from(jobExecutions)\n .innerJoin(jobs, eq(jobExecutions.jobId, jobs.id))\n .where(eq(jobExecutions.id, id))\n .limit(1);\n const row = rows[0];\n return row ? toJobExecution(row.jobExecution, row.job.name ?? row.job.key) : undefined;\n}\n\nexport async function getJobExecutionsByWorkflowRunAttemptId(\n workflowRunAttemptId: string,\n): Promise<JobExecution[]> {\n const rows = await db()\n .select({jobExecution: jobExecutions, job: jobs})\n .from(jobExecutions)\n .innerJoin(jobs, eq(jobExecutions.jobId, jobs.id))\n .where(eq(jobs.workflowRunAttemptId, workflowRunAttemptId))\n .orderBy(asc(jobExecutions.sequence), asc(jobExecutions.id));\n return rows.map((row) => toJobExecution(row.jobExecution, row.job.name ?? row.job.key));\n}\n\nexport async function getJobExecutionsByJobId(jobId: string): Promise<JobExecution[]> {\n const rows = await db()\n .select({jobExecution: jobExecutions, job: jobs})\n .from(jobExecutions)\n .innerJoin(jobs, eq(jobExecutions.jobId, jobs.id))\n .where(eq(jobExecutions.jobId, jobId))\n .orderBy(asc(jobExecutions.sequence), asc(jobExecutions.id));\n return rows.map((row) => toJobExecution(row.jobExecution, row.job.name ?? row.job.key));\n}\n\nexport async function getFirstJobExecutionByJobId(\n jobId: string,\n tx?: Tx,\n): Promise<JobExecution | undefined> {\n const rows = await (tx ?? db())\n .select({jobExecution: jobExecutions, job: jobs})\n .from(jobExecutions)\n .innerJoin(jobs, eq(jobExecutions.jobId, jobs.id))\n .where(eq(jobExecutions.jobId, jobId))\n .orderBy(asc(jobExecutions.sequence), asc(jobExecutions.id))\n .limit(1);\n const row = rows[0];\n return row ? toJobExecution(row.jobExecution, row.job.name ?? row.job.key) : undefined;\n}\n\nexport async function getLatestJobExecutionByJobId(\n jobId: string,\n tx?: Tx,\n): Promise<JobExecution | undefined> {\n const rows = await (tx ?? db())\n .select({jobExecution: jobExecutions, job: jobs})\n .from(jobExecutions)\n .innerJoin(jobs, eq(jobExecutions.jobId, jobs.id))\n .where(eq(jobExecutions.jobId, jobId))\n .orderBy(desc(jobExecutions.sequence), desc(jobExecutions.id))\n .limit(1);\n const row = rows[0];\n return row ? toJobExecution(row.jobExecution, row.job.name ?? row.job.key) : undefined;\n}\n\nexport interface UpdateJobExecutionStatusAtVersionParams {\n jobExecutionId: string;\n status: JobExecutionStatus;\n expectedVersion: number;\n statusReason?: JobStatusReason | null | undefined;\n statusReasonMessage?: string | null | undefined;\n markTimedOut?: boolean;\n secrets?: Pick<SecretsInterModuleClient, 'getVariablesByNamespace'> | undefined;\n}\n\nconst MAX_STATUS_REASON_MESSAGE_LENGTH = 2048;\n\nexport type JobOutputFailure = {\n statusReason: Extract<JobStatusReason, 'output_invalid' | 'output_too_large'>;\n statusReasonMessage: string;\n};\n\nexport function classifyJobOutputFailure(error: unknown): JobOutputFailure | null {\n if (error instanceof JobOutputTooLargeError) {\n return {\n statusReason: 'output_too_large',\n statusReasonMessage: boundedStatusReasonMessage(error.message),\n };\n }\n\n if (\n (error instanceof InterpolationUnresolvableError && error.field === 'job.outputs') ||\n error instanceof JobOutputNotJsonSafeError ||\n error instanceof JobOutputTooManyEntriesError\n ) {\n return {\n statusReason: 'output_invalid',\n statusReasonMessage: boundedStatusReasonMessage(error.message),\n };\n }\n\n return null;\n}\n\nfunction boundedStatusReasonMessage(message: string): string {\n return message.length <= MAX_STATUS_REASON_MESSAGE_LENGTH\n ? message\n : `${message.slice(0, MAX_STATUS_REASON_MESSAGE_LENGTH - 1)}…`;\n}\n\nasync function resolveJobExecutionOutputs(\n tx: Tx,\n params: {\n jobExecutionId: string;\n status: JobExecutionStatus;\n statusReason: JobStatusReason | null;\n secrets?: Pick<SecretsInterModuleClient, 'getVariablesByNamespace'> | undefined;\n },\n): Promise<Record<string, unknown> | null> {\n const [target] = await tx\n .select({execution: jobExecutions, job: jobs, attempt: workflowRunAttempts, run: workflowRuns})\n .from(jobExecutions)\n .innerJoin(jobs, eq(jobExecutions.jobId, jobs.id))\n .innerJoin(workflowRunAttempts, eq(jobs.workflowRunAttemptId, workflowRunAttempts.id))\n .innerJoin(workflowRuns, eq(workflowRunAttempts.workflowRunId, workflowRuns.id))\n .where(eq(jobExecutions.id, params.jobExecutionId))\n .limit(1);\n if (!target) throw new JobNotFoundError(params.jobExecutionId);\n const model =\n target.attempt.model === null ? null : readPersistedWorkflowModel(target.attempt.model);\n if (!model) return null;\n const modelJob = model.jobs.find((job) => job.key === target.job.key);\n if (!modelJob || modelJob.outputs === undefined) return null;\n\n const executionRows = await tx\n .select()\n .from(jobExecutions)\n .where(eq(jobExecutions.jobId, target.job.id))\n .orderBy(asc(jobExecutions.sequence), asc(jobExecutions.id));\n const fallbackName = target.job.name ?? target.job.key;\n const executions = executionRows.map((row) =>\n row.id === target.execution.id\n ? toJobExecution(\n {...row, status: params.status, statusReason: params.statusReason},\n fallbackName,\n )\n : toJobExecution(row, fallbackName),\n );\n const jobExecution = executions.find((execution) => execution.id === target.execution.id);\n if (!jobExecution) throw new JobNotFoundError(params.jobExecutionId);\n\n const stepRows = await tx\n .select()\n .from(steps)\n .where(eq(steps.jobExecutionId, params.jobExecutionId))\n .orderBy(asc(steps.position), asc(steps.id));\n const attemptRows = await tx\n .select()\n .from(stepAttempts)\n .where(eq(stepAttempts.jobExecutionId, params.jobExecutionId))\n .orderBy(asc(stepAttempts.executionOrder), asc(stepAttempts.id));\n const dependencyJobs = await getDirectDependencyJobContexts(target.job.id, tx);\n\n return deriveJobExecutionOutputs({\n run: toWorkflowRun(target.run),\n modelJob,\n job: toJob(target.job),\n jobExecution,\n executions,\n steps: stepRows.map(toStep),\n attempts: attemptRows.map(toStepAttempt),\n jobs: dependencyJobs,\n vars: await loadReferencedVariables({\n model,\n jobs: [modelJob],\n workspaceId: target.run.workspaceId,\n projectId: target.run.projectId,\n definitionId: target.run.definitionId,\n secrets: params.secrets,\n }),\n });\n}\n\nasync function updateJobExecutionStatusAtVersion(\n tx: Tx,\n params: UpdateJobExecutionStatusAtVersionParams,\n): Promise<{execution: JobExecution; changed: boolean} | null> {\n let status = params.status;\n let statusReason = params.statusReason ?? null;\n let statusReasonMessage = params.statusReasonMessage ?? null;\n let outputs: Record<string, unknown> | null | undefined;\n if (TERMINAL_EXECUTION_STATUSES.includes(status)) {\n outputs = null;\n }\n if (status === 'succeeded') {\n try {\n outputs = await resolveJobExecutionOutputs(tx, {\n jobExecutionId: params.jobExecutionId,\n status,\n statusReason,\n secrets: params.secrets,\n });\n } catch (error) {\n const outputFailure = classifyJobOutputFailure(error);\n if (outputFailure === null) throw error;\n status = 'failed';\n statusReason = outputFailure.statusReason;\n statusReasonMessage = outputFailure.statusReasonMessage;\n outputs = null;\n }\n }\n\n const rows = await tx\n .update(jobExecutions)\n .set({\n status,\n statusReason,\n statusReasonMessage,\n ...(outputs === undefined ? {} : {outputs}),\n version: sql`${jobExecutions.version} + 1`,\n updatedAt: new Date(),\n ...(params.markTimedOut ? {timedOutAt: new Date()} : {}),\n ...(TERMINAL_EXECUTION_STATUSES.includes(status) ? {finishedAt: sql`now()`} : {}),\n })\n .where(\n and(\n eq(jobExecutions.id, params.jobExecutionId),\n eq(jobExecutions.version, params.expectedVersion),\n notInArray(jobExecutions.status, TERMINAL_EXECUTION_STATUSES),\n ),\n )\n .returning();\n\n const row = rows[0];\n if (!row) return null;\n if (TERMINAL_EXECUTION_STATUSES.includes(row.status)) {\n await writeJobExecutionTerminatedOutbox(tx, {\n jobId: row.jobId,\n jobExecutionId: row.id,\n status: row.status,\n statusReason: row.statusReason,\n statusReasonMessage: row.statusReasonMessage,\n });\n }\n return {\n execution: toJobExecution(row, await getJobExecutionFallbackName(tx, row.id)),\n changed: true,\n };\n}\n\nexport interface UpdateJobExecutionStatusParams {\n jobExecutionId: string;\n status: JobExecutionStatus;\n expectedVersion: number;\n statusReason?: JobStatusReason | null | undefined;\n statusReasonMessage?: string | null | undefined;\n secrets?: Pick<SecretsInterModuleClient, 'getVariablesByNamespace'> | undefined;\n}\n\nexport async function updateJobExecutionStatus(\n params: UpdateJobExecutionStatusParams,\n): Promise<JobExecution> {\n const statusReason = params.statusReason ?? null;\n const result = await db().transaction(async (tx) => {\n return await optimisticLockRetry({\n updateFn: () =>\n updateJobExecutionStatusAtVersion(tx, {\n jobExecutionId: params.jobExecutionId,\n status: params.status,\n expectedVersion: params.expectedVersion,\n statusReason,\n statusReasonMessage: params.statusReasonMessage,\n secrets: params.secrets,\n }),\n fetchFn: async () => {\n const row = (\n await tx\n .select()\n .from(jobExecutions)\n .where(eq(jobExecutions.id, params.jobExecutionId))\n .limit(1)\n )[0];\n return row ? toJobExecution(row, await getJobExecutionFallbackName(tx, row.id)) : undefined;\n },\n matchFn: (execution) =>\n (execution.status === params.status && execution.statusReason === statusReason) ||\n TERMINAL_EXECUTION_STATUSES.includes(execution.status)\n ? {execution, changed: false}\n : null,\n failureMessage: `Optimistic lock failure: job execution ${params.jobExecutionId} version ${params.expectedVersion}`,\n });\n });\n\n if (result.changed) recordWorkflowJobExecutionStatusChanged(result.execution.status);\n\n return result.execution;\n}\n\nexport async function queueJobExecution(params: {jobExecutionId: string}): Promise<JobExecution> {\n const result = await db().transaction(async (tx) => {\n const [row] = await tx\n .select({jobExecution: jobExecutions, job: jobs})\n .from(jobExecutions)\n .innerJoin(jobs, eq(jobExecutions.jobId, jobs.id))\n .where(eq(jobExecutions.id, params.jobExecutionId))\n .limit(1)\n .for('update');\n if (!row) throw new JobNotFoundError(params.jobExecutionId);\n\n const existing = toJobExecution(row.jobExecution, row.job.name ?? row.job.key);\n if (existing.queuedAt !== null || TERMINAL_EXECUTION_STATUSES.includes(existing.status)) {\n return {execution: existing, changed: false};\n }\n\n const requiredLabels = [...canonicalizeLabels(existing.runner ?? row.job.runner ?? [])];\n if (requiredLabels.length === 0) {\n throw new Error(`Job execution ${params.jobExecutionId} has no required runner labels`);\n }\n\n const [queued] = await tx\n .update(jobExecutions)\n .set({queuedAt: sql`now()`})\n .where(eq(jobExecutions.id, params.jobExecutionId))\n .returning();\n if (!queued?.queuedAt) throw new Error(`Cannot queue job execution ${params.jobExecutionId}`);\n\n await writeJobExecutionQueuedOutbox(tx, {\n jobId: queued.jobId,\n jobExecutionId: queued.id,\n requiredLabels,\n queuedAt: queued.queuedAt,\n });\n\n return {\n execution: toJobExecution(queued, row.job.name ?? row.job.key),\n changed: true,\n };\n });\n\n if (result.changed) recordWorkflowJobExecutionQueued();\n return result.execution;\n}\n\nexport async function recordJobExecutionStartedAt(params: {\n jobExecutionId: string;\n startedAt: Date;\n}): Promise<void> {\n const updated = await db()\n .update(jobExecutions)\n .set({startedAt: params.startedAt})\n .where(and(eq(jobExecutions.id, params.jobExecutionId), isNull(jobExecutions.startedAt)))\n .returning({id: jobExecutions.id});\n\n if (updated.length > 0) recordWorkflowJobExecutionStarted();\n}\n\nexport async function failJobExecutionAsTimedOut(params: {\n jobExecutionId: string;\n workflowRunAttemptId: string;\n expectedVersion: number;\n secrets?: Pick<SecretsInterModuleClient, 'getVariablesByNamespace'> | undefined;\n}): Promise<JobExecution> {\n const result = await db().transaction(async (tx) => {\n const updated = await optimisticLockRetry({\n updateFn: () =>\n updateJobExecutionStatusAtVersion(tx, {\n jobExecutionId: params.jobExecutionId,\n status: 'failed',\n expectedVersion: params.expectedVersion,\n statusReason: 'timed_out',\n markTimedOut: true,\n secrets: params.secrets,\n }),\n fetchFn: async () => {\n const row = (\n await tx\n .select()\n .from(jobExecutions)\n .where(eq(jobExecutions.id, params.jobExecutionId))\n .limit(1)\n )[0];\n return row ? toJobExecution(row, await getJobExecutionFallbackName(tx, row.id)) : undefined;\n },\n matchFn: (execution) => (execution.timedOutAt !== null ? {execution, changed: false} : null),\n failureMessage: `Optimistic lock failure: job execution ${params.jobExecutionId} version ${params.expectedVersion}`,\n });\n\n return updated;\n });\n\n if (result.changed) {\n recordWorkflowJobExecutionStatusChanged(result.execution.status);\n recordWorkflowJobExecutionTimedOut();\n }\n\n return result.execution;\n}\n\nexport async function resolveJobExecutionAfterLeaseExpiry(params: {\n jobExecutionId: string;\n expectedVersion: number;\n secrets?: Pick<SecretsInterModuleClient, 'getVariablesByNamespace'> | undefined;\n}): Promise<{status: RuntimeCompletionStatus; executionVersion: number}> {\n const result = await db().transaction(async (tx) => {\n const jobExecutionSteps = await getStepsByJobExecutionIdForUpdate(params.jobExecutionId, tx);\n let changedJobExecution: JobExecution | null = null;\n\n if (jobExecutionSteps.length === 0) {\n throw new JobNotFoundError(params.jobExecutionId);\n }\n\n if (jobExecutionSteps.every((step) => isTerminal(step.status))) {\n const status = deriveCompletion(jobExecutionSteps);\n const updated = await updateJobExecutionStatusAtVersion(tx, {\n jobExecutionId: params.jobExecutionId,\n status,\n expectedVersion: params.expectedVersion,\n statusReason: statusReasonForStepCompletion(status),\n secrets: params.secrets,\n });\n changedJobExecution = updated?.changed ? updated.execution : null;\n } else {\n const updated = await updateJobExecutionStatusAtVersion(tx, {\n jobExecutionId: params.jobExecutionId,\n status: 'failed',\n expectedVersion: params.expectedVersion,\n statusReason: 'runner_lost',\n secrets: params.secrets,\n });\n if (updated?.changed) {\n changedJobExecution = updated.execution;\n await bulkUpdateStepStatuses(\n {jobExecutionId: params.jobExecutionId, status: 'cancelled'},\n tx,\n );\n }\n }\n\n const jobExecutionRow = (\n await tx\n .select()\n .from(jobExecutions)\n .where(eq(jobExecutions.id, params.jobExecutionId))\n .limit(1)\n )[0];\n if (!jobExecutionRow) {\n throw new Error(`Job execution not found resolving lease expiry: ${params.jobExecutionId}`);\n }\n const status: RuntimeCompletionStatus =\n jobExecutionRow.status === 'succeeded' ? 'succeeded' : 'failed';\n return {status, executionVersion: jobExecutionRow.version, changedJobExecution};\n });\n\n recordWorkflowJobExecutionLeaseExpiryResolved(result.status);\n if (result.changedJobExecution) {\n recordWorkflowJobExecutionStatusChanged(result.changedJobExecution.status);\n }\n\n return {status: result.status, executionVersion: result.executionVersion};\n}\n\nfunction statusReasonForStepCompletion(status: RuntimeCompletionStatus): JobStatusReason | null {\n return status === 'failed' ? 'step_failed' : null;\n}\n"],"names":["readPersistedWorkflowModel","canonicalizeLabels","and","asc","desc","eq","isNull","notInArray","sql","InterpolationUnresolvableError","JobNotFoundError","JobOutputNotJsonSafeError","JobOutputTooLargeError","JobOutputTooManyEntriesError","deriveJobExecutionOutputs","deriveCompletion","isTerminal","recordWorkflowJobExecutionLeaseExpiryResolved","recordWorkflowJobExecutionQueued","recordWorkflowJobExecutionStarted","recordWorkflowJobExecutionStatusChanged","recordWorkflowJobExecutionTimedOut","db","jobExecutions","toJobExecution","jobs","toJob","stepAttempts","toStepAttempt","steps","toStep","workflowRunAttempts","toWorkflowRun","workflowRuns","getDirectDependencyJobContexts","writeJobExecutionQueuedOutbox","writeJobExecutionTerminatedOutbox","loadReferencedVariables","optimisticLockRetry","TERMINAL_EXECUTION_STATUSES","bulkUpdateStepStatuses","getStepsByJobExecutionIdForUpdate","getJobExecutionFallbackName","tx","jobExecutionId","row","select","job","from","innerJoin","jobId","id","where","limit","name","key","getJobExecutionById","rows","jobExecution","undefined","getJobExecutionsByWorkflowRunAttemptId","workflowRunAttemptId","orderBy","sequence","map","getJobExecutionsByJobId","getFirstJobExecutionByJobId","getLatestJobExecutionByJobId","MAX_STATUS_REASON_MESSAGE_LENGTH","classifyJobOutputFailure","error","statusReason","statusReasonMessage","boundedStatusReasonMessage","message","field","length","slice","resolveJobExecutionOutputs","params","target","execution","attempt","run","workflowRunId","model","modelJob","find","outputs","executionRows","fallbackName","executions","status","stepRows","position","attemptRows","executionOrder","dependencyJobs","attempts","vars","workspaceId","projectId","definitionId","secrets","updateJobExecutionStatusAtVersion","includes","outputFailure","update","set","version","updatedAt","Date","markTimedOut","timedOutAt","finishedAt","expectedVersion","returning","changed","updateJobExecutionStatus","result","transaction","updateFn","fetchFn","matchFn","failureMessage","queueJobExecution","for","existing","queuedAt","requiredLabels","runner","Error","queued","recordJobExecutionStartedAt","updated","startedAt","failJobExecutionAsTimedOut","resolveJobExecutionAfterLeaseExpiry","jobExecutionSteps","changedJobExecution","every","step","statusReasonForStepCompletion","jobExecutionRow","executionVersion"],"mappings":"AAAA,SAAQA,0BAA0B,QAAO,+BAA+B;AAExE,SAAQC,kBAAkB,QAAO,yBAAyB;AAC1D,SAAQC,GAAG,EAAEC,GAAG,EAAEC,IAAI,EAAEC,EAAE,EAAEC,MAAM,EAAEC,UAAU,EAAE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MAAM,GACNE,IAAI,CAACzB,eACL6B,KAAK,CAAC/C,GAAGkB,cAAc4B,EAAE,EAAE4B,OAAOnC,cAAc,GAChDS,KAAK,CAAC,EAAC,CACX,CAAC,EAAE;QACJ,IAAI,CAAC0F,iBAAiB;YACpB,MAAM,IAAIZ,MAAM,CAAC,gDAAgD,EAAEpD,OAAOnC,cAAc,EAAE;QAC5F;QACA,MAAMgD,SACJmD,gBAAgBnD,MAAM,KAAK,cAAc,cAAc;QACzD,OAAO;YAACA;YAAQoD,kBAAkBD,gBAAgBlC,OAAO;YAAE8B;QAAmB;IAChF;IAEA1H,8CAA8CsG,OAAO3B,MAAM;IAC3D,IAAI2B,OAAOoB,mBAAmB,EAAE;QAC9BvH,wCAAwCmG,OAAOoB,mBAAmB,CAAC/C,MAAM;IAC3E;IAEA,OAAO;QAACA,QAAQ2B,OAAO3B,MAAM;QAAEoD,kBAAkBzB,OAAOyB,gBAAgB;IAAA;AAC1E;AAEA,SAASF,8BAA8BlD,MAA+B;IACpE,OAAOA,WAAW,WAAW,gBAAgB;AAC/C"}
|
|
@@ -1,5 +1,20 @@
|
|
|
1
1
|
import { type LogOutcomeDto } from '@shipfox/api-workflows-dto';
|
|
2
|
+
import type { JobStatusReason } from '#core/entities/job.js';
|
|
3
|
+
import type { JobExecutionStatus } from '#core/entities/job-execution.js';
|
|
2
4
|
import type { Tx } from '../db.js';
|
|
5
|
+
export declare function writeJobExecutionQueuedOutbox(tx: Tx, params: {
|
|
6
|
+
jobId: string;
|
|
7
|
+
jobExecutionId: string;
|
|
8
|
+
requiredLabels: string[];
|
|
9
|
+
queuedAt: Date;
|
|
10
|
+
}): Promise<void>;
|
|
11
|
+
export declare function writeJobExecutionTerminatedOutbox(tx: Tx, params: {
|
|
12
|
+
jobId: string;
|
|
13
|
+
jobExecutionId: string;
|
|
14
|
+
status: JobExecutionStatus;
|
|
15
|
+
statusReason: JobStatusReason | null;
|
|
16
|
+
statusReasonMessage?: string | null | undefined;
|
|
17
|
+
}): Promise<void>;
|
|
3
18
|
export declare function writeJobStepsSettledOutbox(tx: Tx, params: {
|
|
4
19
|
jobId: string;
|
|
5
20
|
jobExecutionId: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"outbox.d.ts","sourceRoot":"","sources":["../../../src/db/workflow-runs/outbox.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,aAAa,
|
|
1
|
+
{"version":3,"file":"outbox.d.ts","sourceRoot":"","sources":["../../../src/db/workflow-runs/outbox.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,aAAa,EAMnB,MAAM,4BAA4B,CAAC;AAEpC,OAAO,KAAK,EAAC,eAAe,EAAC,MAAM,uBAAuB,CAAC;AAC3D,OAAO,KAAK,EAAC,kBAAkB,EAAC,MAAM,iCAAiC,CAAC;AACxE,OAAO,KAAK,EAAC,EAAE,EAAC,MAAM,UAAU,CAAC;AAMjC,wBAAsB,6BAA6B,CACjD,EAAE,EAAE,EAAE,EACN,MAAM,EAAE;IACN,KAAK,EAAE,MAAM,CAAC;IACd,cAAc,EAAE,MAAM,CAAC;IACvB,cAAc,EAAE,MAAM,EAAE,CAAC;IACzB,QAAQ,EAAE,IAAI,CAAC;CAChB,GACA,OAAO,CAAC,IAAI,CAAC,CAgBf;AAED,wBAAsB,iCAAiC,CACrD,EAAE,EAAE,EAAE,EACN,MAAM,EAAE;IACN,KAAK,EAAE,MAAM,CAAC;IACd,cAAc,EAAE,MAAM,CAAC;IACvB,MAAM,EAAE,kBAAkB,CAAC;IAC3B,YAAY,EAAE,eAAe,GAAG,IAAI,CAAC;IACrC,mBAAmB,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;CACjD,GACA,OAAO,CAAC,IAAI,CAAC,CAsBf;AAMD,wBAAsB,0BAA0B,CAC9C,EAAE,EAAE,EAAE,EACN,MAAM,EAAE;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,cAAc,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,WAAW,GAAG,QAAQ,CAAA;CAAC,GAC9E,OAAO,CAAC,IAAI,CAAC,CAaf;AAED,wBAAsB,gCAAgC,CACpD,EAAE,EAAE,EAAE,EACN,MAAM,EAAE;IACN,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,WAAW,GAAG,QAAQ,GAAG,WAAW,CAAC;IAC7C,UAAU,EAAE,aAAa,CAAC;CAC3B,GACA,OAAO,CAAC,IAAI,CAAC,CAiBf;AA8BD,wBAAsB,8BAA8B,CAClD,EAAE,EAAE,EAAE,EACN,MAAM,EAAE;IACN,KAAK,EAAE,MAAM,CAAC;IACd,YAAY,EAAE,MAAM,CAAC;IACrB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,iBAAiB,EAAE,MAAM,CAAC;IAC1B,QAAQ,EAAE,MAAM,CAAC;CAClB,GACA,OAAO,CAAC,IAAI,CAAC,CAef"}
|
|
@@ -1,9 +1,43 @@
|
|
|
1
|
-
import { WORKFLOWS_JOB_STEPS_SETTLED, WORKFLOWS_STEP_ATTEMPT_TERMINATED, WORKFLOWS_STEP_RESTART_ENQUEUED } from '@shipfox/api-workflows-dto';
|
|
1
|
+
import { WORKFLOWS_JOB_EXECUTION_QUEUED, WORKFLOWS_JOB_EXECUTION_TERMINATED, WORKFLOWS_JOB_STEPS_SETTLED, WORKFLOWS_STEP_ATTEMPT_TERMINATED, WORKFLOWS_STEP_RESTART_ENQUEUED } from '@shipfox/api-workflows-dto';
|
|
2
2
|
import { eq } from 'drizzle-orm';
|
|
3
3
|
import { writeWorkflowsOutboxEvent } from '../outbox-writes.js';
|
|
4
4
|
import { jobExecutions } from '../schema/job-executions.js';
|
|
5
5
|
import { steps } from '../schema/steps.js';
|
|
6
6
|
import { getWorkflowContextForJob } from './shared.js';
|
|
7
|
+
export async function writeJobExecutionQueuedOutbox(tx, params) {
|
|
8
|
+
const identity = await getWorkflowContextForJob(params.jobId, tx);
|
|
9
|
+
await writeWorkflowsOutboxEvent(tx, {
|
|
10
|
+
type: WORKFLOWS_JOB_EXECUTION_QUEUED,
|
|
11
|
+
payload: {
|
|
12
|
+
jobId: params.jobId,
|
|
13
|
+
jobExecutionId: params.jobExecutionId,
|
|
14
|
+
workflowRunId: identity.workflowRunId,
|
|
15
|
+
workflowRunAttemptId: identity.workflowRunAttemptId,
|
|
16
|
+
workspaceId: identity.workspaceId,
|
|
17
|
+
projectId: identity.projectId,
|
|
18
|
+
requiredLabels: params.requiredLabels,
|
|
19
|
+
queuedAt: params.queuedAt.toISOString()
|
|
20
|
+
}
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
export async function writeJobExecutionTerminatedOutbox(tx, params) {
|
|
24
|
+
if (params.status !== 'succeeded' && params.status !== 'failed' && params.status !== 'cancelled') {
|
|
25
|
+
throw new Error(`Cannot enqueue terminal job execution event for status ${params.status}`);
|
|
26
|
+
}
|
|
27
|
+
const identity = await getWorkflowContextForJob(params.jobId, tx);
|
|
28
|
+
await writeWorkflowsOutboxEvent(tx, {
|
|
29
|
+
type: WORKFLOWS_JOB_EXECUTION_TERMINATED,
|
|
30
|
+
payload: {
|
|
31
|
+
jobId: params.jobId,
|
|
32
|
+
jobExecutionId: params.jobExecutionId,
|
|
33
|
+
workflowRunId: identity.workflowRunId,
|
|
34
|
+
workflowRunAttemptId: identity.workflowRunAttemptId,
|
|
35
|
+
status: params.status,
|
|
36
|
+
statusReason: params.statusReason,
|
|
37
|
+
statusReasonMessage: params.statusReasonMessage ?? null
|
|
38
|
+
}
|
|
39
|
+
});
|
|
40
|
+
}
|
|
7
41
|
// Enqueue the steps-settled signal in the same transaction as the final per-step
|
|
8
42
|
// result, so per-step execution observes it exactly once (the outbox is at-least-once;
|
|
9
43
|
// the job workflow dedupes the signal). Drives the Temporal JOB_FINISHED_SIGNAL; the
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/db/workflow-runs/outbox.ts"],"sourcesContent":["import {\n type LogOutcomeDto,\n WORKFLOWS_JOB_STEPS_SETTLED,\n WORKFLOWS_STEP_ATTEMPT_TERMINATED,\n WORKFLOWS_STEP_RESTART_ENQUEUED,\n} from '@shipfox/api-workflows-dto';\nimport {eq} from 'drizzle-orm';\nimport type {Tx} from '../db.js';\nimport {writeWorkflowsOutboxEvent} from '../outbox-writes.js';\nimport {jobExecutions} from '../schema/job-executions.js';\nimport {steps} from '../schema/steps.js';\nimport {getWorkflowContextForJob} from './shared.js';\n\n// Enqueue the steps-settled signal in the same transaction as the final per-step\n// result, so per-step execution observes it exactly once (the outbox is at-least-once;\n// the job workflow dedupes the signal). Drives the Temporal JOB_FINISHED_SIGNAL; the\n// job's terminal fact is emitted separately by updateJobStatusAtVersion.\nexport async function writeJobStepsSettledOutbox(\n tx: Tx,\n params: {jobId: string; jobExecutionId: string; status: 'succeeded' | 'failed'},\n): Promise<void> {\n const identity = await getWorkflowContextForJob(params.jobId, tx);\n\n await writeWorkflowsOutboxEvent(tx, {\n type: WORKFLOWS_JOB_STEPS_SETTLED,\n payload: {\n jobId: params.jobId,\n jobExecutionId: params.jobExecutionId,\n workflowRunId: identity.workflowRunId,\n workflowRunAttemptId: identity.workflowRunAttemptId,\n status: params.status,\n },\n });\n}\n\nexport async function writeStepAttemptTerminatedOutbox(\n tx: Tx,\n params: {\n stepId: string;\n attempt: number;\n status: 'succeeded' | 'failed' | 'cancelled';\n logOutcome: LogOutcomeDto;\n },\n): Promise<void> {\n const identity = await getStepAttemptTerminatedOutboxIdentity(tx, params.stepId);\n\n await writeWorkflowsOutboxEvent(tx, {\n type: WORKFLOWS_STEP_ATTEMPT_TERMINATED,\n payload: {\n jobId: identity.jobId,\n workflowRunId: identity.workflowRunId,\n workflowRunAttemptId: identity.workflowRunAttemptId,\n workspaceId: identity.workspaceId,\n projectId: identity.projectId,\n stepId: params.stepId,\n attempt: params.attempt,\n status: params.status,\n logOutcome: params.logOutcome,\n },\n });\n}\n\nasync function getStepAttemptTerminatedOutboxIdentity(\n tx: Tx,\n stepId: string,\n): Promise<{\n jobId: string;\n workflowRunId: string;\n workflowRunAttemptId: string;\n workspaceId: string;\n projectId: string;\n}> {\n const rows = await tx\n .select({\n jobId: jobExecutions.jobId,\n })\n .from(steps)\n .innerJoin(jobExecutions, eq(steps.jobExecutionId, jobExecutions.id))\n .where(eq(steps.id, stepId))\n .limit(1);\n const step = rows[0];\n if (!step) {\n throw new Error(`Cannot enqueue step-attempt-terminated event: step ${stepId} not found`);\n }\n\n return getWorkflowContextForJob(step.jobId, tx);\n}\n\n// Enqueue the durable audit record of a restart, in the same transaction as the\n// rewind. Looks up the workflow run id like writeJobStepsSettledOutbox.\nexport async function writeStepRestartEnqueuedOutbox(\n tx: Tx,\n params: {\n jobId: string;\n failedStepId: string;\n failedStepAttempt: number;\n restartFromStepId: string;\n feedback: string;\n },\n): Promise<void> {\n const identity = await getWorkflowContextForJob(params.jobId, tx);\n\n await writeWorkflowsOutboxEvent(tx, {\n type: WORKFLOWS_STEP_RESTART_ENQUEUED,\n payload: {\n jobId: params.jobId,\n workflowRunId: identity.workflowRunId,\n workflowRunAttemptId: identity.workflowRunAttemptId,\n failedStepId: params.failedStepId,\n failedStepAttempt: params.failedStepAttempt,\n restartFromStepId: params.restartFromStepId,\n feedback: params.feedback,\n },\n });\n}\n"],"names":["WORKFLOWS_JOB_STEPS_SETTLED","WORKFLOWS_STEP_ATTEMPT_TERMINATED","WORKFLOWS_STEP_RESTART_ENQUEUED","eq","writeWorkflowsOutboxEvent","jobExecutions","steps","getWorkflowContextForJob","
|
|
1
|
+
{"version":3,"sources":["../../../src/db/workflow-runs/outbox.ts"],"sourcesContent":["import {\n type LogOutcomeDto,\n WORKFLOWS_JOB_EXECUTION_QUEUED,\n WORKFLOWS_JOB_EXECUTION_TERMINATED,\n WORKFLOWS_JOB_STEPS_SETTLED,\n WORKFLOWS_STEP_ATTEMPT_TERMINATED,\n WORKFLOWS_STEP_RESTART_ENQUEUED,\n} from '@shipfox/api-workflows-dto';\nimport {eq} from 'drizzle-orm';\nimport type {JobStatusReason} from '#core/entities/job.js';\nimport type {JobExecutionStatus} from '#core/entities/job-execution.js';\nimport type {Tx} from '../db.js';\nimport {writeWorkflowsOutboxEvent} from '../outbox-writes.js';\nimport {jobExecutions} from '../schema/job-executions.js';\nimport {steps} from '../schema/steps.js';\nimport {getWorkflowContextForJob} from './shared.js';\n\nexport async function writeJobExecutionQueuedOutbox(\n tx: Tx,\n params: {\n jobId: string;\n jobExecutionId: string;\n requiredLabels: string[];\n queuedAt: Date;\n },\n): Promise<void> {\n const identity = await getWorkflowContextForJob(params.jobId, tx);\n\n await writeWorkflowsOutboxEvent(tx, {\n type: WORKFLOWS_JOB_EXECUTION_QUEUED,\n payload: {\n jobId: params.jobId,\n jobExecutionId: params.jobExecutionId,\n workflowRunId: identity.workflowRunId,\n workflowRunAttemptId: identity.workflowRunAttemptId,\n workspaceId: identity.workspaceId,\n projectId: identity.projectId,\n requiredLabels: params.requiredLabels,\n queuedAt: params.queuedAt.toISOString(),\n },\n });\n}\n\nexport async function writeJobExecutionTerminatedOutbox(\n tx: Tx,\n params: {\n jobId: string;\n jobExecutionId: string;\n status: JobExecutionStatus;\n statusReason: JobStatusReason | null;\n statusReasonMessage?: string | null | undefined;\n },\n): Promise<void> {\n if (\n params.status !== 'succeeded' &&\n params.status !== 'failed' &&\n params.status !== 'cancelled'\n ) {\n throw new Error(`Cannot enqueue terminal job execution event for status ${params.status}`);\n }\n const identity = await getWorkflowContextForJob(params.jobId, tx);\n\n await writeWorkflowsOutboxEvent(tx, {\n type: WORKFLOWS_JOB_EXECUTION_TERMINATED,\n payload: {\n jobId: params.jobId,\n jobExecutionId: params.jobExecutionId,\n workflowRunId: identity.workflowRunId,\n workflowRunAttemptId: identity.workflowRunAttemptId,\n status: params.status,\n statusReason: params.statusReason,\n statusReasonMessage: params.statusReasonMessage ?? null,\n },\n });\n}\n\n// Enqueue the steps-settled signal in the same transaction as the final per-step\n// result, so per-step execution observes it exactly once (the outbox is at-least-once;\n// the job workflow dedupes the signal). Drives the Temporal JOB_FINISHED_SIGNAL; the\n// job's terminal fact is emitted separately by updateJobStatusAtVersion.\nexport async function writeJobStepsSettledOutbox(\n tx: Tx,\n params: {jobId: string; jobExecutionId: string; status: 'succeeded' | 'failed'},\n): Promise<void> {\n const identity = await getWorkflowContextForJob(params.jobId, tx);\n\n await writeWorkflowsOutboxEvent(tx, {\n type: WORKFLOWS_JOB_STEPS_SETTLED,\n payload: {\n jobId: params.jobId,\n jobExecutionId: params.jobExecutionId,\n workflowRunId: identity.workflowRunId,\n workflowRunAttemptId: identity.workflowRunAttemptId,\n status: params.status,\n },\n });\n}\n\nexport async function writeStepAttemptTerminatedOutbox(\n tx: Tx,\n params: {\n stepId: string;\n attempt: number;\n status: 'succeeded' | 'failed' | 'cancelled';\n logOutcome: LogOutcomeDto;\n },\n): Promise<void> {\n const identity = await getStepAttemptTerminatedOutboxIdentity(tx, params.stepId);\n\n await writeWorkflowsOutboxEvent(tx, {\n type: WORKFLOWS_STEP_ATTEMPT_TERMINATED,\n payload: {\n jobId: identity.jobId,\n workflowRunId: identity.workflowRunId,\n workflowRunAttemptId: identity.workflowRunAttemptId,\n workspaceId: identity.workspaceId,\n projectId: identity.projectId,\n stepId: params.stepId,\n attempt: params.attempt,\n status: params.status,\n logOutcome: params.logOutcome,\n },\n });\n}\n\nasync function getStepAttemptTerminatedOutboxIdentity(\n tx: Tx,\n stepId: string,\n): Promise<{\n jobId: string;\n workflowRunId: string;\n workflowRunAttemptId: string;\n workspaceId: string;\n projectId: string;\n}> {\n const rows = await tx\n .select({\n jobId: jobExecutions.jobId,\n })\n .from(steps)\n .innerJoin(jobExecutions, eq(steps.jobExecutionId, jobExecutions.id))\n .where(eq(steps.id, stepId))\n .limit(1);\n const step = rows[0];\n if (!step) {\n throw new Error(`Cannot enqueue step-attempt-terminated event: step ${stepId} not found`);\n }\n\n return getWorkflowContextForJob(step.jobId, tx);\n}\n\n// Enqueue the durable audit record of a restart, in the same transaction as the\n// rewind. Looks up the workflow run id like writeJobStepsSettledOutbox.\nexport async function writeStepRestartEnqueuedOutbox(\n tx: Tx,\n params: {\n jobId: string;\n failedStepId: string;\n failedStepAttempt: number;\n restartFromStepId: string;\n feedback: string;\n },\n): Promise<void> {\n const identity = await getWorkflowContextForJob(params.jobId, tx);\n\n await writeWorkflowsOutboxEvent(tx, {\n type: WORKFLOWS_STEP_RESTART_ENQUEUED,\n payload: {\n jobId: params.jobId,\n workflowRunId: identity.workflowRunId,\n workflowRunAttemptId: identity.workflowRunAttemptId,\n failedStepId: params.failedStepId,\n failedStepAttempt: params.failedStepAttempt,\n restartFromStepId: params.restartFromStepId,\n feedback: params.feedback,\n },\n });\n}\n"],"names":["WORKFLOWS_JOB_EXECUTION_QUEUED","WORKFLOWS_JOB_EXECUTION_TERMINATED","WORKFLOWS_JOB_STEPS_SETTLED","WORKFLOWS_STEP_ATTEMPT_TERMINATED","WORKFLOWS_STEP_RESTART_ENQUEUED","eq","writeWorkflowsOutboxEvent","jobExecutions","steps","getWorkflowContextForJob","writeJobExecutionQueuedOutbox","tx","params","identity","jobId","type","payload","jobExecutionId","workflowRunId","workflowRunAttemptId","workspaceId","projectId","requiredLabels","queuedAt","toISOString","writeJobExecutionTerminatedOutbox","status","Error","statusReason","statusReasonMessage","writeJobStepsSettledOutbox","writeStepAttemptTerminatedOutbox","getStepAttemptTerminatedOutboxIdentity","stepId","attempt","logOutcome","rows","select","from","innerJoin","id","where","limit","step","writeStepRestartEnqueuedOutbox","failedStepId","failedStepAttempt","restartFromStepId","feedback"],"mappings":"AAAA,SAEEA,8BAA8B,EAC9BC,kCAAkC,EAClCC,2BAA2B,EAC3BC,iCAAiC,EACjCC,+BAA+B,QAC1B,6BAA6B;AACpC,SAAQC,EAAE,QAAO,cAAc;AAI/B,SAAQC,yBAAyB,QAAO,sBAAsB;AAC9D,SAAQC,aAAa,QAAO,8BAA8B;AAC1D,SAAQC,KAAK,QAAO,qBAAqB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SAAS;YACPF,OAAOF,OAAOE,KAAK;YACnBI,eAAeL,SAASK,aAAa;YACrCC,sBAAsBN,SAASM,oBAAoB;YACnD0B,cAAcjC,OAAOiC,YAAY;YACjCC,mBAAmBlC,OAAOkC,iBAAiB;YAC3CC,mBAAmBnC,OAAOmC,iBAAiB;YAC3CC,UAAUpC,OAAOoC,QAAQ;QAC3B;IACF;AACF"}
|
|
@@ -79,7 +79,8 @@ export interface WorkflowRunJobSummaryTarget {
|
|
|
79
79
|
currentAttempt: number;
|
|
80
80
|
}
|
|
81
81
|
/**
|
|
82
|
-
* A page row's jobs: a bounded slice to draw,
|
|
82
|
+
* A page row's jobs: a bounded slice to draw, totals describing all of them, and whether any
|
|
83
|
+
* execution has reached a runner.
|
|
83
84
|
*
|
|
84
85
|
* The preview is what a row can show; `statusCounts` is what it can say. Keeping the counts
|
|
85
86
|
* server-side is what lets a row report a failure that sits past the preview. Counts use the
|
|
@@ -91,6 +92,7 @@ export interface WorkflowRunJobsSummary {
|
|
|
91
92
|
preview: WorkflowRunJobSummary[];
|
|
92
93
|
statusCounts: WorkflowRunJobStatusCount[];
|
|
93
94
|
rawStatusCounts: WorkflowRunJobRawStatusCount[];
|
|
95
|
+
hasStartedJobExecution: boolean;
|
|
94
96
|
}
|
|
95
97
|
export interface WorkflowRunJobStatusCount {
|
|
96
98
|
status: JobStatus | 'listening';
|
|
@@ -116,8 +118,8 @@ export interface WorkflowRunJobRawStatusCount {
|
|
|
116
118
|
* attempt 1's run metadata with attempt 2's jobs, and the row would report a status its strip
|
|
117
119
|
* contradicts.
|
|
118
120
|
*
|
|
119
|
-
* The
|
|
120
|
-
* instant, and the strip combines them into a single glyph row, so under the default
|
|
121
|
+
* The reads share one repeatable-read snapshot. They describe the same jobs and executions at
|
|
122
|
+
* the same instant, and the strip combines them into a single glyph row, so under the default
|
|
121
123
|
* read-committed isolation a job settling between the statements would draw a pending glyph
|
|
122
124
|
* beside a summary counting it as failed. Sequential inside one transaction is the cost of
|
|
123
125
|
* that; at a four-second poll the extra round trip does not register.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"queries.d.ts","sourceRoot":"","sources":["../../../src/db/workflow-runs/queries.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,KAAK,iBAAiB,EAEvB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAsC,KAAK,GAAG,EAAM,MAAM,aAAa,CAAC;AAC/E,OAAO,KAAK,EAAC,OAAO,EAAE,SAAS,EAAE,cAAc,EAAC,MAAM,uBAAuB,CAAC;AAC9E,OAAO,KAAK,EAAC,kBAAkB,EAAC,MAAM,iCAAiC,CAAC;AACxE,OAAO,KAAK,EACV,kBAAkB,EAGlB,WAAW,EACX,iBAAiB,EACjB,iBAAiB,EAClB,MAAM,gCAAgC,CAAC;AASxC,MAAM,MAAM,iBAAiB,GAAG,iBAAiB,CAAC;AAElD,MAAM,WAAW,kBAAkB;IACjC,MAAM,CAAC,EAAE,iBAAiB,GAAG,SAAS,CAAC;IACvC,YAAY,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAClC,aAAa,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IACnC,WAAW,CAAC,EAAE,IAAI,GAAG,SAAS,CAAC;IAC/B,SAAS,CAAC,EAAE,IAAI,GAAG,SAAS,CAAC;CAC9B;AAED,MAAM,WAAW,sBAAsB;IACrC,SAAS,EAAE,MAAM,CAAC;IAClB,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,CAAC,EAAE,iBAAiB,GAAG,SAAS,CAAC;IACvC,OAAO,CAAC,EAAE,kBAAkB,GAAG,SAAS,CAAC;IACzC,YAAY,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;CACpC;AAED,MAAM,WAAW,sBAAsB;IACrC,IAAI,EAAE,WAAW,EAAE,CAAC;IACpB,UAAU,EAAE,iBAAiB,GAAG,IAAI,CAAC;IACrC,kBAAkB,EAAE,MAAM,GAAG,IAAI,CAAC;CACnC;AAED,4EAA4E;A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AE,4BAA4B,EAAE,CAAC;IAChD,sBAAsB,EAAE,OAAO,CAAC;CACjC;AAED,MAAM,WAAW,yBAAyB;IACxC,MAAM,EAAE,SAAS,GAAG,WAAW,CAAC;IAChC,KAAK,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,4BAA4B;IAC3C,MAAM,EAAE,SAAS,CAAC;IAClB,KAAK,EAAE,MAAM,CAAC;CACf;AAED;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAsB,2BAA2B,CAC/C,IAAI,EAAE,SAAS,2BAA2B,EAAE,GAC3C,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,sBAAsB,CAAC,CAAC,CAqI9C;AA+BD,wBAAsB,yBAAyB,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,EAAE,CAAC,CAGzF;AAED,wBAAsB,wBAAwB,CAAC,MAAM,EAAE;IACrD,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,EAAE,kBAAkB,GAAG,SAAS,CAAC;CAC1C,GAAG,OAAO,CAAC,qBAAqB,CAAC,CAgDjC;AAED,wBAAsB,4BAA4B,CAChD,MAAM,GAAE,+BAAoC,GAC3C,OAAO,CAAC,yBAAyB,CAAC,CA0BpC;AAED,wBAAsB,oBAAoB,CACxC,aAAa,EAAE,MAAM,EACrB,OAAO,CAAC,EAAE,MAAM,GAAG,SAAS,GAC3B,OAAO,CAAC,iBAAiB,GAAG,SAAS,CAAC,CA+CxC;AAED,wBAAsB,qBAAqB,CACzC,cAAc,EAAE,MAAM,GACrB,OAAO,CAAC,kBAAkB,GAAG,SAAS,CAAC,CAwCzC"}
|
|
@@ -107,8 +107,8 @@ export async function listWorkflowRuns(params) {
|
|
|
107
107
|
* attempt 1's run metadata with attempt 2's jobs, and the row would report a status its strip
|
|
108
108
|
* contradicts.
|
|
109
109
|
*
|
|
110
|
-
* The
|
|
111
|
-
* instant, and the strip combines them into a single glyph row, so under the default
|
|
110
|
+
* The reads share one repeatable-read snapshot. They describe the same jobs and executions at
|
|
111
|
+
* the same instant, and the strip combines them into a single glyph row, so under the default
|
|
112
112
|
* read-committed isolation a job settling between the statements would draw a pending glyph
|
|
113
113
|
* beside a summary counting it as failed. Sequential inside one transaction is the cost of
|
|
114
114
|
* that; at a four-second poll the extra round trip does not register.
|
|
@@ -142,6 +142,14 @@ export async function listWorkflowRuns(params) {
|
|
|
142
142
|
position: jobs.position,
|
|
143
143
|
jobRank: sql`row_number() over (partition by ${workflowRunAttempts.workflowRunId} order by ${jobs.position} asc, ${jobs.id} asc)`.as('job_rank')
|
|
144
144
|
}).from(jobs).innerJoin(workflowRunAttempts, eq(jobs.workflowRunAttemptId, workflowRunAttempts.id)).leftJoin(selectedExecution, eq(selectedExecution.jobId, jobs.id)).where(attemptFilter).as('ranked');
|
|
145
|
+
// Correlated per job rather than a grouped scan of `job_executions`: an aggregate over the
|
|
146
|
+
// whole table cannot have the page's filter pushed into it, so it would read every execution
|
|
147
|
+
// ever recorded on each poll and grow with history rather than with the page.
|
|
148
|
+
const hasStartedJobExecution = sql`bool_or(exists (
|
|
149
|
+
select 1
|
|
150
|
+
from ${jobExecutions}
|
|
151
|
+
where ${jobExecutions.jobId} = ${jobs.id} and ${jobExecutions.startedAt} is not null
|
|
152
|
+
))`;
|
|
145
153
|
const executionDisplayStatus = sql`
|
|
146
154
|
${selectedExecution.executionStatus}
|
|
147
155
|
`;
|
|
@@ -169,7 +177,8 @@ export async function listWorkflowRuns(params) {
|
|
|
169
177
|
workflowRunId: workflowRunAttempts.workflowRunId,
|
|
170
178
|
rawStatus: jobs.status,
|
|
171
179
|
status: displayStatus,
|
|
172
|
-
count: count()
|
|
180
|
+
count: count(),
|
|
181
|
+
hasStartedJobExecution
|
|
173
182
|
}).from(jobs).innerJoin(workflowRunAttempts, eq(jobs.workflowRunAttemptId, workflowRunAttempts.id)).leftJoin(selectedExecution, eq(selectedExecution.jobId, jobs.id)).where(attemptFilter).groupBy(workflowRunAttempts.workflowRunId, jobs.status, displayStatus)
|
|
174
183
|
};
|
|
175
184
|
}, {
|
|
@@ -179,10 +188,12 @@ export async function listWorkflowRuns(params) {
|
|
|
179
188
|
for (const { workflowRunId, ...summary } of previewRows){
|
|
180
189
|
summaryFor(summaries, workflowRunId).preview.push(summary);
|
|
181
190
|
}
|
|
182
|
-
for (const { workflowRunId, rawStatus, status, count: statusCount } of countRows){
|
|
191
|
+
for (const { workflowRunId, rawStatus, status, count: statusCount, hasStartedJobExecution } of countRows){
|
|
183
192
|
const summary = summaryFor(summaries, workflowRunId);
|
|
184
193
|
appendStatusCount(summary.rawStatusCounts, rawStatus, statusCount);
|
|
185
194
|
appendStatusCount(summary.statusCounts, status, statusCount);
|
|
195
|
+
// One row per (run, verdict, display status), so the run's answer is the OR of its groups.
|
|
196
|
+
summary.hasStartedJobExecution ||= hasStartedJobExecution;
|
|
186
197
|
}
|
|
187
198
|
return summaries;
|
|
188
199
|
}
|
|
@@ -192,7 +203,8 @@ function summaryFor(summaries, workflowRunId) {
|
|
|
192
203
|
const created = {
|
|
193
204
|
preview: [],
|
|
194
205
|
statusCounts: [],
|
|
195
|
-
rawStatusCounts: []
|
|
206
|
+
rawStatusCounts: [],
|
|
207
|
+
hasStartedJobExecution: false
|
|
196
208
|
};
|
|
197
209
|
summaries.set(workflowRunId, created);
|
|
198
210
|
return created;
|
|
@@ -322,7 +334,9 @@ function hydrateWorkflowRunDetail(rows, attempt, latestAttempt) {
|
|
|
322
334
|
...toWorkflowRun(first.run),
|
|
323
335
|
runAttempt: toWorkflowRunAttempt(attempt),
|
|
324
336
|
latestAttempt,
|
|
325
|
-
jobs: []
|
|
337
|
+
jobs: [],
|
|
338
|
+
// Read off the same rows the executions come from, so the flag cannot contradict them.
|
|
339
|
+
hasStartedJobExecution: rows.some((row)=>row.jobExecution?.startedAt != null)
|
|
326
340
|
};
|
|
327
341
|
const jobById = new Map();
|
|
328
342
|
const jobExecutionById = new Map();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/db/workflow-runs/queries.ts"],"sourcesContent":["import {WORKFLOW_RUN_JOB_PREVIEW_LIMIT} from '@shipfox/api-workflows-dto';\nimport {\n paginateTimestampIdRows,\n type TimestampIdCursor,\n timestampIdCursorWhere,\n} from '@shipfox/node-drizzle';\nimport {and, asc, count, desc, eq, gte, lte, type SQL, sql} from 'drizzle-orm';\nimport type {JobMode, JobStatus, ListenerStatus} from '#core/entities/job.js';\nimport type {JobExecutionStatus} from '#core/entities/job-execution.js';\nimport type {\n JobExecutionDetail,\n StepDetail,\n WorkflowJobDetail,\n WorkflowRun,\n WorkflowRunDetail,\n WorkflowRunStatus,\n} from '#core/entities/workflow-run.js';\nimport {db} from '../db.js';\nimport {jobExecutions, toJobExecution} from '../schema/job-executions.js';\nimport {jobs, toJob} from '../schema/jobs.js';\nimport {stepAttempts, toStepAttempt} from '../schema/step-attempts.js';\nimport {steps, toStep} from '../schema/steps.js';\nimport {toWorkflowRunAttempt, workflowRunAttempts} from '../schema/workflow-run-attempts.js';\nimport {toWorkflowRun, workflowRuns} from '../schema/workflow-runs.js';\n\nexport type WorkflowRunCursor = TimestampIdCursor;\n\nexport interface WorkflowRunFilters {\n status?: WorkflowRunStatus | undefined;\n definitionId?: string | undefined;\n triggerSource?: string | undefined;\n createdFrom?: Date | undefined;\n createdTo?: Date | undefined;\n}\n\nexport interface ListWorkflowRunsParams {\n projectId: string;\n limit: number;\n cursor?: WorkflowRunCursor | undefined;\n filters?: WorkflowRunFilters | undefined;\n includeTotal?: boolean | undefined;\n}\n\nexport interface ListWorkflowRunsResult {\n runs: WorkflowRun[];\n nextCursor: WorkflowRunCursor | null;\n filteredTotalCount: number | null;\n}\n\n/** A run-list job glyph: enough to draw and label it, none of its steps. */\nexport interface WorkflowRunJobSummary {\n id: string;\n key: string;\n name: string | null;\n status: JobStatus;\n mode: JobMode;\n listenerStatus: ListenerStatus;\n executionStatus: JobExecutionStatus | null;\n position: number;\n}\n\nexport interface WorkflowRunAggregates {\n status: Array<{value: WorkflowRunStatus; count: number}>;\n triggerSource: Array<{value: string; count: number}>;\n workflow: Array<{value: string; count: number}>;\n}\n\nexport interface WorkflowJobExecutionDepth {\n runningRuns: number;\n runningJobExecutions: number;\n}\n\nexport interface WorkflowJobExecutionDepthParams {\n workspaceId?: string;\n}\n\nexport async function getWorkflowRunById(id: string): Promise<WorkflowRun | undefined> {\n const rows = await db().select().from(workflowRuns).where(eq(workflowRuns.id, id)).limit(1);\n const row = rows[0];\n if (!row) return undefined;\n return toWorkflowRun(row);\n}\n\nexport async function getWorkflowRunByAttemptId(\n workflowRunAttemptId: string,\n): Promise<WorkflowRun | undefined> {\n const rows = await db()\n .select({run: workflowRuns})\n .from(workflowRunAttempts)\n .innerJoin(workflowRuns, eq(workflowRunAttempts.workflowRunId, workflowRuns.id))\n .where(eq(workflowRunAttempts.id, workflowRunAttemptId))\n .limit(1);\n const row = rows[0];\n return row ? toWorkflowRun(row.run) : undefined;\n}\n\nexport async function getWorkflowRunAttemptById(workflowRunAttemptId: string) {\n const rows = await db()\n .select()\n .from(workflowRunAttempts)\n .where(eq(workflowRunAttempts.id, workflowRunAttemptId))\n .limit(1);\n const row = rows[0];\n return row ? toWorkflowRunAttempt(row) : undefined;\n}\n\nexport async function listRunAttempts(params: {workflowRunId: string; projectId: string}) {\n return (\n await db()\n .select({\n attempt: workflowRunAttempts,\n })\n .from(workflowRunAttempts)\n .innerJoin(workflowRuns, eq(workflowRunAttempts.workflowRunId, workflowRuns.id))\n .where(\n and(\n eq(workflowRunAttempts.workflowRunId, params.workflowRunId),\n eq(workflowRuns.projectId, params.projectId),\n ),\n )\n .orderBy(asc(workflowRunAttempts.attempt))\n ).map((row) => toWorkflowRunAttempt(row.attempt));\n}\n\nexport async function getLatestAttempt(params: {\n workflowRunId: string;\n projectId: string;\n}): Promise<number> {\n const [row] = await db()\n .select({value: sql<number>`coalesce(max(${workflowRunAttempts.attempt}), 1)`})\n .from(workflowRunAttempts)\n .innerJoin(workflowRuns, eq(workflowRunAttempts.workflowRunId, workflowRuns.id))\n .where(\n and(\n eq(workflowRunAttempts.workflowRunId, params.workflowRunId),\n eq(workflowRuns.projectId, params.projectId),\n ),\n )\n .limit(1);\n\n return Number(row?.value ?? 1);\n}\n\nexport function buildWorkflowRunListConditions(params: {\n projectId: string;\n filters?: WorkflowRunFilters | undefined;\n cursor?: WorkflowRunCursor | undefined;\n omit?: 'status' | 'definitionId' | 'triggerSource' | undefined;\n}): SQL[] {\n const filters = params.filters;\n const conditions: SQL[] = [eq(workflowRuns.projectId, params.projectId)];\n const cursorCondition = timestampIdCursorWhere({\n timestampColumn: workflowRuns.createdAt,\n idColumn: workflowRuns.id,\n cursor: params.cursor,\n });\n if (cursorCondition) conditions.push(cursorCondition);\n if (filters?.status && params.omit !== 'status') {\n conditions.push(eq(workflowRuns.status, filters.status));\n }\n if (filters?.definitionId && params.omit !== 'definitionId') {\n conditions.push(eq(workflowRuns.definitionId, filters.definitionId));\n }\n if (filters?.triggerSource && params.omit !== 'triggerSource') {\n conditions.push(eq(workflowRuns.triggerSource, filters.triggerSource));\n }\n if (filters?.createdFrom) {\n conditions.push(gte(workflowRuns.createdAt, filters.createdFrom));\n }\n if (filters?.createdTo) {\n conditions.push(lte(workflowRuns.createdAt, filters.createdTo));\n }\n return conditions;\n}\n\nexport async function listWorkflowRuns(\n params: ListWorkflowRunsParams,\n): Promise<ListWorkflowRunsResult> {\n const conditions = buildWorkflowRunListConditions(params);\n const rows = await db()\n .select()\n .from(workflowRuns)\n .where(and(...conditions))\n .orderBy(desc(workflowRuns.createdAt), desc(workflowRuns.id))\n .limit(params.limit + 1);\n\n let totalCount: number | null = null;\n if (params.includeTotal) {\n const [{value} = {value: 0}] = await db()\n .select({value: count()})\n .from(workflowRuns)\n .where(\n and(\n ...buildWorkflowRunListConditions({projectId: params.projectId, filters: params.filters}),\n ),\n );\n totalCount = value;\n }\n\n const page = paginateTimestampIdRows({rows, limit: params.limit, timestampKey: 'createdAt'});\n\n return {\n runs: page.pageRows.map(toWorkflowRun),\n nextCursor: page.nextCursor,\n filteredTotalCount: totalCount,\n };\n}\n\n/** The run whose jobs to fetch, pinned to the attempt the caller already read. */\nexport interface WorkflowRunJobSummaryTarget {\n id: string;\n currentAttempt: number;\n}\n\n/**\n * A page row's jobs: a bounded slice to draw, and totals describing all of them.\n *\n * The preview is what a row can show; `statusCounts` is what it can say. Keeping the counts\n * server-side is what lets a row report a failure that sits past the preview. Counts use the\n * display status derived from the job verdict, listener state, and selected execution state;\n * the row keeps the verdict and evidence separate so the client can apply the same display\n * rule as run detail.\n */\nexport interface WorkflowRunJobsSummary {\n preview: WorkflowRunJobSummary[];\n statusCounts: WorkflowRunJobStatusCount[];\n rawStatusCounts: WorkflowRunJobRawStatusCount[];\n}\n\nexport interface WorkflowRunJobStatusCount {\n status: JobStatus | 'listening';\n count: number;\n}\n\nexport interface WorkflowRunJobRawStatusCount {\n status: JobStatus;\n count: number;\n}\n\n/**\n * Jobs for a page of runs, keyed by run id.\n *\n * Issued once per page rather than once per run: the run list is the one surface that needs\n * every run's jobs at once, and a per-row query would put 50 round trips behind it.\n *\n * Both reads are bounded by the page, not by workflow size. A workflow has no job limit and\n * this list polls while runs are active, so returning every job of every row would let one\n * large workflow decide how much the endpoint moves every four seconds. The preview is cut\n * per run in the database, and everything past it is described by a grouped count instead.\n *\n * The attempt comes from the caller's own read rather than from a second look at\n * `current_attempt`. Re-reading it here would let a re-run landing between the queries pair\n * attempt 1's run metadata with attempt 2's jobs, and the row would report a status its strip\n * contradicts.\n *\n * The two reads share one repeatable-read snapshot. They describe the same jobs at the same\n * instant, and the strip combines them into a single glyph row, so under the default\n * read-committed isolation a job settling between the statements would draw a pending glyph\n * beside a summary counting it as failed. Sequential inside one transaction is the cost of\n * that; at a four-second poll the extra round trip does not register.\n */\nexport async function listWorkflowRunJobSummaries(\n runs: readonly WorkflowRunJobSummaryTarget[],\n): Promise<Map<string, WorkflowRunJobsSummary>> {\n const summaries = new Map<string, WorkflowRunJobsSummary>();\n if (runs.length === 0) return summaries;\n\n // A row-constructor IN over (run, attempt) so each pair is one lookup on the unique index\n // that already covers those two columns.\n const attemptPairs = sql.join(\n runs.map((run) => sql`(${run.id}::uuid, ${run.currentAttempt})`),\n sql`, `,\n );\n const attemptFilter = sql`(${workflowRunAttempts.workflowRunId}, ${workflowRunAttempts.attempt}) in (${attemptPairs})`;\n\n const {previewRows, countRows} = await db().transaction(\n async (tx) => {\n // Pick the execution the detail view would display once per job before either list\n // statement touches it. The existing (job_id, sequence) index supports the latest\n // execution ordering, while the status-first expression preserves the rule that an\n // active execution wins over a newer completed retry.\n const selectedExecution = tx.$with('selected_execution').as(\n tx\n .selectDistinctOn([jobExecutions.jobId], {\n jobId: jobExecutions.jobId,\n executionStatus: sql<JobExecutionStatus>`${jobExecutions.status}`.as(\n 'execution_status',\n ),\n })\n .from(jobExecutions)\n .innerJoin(jobs, eq(jobExecutions.jobId, jobs.id))\n .innerJoin(workflowRunAttempts, eq(jobs.workflowRunAttemptId, workflowRunAttempts.id))\n .where(attemptFilter)\n .orderBy(\n asc(jobExecutions.jobId),\n sql`case when ${jobExecutions.status} = 'running' then 0 else 1 end`,\n desc(jobExecutions.sequence),\n desc(jobExecutions.id),\n ),\n );\n\n const ranked = tx\n .with(selectedExecution)\n .select({\n workflowRunId: workflowRunAttempts.workflowRunId,\n id: jobs.id,\n key: jobs.key,\n name: jobs.name,\n status: jobs.status,\n mode: jobs.mode,\n listenerStatus: jobs.listenerStatus,\n executionStatus: selectedExecution.executionStatus,\n position: jobs.position,\n jobRank:\n sql<number>`row_number() over (partition by ${workflowRunAttempts.workflowRunId} order by ${jobs.position} asc, ${jobs.id} asc)`.as(\n 'job_rank',\n ),\n })\n .from(jobs)\n .innerJoin(workflowRunAttempts, eq(jobs.workflowRunAttemptId, workflowRunAttempts.id))\n .leftJoin(selectedExecution, eq(selectedExecution.jobId, jobs.id))\n .where(attemptFilter)\n .as('ranked');\n\n const executionDisplayStatus = sql<JobExecutionStatus | null>`\n ${selectedExecution.executionStatus}\n `;\n const displayStatus = sql<WorkflowRunJobStatusCount['status']>`\n case\n when ${jobs.status} in ('succeeded', 'failed', 'cancelled', 'skipped') then ${jobs.status}::text\n when ${jobs.mode} = 'listening' and ${jobs.listenerStatus} = 'listening' then 'listening'\n when ${executionDisplayStatus} is not null then ${executionDisplayStatus}::text\n else 'pending'\n end\n `;\n return {\n previewRows: await tx\n .select({\n workflowRunId: ranked.workflowRunId,\n id: ranked.id,\n key: ranked.key,\n name: ranked.name,\n status: ranked.status,\n mode: ranked.mode,\n listenerStatus: ranked.listenerStatus,\n executionStatus: ranked.executionStatus,\n position: ranked.position,\n })\n .from(ranked)\n .where(lte(ranked.jobRank, WORKFLOW_RUN_JOB_PREVIEW_LIMIT))\n .orderBy(asc(ranked.workflowRunId), asc(ranked.position), asc(ranked.id)),\n countRows: await tx\n .with(selectedExecution)\n .select({\n workflowRunId: workflowRunAttempts.workflowRunId,\n rawStatus: jobs.status,\n status: displayStatus,\n count: count(),\n })\n .from(jobs)\n .innerJoin(workflowRunAttempts, eq(jobs.workflowRunAttemptId, workflowRunAttempts.id))\n .leftJoin(selectedExecution, eq(selectedExecution.jobId, jobs.id))\n .where(attemptFilter)\n .groupBy(workflowRunAttempts.workflowRunId, jobs.status, displayStatus),\n };\n },\n {isolationLevel: 'repeatable read', accessMode: 'read only'},\n );\n\n for (const {workflowRunId, ...summary} of previewRows) {\n summaryFor(summaries, workflowRunId).preview.push(summary);\n }\n for (const {workflowRunId, rawStatus, status, count: statusCount} of countRows) {\n const summary = summaryFor(summaries, workflowRunId);\n appendStatusCount(summary.rawStatusCounts, rawStatus, statusCount);\n appendStatusCount(summary.statusCounts, status, statusCount);\n }\n\n return summaries;\n}\n\nfunction summaryFor(\n summaries: Map<string, WorkflowRunJobsSummary>,\n workflowRunId: string,\n): WorkflowRunJobsSummary {\n const existing = summaries.get(workflowRunId);\n if (existing) return existing;\n const created: WorkflowRunJobsSummary = {preview: [], statusCounts: [], rawStatusCounts: []};\n summaries.set(workflowRunId, created);\n return created;\n}\n\nfunction appendStatusCount<T extends string>(\n counts: Array<{status: T; count: number}>,\n status: T,\n count: number,\n): void {\n const existing = counts.find((entry) => entry.status === status);\n if (existing) {\n existing.count += count;\n } else {\n counts.push({status, count});\n }\n}\n\nexport async function listWorkflowRunsByProject(projectId: string): Promise<WorkflowRun[]> {\n const result = await listWorkflowRuns({projectId, limit: 100});\n return result.runs;\n}\n\nexport async function getWorkflowRunAggregates(params: {\n projectId: string;\n filters?: WorkflowRunFilters | undefined;\n}): Promise<WorkflowRunAggregates> {\n const [statusRows, triggerRows, workflowRows] = await Promise.all([\n db()\n .select({value: workflowRuns.status, count: count()})\n .from(workflowRuns)\n .where(\n and(\n ...buildWorkflowRunListConditions({\n projectId: params.projectId,\n filters: params.filters,\n omit: 'status',\n }),\n ),\n )\n .groupBy(workflowRuns.status),\n db()\n .select({value: workflowRuns.triggerSource, count: count()})\n .from(workflowRuns)\n .where(\n and(\n ...buildWorkflowRunListConditions({\n projectId: params.projectId,\n filters: params.filters,\n omit: 'triggerSource',\n }),\n ),\n )\n .groupBy(workflowRuns.triggerSource),\n db()\n .select({value: workflowRuns.definitionId, count: count()})\n .from(workflowRuns)\n .where(\n and(\n ...buildWorkflowRunListConditions({\n projectId: params.projectId,\n filters: params.filters,\n omit: 'definitionId',\n }),\n ),\n )\n .groupBy(workflowRuns.definitionId),\n ]);\n\n return {\n status: statusRows,\n triggerSource: triggerRows,\n workflow: workflowRows,\n };\n}\n\nexport async function getWorkflowJobExecutionDepth(\n params: WorkflowJobExecutionDepthParams = {},\n): Promise<WorkflowJobExecutionDepth> {\n const runConditions = [eq(workflowRuns.status, 'running')];\n const jobConditions = [eq(jobExecutions.status, 'running')];\n if (params.workspaceId) {\n runConditions.push(eq(workflowRuns.workspaceId, params.workspaceId));\n jobConditions.push(eq(workflowRuns.workspaceId, params.workspaceId));\n }\n\n const [runRows, jobRows] = await Promise.all([\n db()\n .select({value: count()})\n .from(workflowRuns)\n .where(and(...runConditions)),\n db()\n .select({value: count()})\n .from(jobExecutions)\n .innerJoin(jobs, eq(jobExecutions.jobId, jobs.id))\n .innerJoin(workflowRunAttempts, eq(jobs.workflowRunAttemptId, workflowRunAttempts.id))\n .innerJoin(workflowRuns, eq(workflowRunAttempts.workflowRunId, workflowRuns.id))\n .where(and(...jobConditions)),\n ]);\n\n return {\n runningRuns: runRows[0]?.value ?? 0,\n runningJobExecutions: jobRows[0]?.value ?? 0,\n };\n}\n\nexport async function getWorkflowRunDetail(\n workflowRunId: string,\n attempt?: number | undefined,\n): Promise<WorkflowRunDetail | undefined> {\n const [target] = await db()\n .select({run: workflowRuns, attempt: workflowRunAttempts})\n .from(workflowRuns)\n .innerJoin(\n workflowRunAttempts,\n and(\n eq(workflowRunAttempts.workflowRunId, workflowRuns.id),\n eq(workflowRunAttempts.attempt, attempt ?? workflowRuns.currentAttempt),\n ),\n )\n .where(eq(workflowRuns.id, workflowRunId))\n .limit(1);\n if (!target) return undefined;\n\n const latestAttempt = await getLatestAttempt({\n workflowRunId: target.run.id,\n projectId: target.run.projectId,\n });\n\n const rows = await db()\n .select({\n run: workflowRuns,\n job: jobs,\n jobExecution: jobExecutions,\n step: steps,\n stepAttempt: stepAttempts,\n })\n .from(workflowRuns)\n .innerJoin(workflowRunAttempts, eq(workflowRunAttempts.id, target.attempt.id))\n .leftJoin(jobs, eq(jobs.workflowRunAttemptId, workflowRunAttempts.id))\n .leftJoin(jobExecutions, eq(jobExecutions.jobId, jobs.id))\n .leftJoin(steps, eq(steps.jobExecutionId, jobExecutions.id))\n .leftJoin(stepAttempts, eq(stepAttempts.stepId, steps.id))\n .where(eq(workflowRuns.id, workflowRunId))\n .orderBy(\n asc(jobs.position),\n asc(jobs.id),\n asc(jobExecutions.sequence),\n asc(jobExecutions.id),\n asc(steps.position),\n asc(steps.id),\n asc(stepAttempts.executionOrder),\n asc(stepAttempts.id),\n );\n\n return hydrateWorkflowRunDetail(rows, target.attempt, latestAttempt);\n}\n\nexport async function getJobExecutionDetail(\n jobExecutionId: string,\n): Promise<JobExecutionDetail | undefined> {\n const rows = await db()\n .select({\n job: jobs,\n jobExecution: jobExecutions,\n step: steps,\n stepAttempt: stepAttempts,\n })\n .from(jobExecutions)\n .innerJoin(jobs, eq(jobExecutions.jobId, jobs.id))\n .innerJoin(workflowRunAttempts, eq(jobs.workflowRunAttemptId, workflowRunAttempts.id))\n .innerJoin(workflowRuns, eq(workflowRunAttempts.workflowRunId, workflowRuns.id))\n .leftJoin(steps, eq(steps.jobExecutionId, jobExecutions.id))\n .leftJoin(stepAttempts, eq(stepAttempts.stepId, steps.id))\n .where(eq(jobExecutions.id, jobExecutionId))\n .orderBy(\n asc(steps.position),\n asc(steps.id),\n asc(stepAttempts.executionOrder),\n asc(stepAttempts.id),\n );\n\n const first = rows[0];\n if (!first) return undefined;\n\n const detail: JobExecutionDetail = {\n ...toJobExecution(first.jobExecution, first.job.name ?? first.job.key),\n steps: [],\n };\n const stepById = new Map<string, StepDetail>();\n for (const row of rows) {\n if (row.step) {\n const step = getOrCreateStepDetail(stepById, detail.steps, row.step);\n if (row.stepAttempt) {\n step.attempts.push(toStepAttempt(row.stepAttempt));\n }\n }\n }\n\n return detail;\n}\n\nfunction hydrateWorkflowRunDetail(\n rows: {\n run: typeof workflowRuns.$inferSelect;\n job: typeof jobs.$inferSelect | null;\n jobExecution: typeof jobExecutions.$inferSelect | null;\n step: typeof steps.$inferSelect | null;\n stepAttempt: typeof stepAttempts.$inferSelect | null;\n }[],\n attempt: typeof workflowRunAttempts.$inferSelect,\n latestAttempt: number,\n): WorkflowRunDetail | undefined {\n const first = rows[0];\n if (!first) return undefined;\n\n const detail: WorkflowRunDetail = {\n ...toWorkflowRun(first.run),\n runAttempt: toWorkflowRunAttempt(attempt),\n latestAttempt,\n jobs: [],\n };\n const jobById = new Map<string, WorkflowJobDetail>();\n const jobExecutionById = new Map<string, JobExecutionDetail>();\n const stepById = new Map<string, StepDetail>();\n\n for (const row of rows) {\n if (!row.job) continue;\n let job = jobById.get(row.job.id);\n if (!job) {\n job = {...toJob(row.job), jobExecutions: []};\n jobById.set(row.job.id, job);\n detail.jobs.push(job);\n }\n\n if (!row.jobExecution) continue;\n let jobExecution = jobExecutionById.get(row.jobExecution.id);\n if (!jobExecution) {\n jobExecution = {\n ...toJobExecution(row.jobExecution, row.job.name ?? row.job.key),\n steps: [],\n };\n jobExecutionById.set(row.jobExecution.id, jobExecution);\n job.jobExecutions.push(jobExecution);\n }\n\n if (!row.step) continue;\n const step = getOrCreateStepDetail(stepById, jobExecution.steps, row.step);\n if (row.stepAttempt) {\n step.attempts.push(toStepAttempt(row.stepAttempt));\n }\n }\n\n return detail;\n}\n\nfunction getOrCreateStepDetail(\n stepById: Map<string, StepDetail>,\n target: StepDetail[],\n row: typeof steps.$inferSelect,\n): StepDetail {\n let step = stepById.get(row.id);\n if (!step) {\n step = {...toStep(row), attempts: []};\n stepById.set(row.id, step);\n target.push(step);\n }\n return step;\n}\n"],"names":["WORKFLOW_RUN_JOB_PREVIEW_LIMIT","paginateTimestampIdRows","timestampIdCursorWhere","and","asc","count","desc","eq","gte","lte","sql","db","jobExecutions","toJobExecution","jobs","toJob","stepAttempts","toStepAttempt","steps","toStep","toWorkflowRunAttempt","workflowRunAttempts","toWorkflowRun","workflowRuns","getWorkflowRunById","id","rows","select","from","where","limit","row","undefined","getWorkflowRunByAttemptId","workflowRunAttemptId","run","innerJoin","workflowRunId","getWorkflowRunAttemptById","listRunAttempts","params","attempt","projectId","orderBy","map","getLatestAttempt","value","Number","buildWorkflowRunListConditions","filters","conditions","cursorCondition","timestampColumn","createdAt","idColumn","cursor","push","status","omit","definitionId","triggerSource","createdFrom","createdTo","listWorkflowRuns","totalCount","includeTotal","page","timestampKey","runs","pageRows","nextCursor","filteredTotalCount","listWorkflowRunJobSummaries","summaries","Map","length","attemptPairs","join","currentAttempt","attemptFilter","previewRows","countRows","transaction","tx","selectedExecution","$with","as","selectDistinctOn","jobId","executionStatus","sequence","ranked","with","key","name","mode","listenerStatus","position","jobRank","leftJoin","executionDisplayStatus","displayStatus","rawStatus","groupBy","isolationLevel","accessMode","summary","summaryFor","preview","statusCount","appendStatusCount","rawStatusCounts","statusCounts","existing","get","created","set","counts","find","entry","listWorkflowRunsByProject","result","getWorkflowRunAggregates","statusRows","triggerRows","workflowRows","Promise","all","workflow","getWorkflowJobExecutionDepth","runConditions","jobConditions","workspaceId","runRows","jobRows","runningRuns","runningJobExecutions","getWorkflowRunDetail","target","latestAttempt","job","jobExecution","step","stepAttempt","jobExecutionId","stepId","executionOrder","hydrateWorkflowRunDetail","getJobExecutionDetail","first","detail","stepById","getOrCreateStepDetail","attempts","runAttempt","jobById","jobExecutionById"],"mappings":"AAAA,SAAQA,8BAA8B,QAAO,6BAA6B;AAC1E,SACEC,uBAAuB,EAEvBC,sBAAsB,QACjB,wBAAwB;AAC/B,SAAQC,GAAG,EAAEC,GAAG,EAAEC,KAAK,EAAEC,IAAI,EAAEC,EAAE,EAAEC,GAAG,EAAEC,GAAG,EAAYC,GAAG,QAAO,cAAc;AAW/E,SAAQC,EAAE,QAAO,WAAW;AAC5B,SAAQC,aAAa,EAAEC,cAAc,QAAO,8BAA8B;AAC1E,SAAQC,IAAI,EAAEC,KAAK,QAAO,oBAAoB;AAC9C,SAAQC,YAAY,EAAEC,aAAa,QAAO,6BAA6B;AACvE,SAAQC,KAAK,EAAEC,MAAM,QAAO,qBAAqB;AACjD,SAAQC,oBAAoB,EAAEC,mBAAmB,QAAO,qCAAqC;AAC7F,SAAQC,aAAa,EAAEC,YAAY,QAAO,6BAA6B;AAqDvE,OAAO,eAAeC,mBAAmBC,EAAU;IACjD,MAAMC,OAAO,MAAMf,KAAKgB,MAAM,GAAGC,IAAI,CAACL,cAAcM,KAAK,CAACtB,GAAGgB,aAAaE,EAAE,EAAEA,KAAKK,KAAK,CAAC;IACzF,MAAMC,MAAML,IAAI,CAAC,EAAE;IACnB,IAAI,CAACK,KAAK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AAI,CAACvC,cAAcc,IAAIgH,WAAW;QAClD;IACF;IAEA,OAAOO;AACT;AAEA,SAASE,sBACPD,QAAiC,EACjCb,MAAoB,EACpB3G,GAA8B;IAE9B,IAAI+G,OAAOS,SAASrC,GAAG,CAACnF,IAAIN,EAAE;IAC9B,IAAI,CAACqH,MAAM;QACTA,OAAO;YAAC,GAAG3H,OAAOY,IAAI;YAAE0H,UAAU,EAAE;QAAA;QACpCF,SAASnC,GAAG,CAACrF,IAAIN,EAAE,EAAEqH;QACrBJ,OAAOlF,IAAI,CAACsF;IACd;IACA,OAAOA;AACT"}
|
|
1
|
+
{"version":3,"sources":["../../../src/db/workflow-runs/queries.ts"],"sourcesContent":["import {WORKFLOW_RUN_JOB_PREVIEW_LIMIT} from '@shipfox/api-workflows-dto';\nimport {\n paginateTimestampIdRows,\n type TimestampIdCursor,\n timestampIdCursorWhere,\n} from '@shipfox/node-drizzle';\nimport {and, asc, count, desc, eq, gte, lte, type SQL, sql} from 'drizzle-orm';\nimport type {JobMode, JobStatus, ListenerStatus} from '#core/entities/job.js';\nimport type {JobExecutionStatus} from '#core/entities/job-execution.js';\nimport type {\n JobExecutionDetail,\n StepDetail,\n WorkflowJobDetail,\n WorkflowRun,\n WorkflowRunDetail,\n WorkflowRunStatus,\n} from '#core/entities/workflow-run.js';\nimport {db} from '../db.js';\nimport {jobExecutions, toJobExecution} from '../schema/job-executions.js';\nimport {jobs, toJob} from '../schema/jobs.js';\nimport {stepAttempts, toStepAttempt} from '../schema/step-attempts.js';\nimport {steps, toStep} from '../schema/steps.js';\nimport {toWorkflowRunAttempt, workflowRunAttempts} from '../schema/workflow-run-attempts.js';\nimport {toWorkflowRun, workflowRuns} from '../schema/workflow-runs.js';\n\nexport type WorkflowRunCursor = TimestampIdCursor;\n\nexport interface WorkflowRunFilters {\n status?: WorkflowRunStatus | undefined;\n definitionId?: string | undefined;\n triggerSource?: string | undefined;\n createdFrom?: Date | undefined;\n createdTo?: Date | undefined;\n}\n\nexport interface ListWorkflowRunsParams {\n projectId: string;\n limit: number;\n cursor?: WorkflowRunCursor | undefined;\n filters?: WorkflowRunFilters | undefined;\n includeTotal?: boolean | undefined;\n}\n\nexport interface ListWorkflowRunsResult {\n runs: WorkflowRun[];\n nextCursor: WorkflowRunCursor | null;\n filteredTotalCount: number | null;\n}\n\n/** A run-list job glyph: enough to draw and label it, none of its steps. */\nexport interface WorkflowRunJobSummary {\n id: string;\n key: string;\n name: string | null;\n status: JobStatus;\n mode: JobMode;\n listenerStatus: ListenerStatus;\n executionStatus: JobExecutionStatus | null;\n position: number;\n}\n\nexport interface WorkflowRunAggregates {\n status: Array<{value: WorkflowRunStatus; count: number}>;\n triggerSource: Array<{value: string; count: number}>;\n workflow: Array<{value: string; count: number}>;\n}\n\nexport interface WorkflowJobExecutionDepth {\n runningRuns: number;\n runningJobExecutions: number;\n}\n\nexport interface WorkflowJobExecutionDepthParams {\n workspaceId?: string;\n}\n\nexport async function getWorkflowRunById(id: string): Promise<WorkflowRun | undefined> {\n const rows = await db().select().from(workflowRuns).where(eq(workflowRuns.id, id)).limit(1);\n const row = rows[0];\n if (!row) return undefined;\n return toWorkflowRun(row);\n}\n\nexport async function getWorkflowRunByAttemptId(\n workflowRunAttemptId: string,\n): Promise<WorkflowRun | undefined> {\n const rows = await db()\n .select({run: workflowRuns})\n .from(workflowRunAttempts)\n .innerJoin(workflowRuns, eq(workflowRunAttempts.workflowRunId, workflowRuns.id))\n .where(eq(workflowRunAttempts.id, workflowRunAttemptId))\n .limit(1);\n const row = rows[0];\n return row ? toWorkflowRun(row.run) : undefined;\n}\n\nexport async function getWorkflowRunAttemptById(workflowRunAttemptId: string) {\n const rows = await db()\n .select()\n .from(workflowRunAttempts)\n .where(eq(workflowRunAttempts.id, workflowRunAttemptId))\n .limit(1);\n const row = rows[0];\n return row ? toWorkflowRunAttempt(row) : undefined;\n}\n\nexport async function listRunAttempts(params: {workflowRunId: string; projectId: string}) {\n return (\n await db()\n .select({\n attempt: workflowRunAttempts,\n })\n .from(workflowRunAttempts)\n .innerJoin(workflowRuns, eq(workflowRunAttempts.workflowRunId, workflowRuns.id))\n .where(\n and(\n eq(workflowRunAttempts.workflowRunId, params.workflowRunId),\n eq(workflowRuns.projectId, params.projectId),\n ),\n )\n .orderBy(asc(workflowRunAttempts.attempt))\n ).map((row) => toWorkflowRunAttempt(row.attempt));\n}\n\nexport async function getLatestAttempt(params: {\n workflowRunId: string;\n projectId: string;\n}): Promise<number> {\n const [row] = await db()\n .select({value: sql<number>`coalesce(max(${workflowRunAttempts.attempt}), 1)`})\n .from(workflowRunAttempts)\n .innerJoin(workflowRuns, eq(workflowRunAttempts.workflowRunId, workflowRuns.id))\n .where(\n and(\n eq(workflowRunAttempts.workflowRunId, params.workflowRunId),\n eq(workflowRuns.projectId, params.projectId),\n ),\n )\n .limit(1);\n\n return Number(row?.value ?? 1);\n}\n\nexport function buildWorkflowRunListConditions(params: {\n projectId: string;\n filters?: WorkflowRunFilters | undefined;\n cursor?: WorkflowRunCursor | undefined;\n omit?: 'status' | 'definitionId' | 'triggerSource' | undefined;\n}): SQL[] {\n const filters = params.filters;\n const conditions: SQL[] = [eq(workflowRuns.projectId, params.projectId)];\n const cursorCondition = timestampIdCursorWhere({\n timestampColumn: workflowRuns.createdAt,\n idColumn: workflowRuns.id,\n cursor: params.cursor,\n });\n if (cursorCondition) conditions.push(cursorCondition);\n if (filters?.status && params.omit !== 'status') {\n conditions.push(eq(workflowRuns.status, filters.status));\n }\n if (filters?.definitionId && params.omit !== 'definitionId') {\n conditions.push(eq(workflowRuns.definitionId, filters.definitionId));\n }\n if (filters?.triggerSource && params.omit !== 'triggerSource') {\n conditions.push(eq(workflowRuns.triggerSource, filters.triggerSource));\n }\n if (filters?.createdFrom) {\n conditions.push(gte(workflowRuns.createdAt, filters.createdFrom));\n }\n if (filters?.createdTo) {\n conditions.push(lte(workflowRuns.createdAt, filters.createdTo));\n }\n return conditions;\n}\n\nexport async function listWorkflowRuns(\n params: ListWorkflowRunsParams,\n): Promise<ListWorkflowRunsResult> {\n const conditions = buildWorkflowRunListConditions(params);\n const rows = await db()\n .select()\n .from(workflowRuns)\n .where(and(...conditions))\n .orderBy(desc(workflowRuns.createdAt), desc(workflowRuns.id))\n .limit(params.limit + 1);\n\n let totalCount: number | null = null;\n if (params.includeTotal) {\n const [{value} = {value: 0}] = await db()\n .select({value: count()})\n .from(workflowRuns)\n .where(\n and(\n ...buildWorkflowRunListConditions({projectId: params.projectId, filters: params.filters}),\n ),\n );\n totalCount = value;\n }\n\n const page = paginateTimestampIdRows({rows, limit: params.limit, timestampKey: 'createdAt'});\n\n return {\n runs: page.pageRows.map(toWorkflowRun),\n nextCursor: page.nextCursor,\n filteredTotalCount: totalCount,\n };\n}\n\n/** The run whose jobs to fetch, pinned to the attempt the caller already read. */\nexport interface WorkflowRunJobSummaryTarget {\n id: string;\n currentAttempt: number;\n}\n\n/**\n * A page row's jobs: a bounded slice to draw, totals describing all of them, and whether any\n * execution has reached a runner.\n *\n * The preview is what a row can show; `statusCounts` is what it can say. Keeping the counts\n * server-side is what lets a row report a failure that sits past the preview. Counts use the\n * display status derived from the job verdict, listener state, and selected execution state;\n * the row keeps the verdict and evidence separate so the client can apply the same display\n * rule as run detail.\n */\nexport interface WorkflowRunJobsSummary {\n preview: WorkflowRunJobSummary[];\n statusCounts: WorkflowRunJobStatusCount[];\n rawStatusCounts: WorkflowRunJobRawStatusCount[];\n hasStartedJobExecution: boolean;\n}\n\nexport interface WorkflowRunJobStatusCount {\n status: JobStatus | 'listening';\n count: number;\n}\n\nexport interface WorkflowRunJobRawStatusCount {\n status: JobStatus;\n count: number;\n}\n\n/**\n * Jobs for a page of runs, keyed by run id.\n *\n * Issued once per page rather than once per run: the run list is the one surface that needs\n * every run's jobs at once, and a per-row query would put 50 round trips behind it.\n *\n * Both reads are bounded by the page, not by workflow size. A workflow has no job limit and\n * this list polls while runs are active, so returning every job of every row would let one\n * large workflow decide how much the endpoint moves every four seconds. The preview is cut\n * per run in the database, and everything past it is described by a grouped count instead.\n *\n * The attempt comes from the caller's own read rather than from a second look at\n * `current_attempt`. Re-reading it here would let a re-run landing between the queries pair\n * attempt 1's run metadata with attempt 2's jobs, and the row would report a status its strip\n * contradicts.\n *\n * The reads share one repeatable-read snapshot. They describe the same jobs and executions at\n * the same instant, and the strip combines them into a single glyph row, so under the default\n * read-committed isolation a job settling between the statements would draw a pending glyph\n * beside a summary counting it as failed. Sequential inside one transaction is the cost of\n * that; at a four-second poll the extra round trip does not register.\n */\nexport async function listWorkflowRunJobSummaries(\n runs: readonly WorkflowRunJobSummaryTarget[],\n): Promise<Map<string, WorkflowRunJobsSummary>> {\n const summaries = new Map<string, WorkflowRunJobsSummary>();\n if (runs.length === 0) return summaries;\n\n // A row-constructor IN over (run, attempt) so each pair is one lookup on the unique index\n // that already covers those two columns.\n const attemptPairs = sql.join(\n runs.map((run) => sql`(${run.id}::uuid, ${run.currentAttempt})`),\n sql`, `,\n );\n const attemptFilter = sql`(${workflowRunAttempts.workflowRunId}, ${workflowRunAttempts.attempt}) in (${attemptPairs})`;\n\n const {previewRows, countRows} = await db().transaction(\n async (tx) => {\n // Pick the execution the detail view would display once per job before either list\n // statement touches it. The existing (job_id, sequence) index supports the latest\n // execution ordering, while the status-first expression preserves the rule that an\n // active execution wins over a newer completed retry.\n const selectedExecution = tx.$with('selected_execution').as(\n tx\n .selectDistinctOn([jobExecutions.jobId], {\n jobId: jobExecutions.jobId,\n executionStatus: sql<JobExecutionStatus>`${jobExecutions.status}`.as(\n 'execution_status',\n ),\n })\n .from(jobExecutions)\n .innerJoin(jobs, eq(jobExecutions.jobId, jobs.id))\n .innerJoin(workflowRunAttempts, eq(jobs.workflowRunAttemptId, workflowRunAttempts.id))\n .where(attemptFilter)\n .orderBy(\n asc(jobExecutions.jobId),\n sql`case when ${jobExecutions.status} = 'running' then 0 else 1 end`,\n desc(jobExecutions.sequence),\n desc(jobExecutions.id),\n ),\n );\n\n const ranked = tx\n .with(selectedExecution)\n .select({\n workflowRunId: workflowRunAttempts.workflowRunId,\n id: jobs.id,\n key: jobs.key,\n name: jobs.name,\n status: jobs.status,\n mode: jobs.mode,\n listenerStatus: jobs.listenerStatus,\n executionStatus: selectedExecution.executionStatus,\n position: jobs.position,\n jobRank:\n sql<number>`row_number() over (partition by ${workflowRunAttempts.workflowRunId} order by ${jobs.position} asc, ${jobs.id} asc)`.as(\n 'job_rank',\n ),\n })\n .from(jobs)\n .innerJoin(workflowRunAttempts, eq(jobs.workflowRunAttemptId, workflowRunAttempts.id))\n .leftJoin(selectedExecution, eq(selectedExecution.jobId, jobs.id))\n .where(attemptFilter)\n .as('ranked');\n // Correlated per job rather than a grouped scan of `job_executions`: an aggregate over the\n // whole table cannot have the page's filter pushed into it, so it would read every execution\n // ever recorded on each poll and grow with history rather than with the page.\n const hasStartedJobExecution = sql<boolean>`bool_or(exists (\n select 1\n from ${jobExecutions}\n where ${jobExecutions.jobId} = ${jobs.id} and ${jobExecutions.startedAt} is not null\n ))`;\n\n const executionDisplayStatus = sql<JobExecutionStatus | null>`\n ${selectedExecution.executionStatus}\n `;\n const displayStatus = sql<WorkflowRunJobStatusCount['status']>`\n case\n when ${jobs.status} in ('succeeded', 'failed', 'cancelled', 'skipped') then ${jobs.status}::text\n when ${jobs.mode} = 'listening' and ${jobs.listenerStatus} = 'listening' then 'listening'\n when ${executionDisplayStatus} is not null then ${executionDisplayStatus}::text\n else 'pending'\n end\n `;\n return {\n previewRows: await tx\n .select({\n workflowRunId: ranked.workflowRunId,\n id: ranked.id,\n key: ranked.key,\n name: ranked.name,\n status: ranked.status,\n mode: ranked.mode,\n listenerStatus: ranked.listenerStatus,\n executionStatus: ranked.executionStatus,\n position: ranked.position,\n })\n .from(ranked)\n .where(lte(ranked.jobRank, WORKFLOW_RUN_JOB_PREVIEW_LIMIT))\n .orderBy(asc(ranked.workflowRunId), asc(ranked.position), asc(ranked.id)),\n countRows: await tx\n .with(selectedExecution)\n .select({\n workflowRunId: workflowRunAttempts.workflowRunId,\n rawStatus: jobs.status,\n status: displayStatus,\n count: count(),\n hasStartedJobExecution,\n })\n .from(jobs)\n .innerJoin(workflowRunAttempts, eq(jobs.workflowRunAttemptId, workflowRunAttempts.id))\n .leftJoin(selectedExecution, eq(selectedExecution.jobId, jobs.id))\n .where(attemptFilter)\n .groupBy(workflowRunAttempts.workflowRunId, jobs.status, displayStatus),\n };\n },\n {isolationLevel: 'repeatable read', accessMode: 'read only'},\n );\n\n for (const {workflowRunId, ...summary} of previewRows) {\n summaryFor(summaries, workflowRunId).preview.push(summary);\n }\n for (const {\n workflowRunId,\n rawStatus,\n status,\n count: statusCount,\n hasStartedJobExecution,\n } of countRows) {\n const summary = summaryFor(summaries, workflowRunId);\n appendStatusCount(summary.rawStatusCounts, rawStatus, statusCount);\n appendStatusCount(summary.statusCounts, status, statusCount);\n // One row per (run, verdict, display status), so the run's answer is the OR of its groups.\n summary.hasStartedJobExecution ||= hasStartedJobExecution;\n }\n\n return summaries;\n}\n\nfunction summaryFor(\n summaries: Map<string, WorkflowRunJobsSummary>,\n workflowRunId: string,\n): WorkflowRunJobsSummary {\n const existing = summaries.get(workflowRunId);\n if (existing) return existing;\n const created: WorkflowRunJobsSummary = {\n preview: [],\n statusCounts: [],\n rawStatusCounts: [],\n hasStartedJobExecution: false,\n };\n summaries.set(workflowRunId, created);\n return created;\n}\n\nfunction appendStatusCount<T extends string>(\n counts: Array<{status: T; count: number}>,\n status: T,\n count: number,\n): void {\n const existing = counts.find((entry) => entry.status === status);\n if (existing) {\n existing.count += count;\n } else {\n counts.push({status, count});\n }\n}\n\nexport async function listWorkflowRunsByProject(projectId: string): Promise<WorkflowRun[]> {\n const result = await listWorkflowRuns({projectId, limit: 100});\n return result.runs;\n}\n\nexport async function getWorkflowRunAggregates(params: {\n projectId: string;\n filters?: WorkflowRunFilters | undefined;\n}): Promise<WorkflowRunAggregates> {\n const [statusRows, triggerRows, workflowRows] = await Promise.all([\n db()\n .select({value: workflowRuns.status, count: count()})\n .from(workflowRuns)\n .where(\n and(\n ...buildWorkflowRunListConditions({\n projectId: params.projectId,\n filters: params.filters,\n omit: 'status',\n }),\n ),\n )\n .groupBy(workflowRuns.status),\n db()\n .select({value: workflowRuns.triggerSource, count: count()})\n .from(workflowRuns)\n .where(\n and(\n ...buildWorkflowRunListConditions({\n projectId: params.projectId,\n filters: params.filters,\n omit: 'triggerSource',\n }),\n ),\n )\n .groupBy(workflowRuns.triggerSource),\n db()\n .select({value: workflowRuns.definitionId, count: count()})\n .from(workflowRuns)\n .where(\n and(\n ...buildWorkflowRunListConditions({\n projectId: params.projectId,\n filters: params.filters,\n omit: 'definitionId',\n }),\n ),\n )\n .groupBy(workflowRuns.definitionId),\n ]);\n\n return {\n status: statusRows,\n triggerSource: triggerRows,\n workflow: workflowRows,\n };\n}\n\nexport async function getWorkflowJobExecutionDepth(\n params: WorkflowJobExecutionDepthParams = {},\n): Promise<WorkflowJobExecutionDepth> {\n const runConditions = [eq(workflowRuns.status, 'running')];\n const jobConditions = [eq(jobExecutions.status, 'running')];\n if (params.workspaceId) {\n runConditions.push(eq(workflowRuns.workspaceId, params.workspaceId));\n jobConditions.push(eq(workflowRuns.workspaceId, params.workspaceId));\n }\n\n const [runRows, jobRows] = await Promise.all([\n db()\n .select({value: count()})\n .from(workflowRuns)\n .where(and(...runConditions)),\n db()\n .select({value: count()})\n .from(jobExecutions)\n .innerJoin(jobs, eq(jobExecutions.jobId, jobs.id))\n .innerJoin(workflowRunAttempts, eq(jobs.workflowRunAttemptId, workflowRunAttempts.id))\n .innerJoin(workflowRuns, eq(workflowRunAttempts.workflowRunId, workflowRuns.id))\n .where(and(...jobConditions)),\n ]);\n\n return {\n runningRuns: runRows[0]?.value ?? 0,\n runningJobExecutions: jobRows[0]?.value ?? 0,\n };\n}\n\nexport async function getWorkflowRunDetail(\n workflowRunId: string,\n attempt?: number | undefined,\n): Promise<WorkflowRunDetail | undefined> {\n const [target] = await db()\n .select({run: workflowRuns, attempt: workflowRunAttempts})\n .from(workflowRuns)\n .innerJoin(\n workflowRunAttempts,\n and(\n eq(workflowRunAttempts.workflowRunId, workflowRuns.id),\n eq(workflowRunAttempts.attempt, attempt ?? workflowRuns.currentAttempt),\n ),\n )\n .where(eq(workflowRuns.id, workflowRunId))\n .limit(1);\n if (!target) return undefined;\n\n const latestAttempt = await getLatestAttempt({\n workflowRunId: target.run.id,\n projectId: target.run.projectId,\n });\n\n const rows = await db()\n .select({\n run: workflowRuns,\n job: jobs,\n jobExecution: jobExecutions,\n step: steps,\n stepAttempt: stepAttempts,\n })\n .from(workflowRuns)\n .innerJoin(workflowRunAttempts, eq(workflowRunAttempts.id, target.attempt.id))\n .leftJoin(jobs, eq(jobs.workflowRunAttemptId, workflowRunAttempts.id))\n .leftJoin(jobExecutions, eq(jobExecutions.jobId, jobs.id))\n .leftJoin(steps, eq(steps.jobExecutionId, jobExecutions.id))\n .leftJoin(stepAttempts, eq(stepAttempts.stepId, steps.id))\n .where(eq(workflowRuns.id, workflowRunId))\n .orderBy(\n asc(jobs.position),\n asc(jobs.id),\n asc(jobExecutions.sequence),\n asc(jobExecutions.id),\n asc(steps.position),\n asc(steps.id),\n asc(stepAttempts.executionOrder),\n asc(stepAttempts.id),\n );\n\n return hydrateWorkflowRunDetail(rows, target.attempt, latestAttempt);\n}\n\nexport async function getJobExecutionDetail(\n jobExecutionId: string,\n): Promise<JobExecutionDetail | undefined> {\n const rows = await db()\n .select({\n job: jobs,\n jobExecution: jobExecutions,\n step: steps,\n stepAttempt: stepAttempts,\n })\n .from(jobExecutions)\n .innerJoin(jobs, eq(jobExecutions.jobId, jobs.id))\n .innerJoin(workflowRunAttempts, eq(jobs.workflowRunAttemptId, workflowRunAttempts.id))\n .innerJoin(workflowRuns, eq(workflowRunAttempts.workflowRunId, workflowRuns.id))\n .leftJoin(steps, eq(steps.jobExecutionId, jobExecutions.id))\n .leftJoin(stepAttempts, eq(stepAttempts.stepId, steps.id))\n .where(eq(jobExecutions.id, jobExecutionId))\n .orderBy(\n asc(steps.position),\n asc(steps.id),\n asc(stepAttempts.executionOrder),\n asc(stepAttempts.id),\n );\n\n const first = rows[0];\n if (!first) return undefined;\n\n const detail: JobExecutionDetail = {\n ...toJobExecution(first.jobExecution, first.job.name ?? first.job.key),\n steps: [],\n };\n const stepById = new Map<string, StepDetail>();\n for (const row of rows) {\n if (row.step) {\n const step = getOrCreateStepDetail(stepById, detail.steps, row.step);\n if (row.stepAttempt) {\n step.attempts.push(toStepAttempt(row.stepAttempt));\n }\n }\n }\n\n return detail;\n}\n\nfunction hydrateWorkflowRunDetail(\n rows: {\n run: typeof workflowRuns.$inferSelect;\n job: typeof jobs.$inferSelect | null;\n jobExecution: typeof jobExecutions.$inferSelect | null;\n step: typeof steps.$inferSelect | null;\n stepAttempt: typeof stepAttempts.$inferSelect | null;\n }[],\n attempt: typeof workflowRunAttempts.$inferSelect,\n latestAttempt: number,\n): WorkflowRunDetail | undefined {\n const first = rows[0];\n if (!first) return undefined;\n\n const detail: WorkflowRunDetail = {\n ...toWorkflowRun(first.run),\n runAttempt: toWorkflowRunAttempt(attempt),\n latestAttempt,\n jobs: [],\n // Read off the same rows the executions come from, so the flag cannot contradict them.\n hasStartedJobExecution: rows.some((row) => row.jobExecution?.startedAt != null),\n };\n const jobById = new Map<string, WorkflowJobDetail>();\n const jobExecutionById = new Map<string, JobExecutionDetail>();\n const stepById = new Map<string, StepDetail>();\n\n for (const row of rows) {\n if (!row.job) continue;\n let job = jobById.get(row.job.id);\n if (!job) {\n job = {...toJob(row.job), jobExecutions: []};\n jobById.set(row.job.id, job);\n detail.jobs.push(job);\n }\n\n if (!row.jobExecution) continue;\n let jobExecution = jobExecutionById.get(row.jobExecution.id);\n if (!jobExecution) {\n jobExecution = {\n ...toJobExecution(row.jobExecution, row.job.name ?? row.job.key),\n steps: [],\n };\n jobExecutionById.set(row.jobExecution.id, jobExecution);\n job.jobExecutions.push(jobExecution);\n }\n\n if (!row.step) continue;\n const step = getOrCreateStepDetail(stepById, jobExecution.steps, row.step);\n if (row.stepAttempt) {\n step.attempts.push(toStepAttempt(row.stepAttempt));\n }\n }\n\n return detail;\n}\n\nfunction getOrCreateStepDetail(\n stepById: Map<string, StepDetail>,\n target: StepDetail[],\n row: typeof steps.$inferSelect,\n): StepDetail {\n let step = stepById.get(row.id);\n if (!step) {\n step = {...toStep(row), attempts: []};\n stepById.set(row.id, step);\n target.push(step);\n }\n return step;\n}\n"],"names":["WORKFLOW_RUN_JOB_PREVIEW_LIMIT","paginateTimestampIdRows","timestampIdCursorWhere","and","asc","count","desc","eq","gte","lte","sql","db","jobExecutions","toJobExecution","jobs","toJob","stepAttempts","toStepAttempt","steps","toStep","toWorkflowRunAttempt","workflowRunAttempts","toWorkflowRun","workflowRuns","getWorkflowRunById","id","rows","select","from","where","limit","row","undefined","getWorkflowRunByAttemptId","workflowRunAttemptId","run","innerJoin","workflowRunId","getWorkflowRunAttemptById","listRunAttempts","params","attempt","projectId","orderBy","map","getLatestAttempt","value","Number","buildWorkflowRunListConditions","filters","conditions","cursorCondition","timestampColumn","createdAt","idColumn","cursor","push","status","omit","definitionId","triggerSource","createdFrom","createdTo","listWorkflowRuns","totalCount","includeTotal","page","timestampKey","runs","pageRows","nextCursor","filteredTotalCount","listWorkflowRunJobSummaries","summaries","Map","length","attemptPairs","join","currentAttempt","attemptFilter","previewRows","countRows","transaction","tx","selectedExecution","$with","as","selectDistinctOn","jobId","executionStatus","sequence","ranked","with","key","name","mode","listenerStatus","position","jobRank","leftJoin","hasStartedJobExecution","startedAt","executionDisplayStatus","displayStatus","rawStatus","groupBy","isolationLevel","accessMode","summary","summaryFor","preview","statusCount","appendStatusCount","rawStatusCounts","statusCounts","existing","get","created","set","counts","find","entry","listWorkflowRunsByProject","result","getWorkflowRunAggregates","statusRows","triggerRows","workflowRows","Promise","all","workflow","getWorkflowJobExecutionDepth","runConditions","jobConditions","workspaceId","runRows","jobRows","runningRuns","runningJobExecutions","getWorkflowRunDetail","target","latestAttempt","job","jobExecution","step","stepAttempt","jobExecutionId","stepId","executionOrder","hydrateWorkflowRunDetail","getJobExecutionDetail","first","detail","stepById","getOrCreateStepDetail","attempts","runAttempt","some","jobById","jobExecutionById"],"mappings":"AAAA,SAAQA,8BAA8B,QAAO,6BAA6B;AAC1E,SACEC,uBAAuB,EAEvBC,sBAAsB,QACjB,wBAAwB;AAC/B,SAAQC,GAAG,EAAEC,GAAG,EAAEC,KAAK,EAAEC,IAAI,EAAEC,EAAE,EAAEC,GAAG,EAAEC,GAAG,EAAYC,GAAG,QAAO,cAAc;AAW/E,SAAQC,EAAE,QAAO,WAAW;AAC5B,SAAQC,aAAa,EAAEC,cAAc,QAAO,8BAA8B;AAC1E,SAAQC,IAAI,EAAEC,KAAK,QAAO,oBAAoB;AAC9C,SAAQC,YAAY,EAAEC,aAAa,QAAO,6BAA6B;AACvE,SAAQC,KAAK,EAAEC,MAAM,QAAO,qBAAqB;AACjD,SAAQC,oBAAoB,EAAEC,mBAAmB,QAAO,qCAAqC;AAC7F,SAAQC,aAAa,EAAEC,YAAY,QAAO,6BAA6B;AAqDvE,OAAO,eAAeC,mBAAmBC,EAAU;IACjD,MAAMC,OAAO,MAAMf,KAAKgB,MAAM,GAAGC,IAAI,CAACL,cAAcM,KAAK,CAACtB,GAAGgB,aAAaE,EAAE,EAAEA,KAAKK,KAAK,CAAC;IACzF,MAAMC,MAAML,IAAI,CAAC,EAAE;IACnB,IAAI,CAACK,KAAK,OAAOC;IACjB,OAAOV,cAAcS;AACvB;AAEA,OAAO,eAAeE,0BACpBC,oBAA4B;IAE5B,MAAMR,OAAO,MAAMf,KAChBgB,MAAM,CAAC;QAACQ,KAAKZ;IAAY,GACzBK,IAAI,CAACP,qBACLe,SAAS,CAACb,cAAchB,GAAGc,oBAAoBgB,aAAa,EAAEd,aAAaE,EAAE,GAC7EI,KAAK,CAACtB,GAAGc,oBAAoBI,EAAE,EAAES,uBACjCJ,KAAK,CAAC;IACT,MAAMC,MAAML,IAAI,CAAC,EAAE;IACn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