@shipfox/api-workflows 7.1.0 → 8.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 +4 -4
- package/CHANGELOG.md +15 -0
- package/dist/core/agent-defaults.d.ts +2 -1
- package/dist/core/agent-defaults.d.ts.map +1 -1
- package/dist/core/agent-defaults.js.map +1 -1
- package/dist/core/agent-tools.d.ts +3 -2
- package/dist/core/agent-tools.d.ts.map +1 -1
- package/dist/core/agent-tools.js.map +1 -1
- package/dist/core/checkout.d.ts +2 -2
- package/dist/core/checkout.d.ts.map +1 -1
- package/dist/core/checkout.js.map +1 -1
- package/dist/core/entities/step.d.ts +2 -1
- package/dist/core/entities/step.d.ts.map +1 -1
- package/dist/core/entities/step.js.map +1 -1
- package/dist/core/run-workflow.d.ts +2 -2
- package/dist/core/run-workflow.d.ts.map +1 -1
- package/dist/core/run-workflow.js.map +1 -1
- package/dist/core/step-config/agent.d.ts +1 -1
- package/dist/core/step-config/agent.d.ts.map +1 -1
- package/dist/core/step-config/agent.js.map +1 -1
- package/dist/db/job-listeners.d.ts +2 -2
- package/dist/db/job-listeners.d.ts.map +1 -1
- package/dist/db/job-listeners.js.map +1 -1
- package/dist/db/workflow-runs/run-create.d.ts +2 -2
- package/dist/db/workflow-runs/run-create.d.ts.map +1 -1
- package/dist/db/workflow-runs/run-create.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/presentation/inter-module.d.ts +2 -2
- package/dist/presentation/inter-module.d.ts.map +1 -1
- package/dist/presentation/inter-module.js +2 -1
- package/dist/presentation/inter-module.js.map +1 -1
- package/dist/presentation/routes/cancel-run.d.ts +1 -1
- package/dist/presentation/routes/cancel-run.d.ts.map +1 -1
- package/dist/presentation/routes/cancel-run.js.map +1 -1
- package/dist/presentation/routes/checkout-token.d.ts +2 -2
- package/dist/presentation/routes/checkout-token.d.ts.map +1 -1
- package/dist/presentation/routes/checkout-token.js +1 -1
- package/dist/presentation/routes/checkout-token.js.map +1 -1
- package/dist/presentation/routes/get-run-aggregates.d.ts +1 -1
- package/dist/presentation/routes/get-run-aggregates.d.ts.map +1 -1
- package/dist/presentation/routes/get-run-aggregates.js.map +1 -1
- package/dist/presentation/routes/get-run.d.ts +1 -1
- package/dist/presentation/routes/get-run.d.ts.map +1 -1
- package/dist/presentation/routes/get-run.js.map +1 -1
- package/dist/presentation/routes/index.d.ts +2 -2
- package/dist/presentation/routes/index.d.ts.map +1 -1
- package/dist/presentation/routes/index.js.map +1 -1
- package/dist/presentation/routes/list-run-attempts.d.ts +1 -1
- package/dist/presentation/routes/list-run-attempts.d.ts.map +1 -1
- package/dist/presentation/routes/list-run-attempts.js.map +1 -1
- package/dist/presentation/routes/list-runs.d.ts +1 -1
- package/dist/presentation/routes/list-runs.d.ts.map +1 -1
- package/dist/presentation/routes/list-runs.js.map +1 -1
- package/dist/presentation/routes/project-access.d.ts +1 -1
- package/dist/presentation/routes/project-access.d.ts.map +1 -1
- package/dist/presentation/routes/project-access.js.map +1 -1
- package/dist/presentation/routes/require-accessible-run.d.ts +1 -1
- package/dist/presentation/routes/require-accessible-run.d.ts.map +1 -1
- package/dist/presentation/routes/require-accessible-run.js.map +1 -1
- package/dist/presentation/routes/rerun-run.d.ts +1 -1
- package/dist/presentation/routes/rerun-run.d.ts.map +1 -1
- package/dist/presentation/routes/rerun-run.js.map +1 -1
- package/dist/temporal/activities/index.d.ts +2 -2
- package/dist/temporal/activities/index.d.ts.map +1 -1
- package/dist/temporal/activities/index.js.map +1 -1
- package/dist/temporal/activities/orchestration-activities.d.ts +2 -2
- package/dist/temporal/activities/orchestration-activities.d.ts.map +1 -1
- package/dist/temporal/activities/orchestration-activities.js.map +1 -1
- package/dist/tsconfig.test.tsbuildinfo +1 -1
- package/package.json +9 -9
- package/src/core/agent-defaults.ts +2 -1
- package/src/core/agent-tool-capability-warning.test.ts +1 -1
- package/src/core/agent-tools.ts +2 -2
- package/src/core/checkout.test.ts +2 -2
- package/src/core/checkout.ts +2 -2
- package/src/core/entities/step.ts +1 -2
- package/src/core/run-workflow.test.ts +2 -0
- package/src/core/run-workflow.ts +2 -2
- package/src/core/step-config/agent.ts +1 -1
- package/src/core/step-config/materialize-workflow-model.test.ts +11 -2
- package/src/db/job-listeners.ts +2 -2
- package/src/db/workflow-runs/run-create.test.ts +11 -2
- package/src/db/workflow-runs/run-create.ts +2 -2
- package/src/index.ts +2 -2
- package/src/presentation/inter-module.ts +4 -7
- package/src/presentation/routes/agent-runtime-config.test.ts +2 -35
- package/src/presentation/routes/cancel-run.test.ts +1 -1
- package/src/presentation/routes/cancel-run.ts +1 -1
- package/src/presentation/routes/checkout-token.test.ts +4 -37
- package/src/presentation/routes/checkout-token.ts +2 -2
- package/src/presentation/routes/get-run-aggregates.test.ts +1 -1
- package/src/presentation/routes/get-run-aggregates.ts +1 -1
- package/src/presentation/routes/get-run.test.ts +1 -1
- package/src/presentation/routes/get-run.ts +1 -1
- package/src/presentation/routes/get-step-secrets.test.ts +2 -2
- package/src/presentation/routes/index.test.ts +3 -3
- package/src/presentation/routes/index.ts +2 -2
- package/src/presentation/routes/list-run-attempts.test.ts +1 -1
- package/src/presentation/routes/list-run-attempts.ts +1 -1
- package/src/presentation/routes/list-runs.test.ts +1 -1
- package/src/presentation/routes/list-runs.ts +1 -1
- package/src/presentation/routes/next-step.test.ts +9 -57
- package/src/presentation/routes/project-access.ts +1 -1
- package/src/presentation/routes/report-step.test.ts +2 -3
- package/src/presentation/routes/require-accessible-run.ts +1 -1
- package/src/presentation/routes/rerun-run.test.ts +1 -1
- package/src/presentation/routes/rerun-run.ts +1 -1
- package/src/temporal/activities/index.ts +2 -2
- package/src/temporal/activities/orchestration-activities.ts +2 -2
- package/test/fixtures/agent-inter-module.ts +31 -1
- package/test/fixtures/auth-inter-module.ts +2 -13
- package/test/fixtures/lease-token.ts +43 -29
- package/test/fixtures/projects-inter-module.ts +1 -1
- package/tsconfig.build.tsbuildinfo +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/db/job-listeners.ts"],"sourcesContent":["import type {AgentInterModuleClient} from '@shipfox/api-agent-dto/inter-module';\nimport {readPersistedWorkflowModel} from '@shipfox/api-definitions-dto';\nimport type {IntegrationsModuleClient} from '@shipfox/api-integration-core-dto';\nimport type {ProjectsModuleClient} from '@shipfox/api-projects-dto';\nimport {\n WORKFLOWS_JOB_ACTIVATED,\n type WorkflowsJobActivatedEventDto,\n} from '@shipfox/api-workflows-dto';\nimport {and, asc, count, eq, inArray, isNull, notInArray, sql} from 'drizzle-orm';\nimport {type AgentDefaultsResolver, createAgentDefaultsResolver} from '#core/agent-defaults.js';\nimport {loadAgentToolMaterializationContext} from '#core/agent-tools.js';\nimport {isJobTerminal, type JobStatus, type ResolutionReason} from '#core/entities/job.js';\nimport type {JobExecutionStatus, WorkflowExecutionEvent} from '#core/entities/job-execution.js';\nimport {type DeriveJobSuccessResult, deriveJobSuccess} from '#core/job-transition/index.js';\nimport {\n type MaterializedListenerExecution,\n materializeListenerExecution,\n} from '#core/listener-execution-materialization.js';\nimport {\n applyListenerFilterSnapshots,\n assembleListenerSnapshotContext,\n type ListenerTriggerWithSnapshot,\n planListenerFilterSnapshots,\n} from '#core/step-config/assemble-run-context.js';\nimport {\n recordListenerEventsCoalesced,\n recordWorkflowJobExecutionStatusChanged,\n recordWorkflowListenerResolved,\n} from '#metrics/instance.js';\nimport {db, type Tx} from './db.js';\nimport {writeWorkflowsOutboxEvent} from './outbox-writes.js';\nimport {type JobExecutionDb, jobExecutions, toJobExecution} from './schema/job-executions.js';\nimport {type JobListenerEventDb, jobListenerEvents} from './schema/job-listener-events.js';\nimport {jobs, toJob} from './schema/jobs.js';\nimport {steps} from './schema/steps.js';\nimport {workflowRunAttempts} from './schema/workflow-run-attempts.js';\nimport {toWorkflowRun, workflowRuns} from './schema/workflow-runs.js';\nimport {\n bulkUpdateStepStatuses,\n getDirectDependencyJobContexts,\n updateJobStatusAtVersion,\n} from './workflow-runs.js';\n\nconst TERMINAL_EXECUTION_STATUSES: JobExecutionStatus[] = ['succeeded', 'failed', 'cancelled'];\nconst MAX_LISTENER_RESOLUTION_ATTEMPTS = 3;\n\nexport interface ActivateJobListenerParams {\n jobId: string;\n expectedVersion: number;\n}\n\nexport interface ActivateJobListenerResult {\n status: 'running' | 'terminal';\n jobStatus: JobStatus;\n jobVersion: number;\n executionCount: number;\n}\n\ntype JobActivatedListenerMatcher = Extract<\n WorkflowsJobActivatedEventDto,\n {mode: 'listening'}\n>['on'][number] &\n ListenerTriggerWithSnapshot;\n\nfunction applyActivatedListenerFilterSnapshots(\n plans: Parameters<typeof applyListenerFilterSnapshots>[0],\n context: Parameters<typeof applyListenerFilterSnapshots>[1],\n): JobActivatedListenerMatcher[] {\n return applyListenerFilterSnapshots(plans, context);\n}\n\nexport async function activateJobListener(\n params: ActivateJobListenerParams,\n): Promise<ActivateJobListenerResult> {\n return await db().transaction(async (tx) => {\n const [target] = await tx\n .select({job: jobs, run: workflowRuns})\n .from(jobs)\n .innerJoin(workflowRunAttempts, eq(jobs.workflowRunAttemptId, workflowRunAttempts.id))\n .innerJoin(workflowRuns, eq(workflowRunAttempts.workflowRunId, workflowRuns.id))\n .where(eq(jobs.id, params.jobId))\n .limit(1)\n .for('update');\n if (!target) throw new Error(`Job not found: ${params.jobId}`);\n\n const [{value: executionCount} = {value: 0}] = await tx\n .select({value: count()})\n .from(jobExecutions)\n .where(eq(jobExecutions.jobId, params.jobId));\n\n if (['succeeded', 'failed', 'cancelled', 'skipped'].includes(target.job.status)) {\n return {\n status: 'terminal',\n jobStatus: target.job.status,\n jobVersion: target.job.version,\n executionCount,\n };\n }\n\n let job = toJob(target.job);\n if (target.job.status === 'pending') {\n const updated = await updateJobStatusAtVersion(tx, {\n jobId: params.jobId,\n status: 'running',\n expectedVersion: params.expectedVersion,\n });\n if (!updated) {\n const [existing] = await tx.select().from(jobs).where(eq(jobs.id, params.jobId)).limit(1);\n if (existing?.status !== 'running') {\n throw new Error(\n `Optimistic lock failure activating listener job ${params.jobId} version ${params.expectedVersion}`,\n );\n }\n job = toJob(existing);\n } else {\n job = updated.job;\n }\n }\n\n const listenerRows = await tx\n .update(jobs)\n .set({listenerStatus: 'listening', updatedAt: new Date()})\n .where(and(eq(jobs.id, params.jobId), eq(jobs.listenerStatus, 'inactive')))\n .returning();\n\n if (listenerRows[0]) {\n const matchers = {\n on: target.job.listeningOn ?? [],\n until: target.job.listeningUntil ?? null,\n };\n const snapshotPlan = planListenerFilterSnapshots(matchers);\n const dependencyJobs =\n snapshotPlan.jobKeys.size === 0\n ? []\n : await getDirectDependencyJobContexts(params.jobId, tx);\n const snapshotContext = assembleListenerSnapshotContext({\n job: toJob(target.job),\n run: toWorkflowRun(target.run),\n triggerPayload: target.run.triggerPayload,\n inputs: target.run.inputs,\n plan: snapshotPlan,\n dependencyJobs,\n });\n\n await writeWorkflowsOutboxEvent(tx, {\n type: WORKFLOWS_JOB_ACTIVATED,\n payload: {\n jobId: params.jobId,\n workflowRunId: target.run.id,\n workspaceId: target.run.workspaceId,\n mode: 'listening',\n on: applyActivatedListenerFilterSnapshots(snapshotPlan.on, snapshotContext),\n until:\n matchers.until === null\n ? null\n : applyActivatedListenerFilterSnapshots(snapshotPlan.until, snapshotContext),\n },\n });\n }\n\n return {status: 'running', jobStatus: job.status, jobVersion: job.version, executionCount};\n });\n}\n\nexport type DrainListenerEventsResult =\n | {\n kind: 'execution';\n jobExecutionId: string;\n executionVersion: number;\n sequence: number;\n requiredLabels: string[];\n status: JobExecutionStatus;\n }\n | {kind: 'resolve-requested'}\n | {kind: 'empty'};\n\nexport interface DrainListenerEventsParams {\n jobId: string;\n expectedSequence: number;\n maxSize?: number | undefined;\n integrations?: IntegrationsModuleClient | undefined;\n projects?: ProjectsModuleClient | undefined;\n resolveAgentDefaults?: AgentDefaultsResolver | undefined;\n agent?: AgentInterModuleClient | undefined;\n}\n\nexport async function drainListenerEventsIntoExecution(\n params: DrainListenerEventsParams,\n): Promise<DrainListenerEventsResult> {\n const drained = await db().transaction(async (tx) => {\n const existing = await findExistingExecution(params, tx);\n if (existing) return {result: existing};\n\n const resolveRequested = await hasPendingResolveEvent(params.jobId, tx);\n if (resolveRequested) return {result: {kind: 'resolve-requested' as const}};\n\n const bufferedEvents = await lockBufferedFireEvents(params, tx);\n if (bufferedEvents.length === 0) return {result: {kind: 'empty' as const}};\n\n const target = await loadListenerMaterializationTarget(params.jobId, tx);\n const model =\n target.attempt.model === null ? null : readPersistedWorkflowModel(target.attempt.model);\n const agentToolContext =\n target.attempt.agentToolMaterialization === null\n ? await loadAgentToolMaterializationContext({\n model,\n workspaceId: target.run.workspaceId,\n projectId: target.run.projectId,\n integrations: params.integrations,\n projects: params.projects,\n })\n : undefined;\n const materialized = await materializeListenerExecution({\n model,\n run: toWorkflowRun(target.run),\n job: toJob(target.job),\n sequence: params.expectedSequence,\n triggerEvents: listenerTriggerEvents(bufferedEvents),\n priorExecutions: target.priorExecutions,\n resolveAgentDefaults:\n params.resolveAgentDefaults ??\n (params.agent\n ? createAgentDefaultsResolver(params.agent, target.run.workspaceId)\n : undefined),\n agentToolContext,\n agentToolSnapshot: target.attempt.agentToolMaterialization,\n });\n const execution = await persistMaterializedListenerExecution(tx, {\n jobId: params.jobId,\n sequence: params.expectedSequence,\n bufferedEventIds: bufferedEvents.map((event) => event.id),\n materialized,\n });\n\n if (materialized.status === 'failed') {\n recordWorkflowJobExecutionStatusChanged(materialized.status);\n }\n\n return {\n result: drainExecutionResult(execution),\n batchSize: bufferedEvents.length,\n };\n });\n\n if (drained.result.kind === 'execution' && drained.batchSize !== undefined) {\n recordListenerEventsCoalesced(drained.batchSize);\n }\n\n return drained.result;\n}\n\nexport interface ListenerBufferPeek {\n fireCount: number;\n resolvePending: boolean;\n oldestAgeMs: number;\n newestAgeMs: number;\n}\n\nexport async function peekListenerBuffer(params: {jobId: string}): Promise<ListenerBufferPeek> {\n const [row] = await db()\n .select({\n fireCount: sql<number>`count(*) filter (where ${jobListenerEvents.disposition} = 'fire')::integer`,\n resolvePending: sql<boolean>`coalesce(bool_or(${jobListenerEvents.disposition} = 'resolve'), false)`,\n oldestAgeMs: sql<number>`coalesce(floor(extract(epoch from (statement_timestamp() - min(${jobListenerEvents.receivedAt}) filter (where ${jobListenerEvents.disposition} = 'fire'))) * 1000), 0)::integer`,\n newestAgeMs: sql<number>`coalesce(floor(extract(epoch from (statement_timestamp() - max(${jobListenerEvents.receivedAt}) filter (where ${jobListenerEvents.disposition} = 'fire'))) * 1000), 0)::integer`,\n })\n .from(jobListenerEvents)\n .where(\n and(\n eq(jobListenerEvents.jobId, params.jobId),\n isNull(jobListenerEvents.consumedByExecutionId),\n ),\n );\n\n return {\n fireCount: row?.fireCount ?? 0,\n resolvePending: row?.resolvePending ?? false,\n oldestAgeMs: row?.oldestAgeMs ?? 0,\n newestAgeMs: row?.newestAgeMs ?? 0,\n };\n}\n\nexport async function resolveJobListener(params: {\n jobId: string;\n reason: ResolutionReason;\n}): Promise<{status: 'succeeded' | 'failed'; jobVersion: number}> {\n let result: ApplyJobListenerResolutionResult | undefined;\n for (let attempt = 0; attempt < MAX_LISTENER_RESOLUTION_ATTEMPTS; attempt += 1) {\n const decision = await deriveJobListenerResolutionDecision(params.jobId);\n result = await applyJobListenerResolution(params, decision);\n if (result.kind === 'applied') break;\n }\n\n if (result?.kind !== 'applied') {\n throw new Error(`Optimistic lock failure resolving listener job ${params.jobId}`);\n }\n\n if (result.changed) recordWorkflowListenerResolved(params.reason);\n return {status: result.status, jobVersion: result.jobVersion};\n}\n\ntype JobListenerResolutionDecision = DeriveJobSuccessResult & {\n expectedVersion: number;\n};\n\ntype ApplyJobListenerResolutionResult =\n | {\n kind: 'applied';\n status: 'succeeded' | 'failed';\n jobVersion: number;\n changed: boolean;\n }\n | {kind: 'stale'};\n\nasync function deriveJobListenerResolutionDecision(\n jobId: string,\n): Promise<JobListenerResolutionDecision> {\n const [jobRow] = await db().select().from(jobs).where(eq(jobs.id, jobId)).limit(1);\n if (!jobRow) throw new Error(`Job not found: ${jobId}`);\n\n const [executionRows, dependencyJobs] = await Promise.all([\n db()\n .select()\n .from(jobExecutions)\n .where(eq(jobExecutions.jobId, jobId))\n .orderBy(asc(jobExecutions.sequence), asc(jobExecutions.id)),\n getDirectDependencyJobContexts(jobId),\n ]);\n return {\n expectedVersion: jobRow.version,\n ...deriveJobSuccess({\n success: jobRow.success,\n executions: executionRows.map(toJobExecution),\n jobs: dependencyJobs,\n }),\n };\n}\n\nasync function applyJobListenerResolution(\n params: {\n jobId: string;\n reason: ResolutionReason;\n },\n decision: JobListenerResolutionDecision,\n): Promise<ApplyJobListenerResolutionResult> {\n return await db().transaction(async (tx) => {\n const [jobRow] = await tx\n .select()\n .from(jobs)\n .where(eq(jobs.id, params.jobId))\n .limit(1)\n .for('update');\n if (!jobRow) throw new Error(`Job not found: ${params.jobId}`);\n\n if (jobRow.version !== decision.expectedVersion && !isJobTerminal(jobRow.status)) {\n return {kind: 'stale' as const};\n }\n\n const listenerRows = await tx\n .update(jobs)\n .set({\n listenerStatus: 'resolved',\n resolutionReason: params.reason,\n updatedAt: new Date(),\n })\n .where(and(eq(jobs.id, params.jobId), notInArray(jobs.listenerStatus, ['resolved'])))\n .returning({id: jobs.id});\n\n const updated = await updateJobStatusAtVersion(tx, {\n jobId: params.jobId,\n status: decision.status,\n expectedVersion: decision.expectedVersion,\n statusReason: decision.statusReason,\n evaluationTrace: decision.trace,\n });\n const job = updated?.job ?? toJob(jobRow);\n const resolvedStatus: 'succeeded' | 'failed' =\n job.status === 'succeeded' ? 'succeeded' : 'failed';\n return {\n kind: 'applied' as const,\n status: resolvedStatus,\n jobVersion: job.version,\n changed: listenerRows.length > 0 || updated?.changed === true,\n };\n });\n}\n\nexport async function settleListenerJobExecution(params: {\n jobExecutionId: string;\n status: Extract<JobExecutionStatus, 'failed' | 'cancelled'>;\n}): Promise<void> {\n const changed = await db().transaction(async (tx) => {\n const [execution] = await tx\n .update(jobExecutions)\n .set({\n status: params.status,\n statusReason: params.status === 'failed' ? 'step_failed' : 'run_cancelled',\n version: sql`${jobExecutions.version} + 1`,\n updatedAt: new Date(),\n finishedAt: sql`now()`,\n })\n .where(\n and(\n eq(jobExecutions.id, params.jobExecutionId),\n notInArray(jobExecutions.status, TERMINAL_EXECUTION_STATUSES),\n ),\n )\n .returning();\n if (!execution) return false;\n await bulkUpdateStepStatuses(\n {jobExecutionId: params.jobExecutionId, status: params.status},\n tx,\n );\n return true;\n });\n\n if (changed) {\n recordWorkflowJobExecutionStatusChanged(params.status);\n }\n}\n\nexport async function countActiveListeners(): Promise<number> {\n const [row] = await db()\n .select({value: count()})\n .from(jobs)\n .where(eq(jobs.listenerStatus, 'listening'));\n return row?.value ?? 0;\n}\n\nasync function findExistingExecution(\n params: DrainListenerEventsParams,\n tx: Tx,\n): Promise<Extract<DrainListenerEventsResult, {kind: 'execution'}> | undefined> {\n const [existing] = await tx\n .select()\n .from(jobExecutions)\n .where(\n and(\n eq(jobExecutions.jobId, params.jobId),\n eq(jobExecutions.sequence, params.expectedSequence),\n ),\n )\n .limit(1);\n if (!existing) return undefined;\n return drainExecutionResult(existing);\n}\n\nasync function hasPendingResolveEvent(jobId: string, tx: Tx): Promise<boolean> {\n const [resolveEvent] = await tx\n .select({id: jobListenerEvents.id})\n .from(jobListenerEvents)\n .where(\n and(\n eq(jobListenerEvents.jobId, jobId),\n eq(jobListenerEvents.disposition, 'resolve'),\n isNull(jobListenerEvents.consumedByExecutionId),\n ),\n )\n .orderBy(asc(jobListenerEvents.receivedAt), asc(jobListenerEvents.id))\n .limit(1)\n .for('update');\n return resolveEvent !== undefined;\n}\n\nasync function lockBufferedFireEvents(\n params: DrainListenerEventsParams,\n tx: Tx,\n): Promise<JobListenerEventDb[]> {\n const bufferedQuery = tx\n .select()\n .from(jobListenerEvents)\n .where(\n and(\n eq(jobListenerEvents.jobId, params.jobId),\n eq(jobListenerEvents.disposition, 'fire'),\n isNull(jobListenerEvents.consumedByExecutionId),\n ),\n )\n .orderBy(asc(jobListenerEvents.receivedAt), asc(jobListenerEvents.id));\n return await (params.maxSize === undefined\n ? bufferedQuery\n : bufferedQuery.limit(params.maxSize)\n ).for('update');\n}\n\nfunction listenerTriggerEvents(\n bufferedEvents: readonly JobListenerEventDb[],\n): WorkflowExecutionEvent[] {\n return bufferedEvents.map((event) => ({\n source: event.source,\n event: event.event,\n delivery_id: event.deliveryId,\n received_at: event.receivedAt.toISOString(),\n data: event.payload,\n }));\n}\n\nasync function persistMaterializedListenerExecution(\n tx: Tx,\n params: {\n readonly jobId: string;\n readonly sequence: number;\n readonly bufferedEventIds: readonly string[];\n readonly materialized: MaterializedListenerExecution;\n },\n): Promise<JobExecutionDb> {\n const [execution] = await tx\n .insert(jobExecutions)\n .values({\n jobId: params.jobId,\n sequence: params.sequence,\n name: params.materialized.name,\n runner: params.materialized.runner.length === 0 ? null : [...params.materialized.runner],\n status: params.materialized.status,\n statusReason: params.materialized.statusReason,\n triggerEvents: [...params.materialized.triggerEvents],\n evaluationTrace: params.materialized.evaluationTrace,\n ...(params.materialized.status === 'failed' ? {finishedAt: sql`now()`} : {}),\n })\n .returning();\n if (!execution) throw new Error('Insert returned no rows');\n\n await tx\n .update(jobListenerEvents)\n .set({consumedByExecutionId: execution.id})\n .where(inArray(jobListenerEvents.id, [...params.bufferedEventIds]));\n\n if (params.materialized.status === 'pending' && params.materialized.steps.length > 0) {\n await tx.insert(steps).values(\n params.materialized.steps.map((step) => ({\n jobExecutionId: execution.id,\n key: step.key,\n name: step.name,\n sourceLocation: step.sourceLocation,\n status: step.status,\n type: step.type,\n config: step.config,\n configPlan: step.configPlan ?? null,\n authoredConfig: step.authoredConfig,\n condition: step.condition ?? null,\n position: step.position,\n })),\n );\n }\n\n return execution;\n}\n\nfunction drainExecutionResult(\n execution: JobExecutionDb,\n): Extract<DrainListenerEventsResult, {kind: 'execution'}> {\n return {\n kind: 'execution',\n jobExecutionId: execution.id,\n executionVersion: execution.version,\n sequence: execution.sequence,\n requiredLabels: execution.runner ?? [],\n status: execution.status,\n };\n}\n\nasync function loadListenerMaterializationTarget(jobId: string, tx: Tx) {\n const [target] = await tx\n .select({job: jobs, attempt: workflowRunAttempts, run: workflowRuns})\n .from(jobs)\n .innerJoin(workflowRunAttempts, eq(jobs.workflowRunAttemptId, workflowRunAttempts.id))\n .innerJoin(workflowRuns, eq(workflowRunAttempts.workflowRunId, workflowRuns.id))\n .where(eq(jobs.id, jobId))\n .limit(1)\n .for('update');\n if (!target) throw new Error(`Job not found: ${jobId}`);\n\n const priorExecutions = await tx\n .select()\n .from(jobExecutions)\n .where(eq(jobExecutions.jobId, jobId))\n .orderBy(asc(jobExecutions.sequence), asc(jobExecutions.id));\n return {...target, priorExecutions: priorExecutions.map(toJobExecution)};\n}\n"],"names":["readPersistedWorkflowModel","WORKFLOWS_JOB_ACTIVATED","and","asc","count","eq","inArray","isNull","notInArray","sql","createAgentDefaultsResolver","loadAgentToolMaterializationContext","isJobTerminal","deriveJobSuccess","materializeListenerExecution","applyListenerFilterSnapshots","assembleListenerSnapshotContext","planListenerFilterSnapshots","recordListenerEventsCoalesced","recordWorkflowJobExecutionStatusChanged","recordWorkflowListenerResolved","db","writeWorkflowsOutboxEvent","jobExecutions","toJobExecution","jobListenerEvents","jobs","toJob","steps","workflowRunAttempts","toWorkflowRun","workflowRuns","bulkUpdateStepStatuses","getDirectDependencyJobContexts","updateJobStatusAtVersion","TERMINAL_EXECUTION_STATUSES","MAX_LISTENER_RESOLUTION_ATTEMPTS","applyActivatedListenerFilterSnapshots","plans","context","activateJobListener","params","transaction","tx","target","select","job","run","from","innerJoin","workflowRunAttemptId","id","workflowRunId","where","jobId","limit","for","Error","value","executionCount","includes","status","jobStatus","jobVersion","version","updated","expectedVersion","existing","listenerRows","update","set","listenerStatus","updatedAt","Date","returning","matchers","on","listeningOn","until","listeningUntil","snapshotPlan","dependencyJobs","jobKeys","size","snapshotContext","triggerPayload","inputs","plan","type","payload","workspaceId","mode","drainListenerEventsIntoExecution","drained","findExistingExecution","result","resolveRequested","hasPendingResolveEvent","kind","bufferedEvents","lockBufferedFireEvents","length","loadListenerMaterializationTarget","model","attempt","agentToolContext","agentToolMaterialization","projectId","integrations","projects","undefined","materialized","sequence","expectedSequence","triggerEvents","listenerTriggerEvents","priorExecutions","resolveAgentDefaults","agent","agentToolSnapshot","execution","persistMaterializedListenerExecution","bufferedEventIds","map","event","drainExecutionResult","batchSize","peekListenerBuffer","row","fireCount","disposition","resolvePending","oldestAgeMs","receivedAt","newestAgeMs","consumedByExecutionId","resolveJobListener","decision","deriveJobListenerResolutionDecision","applyJobListenerResolution","changed","reason","jobRow","executionRows","Promise","all","orderBy","success","executions","resolutionReason","statusReason","evaluationTrace","trace","resolvedStatus","settleListenerJobExecution","finishedAt","jobExecutionId","countActiveListeners","resolveEvent","bufferedQuery","maxSize","source","delivery_id","deliveryId","received_at","toISOString","data","insert","values","name","runner","step","key","sourceLocation","config","configPlan","authoredConfig","condition","position","executionVersion","requiredLabels"],"mappings":"AACA,SAAQA,0BAA0B,QAAO,+BAA+B;AAGxE,SACEC,uBAAuB,QAElB,6BAA6B;AACpC,SAAQC,GAAG,EAAEC,GAAG,EAAEC,KAAK,EAAEC,EAAE,EAAEC,OAAO,EAAEC,MAAM,EAAEC,UAAU,EAAEC,GAAG,QAAO,cAAc;AAClF,SAAoCC,2BAA2B,QAAO,0BAA0B;AAChG,SAAQC,mCAAmC,QAAO,uBAAuB;AACzE,SAAQC,aAAa,QAA8C,wBAAwB;AAE3F,SAAqCC,gBAAgB,QAAO,gCAAgC;AAC5F,SAEEC,4BAA4B,QACvB,8CAA8C;AACrD,SACEC,4BAA4B,EAC5BC,+BAA+B,EAE/BC,2BAA2B,QACtB,4CAA4C;AACnD,SACEC,6BAA6B,EAC7BC,uCAAuC,EACvCC,8BAA8B,QACzB,uBAAuB;AAC9B,SAAQC,EAAE,QAAgB,UAAU;AACpC,S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IAEA,OAAO1D;AACT;AAEA,SAASK,qBACPL,SAAyB;IAEzB,OAAO;QACLtB,MAAM;QACN0D,gBAAgBpC,UAAUrE,EAAE;QAC5BgI,kBAAkB3D,UAAUxD,OAAO;QACnCgD,UAAUQ,UAAUR,QAAQ;QAC5BoE,gBAAgB5D,UAAUkD,MAAM,IAAI,EAAE;QACtC7G,QAAQ2D,UAAU3D,MAAM;IAC1B;AACF;AAEA,eAAeyC,kCAAkChD,KAAa,EAAEX,EAAM;IACpE,MAAM,CAACC,OAAO,GAAG,MAAMD,GACpBE,MAAM,CAAC;QAACC,KAAKpB;QAAM8E,SAAS3E;QAAqBkB,KAAKhB;IAAY,GAClEiB,IAAI,CAACtB,MACLuB,SAAS,CAACpB,qBAAqBxB,GAAGqB,KAAKwB,oBAAoB,EAAErB,oBAAoBsB,EAAE,GACnFF,SAAS,CAAClB,cAAc1B,GAAGwB,oBAAoBuB,aAAa,EAAErB,aAAaoB,EAAE,GAC7EE,KAAK,CAAChD,GAAGqB,KAAKyB,EAAE,EAAEG,QAClBC,KAAK,CAAC,GACNC,GAAG,CAAC;IACP,IAAI,CAACZ,QAAQ,MAAM,IAAIa,MAAM,CAAC,eAAe,EAAEH,OAAO;IAEtD,MAAM8D,kBAAkB,MAAMzE,GAC3BE,MAAM,GACNG,IAAI,CAACzB,eACL8B,KAAK,CAAChD,GAAGkB,cAAc+B,KAAK,EAAEA,QAC9B4F,OAAO,CAAC/I,IAAIoB,cAAcyF,QAAQ,GAAG7G,IAAIoB,cAAc4B,EAAE;IAC5D,OAAO;QAAC,GAAGP,MAAM;QAAEwE,iBAAiBA,gBAAgBO,GAAG,CAACnG;IAAe;AACzE"}
|
|
1
|
+
{"version":3,"sources":["../../src/db/job-listeners.ts"],"sourcesContent":["import type {AgentInterModuleClient} from '@shipfox/api-agent-dto/inter-module';\nimport {readPersistedWorkflowModel} from '@shipfox/api-definitions-dto';\nimport type {IntegrationsModuleClient} from '@shipfox/api-integration-core-dto/inter-module';\nimport type {ProjectsModuleClient} from '@shipfox/api-projects-dto/inter-module';\nimport {\n WORKFLOWS_JOB_ACTIVATED,\n type WorkflowsJobActivatedEventDto,\n} from '@shipfox/api-workflows-dto';\nimport {and, asc, count, eq, inArray, isNull, notInArray, sql} from 'drizzle-orm';\nimport {type AgentDefaultsResolver, createAgentDefaultsResolver} from '#core/agent-defaults.js';\nimport {loadAgentToolMaterializationContext} from '#core/agent-tools.js';\nimport {isJobTerminal, type JobStatus, type ResolutionReason} from '#core/entities/job.js';\nimport type {JobExecutionStatus, WorkflowExecutionEvent} from '#core/entities/job-execution.js';\nimport {type DeriveJobSuccessResult, deriveJobSuccess} from '#core/job-transition/index.js';\nimport {\n type MaterializedListenerExecution,\n materializeListenerExecution,\n} from '#core/listener-execution-materialization.js';\nimport {\n applyListenerFilterSnapshots,\n assembleListenerSnapshotContext,\n type ListenerTriggerWithSnapshot,\n planListenerFilterSnapshots,\n} from '#core/step-config/assemble-run-context.js';\nimport {\n recordListenerEventsCoalesced,\n recordWorkflowJobExecutionStatusChanged,\n recordWorkflowListenerResolved,\n} from '#metrics/instance.js';\nimport {db, type Tx} from './db.js';\nimport {writeWorkflowsOutboxEvent} from './outbox-writes.js';\nimport {type JobExecutionDb, jobExecutions, toJobExecution} from './schema/job-executions.js';\nimport {type JobListenerEventDb, jobListenerEvents} from './schema/job-listener-events.js';\nimport {jobs, toJob} from './schema/jobs.js';\nimport {steps} from './schema/steps.js';\nimport {workflowRunAttempts} from './schema/workflow-run-attempts.js';\nimport {toWorkflowRun, workflowRuns} from './schema/workflow-runs.js';\nimport {\n bulkUpdateStepStatuses,\n getDirectDependencyJobContexts,\n updateJobStatusAtVersion,\n} from './workflow-runs.js';\n\nconst TERMINAL_EXECUTION_STATUSES: JobExecutionStatus[] = ['succeeded', 'failed', 'cancelled'];\nconst MAX_LISTENER_RESOLUTION_ATTEMPTS = 3;\n\nexport interface ActivateJobListenerParams {\n jobId: string;\n expectedVersion: number;\n}\n\nexport interface ActivateJobListenerResult {\n status: 'running' | 'terminal';\n jobStatus: JobStatus;\n jobVersion: number;\n executionCount: number;\n}\n\ntype JobActivatedListenerMatcher = Extract<\n WorkflowsJobActivatedEventDto,\n {mode: 'listening'}\n>['on'][number] &\n ListenerTriggerWithSnapshot;\n\nfunction applyActivatedListenerFilterSnapshots(\n plans: Parameters<typeof applyListenerFilterSnapshots>[0],\n context: Parameters<typeof applyListenerFilterSnapshots>[1],\n): JobActivatedListenerMatcher[] {\n return applyListenerFilterSnapshots(plans, context);\n}\n\nexport async function activateJobListener(\n params: ActivateJobListenerParams,\n): Promise<ActivateJobListenerResult> {\n return await db().transaction(async (tx) => {\n const [target] = await tx\n .select({job: jobs, run: workflowRuns})\n .from(jobs)\n .innerJoin(workflowRunAttempts, eq(jobs.workflowRunAttemptId, workflowRunAttempts.id))\n .innerJoin(workflowRuns, eq(workflowRunAttempts.workflowRunId, workflowRuns.id))\n .where(eq(jobs.id, params.jobId))\n .limit(1)\n .for('update');\n if (!target) throw new Error(`Job not found: ${params.jobId}`);\n\n const [{value: executionCount} = {value: 0}] = await tx\n .select({value: count()})\n .from(jobExecutions)\n .where(eq(jobExecutions.jobId, params.jobId));\n\n if (['succeeded', 'failed', 'cancelled', 'skipped'].includes(target.job.status)) {\n return {\n status: 'terminal',\n jobStatus: target.job.status,\n jobVersion: target.job.version,\n executionCount,\n };\n }\n\n let job = toJob(target.job);\n if (target.job.status === 'pending') {\n const updated = await updateJobStatusAtVersion(tx, {\n jobId: params.jobId,\n status: 'running',\n expectedVersion: params.expectedVersion,\n });\n if (!updated) {\n const [existing] = await tx.select().from(jobs).where(eq(jobs.id, params.jobId)).limit(1);\n if (existing?.status !== 'running') {\n throw new Error(\n `Optimistic lock failure activating listener job ${params.jobId} version ${params.expectedVersion}`,\n );\n }\n job = toJob(existing);\n } else {\n job = updated.job;\n }\n }\n\n const listenerRows = await tx\n .update(jobs)\n .set({listenerStatus: 'listening', updatedAt: new Date()})\n .where(and(eq(jobs.id, params.jobId), eq(jobs.listenerStatus, 'inactive')))\n .returning();\n\n if (listenerRows[0]) {\n const matchers = {\n on: target.job.listeningOn ?? [],\n until: target.job.listeningUntil ?? null,\n };\n const snapshotPlan = planListenerFilterSnapshots(matchers);\n const dependencyJobs =\n snapshotPlan.jobKeys.size === 0\n ? []\n : await getDirectDependencyJobContexts(params.jobId, tx);\n const snapshotContext = assembleListenerSnapshotContext({\n job: toJob(target.job),\n run: toWorkflowRun(target.run),\n triggerPayload: target.run.triggerPayload,\n inputs: target.run.inputs,\n plan: snapshotPlan,\n dependencyJobs,\n });\n\n await writeWorkflowsOutboxEvent(tx, {\n type: WORKFLOWS_JOB_ACTIVATED,\n payload: {\n jobId: params.jobId,\n workflowRunId: target.run.id,\n workspaceId: target.run.workspaceId,\n mode: 'listening',\n on: applyActivatedListenerFilterSnapshots(snapshotPlan.on, snapshotContext),\n until:\n matchers.until === null\n ? null\n : applyActivatedListenerFilterSnapshots(snapshotPlan.until, snapshotContext),\n },\n });\n }\n\n return {status: 'running', jobStatus: job.status, jobVersion: job.version, executionCount};\n });\n}\n\nexport type DrainListenerEventsResult =\n | {\n kind: 'execution';\n jobExecutionId: string;\n executionVersion: number;\n sequence: number;\n requiredLabels: string[];\n status: JobExecutionStatus;\n }\n | {kind: 'resolve-requested'}\n | {kind: 'empty'};\n\nexport interface DrainListenerEventsParams {\n jobId: string;\n expectedSequence: number;\n maxSize?: number | undefined;\n integrations?: IntegrationsModuleClient | undefined;\n projects?: ProjectsModuleClient | undefined;\n resolveAgentDefaults?: AgentDefaultsResolver | undefined;\n agent?: AgentInterModuleClient | undefined;\n}\n\nexport async function drainListenerEventsIntoExecution(\n params: DrainListenerEventsParams,\n): Promise<DrainListenerEventsResult> {\n const drained = await db().transaction(async (tx) => {\n const existing = await findExistingExecution(params, tx);\n if (existing) return {result: existing};\n\n const resolveRequested = await hasPendingResolveEvent(params.jobId, tx);\n if (resolveRequested) return {result: {kind: 'resolve-requested' as const}};\n\n const bufferedEvents = await lockBufferedFireEvents(params, tx);\n if (bufferedEvents.length === 0) return {result: {kind: 'empty' as const}};\n\n const target = await loadListenerMaterializationTarget(params.jobId, tx);\n const model =\n target.attempt.model === null ? null : readPersistedWorkflowModel(target.attempt.model);\n const agentToolContext =\n target.attempt.agentToolMaterialization === null\n ? await loadAgentToolMaterializationContext({\n model,\n workspaceId: target.run.workspaceId,\n projectId: target.run.projectId,\n integrations: params.integrations,\n projects: params.projects,\n })\n : undefined;\n const materialized = await materializeListenerExecution({\n model,\n run: toWorkflowRun(target.run),\n job: toJob(target.job),\n sequence: params.expectedSequence,\n triggerEvents: listenerTriggerEvents(bufferedEvents),\n priorExecutions: target.priorExecutions,\n resolveAgentDefaults:\n params.resolveAgentDefaults ??\n (params.agent\n ? createAgentDefaultsResolver(params.agent, target.run.workspaceId)\n : undefined),\n agentToolContext,\n agentToolSnapshot: target.attempt.agentToolMaterialization,\n });\n const execution = await persistMaterializedListenerExecution(tx, {\n jobId: params.jobId,\n sequence: params.expectedSequence,\n bufferedEventIds: bufferedEvents.map((event) => event.id),\n materialized,\n });\n\n if (materialized.status === 'failed') {\n recordWorkflowJobExecutionStatusChanged(materialized.status);\n }\n\n return {\n result: drainExecutionResult(execution),\n batchSize: bufferedEvents.length,\n };\n });\n\n if (drained.result.kind === 'execution' && drained.batchSize !== undefined) {\n recordListenerEventsCoalesced(drained.batchSize);\n }\n\n return drained.result;\n}\n\nexport interface ListenerBufferPeek {\n fireCount: number;\n resolvePending: boolean;\n oldestAgeMs: number;\n newestAgeMs: number;\n}\n\nexport async function peekListenerBuffer(params: {jobId: string}): Promise<ListenerBufferPeek> {\n const [row] = await db()\n .select({\n fireCount: sql<number>`count(*) filter (where ${jobListenerEvents.disposition} = 'fire')::integer`,\n resolvePending: sql<boolean>`coalesce(bool_or(${jobListenerEvents.disposition} = 'resolve'), false)`,\n oldestAgeMs: sql<number>`coalesce(floor(extract(epoch from (statement_timestamp() - min(${jobListenerEvents.receivedAt}) filter (where ${jobListenerEvents.disposition} = 'fire'))) * 1000), 0)::integer`,\n newestAgeMs: sql<number>`coalesce(floor(extract(epoch from (statement_timestamp() - max(${jobListenerEvents.receivedAt}) filter (where ${jobListenerEvents.disposition} = 'fire'))) * 1000), 0)::integer`,\n })\n .from(jobListenerEvents)\n .where(\n and(\n eq(jobListenerEvents.jobId, params.jobId),\n isNull(jobListenerEvents.consumedByExecutionId),\n ),\n );\n\n return {\n fireCount: row?.fireCount ?? 0,\n resolvePending: row?.resolvePending ?? false,\n oldestAgeMs: row?.oldestAgeMs ?? 0,\n newestAgeMs: row?.newestAgeMs ?? 0,\n };\n}\n\nexport async function resolveJobListener(params: {\n jobId: string;\n reason: ResolutionReason;\n}): Promise<{status: 'succeeded' | 'failed'; jobVersion: number}> {\n let result: ApplyJobListenerResolutionResult | undefined;\n for (let attempt = 0; attempt < MAX_LISTENER_RESOLUTION_ATTEMPTS; attempt += 1) {\n const decision = await deriveJobListenerResolutionDecision(params.jobId);\n result = await applyJobListenerResolution(params, decision);\n if (result.kind === 'applied') break;\n }\n\n if (result?.kind !== 'applied') {\n throw new Error(`Optimistic lock failure resolving listener job ${params.jobId}`);\n }\n\n if (result.changed) recordWorkflowListenerResolved(params.reason);\n return {status: result.status, jobVersion: result.jobVersion};\n}\n\ntype JobListenerResolutionDecision = DeriveJobSuccessResult & {\n expectedVersion: number;\n};\n\ntype ApplyJobListenerResolutionResult =\n | {\n kind: 'applied';\n status: 'succeeded' | 'failed';\n jobVersion: number;\n changed: boolean;\n }\n | {kind: 'stale'};\n\nasync function deriveJobListenerResolutionDecision(\n jobId: string,\n): Promise<JobListenerResolutionDecision> {\n const [jobRow] = await db().select().from(jobs).where(eq(jobs.id, jobId)).limit(1);\n if (!jobRow) throw new Error(`Job not found: ${jobId}`);\n\n const [executionRows, dependencyJobs] = await Promise.all([\n db()\n .select()\n .from(jobExecutions)\n .where(eq(jobExecutions.jobId, jobId))\n .orderBy(asc(jobExecutions.sequence), asc(jobExecutions.id)),\n getDirectDependencyJobContexts(jobId),\n ]);\n return {\n expectedVersion: jobRow.version,\n ...deriveJobSuccess({\n success: jobRow.success,\n executions: executionRows.map(toJobExecution),\n jobs: dependencyJobs,\n }),\n };\n}\n\nasync function applyJobListenerResolution(\n params: {\n jobId: string;\n reason: ResolutionReason;\n },\n decision: JobListenerResolutionDecision,\n): Promise<ApplyJobListenerResolutionResult> {\n return await db().transaction(async (tx) => {\n const [jobRow] = await tx\n .select()\n .from(jobs)\n .where(eq(jobs.id, params.jobId))\n .limit(1)\n .for('update');\n if (!jobRow) throw new Error(`Job not found: ${params.jobId}`);\n\n if (jobRow.version !== decision.expectedVersion && !isJobTerminal(jobRow.status)) {\n return {kind: 'stale' as const};\n }\n\n const listenerRows = await tx\n .update(jobs)\n .set({\n listenerStatus: 'resolved',\n resolutionReason: params.reason,\n updatedAt: new Date(),\n })\n .where(and(eq(jobs.id, params.jobId), notInArray(jobs.listenerStatus, ['resolved'])))\n .returning({id: jobs.id});\n\n const updated = await updateJobStatusAtVersion(tx, {\n jobId: params.jobId,\n status: decision.status,\n expectedVersion: decision.expectedVersion,\n statusReason: decision.statusReason,\n evaluationTrace: decision.trace,\n });\n const job = updated?.job ?? toJob(jobRow);\n const resolvedStatus: 'succeeded' | 'failed' =\n job.status === 'succeeded' ? 'succeeded' : 'failed';\n return {\n kind: 'applied' as const,\n status: resolvedStatus,\n jobVersion: job.version,\n changed: listenerRows.length > 0 || updated?.changed === true,\n };\n });\n}\n\nexport async function settleListenerJobExecution(params: {\n jobExecutionId: string;\n status: Extract<JobExecutionStatus, 'failed' | 'cancelled'>;\n}): Promise<void> {\n const changed = await db().transaction(async (tx) => {\n const [execution] = await tx\n .update(jobExecutions)\n .set({\n status: params.status,\n statusReason: params.status === 'failed' ? 'step_failed' : 'run_cancelled',\n version: sql`${jobExecutions.version} + 1`,\n updatedAt: new Date(),\n finishedAt: sql`now()`,\n })\n .where(\n and(\n eq(jobExecutions.id, params.jobExecutionId),\n notInArray(jobExecutions.status, TERMINAL_EXECUTION_STATUSES),\n ),\n )\n .returning();\n if (!execution) return false;\n await bulkUpdateStepStatuses(\n {jobExecutionId: params.jobExecutionId, status: params.status},\n tx,\n );\n return true;\n });\n\n if (changed) {\n recordWorkflowJobExecutionStatusChanged(params.status);\n }\n}\n\nexport async function countActiveListeners(): Promise<number> {\n const [row] = await db()\n .select({value: count()})\n .from(jobs)\n .where(eq(jobs.listenerStatus, 'listening'));\n return row?.value ?? 0;\n}\n\nasync function findExistingExecution(\n params: DrainListenerEventsParams,\n tx: Tx,\n): Promise<Extract<DrainListenerEventsResult, {kind: 'execution'}> | undefined> {\n const [existing] = await tx\n .select()\n .from(jobExecutions)\n .where(\n and(\n eq(jobExecutions.jobId, params.jobId),\n eq(jobExecutions.sequence, params.expectedSequence),\n ),\n )\n .limit(1);\n if (!existing) return undefined;\n return drainExecutionResult(existing);\n}\n\nasync function hasPendingResolveEvent(jobId: string, tx: Tx): Promise<boolean> {\n const [resolveEvent] = await tx\n .select({id: jobListenerEvents.id})\n .from(jobListenerEvents)\n .where(\n and(\n eq(jobListenerEvents.jobId, jobId),\n eq(jobListenerEvents.disposition, 'resolve'),\n isNull(jobListenerEvents.consumedByExecutionId),\n ),\n )\n .orderBy(asc(jobListenerEvents.receivedAt), asc(jobListenerEvents.id))\n .limit(1)\n .for('update');\n return resolveEvent !== undefined;\n}\n\nasync function lockBufferedFireEvents(\n params: DrainListenerEventsParams,\n tx: Tx,\n): Promise<JobListenerEventDb[]> {\n const bufferedQuery = tx\n .select()\n .from(jobListenerEvents)\n .where(\n and(\n eq(jobListenerEvents.jobId, params.jobId),\n eq(jobListenerEvents.disposition, 'fire'),\n isNull(jobListenerEvents.consumedByExecutionId),\n ),\n )\n .orderBy(asc(jobListenerEvents.receivedAt), asc(jobListenerEvents.id));\n return await (params.maxSize === undefined\n ? bufferedQuery\n : bufferedQuery.limit(params.maxSize)\n ).for('update');\n}\n\nfunction listenerTriggerEvents(\n bufferedEvents: readonly JobListenerEventDb[],\n): WorkflowExecutionEvent[] {\n return bufferedEvents.map((event) => ({\n source: event.source,\n event: event.event,\n delivery_id: event.deliveryId,\n received_at: event.receivedAt.toISOString(),\n data: event.payload,\n }));\n}\n\nasync function persistMaterializedListenerExecution(\n tx: Tx,\n params: {\n readonly jobId: string;\n readonly sequence: number;\n readonly bufferedEventIds: readonly string[];\n readonly materialized: MaterializedListenerExecution;\n },\n): Promise<JobExecutionDb> {\n const [execution] = await tx\n .insert(jobExecutions)\n .values({\n jobId: params.jobId,\n sequence: params.sequence,\n name: params.materialized.name,\n runner: params.materialized.runner.length === 0 ? null : [...params.materialized.runner],\n status: params.materialized.status,\n statusReason: params.materialized.statusReason,\n triggerEvents: [...params.materialized.triggerEvents],\n evaluationTrace: params.materialized.evaluationTrace,\n ...(params.materialized.status === 'failed' ? {finishedAt: sql`now()`} : {}),\n })\n .returning();\n if (!execution) throw new Error('Insert returned no rows');\n\n await tx\n .update(jobListenerEvents)\n .set({consumedByExecutionId: execution.id})\n .where(inArray(jobListenerEvents.id, [...params.bufferedEventIds]));\n\n if (params.materialized.status === 'pending' && params.materialized.steps.length > 0) {\n await tx.insert(steps).values(\n params.materialized.steps.map((step) => ({\n jobExecutionId: execution.id,\n key: step.key,\n name: step.name,\n sourceLocation: step.sourceLocation,\n status: step.status,\n type: step.type,\n config: step.config,\n configPlan: step.configPlan ?? null,\n authoredConfig: step.authoredConfig,\n condition: step.condition ?? null,\n position: step.position,\n })),\n );\n }\n\n return execution;\n}\n\nfunction drainExecutionResult(\n execution: JobExecutionDb,\n): Extract<DrainListenerEventsResult, {kind: 'execution'}> {\n return {\n kind: 'execution',\n jobExecutionId: execution.id,\n executionVersion: execution.version,\n sequence: execution.sequence,\n requiredLabels: execution.runner ?? [],\n status: execution.status,\n };\n}\n\nasync function loadListenerMaterializationTarget(jobId: string, tx: Tx) {\n const [target] = await tx\n .select({job: jobs, attempt: workflowRunAttempts, run: workflowRuns})\n .from(jobs)\n .innerJoin(workflowRunAttempts, eq(jobs.workflowRunAttemptId, workflowRunAttempts.id))\n .innerJoin(workflowRuns, eq(workflowRunAttempts.workflowRunId, workflowRuns.id))\n .where(eq(jobs.id, jobId))\n .limit(1)\n .for('update');\n if (!target) throw new Error(`Job not found: ${jobId}`);\n\n const priorExecutions = await tx\n .select()\n .from(jobExecutions)\n .where(eq(jobExecutions.jobId, jobId))\n .orderBy(asc(jobExecutions.sequence), asc(jobExecutions.id));\n return {...target, priorExecutions: priorExecutions.map(toJobExecution)};\n}\n"],"names":["readPersistedWorkflowModel","WORKFLOWS_JOB_ACTIVATED","and","asc","count","eq","inArray","isNull","notInArray","sql","createAgentDefaultsResolver","loadAgentToolMaterializationContext","isJobTerminal","deriveJobSuccess","materializeListenerExecution","applyListenerFilterSnapshots","assembleListenerSnapshotContext","planListenerFilterSnapshots","recordListenerEventsCoalesced","recordWorkflowJobExecutionStatusChanged","recordWorkflowListenerResolved","db","writeWorkflowsOutboxEvent","jobExecutions","toJobExecution","jobListenerEvents","jobs","toJob","steps","workflowRunAttempts","toWorkflowRun","workflowRuns","bulkUpdateStepStatuses","getDirectDependencyJobContexts","updateJobStatusAtVersion","TERMINAL_EXECUTION_STATUSES","MAX_LISTENER_RESOLUTION_ATTEMPTS","applyActivatedListenerFilterSnapshots","plans","context","activateJobListener","params","transaction","tx","target","select","job","run","from","innerJoin","workflowRunAttemptId","id","workflowRunId","where","jobId","limit","for","Error","value","executionCount","includes","status","jobStatus","jobVersion","version","updated","expectedVersion","existing","listenerRows","update","set","listenerStatus","updatedAt","Date","returning","matchers","on","listeningOn","until","listeningUntil","snapshotPlan","dependencyJobs","jobKeys","size","snapshotContext","triggerPayload","inputs","plan","type","payload","workspaceId","mode","drainListenerEventsIntoExecution","drained","findExistingExecution","result","resolveRequested","hasPendingResolveEvent","kind","bufferedEvents","lockBufferedFireEvents","length","loadListenerMaterializationTarget","model","attempt","agentToolContext","agentToolMaterialization","projectId","integrations","projects","undefined","materialized","sequence","expectedSequence","triggerEvents","listenerTriggerEvents","priorExecutions","resolveAgentDefaults","agent","agentToolSnapshot","execution","persistMaterializedListenerExecution","bufferedEventIds","map","event","drainExecutionResult","batchSize","peekListenerBuffer","row","fireCount","disposition","resolvePending","oldestAgeMs","receivedAt","newestAgeMs","consumedByExecutionId","resolveJobListener","decision","deriveJobListenerResolutionDecision","applyJobListenerResolution","changed","reason","jobRow","executionRows","Promise","all","orderBy","success","executions","resolutionReason","statusReason","evaluationTrace","trace","resolvedStatus","settleListenerJobExecution","finishedAt","jobExecutionId","countActiveListeners","resolveEvent","bufferedQuery","maxSize","source","delivery_id","deliveryId","received_at","toISOString","data","insert","values","name","runner","step","key","sourceLocation","config","configPlan","authoredConfig","condition","position","executionVersion","requiredLabels"],"mappings":"AACA,SAAQA,0BAA0B,QAAO,+BAA+B;AAGxE,SACEC,uBAAuB,QAElB,6BAA6B;AACpC,SAAQC,GAAG,EAAEC,GAAG,EAAEC,KAAK,EAAEC,EAAE,EAAEC,OAAO,EAAEC,MAAM,EAAEC,UAAU,EAAEC,GAAG,QAAO,cAAc;AAClF,SAAoCC,2BAA2B,QAAO,0BAA0B;AAChG,SAAQC,mCAAmC,QAAO,uBAAuB;AACzE,SAAQC,aAAa,QAA8C,wBAAwB;AAE3F,SAAqCC,gBAAgB,QAAO,gCAAgC;AAC5F,SAEEC,4BAA4B,QACvB,8CAA8C;AACrD,SACEC,4BAA4B,EAC5BC,+BAA+B,EAE/BC,2BAA2B,QACtB,4CAA4C;AACnD,SACEC,6BAA6B,EAC7BC,uCAAuC,EACvCC,8BAA8B,QACzB,uBAAuB;AAC9B,SAAQC,EAAE,QAAgB,UAAU;AACpC,SAAQC,yBAAyB,QAAO,qBAAqB;AAC7D,SAA6BC,aAAa,EAAEC,cAAc,QAAO,6BAA6B;AAC9F,SAAiCC,iBAAiB,QAAO,kCAAkC;AAC3F,SAAQC,IAAI,EAAEC,KAAK,QAAO,mBAAmB;AAC7C,SAAQC,KAAK,QAAO,oBAAoB;AACxC,SAAQC,mBAAmB,QAAO,oCAAoC;AAC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AU3D,MAAM;IAC1B;AACF;AAEA,eAAeyC,kCAAkChD,KAAa,EAAEX,EAAM;IACpE,MAAM,CAACC,OAAO,GAAG,MAAMD,GACpBE,MAAM,CAAC;QAACC,KAAKpB;QAAM8E,SAAS3E;QAAqBkB,KAAKhB;IAAY,GAClEiB,IAAI,CAACtB,MACLuB,SAAS,CAACpB,qBAAqBxB,GAAGqB,KAAKwB,oBAAoB,EAAErB,oBAAoBsB,EAAE,GACnFF,SAAS,CAAClB,cAAc1B,GAAGwB,oBAAoBuB,aAAa,EAAErB,aAAaoB,EAAE,GAC7EE,KAAK,CAAChD,GAAGqB,KAAKyB,EAAE,EAAEG,QAClBC,KAAK,CAAC,GACNC,GAAG,CAAC;IACP,IAAI,CAACZ,QAAQ,MAAM,IAAIa,MAAM,CAAC,eAAe,EAAEH,OAAO;IAEtD,MAAM8D,kBAAkB,MAAMzE,GAC3BE,MAAM,GACNG,IAAI,CAACzB,eACL8B,KAAK,CAAChD,GAAGkB,cAAc+B,KAAK,EAAEA,QAC9B4F,OAAO,CAAC/I,IAAIoB,cAAcyF,QAAQ,GAAG7G,IAAIoB,cAAc4B,EAAE;IAC5D,OAAO;QAAC,GAAGP,MAAM;QAAEwE,iBAAiBA,gBAAgBO,GAAG,CAACnG;IAAe;AACzE"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { type WorkflowModel } from '@shipfox/api-definitions-dto';
|
|
2
|
-
import type { IntegrationsModuleClient } from '@shipfox/api-integration-core-dto';
|
|
3
|
-
import type { ProjectsModuleClient } from '@shipfox/api-projects-dto';
|
|
2
|
+
import type { IntegrationsModuleClient } from '@shipfox/api-integration-core-dto/inter-module';
|
|
3
|
+
import type { ProjectsModuleClient } from '@shipfox/api-projects-dto/inter-module';
|
|
4
4
|
import type { SecretsInterModuleClient } from '@shipfox/api-secrets-dto/inter-module';
|
|
5
5
|
import type { AgentDefaultsResolver } from '#core/agent-defaults.js';
|
|
6
6
|
import type { TriggerPayload, WorkflowRun, WorkflowSourceSnapshot } from '#core/entities/workflow-run.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-create.d.ts","sourceRoot":"","sources":["../../../src/db/workflow-runs/run-create.ts"],"names":[],"mappings":"AAAA,OAAO,EAA8B,KAAK,aAAa,EAAC,MAAM,8BAA8B,CAAC;AAC7F,OAAO,KAAK,EAAC,wBAAwB,EAAC,MAAM,
|
|
1
|
+
{"version":3,"file":"run-create.d.ts","sourceRoot":"","sources":["../../../src/db/workflow-runs/run-create.ts"],"names":[],"mappings":"AAAA,OAAO,EAA8B,KAAK,aAAa,EAAC,MAAM,8BAA8B,CAAC;AAC7F,OAAO,KAAK,EAAC,wBAAwB,EAAC,MAAM,gDAAgD,CAAC;AAC7F,OAAO,KAAK,EAAC,oBAAoB,EAAC,MAAM,wCAAwC,CAAC;AACjF,OAAO,KAAK,EAAC,wBAAwB,EAAC,MAAM,uCAAuC,CAAC;AAIpF,OAAO,KAAK,EAAC,qBAAqB,EAAC,MAAM,yBAAyB,CAAC;AAKnE,OAAO,KAAK,EACV,cAAc,EACd,WAAW,EACX,sBAAsB,EACvB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAC,8BAA8B,EAAC,MAAM,iBAAiB,CAAC;AAa/D,MAAM,MAAM,gBAAgB,GAAG,aAAa,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,CAAC;AAE7D,MAAM,WAAW,kBAAkB;IACjC,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,KAAK,EAAE,8BAA8B,CAAC,OAAO,CAAC,CAAC;IACxD,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CACtC;AAED,MAAM,WAAW,uBAAuB;IACtC,WAAW,EAAE,MAAM,CAAC;IACpB,SAAS,EAAE,MAAM,CAAC;IAClB,YAAY,EAAE,MAAM,CAAC;IACrB,IAAI,CAA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-dto';\nimport type {IntegrationsModuleClient} from '@shipfox/api-integration-core-dto';\nimport type {ProjectsModuleClient} from '@shipfox/api-projects-dto';\nimport type {SecretsInterModuleClient} from '@shipfox/api-secrets-dto/inter-module';\nimport {analyzeContextKeyAccess, type ResolvedFieldSegment} from '@shipfox/expression';\nimport {logger} from '@shipfox/node-opentelemetry';\nimport {eq} from 'drizzle-orm';\nimport type {AgentDefaultsResolver} from '#core/agent-defaults.js';\nimport {\n createAgentToolMaterializationSnapshot,\n loadAgentToolMaterializationContext,\n} from '#core/agent-tools.js';\nimport type {\n TriggerPayload,\n WorkflowRun,\n WorkflowSourceSnapshot,\n} from '#core/entities/workflow-run.js';\nimport {InterpolationUnresolvableError} from '#core/errors.js';\nimport type {MaterializedWorkflowJob} from '#core/step-config/materialize-workflow-model.js';\nimport type {WorkflowStepTemplateDiagnostic} from '#core/step-config/resolve-step-config.js';\nimport {\n deriveInitialJobExecutionPlan,\n materializeWorkflowRunJobs,\n} from '#core/workflow-run-creation.js';\nimport {recordWorkflowRunCreated} from '#metrics/instance.js';\nimport {db} from '../db.js';\nimport {workflowRunAttempts} from '../schema/workflow-run-attempts.js';\nimport {toWorkflowRun, workflowRuns} from '../schema/workflow-runs.js';\nimport {type MaterializedRunGraphJob, persistMaterializedRunGraph} from './run-graph.js';\n\nexport type WorkflowModelJob = WorkflowModel['jobs'][number];\n\nexport interface ReferencedVariable {\n readonly key: string;\n readonly field: InterpolationUnresolvableError['field'];\n readonly source: string;\n readonly envKey?: string | undefined;\n}\n\nexport interface CreateWorkflowRunParams {\n workspaceId: string;\n projectId: string;\n definitionId: string;\n name?: string | undefined;\n model: WorkflowModel;\n triggerPayload: TriggerPayload;\n inputs?: Record<string, unknown> | undefined;\n sourceSnapshot?: WorkflowSourceSnapshot | null | undefined;\n triggerIdempotencyKey?: string | undefined;\n resolveAgentDefaults?: AgentDefaultsResolver | undefined;\n secrets?: Pick<SecretsInterModuleClient, 'getVariablesByNamespace'> | undefined;\n integrations?: IntegrationsModuleClient | undefined;\n projects?: ProjectsModuleClient | undefined;\n}\n\nexport async function createWorkflowRun(params: CreateWorkflowRunParams): Promise<WorkflowRun> {\n const agentToolContext =\n params.integrations === undefined\n ? undefined\n : await loadAgentToolMaterializationContext({\n model: params.model,\n workspaceId: params.workspaceId,\n projectId: params.projectId,\n integrations: params.integrations,\n projects: params.projects,\n });\n const agentToolMaterialization = createAgentToolMaterializationSnapshot({\n model: params.model,\n context: agentToolContext,\n });\n const result = await db().transaction(async (tx) => {\n const insertResult = await tx\n .insert(workflowRuns)\n .values({\n workspaceId: params.workspaceId,\n projectId: params.projectId,\n definitionId: params.definitionId,\n name: params.name ?? params.model.name,\n status: 'pending',\n currentAttempt: 1,\n triggerProvider: params.triggerPayload.provider ?? null,\n triggerSource: params.triggerPayload.source,\n triggerEvent: params.triggerPayload.event,\n triggerPayload: params.triggerPayload,\n inputs: params.inputs ?? null,\n sourceSnapshot: params.sourceSnapshot ?? null,\n triggerIdempotencyKey: params.triggerIdempotencyKey ?? null,\n })\n .onConflictDoNothing({target: workflowRuns.triggerIdempotencyKey})\n .returning();\n\n const runRow = insertResult[0];\n if (!runRow) {\n // Conflict path: skip jobs/steps/outbox so the first insert keeps ownership of side effects.\n if (!params.triggerIdempotencyKey) {\n throw new Error('Insert returned no rows');\n }\n const existing = await tx\n .select()\n .from(workflowRuns)\n .where(eq(workflowRuns.triggerIdempotencyKey, params.triggerIdempotencyKey))\n .limit(1);\n const existingRow = existing[0];\n if (!existingRow) {\n throw new Error(\n `Idempotency conflict but existing run missing for key ${params.triggerIdempotencyKey}`,\n );\n }\n return {run: toWorkflowRun(existingRow), created: false};\n }\n\n const run = toWorkflowRun(runRow);\n const [attemptRow] = await tx\n .insert(workflowRunAttempts)\n .values({\n workflowRunId: runRow.id,\n attempt: 1,\n status: 'pending',\n model: createWorkflowModelSnapshot(params.model),\n agentToolMaterialization,\n })\n .returning();\n if (!attemptRow) throw new Error('Insert returned no rows');\n\n // Resolving one-shot templates here gives interpolation access to the inserted run id.\n // If resolution fails, the transaction rolls back the run, jobs, steps, and outbox event together.\n // Listening steps are resolved later when a job execution is created.\n const oneShotJobs = params.model.jobs.filter((job) => job.mode !== 'listening');\n const vars = await loadReferencedVariables({\n model: params.model,\n jobs: oneShotJobs,\n workspaceId: params.workspaceId,\n projectId: params.projectId,\n definitionId: params.definitionId,\n secrets: params.secrets,\n });\n const materializedJobs = await materializeWorkflowRunJobs({\n run,\n model: params.model,\n triggerPayload: params.triggerPayload,\n inputs: params.inputs ?? null,\n vars,\n resolveAgentDefaults: params.resolveAgentDefaults,\n definitionId: params.definitionId,\n agentToolContext,\n agentToolSnapshot: agentToolMaterialization,\n });\n\n const graphJobs = materializeRunGraphJobs({\n params,\n run,\n vars,\n materializedJobs,\n });\n await persistMaterializedRunGraph(tx, {\n run,\n workflowRunAttempt: attemptRow,\n materializedJobs: graphJobs,\n });\n\n logTemplateDiagnostics({\n workflowRunId: runRow.id,\n diagnostics: materializedJobs.flatMap((job) =>\n job.steps.flatMap((step) =>\n (step.diagnostics ?? []).map((diagnostic) => ({\n jobKey: job.key,\n stepName: step.name,\n ...diagnostic,\n })),\n ),\n ),\n });\n\n return {run, created: true};\n });\n\n if (result.created)\n recordWorkflowRunCreated(result.run.triggerPayload.provider ?? result.run.triggerSource);\n\n return result.run;\n}\n\nexport async function loadReferencedVariables(params: {\n readonly model: WorkflowModel;\n readonly jobs?: readonly WorkflowModelJob[] | undefined;\n readonly workspaceId: string;\n readonly projectId: string;\n readonly definitionId: string;\n readonly secrets?: Pick<SecretsInterModuleClient, 'getVariablesByNamespace'> | undefined;\n}): Promise<Record<string, string> | undefined> {\n const references = referencedVariables(params.model, params.jobs ?? params.model.jobs);\n const keys = [...new Set(references.map((reference) => reference.key))].sort();\n if (keys.length === 0) return undefined;\n\n if (!params.secrets) throw new Error('Secrets client is not configured.');\n const {values: vars} = await params.secrets.getVariablesByNamespace({\n workspaceId: params.workspaceId,\n projectId: params.projectId,\n namespace: '',\n });\n const missingKey = keys.find((key) => !(key in vars));\n if (missingKey !== undefined) {\n const reference = references.find((candidate) => candidate.key === missingKey);\n throw new InterpolationUnresolvableError(params.definitionId, {\n field: reference?.field ?? 'env',\n source: reference?.source ?? `vars.${missingKey}`,\n ...(reference?.envKey === undefined ? {} : {envKey: reference.envKey}),\n });\n }\n\n return vars;\n}\n\nfunction materializeRunGraphJobs(params: {\n readonly params: CreateWorkflowRunParams;\n readonly run: WorkflowRun;\n readonly vars: Record<string, string> | undefined;\n readonly materializedJobs: readonly MaterializedWorkflowJob[];\n}): readonly MaterializedRunGraphJob[] {\n return params.materializedJobs.map((job, jobIndex) => ({\n job: {\n key: job.key,\n mode: job.mode,\n name: workflowTemplateSource(job.name),\n status: 'pending' as const,\n checkoutPersistCredentials: job.checkout.persistCredentials,\n checkoutPermissionsContents: job.checkout.permissions.contents,\n success: job.success ?? null,\n executionTimeoutMs: job.executionTimeoutMs ?? null,\n listeningTimeoutMs: job.listening?.timeoutMs ?? null,\n maxExecutions: job.listening?.maxExecutions ?? null,\n onResolve: job.listening?.onResolve ?? null,\n batchDebounceMs: job.listening?.batch?.debounceMs ?? null,\n batchMaxSize: job.listening?.batch?.maxSize ?? null,\n batchMaxWaitMs: job.listening?.batch?.maxWaitMs ?? null,\n listeningOn: job.listening?.on ? [...job.listening.on] : null,\n listeningUntil: job.listening?.until ? [...job.listening.until] : null,\n dependencies: [...job.dependencies],\n runner: job.runner.length === 0 ? null : [...job.runner],\n position: job.position,\n },\n createExecution: (jobRow) => {\n if (jobRow.mode === 'listening') return undefined;\n\n const fallbackName = `${jobRow.key} #1`;\n const modelJob = params.params.model.jobs[jobIndex];\n if (!modelJob) return undefined;\n const executionPlan = deriveInitialJobExecutionPlan({\n run: params.run,\n modelJob,\n job,\n jobId: jobRow.id,\n sequence: 1,\n fallbackName,\n triggerPayload: params.params.triggerPayload,\n inputs: params.params.inputs ?? null,\n vars: params.vars,\n });\n\n return {\n sequence: 1,\n name: executionPlan.name,\n runner: [...executionPlan.runner],\n status: 'pending' as const,\n evaluationTrace:\n executionPlan.evaluationTrace?.length === 0 ? null : executionPlan.evaluationTrace,\n };\n },\n createSteps: () =>\n job.steps.map((step) => ({\n key: step.key,\n name: step.name,\n sourceLocation: step.sourceLocation,\n status: step.status,\n type: step.type,\n config: step.config,\n condition: step.condition ?? null,\n configPlan: step.configPlan ?? null,\n authoredConfig: step.authoredConfig,\n position: step.position,\n })),\n }));\n}\n\nfunction referencedVariables(\n model: WorkflowModel,\n jobs: readonly WorkflowModelJob[],\n): readonly ReferencedVariable[] {\n const references: ReferencedVariable[] = [];\n\n if (jobs.length > 0) {\n collectTemplateVariableReferences(model.templates?.env, references);\n }\n\n for (const job of jobs) {\n collectFieldVariableReferences(job.name, references, {field: 'job.name'});\n for (const template of job.runnerTemplates ?? []) {\n collectFieldVariableReferences(template, references, {field: 'job.runner'});\n }\n collectTemplateVariableReferences(job.outputs, references, {field: 'job.outputs'});\n collectTemplateVariableReferences(job.templates?.env, references);\n\n for (const step of job.steps) {\n collectFieldVariableReferences(step.templates?.name, references, {field: 'step.name'});\n if (step.kind === 'run') {\n collectFieldVariableReferences(step.templates?.command, references, {field: 'run'});\n collectTemplateVariableReferences(step.templates?.env, references);\n } else {\n collectFieldVariableReferences(step.templates?.prompt, references, {field: 'agent.prompt'});\n collectFieldVariableReferences(step.templates?.model, references, {field: 'agent.model'});\n collectFieldVariableReferences(step.templates?.provider, references, {\n field: 'agent.provider',\n });\n }\n }\n }\n\n return references;\n}\n\nfunction collectTemplateVariableReferences(\n templates: Readonly<Record<string, readonly ResolvedFieldSegment[]>> | undefined,\n references: ReferencedVariable[],\n source?: {\n readonly field: InterpolationUnresolvableError['field'];\n },\n): void {\n for (const [envKey, template] of Object.entries(templates ?? {})) {\n collectFieldVariableReferences(\n template,\n references,\n source === undefined ? {field: 'env', envKey} : source,\n );\n }\n}\n\nfunction collectFieldVariableReferences(\n template: readonly ResolvedFieldSegment[] | undefined,\n references: ReferencedVariable[],\n source: {\n readonly field: InterpolationUnresolvableError['field'];\n readonly envKey?: string | undefined;\n },\n): void {\n for (const segment of template ?? []) {\n if (segment.kind === 'literal') continue;\n const keyAccess = analyzeContextKeyAccess(segment.expression);\n for (const reference of keyAccess.references) {\n if (reference.root !== 'vars') continue;\n references.push({\n key: reference.key,\n field: source.field,\n source: segment.expression.source,\n envKey: source.envKey,\n });\n }\n }\n}\n\nfunction workflowTemplateSource(template: MaterializedWorkflowJob['name']): string | null {\n if (template === undefined) return null;\n\n return template\n .map((segment) =>\n segment.kind === 'literal' ? segment.value : `$${'{{'} ${segment.expression.source} ${'}}'}`,\n )\n .join('');\n}\n\nfunction logTemplateDiagnostics(params: {\n readonly workflowRunId: string;\n readonly diagnostics: readonly (WorkflowStepTemplateDiagnostic & {\n readonly jobKey: string;\n readonly stepName: string;\n })[];\n}): void {\n if (params.diagnostics.length === 0) return;\n\n logger().warn(\n {workflowRunId: params.workflowRunId, diagnostics: params.diagnostics},\n 'Workflow interpolation resolved with diagnostics',\n );\n}\n"],"names":["createWorkflowModelSnapshot","analyzeContextKeyAccess","logger","eq","createAgentToolMaterializationSnapshot","loadAgentToolMaterializationContext","InterpolationUnresolvableError","deriveInitialJobExecutionPlan","materializeWorkflowRunJobs","recordWorkflowRunCreated","db","workflowRunAttempts","toWorkflowRun","workflowRuns","persistMaterializedRunGraph","createWorkflowRun","params","agentToolContext","integrations","undefined","model","workspaceId","projectId","projects","agentToolMaterialization","context","result","transaction","tx","insertResult","insert","values","definitionId","name","status","currentAttempt","triggerProvider","triggerPayload","provider","triggerSource","source","triggerEvent","event","inputs","sourceSnapshot","triggerIdempotencyKey","onConflictDoNothing","target","returning","runRow","Error","existing","select","from","where","limit","existingRow","run","created","attemptRow","workflowRunId","id","attempt","oneShotJobs","jobs","filter","job","mode","vars","loadReferencedVariables","secrets","materializedJobs","resolveAgentDefaults","agentToolSnapshot","graphJobs","materializeRunGraphJobs","workflowRunAttempt","logTemplateDiagnostics","diagnostics","flatMap","steps","step","map","diagnostic","jobKey","key","stepName","references","referencedVariables","keys","Set","reference","sort","length","getVariablesByNamespace","namespace","missingKey","find","candidate","field","envKey","jobIndex","workflowTemplateSource","checkoutPersistCredentials","checkout","persistCredentials","checkoutPermissionsContents","permissions","contents","success","executionTimeoutMs","listeningTimeoutMs","listening","timeoutMs","maxExecutions","onResolve","batchDebounceMs","batch","debounceMs","batchMaxSize","maxSize","batchMaxWaitMs","maxWaitMs","listeningOn","on","listeningUntil","until","dependencies","runner","position","createExecution","jobRow","fallbackName","modelJob","executionPlan","jobId","sequence","evaluationTrace","createSteps","sourceLocation","type","config","condition","configPlan","authoredConfig","collectTemplateVariableReferences","templates","env","collectFieldVariableReferences","template","runnerTemplates","outputs","kind","command","prompt","Object","entries","segment","keyAccess","expression","root","push","value","join","warn"],"mappings":"AAAA,SAAQA,2BAA2B,QAA2B,+BAA+B;AAI7F,SAAQC,uBAAuB,QAAkC,sBAAsB;AACvF,SAAQC,MAAM,QAAO,8BAA8B;AACnD,SAAQC,EAAE,QAAO,cAAc;AAE/B,SACEC,sCAAsC,EACtCC,mCAAmC,QAC9B,uBAAuB;AAM9B,SAAQC,8BAA8B,QAAO,kBAAkB;AAG/D,SACEC,6BAA6B,EAC7BC,0BAA0B,QACrB,iCAAiC;AACxC,SAAQC,wBAAwB,QAAO,uBAAuB;AAC9D,SAAQC,EAAE,QAAO,WAAW;AAC5B,SAAQC,mBAAmB,QAAO,qCAAqC;AACvE,SAAQC,aAAa,EAAEC,YAAY,QAAO,6BAA6B;AACvE,SAAsCC,2BAA2B,QAAO,iBAAiB;AA2BzF,OAAO,eAAeC,kBAAkBC,MAA+B;IACrE,MAAMC,mBACJD,OAAOE,YAAY,KAAKC,YACpBA,YACA,MAAMd,oCAAoC;QACxCe,OAAOJ,OAAOI,KAAK;QACnBC,aAAaL,OAAOK,WAAW;QAC/BC,WAAWN,OAAOM,SAAS;QAC3BJ,cAAcF,OAAOE,YAAY;QACjCK,UAAUP,OAAOO,QAAQ;IAC3B;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AAMqH,WAAWR,YAAY,EAAE,CAAE;QACpC,IAAIQ,QAAQL,IAAI,KAAK,WAAW;QAChC,MAAMM,YAAY7J,wBAAwB4J,QAAQE,UAAU;QAC5D,KAAK,MAAMpE,aAAamE,UAAUvE,UAAU,CAAE;YAC5C,IAAII,UAAUqE,IAAI,KAAK,QAAQ;YAC/BzE,WAAW0E,IAAI,CAAC;gBACd5E,KAAKM,UAAUN,GAAG;gBAClBc,OAAO3D,OAAO2D,KAAK;gBACnB3D,QAAQqH,QAAQE,UAAU,CAACvH,MAAM;gBACjC4D,QAAQ5D,OAAO4D,MAAM;YACvB;QACF;IACF;AACF;AAEA,SAASE,uBAAuB+C,QAAyC;IACvE,IAAIA,aAAalI,WAAW,OAAO;IAEnC,OAAOkI,SACJnE,GAAG,CAAC,CAAC2E,UACJA,QAAQL,IAAI,KAAK,YAAYK,QAAQK,KAAK,GAAG,CAAC,CAAC,EAAE,KAAK,CAAC,EAAEL,QAAQE,UAAU,CAACvH,MAAM,CAAC,CAAC,EAAE,MAAM,EAE7F2H,IAAI,CAAC;AACV;AAEA,SAAStF,uBAAuB7D,MAM/B;IACC,IAAIA,OAAO8D,WAAW,CAACe,MAAM,KAAK,GAAG;IAErC3F,SAASkK,IAAI,CACX;QAACxG,eAAe5C,OAAO4C,aAAa;QAAEkB,aAAa9D,OAAO8D,WAAW;IAAA,GACrE;AAEJ"}
|
|
1
|
+
{"version":3,"sources":["../../../src/db/workflow-runs/run-create.ts"],"sourcesContent":["import {createWorkflowModelSnapshot, type WorkflowModel} from '@shipfox/api-definitions-dto';\nimport type {IntegrationsModuleClient} from '@shipfox/api-integration-core-dto/inter-module';\nimport type {ProjectsModuleClient} from '@shipfox/api-projects-dto/inter-module';\nimport type {SecretsInterModuleClient} from '@shipfox/api-secrets-dto/inter-module';\nimport {analyzeContextKeyAccess, type ResolvedFieldSegment} from '@shipfox/expression';\nimport {logger} from '@shipfox/node-opentelemetry';\nimport {eq} from 'drizzle-orm';\nimport type {AgentDefaultsResolver} from '#core/agent-defaults.js';\nimport {\n createAgentToolMaterializationSnapshot,\n loadAgentToolMaterializationContext,\n} from '#core/agent-tools.js';\nimport type {\n TriggerPayload,\n WorkflowRun,\n WorkflowSourceSnapshot,\n} from '#core/entities/workflow-run.js';\nimport {InterpolationUnresolvableError} from '#core/errors.js';\nimport type {MaterializedWorkflowJob} from '#core/step-config/materialize-workflow-model.js';\nimport type {WorkflowStepTemplateDiagnostic} from '#core/step-config/resolve-step-config.js';\nimport {\n deriveInitialJobExecutionPlan,\n materializeWorkflowRunJobs,\n} from '#core/workflow-run-creation.js';\nimport {recordWorkflowRunCreated} from '#metrics/instance.js';\nimport {db} from '../db.js';\nimport {workflowRunAttempts} from '../schema/workflow-run-attempts.js';\nimport {toWorkflowRun, workflowRuns} from '../schema/workflow-runs.js';\nimport {type MaterializedRunGraphJob, persistMaterializedRunGraph} from './run-graph.js';\n\nexport type WorkflowModelJob = WorkflowModel['jobs'][number];\n\nexport interface ReferencedVariable {\n readonly key: string;\n readonly field: InterpolationUnresolvableError['field'];\n readonly source: string;\n readonly envKey?: string | undefined;\n}\n\nexport interface CreateWorkflowRunParams {\n workspaceId: string;\n projectId: string;\n definitionId: string;\n name?: string | undefined;\n model: WorkflowModel;\n triggerPayload: TriggerPayload;\n inputs?: Record<string, unknown> | undefined;\n sourceSnapshot?: WorkflowSourceSnapshot | null | undefined;\n triggerIdempotencyKey?: string | undefined;\n resolveAgentDefaults?: AgentDefaultsResolver | undefined;\n secrets?: Pick<SecretsInterModuleClient, 'getVariablesByNamespace'> | undefined;\n integrations?: IntegrationsModuleClient | undefined;\n projects?: ProjectsModuleClient | undefined;\n}\n\nexport async function createWorkflowRun(params: CreateWorkflowRunParams): Promise<WorkflowRun> {\n const agentToolContext =\n params.integrations === undefined\n ? undefined\n : await loadAgentToolMaterializationContext({\n model: params.model,\n workspaceId: params.workspaceId,\n projectId: params.projectId,\n integrations: params.integrations,\n projects: params.projects,\n });\n const agentToolMaterialization = createAgentToolMaterializationSnapshot({\n model: params.model,\n context: agentToolContext,\n });\n const result = await db().transaction(async (tx) => {\n const insertResult = await tx\n .insert(workflowRuns)\n .values({\n workspaceId: params.workspaceId,\n projectId: params.projectId,\n definitionId: params.definitionId,\n name: params.name ?? params.model.name,\n status: 'pending',\n currentAttempt: 1,\n triggerProvider: params.triggerPayload.provider ?? null,\n triggerSource: params.triggerPayload.source,\n triggerEvent: params.triggerPayload.event,\n triggerPayload: params.triggerPayload,\n inputs: params.inputs ?? null,\n sourceSnapshot: params.sourceSnapshot ?? null,\n triggerIdempotencyKey: params.triggerIdempotencyKey ?? null,\n })\n .onConflictDoNothing({target: workflowRuns.triggerIdempotencyKey})\n .returning();\n\n const runRow = insertResult[0];\n if (!runRow) {\n // Conflict path: skip jobs/steps/outbox so the first insert keeps ownership of side effects.\n if (!params.triggerIdempotencyKey) {\n throw new Error('Insert returned no rows');\n }\n const existing = await tx\n .select()\n .from(workflowRuns)\n .where(eq(workflowRuns.triggerIdempotencyKey, params.triggerIdempotencyKey))\n .limit(1);\n const existingRow = existing[0];\n if (!existingRow) {\n throw new Error(\n `Idempotency conflict but existing run missing for key ${params.triggerIdempotencyKey}`,\n );\n }\n return {run: toWorkflowRun(existingRow), created: false};\n }\n\n const run = toWorkflowRun(runRow);\n const [attemptRow] = await tx\n .insert(workflowRunAttempts)\n .values({\n workflowRunId: runRow.id,\n attempt: 1,\n status: 'pending',\n model: createWorkflowModelSnapshot(params.model),\n agentToolMaterialization,\n })\n .returning();\n if (!attemptRow) throw new Error('Insert returned no rows');\n\n // Resolving one-shot templates here gives interpolation access to the inserted run id.\n // If resolution fails, the transaction rolls back the run, jobs, steps, and outbox event together.\n // Listening steps are resolved later when a job execution is created.\n const oneShotJobs = params.model.jobs.filter((job) => job.mode !== 'listening');\n const vars = await loadReferencedVariables({\n model: params.model,\n jobs: oneShotJobs,\n workspaceId: params.workspaceId,\n projectId: params.projectId,\n definitionId: params.definitionId,\n secrets: params.secrets,\n });\n const materializedJobs = await materializeWorkflowRunJobs({\n run,\n model: params.model,\n triggerPayload: params.triggerPayload,\n inputs: params.inputs ?? null,\n vars,\n resolveAgentDefaults: params.resolveAgentDefaults,\n definitionId: params.definitionId,\n agentToolContext,\n agentToolSnapshot: agentToolMaterialization,\n });\n\n const graphJobs = materializeRunGraphJobs({\n params,\n run,\n vars,\n materializedJobs,\n });\n await persistMaterializedRunGraph(tx, {\n run,\n workflowRunAttempt: attemptRow,\n materializedJobs: graphJobs,\n });\n\n logTemplateDiagnostics({\n workflowRunId: runRow.id,\n diagnostics: materializedJobs.flatMap((job) =>\n job.steps.flatMap((step) =>\n (step.diagnostics ?? []).map((diagnostic) => ({\n jobKey: job.key,\n stepName: step.name,\n ...diagnostic,\n })),\n ),\n ),\n });\n\n return {run, created: true};\n });\n\n if (result.created)\n recordWorkflowRunCreated(result.run.triggerPayload.provider ?? result.run.triggerSource);\n\n return result.run;\n}\n\nexport async function loadReferencedVariables(params: {\n readonly model: WorkflowModel;\n readonly jobs?: readonly WorkflowModelJob[] | undefined;\n readonly workspaceId: string;\n readonly projectId: string;\n readonly definitionId: string;\n readonly secrets?: Pick<SecretsInterModuleClient, 'getVariablesByNamespace'> | undefined;\n}): Promise<Record<string, string> | undefined> {\n const references = referencedVariables(params.model, params.jobs ?? params.model.jobs);\n const keys = [...new Set(references.map((reference) => reference.key))].sort();\n if (keys.length === 0) return undefined;\n\n if (!params.secrets) throw new Error('Secrets client is not configured.');\n const {values: vars} = await params.secrets.getVariablesByNamespace({\n workspaceId: params.workspaceId,\n projectId: params.projectId,\n namespace: '',\n });\n const missingKey = keys.find((key) => !(key in vars));\n if (missingKey !== undefined) {\n const reference = references.find((candidate) => candidate.key === missingKey);\n throw new InterpolationUnresolvableError(params.definitionId, {\n field: reference?.field ?? 'env',\n source: reference?.source ?? `vars.${missingKey}`,\n ...(reference?.envKey === undefined ? {} : {envKey: reference.envKey}),\n });\n }\n\n return vars;\n}\n\nfunction materializeRunGraphJobs(params: {\n readonly params: CreateWorkflowRunParams;\n readonly run: WorkflowRun;\n readonly vars: Record<string, string> | undefined;\n readonly materializedJobs: readonly MaterializedWorkflowJob[];\n}): readonly MaterializedRunGraphJob[] {\n return params.materializedJobs.map((job, jobIndex) => ({\n job: {\n key: job.key,\n mode: job.mode,\n name: workflowTemplateSource(job.name),\n status: 'pending' as const,\n checkoutPersistCredentials: job.checkout.persistCredentials,\n checkoutPermissionsContents: job.checkout.permissions.contents,\n success: job.success ?? null,\n executionTimeoutMs: job.executionTimeoutMs ?? null,\n listeningTimeoutMs: job.listening?.timeoutMs ?? null,\n maxExecutions: job.listening?.maxExecutions ?? null,\n onResolve: job.listening?.onResolve ?? null,\n batchDebounceMs: job.listening?.batch?.debounceMs ?? null,\n batchMaxSize: job.listening?.batch?.maxSize ?? null,\n batchMaxWaitMs: job.listening?.batch?.maxWaitMs ?? null,\n listeningOn: job.listening?.on ? [...job.listening.on] : null,\n listeningUntil: job.listening?.until ? [...job.listening.until] : null,\n dependencies: [...job.dependencies],\n runner: job.runner.length === 0 ? null : [...job.runner],\n position: job.position,\n },\n createExecution: (jobRow) => {\n if (jobRow.mode === 'listening') return undefined;\n\n const fallbackName = `${jobRow.key} #1`;\n const modelJob = params.params.model.jobs[jobIndex];\n if (!modelJob) return undefined;\n const executionPlan = deriveInitialJobExecutionPlan({\n run: params.run,\n modelJob,\n job,\n jobId: jobRow.id,\n sequence: 1,\n fallbackName,\n triggerPayload: params.params.triggerPayload,\n inputs: params.params.inputs ?? null,\n vars: params.vars,\n });\n\n return {\n sequence: 1,\n name: executionPlan.name,\n runner: [...executionPlan.runner],\n status: 'pending' as const,\n evaluationTrace:\n executionPlan.evaluationTrace?.length === 0 ? null : executionPlan.evaluationTrace,\n };\n },\n createSteps: () =>\n job.steps.map((step) => ({\n key: step.key,\n name: step.name,\n sourceLocation: step.sourceLocation,\n status: step.status,\n type: step.type,\n config: step.config,\n condition: step.condition ?? null,\n configPlan: step.configPlan ?? null,\n authoredConfig: step.authoredConfig,\n position: step.position,\n })),\n }));\n}\n\nfunction referencedVariables(\n model: WorkflowModel,\n jobs: readonly WorkflowModelJob[],\n): readonly ReferencedVariable[] {\n const references: ReferencedVariable[] = [];\n\n if (jobs.length > 0) {\n collectTemplateVariableReferences(model.templates?.env, references);\n }\n\n for (const job of jobs) {\n collectFieldVariableReferences(job.name, references, {field: 'job.name'});\n for (const template of job.runnerTemplates ?? []) {\n collectFieldVariableReferences(template, references, {field: 'job.runner'});\n }\n collectTemplateVariableReferences(job.outputs, references, {field: 'job.outputs'});\n collectTemplateVariableReferences(job.templates?.env, references);\n\n for (const step of job.steps) {\n collectFieldVariableReferences(step.templates?.name, references, {field: 'step.name'});\n if (step.kind === 'run') {\n collectFieldVariableReferences(step.templates?.command, references, {field: 'run'});\n collectTemplateVariableReferences(step.templates?.env, references);\n } else {\n collectFieldVariableReferences(step.templates?.prompt, references, {field: 'agent.prompt'});\n collectFieldVariableReferences(step.templates?.model, references, {field: 'agent.model'});\n collectFieldVariableReferences(step.templates?.provider, references, {\n field: 'agent.provider',\n });\n }\n }\n }\n\n return references;\n}\n\nfunction collectTemplateVariableReferences(\n templates: Readonly<Record<string, readonly ResolvedFieldSegment[]>> | undefined,\n references: ReferencedVariable[],\n source?: {\n readonly field: InterpolationUnresolvableError['field'];\n },\n): void {\n for (const [envKey, template] of Object.entries(templates ?? {})) {\n collectFieldVariableReferences(\n template,\n references,\n source === undefined ? {field: 'env', envKey} : source,\n );\n }\n}\n\nfunction collectFieldVariableReferences(\n template: readonly ResolvedFieldSegment[] | undefined,\n references: ReferencedVariable[],\n source: {\n readonly field: InterpolationUnresolvableError['field'];\n readonly envKey?: string | undefined;\n },\n): void {\n for (const segment of template ?? []) {\n if (segment.kind === 'literal') continue;\n const keyAccess = analyzeContextKeyAccess(segment.expression);\n for (const reference of keyAccess.references) {\n if (reference.root !== 'vars') continue;\n references.push({\n key: reference.key,\n field: source.field,\n source: segment.expression.source,\n envKey: source.envKey,\n });\n }\n }\n}\n\nfunction workflowTemplateSource(template: MaterializedWorkflowJob['name']): string | null {\n if (template === undefined) return null;\n\n return template\n .map((segment) =>\n segment.kind === 'literal' ? segment.value : `$${'{{'} ${segment.expression.source} ${'}}'}`,\n )\n .join('');\n}\n\nfunction logTemplateDiagnostics(params: {\n readonly workflowRunId: string;\n readonly diagnostics: readonly (WorkflowStepTemplateDiagnostic & {\n readonly jobKey: string;\n readonly stepName: string;\n })[];\n}): void {\n if (params.diagnostics.length === 0) return;\n\n logger().warn(\n {workflowRunId: params.workflowRunId, diagnostics: params.diagnostics},\n 'Workflow interpolation resolved with diagnostics',\n );\n}\n"],"names":["createWorkflowModelSnapshot","analyzeContextKeyAccess","logger","eq","createAgentToolMaterializationSnapshot","loadAgentToolMaterializationContext","InterpolationUnresolvableError","deriveInitialJobExecutionPlan","materializeWorkflowRunJobs","recordWorkflowRunCreated","db","workflowRunAttempts","toWorkflowRun","workflowRuns","persistMaterializedRunGraph","createWorkflowRun","params","agentToolContext","integrations","undefined","model","workspaceId","projectId","projects","agentToolMaterialization","context","result","transaction","tx","insertResult","insert","values","definitionId","name","status","currentAttempt","triggerProvider","triggerPayload","provider","triggerSource","source","triggerEvent","event","inputs","sourceSnapshot","triggerIdempotencyKey","onConflictDoNothing","target","returning","runRow","Error","existing","select","from","where","limit","existingRow","run","created","attemptRow","workflowRunId","id","attempt","oneShotJobs","jobs","filter","job","mode","vars","loadReferencedVariables","secrets","materializedJobs","resolveAgentDefaults","agentToolSnapshot","graphJobs","materializeRunGraphJobs","workflowRunAttempt","logTemplateDiagnostics","diagnostics","flatMap","steps","step","map","diagnostic","jobKey","key","stepName","references","referencedVariables","keys","Set","reference","sort","length","getVariablesByNamespace","namespace","missingKey","find","candidate","field","envKey","jobIndex","workflowTemplateSource","checkoutPersistCredentials","checkout","persistCredentials","checkoutPermissionsContents","permissions","contents","success","executionTimeoutMs","listeningTimeoutMs","listening","timeoutMs","maxExecutions","onResolve","batchDebounceMs","batch","debounceMs","batchMaxSize","maxSize","batchMaxWaitMs","maxWaitMs","listeningOn","on","listeningUntil","until","dependencies","runner","position","createExecution","jobRow","fallbackName","modelJob","executionPlan","jobId","sequence","evaluationTrace","createSteps","sourceLocation","type","config","condition","configPlan","authoredConfig","collectTemplateVariableReferences","templates","env","collectFieldVariableReferences","template","runnerTemplates","outputs","kind","command","prompt","Object","entries","segment","keyAccess","expression","root","push","value","join","warn"],"mappings":"AAAA,SAAQA,2BAA2B,QAA2B,+BAA+B;AAI7F,SAAQC,uBAAuB,QAAkC,sBAAsB;AACvF,SAAQC,MAAM,QAAO,8BAA8B;AACnD,SAAQC,EAAE,QAAO,cAAc;AAE/B,SACEC,sCAAsC,EACtCC,mCAAmC,QAC9B,uBAAuB;AAM9B,SAAQC,8BAA8B,QAAO,kBAAkB;AAG/D,SACEC,6BAA6B,EAC7BC,0BAA0B,QACrB,iCAAiC;AACxC,SAAQC,wBAAwB,QAAO,uBAAuB;AAC9D,SAAQC,EAAE,QAAO,WAAW;AAC5B,SAAQC,mBAAmB,QAAO,qCAAqC;AACvE,SAAQC,aAAa,EAAEC,YAAY,QAAO,6BAA6B;AACvE,SAAsCC,2BAA2B,QAAO,iBAAiB;AA2BzF,OAAO,eAAeC,kBAAkBC,MAA+B;IACrE,MAAMC,mBACJD,OAAOE,YAAY,KAAKC,YACpBA,YACA,MAAMd,oCAAoC;QACxCe,OAAOJ,OAAOI,KAAK;QACnBC,aAAaL,OAAOK,WAAW;QAC/BC,WAAWN,OAAOM,SAAS;QAC3BJ,cAAcF,OAAOE,YAAY;QACjCK,UAAUP,OAAOO,QAAQ;IAC3B;IACN,MAAMC,2BAA2BpB,uCAAuC;QACtEgB,OAAOJ,OAAOI,KAAK;QACnBK,SAASR;IACX;IACA,MAAMS,SAAS,MAAMhB,KAAKiB,WAAW,CAAC,OAAOC;QAC3C,MAAMC,eAAe,MAAMD,GACxBE,MAAM,CAACjB,cACPkB,MAAM,CAAC;YACNV,aAAaL,OAAOK,WAAW;YAC/BC,WAAWN,OAAOM,S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M,UAAUN,GAAG;gBAClBc,OAAO3D,OAAO2D,KAAK;gBACnB3D,QAAQqH,QAAQE,UAAU,CAACvH,MAAM;gBACjC4D,QAAQ5D,OAAO4D,MAAM;YACvB;QACF;IACF;AACF;AAEA,SAASE,uBAAuB+C,QAAyC;IACvE,IAAIA,aAAalI,WAAW,OAAO;IAEnC,OAAOkI,SACJnE,GAAG,CAAC,CAAC2E,UACJA,QAAQL,IAAI,KAAK,YAAYK,QAAQK,KAAK,GAAG,CAAC,CAAC,EAAE,KAAK,CAAC,EAAEL,QAAQE,UAAU,CAACvH,MAAM,CAAC,CAAC,EAAE,MAAM,EAE7F2H,IAAI,CAAC;AACV;AAEA,SAAStF,uBAAuB7D,MAM/B;IACC,IAAIA,OAAO8D,WAAW,CAACe,MAAM,KAAK,GAAG;IAErC3F,SAASkK,IAAI,CACX;QAACxG,eAAe5C,OAAO4C,aAAa;QAAEkB,aAAa9D,OAAO8D,WAAW;IAAA,GACrE;AAEJ"}
|
package/dist/index.d.ts
CHANGED
|
@@ -2,8 +2,8 @@ import type { AnnotationsInterModuleClient } from '@shipfox/annotations-dto/inte
|
|
|
2
2
|
import type { AgentInterModuleClient } from '@shipfox/api-agent-dto/inter-module';
|
|
3
3
|
import type { AuthInterModuleClient } from '@shipfox/api-auth-dto/inter-module';
|
|
4
4
|
import type { DefinitionsInterModuleClient } from '@shipfox/api-definitions-dto/inter-module';
|
|
5
|
-
import type { IntegrationsModuleClient } from '@shipfox/api-integration-core-dto';
|
|
6
|
-
import type { ProjectsModuleClient } from '@shipfox/api-projects-dto';
|
|
5
|
+
import type { IntegrationsModuleClient } from '@shipfox/api-integration-core-dto/inter-module';
|
|
6
|
+
import type { ProjectsModuleClient } from '@shipfox/api-projects-dto/inter-module';
|
|
7
7
|
import type { RunnersInterModuleClient } from '@shipfox/api-runners-dto/inter-module';
|
|
8
8
|
import type { SecretsInterModuleClient } from '@shipfox/api-secrets-dto/inter-module';
|
|
9
9
|
import { type ShipfoxModule } from '@shipfox/node-module';
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAC,4BAA4B,EAAC,MAAM,uCAAuC,CAAC;AACxF,OAAO,KAAK,EAAC,sBAAsB,EAAC,MAAM,qCAAqC,CAAC;AAChF,OAAO,KAAK,EAAC,qBAAqB,EAAC,MAAM,oCAAoC,CAAC;AAC9E,OAAO,KAAK,EAAC,4BAA4B,EAAC,MAAM,2CAA2C,CAAC;AAC5F,OAAO,KAAK,EAAC,wBAAwB,EAAC,MAAM,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAC,4BAA4B,EAAC,MAAM,uCAAuC,CAAC;AACxF,OAAO,KAAK,EAAC,sBAAsB,EAAC,MAAM,qCAAqC,CAAC;AAChF,OAAO,KAAK,EAAC,qBAAqB,EAAC,MAAM,oCAAoC,CAAC;AAC9E,OAAO,KAAK,EAAC,4BAA4B,EAAC,MAAM,2CAA2C,CAAC;AAC5F,OAAO,KAAK,EAAC,wBAAwB,EAAC,MAAM,gDAAgD,CAAC;AAC7F,OAAO,KAAK,EAAC,oBAAoB,EAAC,MAAM,wCAAwC,CAAC;AAOjF,OAAO,KAAK,EAAC,wBAAwB,EAAC,MAAM,uCAAuC,CAAC;AACpF,OAAO,KAAK,EAAC,wBAAwB,EAAC,MAAM,uCAAuC,CAAC;AASpF,OAAO,EAAC,KAAK,aAAa,EAAoB,MAAM,sBAAsB,CAAC;AAgB3E,YAAY,EACV,GAAG,EACH,gBAAgB,EAChB,2BAA2B,EAC3B,iBAAiB,EACjB,IAAI,EACJ,cAAc,EACd,WAAW,EACX,sBAAsB,GACvB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACL,uBAAuB,EACvB,8BAA8B,EAC9B,2BAA2B,EAC3B,oBAAoB,EACpB,WAAW,EACX,8BAA8B,GAC/B,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACL,OAAO,EACP,KAAK,4BAA4B,EACjC,KAAK,4BAA4B,EACjC,EAAE,EACF,sBAAsB,EACtB,WAAW,EACX,0BAA0B,EAC1B,cAAc,EACd,eAAe,GAChB,MAAM,cAAc,CAAC;AACtB,OAAO,EAAC,qBAAqB,EAAC,MAAM,qCAAqC,CAAC;AAO1E,wBAAgB,qBAAqB,CAAC,EACpC,KAAK,EACL,WAAW,EACX,WAAW,EACX,IAAI,EACJ,YAAY,EACZ,QAAQ,EACR,OAAO,EACP,OAAO,GACR,EAAE;IACD,KAAK,EAAE,sBAAsB,CAAC;IAC9B,WAAW,EAAE,4BAA4B,CAAC;IAC1C,WAAW,EAAE,4BAA4B,CAAC;IAC1C,IAAI,EAAE,qBAAqB,CAAC;IAC5B,YAAY,EAAE,wBAAwB,CAAC;IACvC,QAAQ,EAAE,oBAAoB,CAAC;IAC/B,OAAO,EAAE,wBAAwB,CAAC;IAClC,OAAO,EAAE,wBAAwB,CAAC;CACnC,GAAG,aAAa,CA8ChB"}
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import {dirname, resolve} from 'node:path';\nimport {fileURLToPath} from 'node:url';\nimport type {AnnotationsInterModuleClient} from '@shipfox/annotations-dto/inter-module';\nimport type {AgentInterModuleClient} from '@shipfox/api-agent-dto/inter-module';\nimport type {AuthInterModuleClient} from '@shipfox/api-auth-dto/inter-module';\nimport type {DefinitionsInterModuleClient} from '@shipfox/api-definitions-dto/inter-module';\nimport type {IntegrationsModuleClient} from '@shipfox/api-integration-core-dto';\nimport type {ProjectsModuleClient} from '@shipfox/api-projects-dto';\nimport {\n RUNNER_JOB_CLAIMED,\n RUNNER_JOB_LEASE_EXPIRED,\n RUNNER_JOB_QUEUED,\n type RunnersEventMap,\n} from '@shipfox/api-runners-dto';\nimport type {RunnersInterModuleClient} from '@shipfox/api-runners-dto/inter-module';\nimport type {SecretsInterModuleClient} from '@shipfox/api-secrets-dto/inter-module';\nimport {\n WORKFLOWS_JOB_EVENT_DELIVERED,\n WORKFLOWS_JOB_STEPS_SETTLED,\n WORKFLOWS_WORKFLOW_RUN_ATTEMPT_CREATED,\n WORKFLOWS_WORKFLOW_RUN_CANCELLED,\n type WorkflowsEventMapDto,\n workflowsEventSchemas,\n} from '@shipfox/api-workflows-dto';\nimport {type ShipfoxModule, subscriberFactory} from '@shipfox/node-module';\nimport {db, migrationsPath, workflowsOutbox} from '#db/index.js';\nimport {registerWorkflowsServiceMetrics} from '#metrics/index.js';\nimport {\n createWorkflowRoutes,\n onJobEventDelivered,\n onJobStepsSettled,\n onRunnerJobClaimed,\n onRunnerJobLeaseExpired,\n onRunnerJobQueued,\n onWorkflowRunAttemptCreated,\n onWorkflowRunCancelled,\n} from '#presentation/index.js';\nimport {createWorkflowsInterModulePresentation} from '#presentation/inter-module.js';\nimport {createOrchestrationActivities, WORKFLOWS_TASK_QUEUE} from '#temporal/index.js';\n\nexport type {\n Job,\n JobListenerEvent,\n JobListenerEventDisposition,\n RunWorkflowParams,\n Step,\n TriggerPayload,\n WorkflowRun,\n WorkflowSourceSnapshot,\n} from '#core/index.js';\nexport {\n DefinitionNotFoundError,\n InterpolationUnresolvableError,\n isPermanentRunWorkflowError,\n ProjectMismatchError,\n runWorkflow,\n WorkflowRunNotCancellableError,\n} from '#core/index.js';\nexport {\n closeDb,\n type DeliverEventToListenerParams,\n type DeliverEventToListenerResult,\n db,\n deliverEventToListener,\n getStepById,\n getStepByIdForJobExecution,\n migrationsPath,\n workflowsOutbox,\n} from '#db/index.js';\nexport {loadRunningLeasedStep} from '#presentation/routes/leased-step.js';\n\nconst packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..');\nconst workflowsPath = resolve(packageRoot, 'dist/temporal/workflows/index.js');\n\nconst subscriber = subscriberFactory<WorkflowsEventMapDto & RunnersEventMap>();\n\nexport function createWorkflowsModule({\n agent,\n definitions,\n annotations,\n auth,\n integrations,\n projects,\n runners,\n secrets,\n}: {\n agent: AgentInterModuleClient;\n definitions: DefinitionsInterModuleClient;\n annotations: AnnotationsInterModuleClient;\n auth: AuthInterModuleClient;\n integrations: IntegrationsModuleClient;\n projects: ProjectsModuleClient;\n runners: RunnersInterModuleClient;\n secrets: SecretsInterModuleClient;\n}): ShipfoxModule {\n return {\n name: 'workflows',\n database: {db, migrationsPath},\n routes: createWorkflowRoutes({\n agent,\n annotations,\n auth,\n integrations,\n projects,\n runners,\n secrets,\n }),\n metrics: registerWorkflowsServiceMetrics,\n publishers: [\n {name: 'workflows', table: workflowsOutbox, db, eventSchemas: workflowsEventSchemas},\n ],\n subscribers: [\n subscriber(WORKFLOWS_WORKFLOW_RUN_ATTEMPT_CREATED, onWorkflowRunAttemptCreated),\n subscriber(WORKFLOWS_WORKFLOW_RUN_CANCELLED, onWorkflowRunCancelled),\n subscriber(WORKFLOWS_JOB_EVENT_DELIVERED, onJobEventDelivered),\n subscriber(WORKFLOWS_JOB_STEPS_SETTLED, onJobStepsSettled),\n subscriber(RUNNER_JOB_LEASE_EXPIRED, onRunnerJobLeaseExpired),\n subscriber(RUNNER_JOB_QUEUED, onRunnerJobQueued),\n subscriber(RUNNER_JOB_CLAIMED, onRunnerJobClaimed),\n ],\n workers: [\n {\n taskQueue: WORKFLOWS_TASK_QUEUE,\n workflowsPath,\n activities: () =>\n createOrchestrationActivities({agent, integrations, projects, runners, secrets}),\n workflows: [],\n },\n ],\n interModulePresentations: [\n createWorkflowsInterModulePresentation({\n agent,\n definitions,\n integrations,\n projects,\n runners,\n secrets,\n }),\n ],\n };\n}\n"],"names":["dirname","resolve","fileURLToPath","RUNNER_JOB_CLAIMED","RUNNER_JOB_LEASE_EXPIRED","RUNNER_JOB_QUEUED","WORKFLOWS_JOB_EVENT_DELIVERED","WORKFLOWS_JOB_STEPS_SETTLED","WORKFLOWS_WORKFLOW_RUN_ATTEMPT_CREATED","WORKFLOWS_WORKFLOW_RUN_CANCELLED","workflowsEventSchemas","subscriberFactory","db","migrationsPath","workflowsOutbox","registerWorkflowsServiceMetrics","createWorkflowRoutes","onJobEventDelivered","onJobStepsSettled","onRunnerJobClaimed","onRunnerJobLeaseExpired","onRunnerJobQueued","onWorkflowRunAttemptCreated","onWorkflowRunCancelled","createWorkflowsInterModulePresentation","createOrchestrationActivities","WORKFLOWS_TASK_QUEUE","DefinitionNotFoundError","InterpolationUnresolvableError","isPermanentRunWorkflowError","ProjectMismatchError","runWorkflow","WorkflowRunNotCancellableError","closeDb","deliverEventToListener","getStepById","getStepByIdForJobExecution","loadRunningLeasedStep","packageRoot","url","workflowsPath","subscriber","createWorkflowsModule","agent","definitions","annotations","auth","integrations","projects","runners","secrets","name","database","routes","metrics","publishers","table","eventSchemas","subscribers","workers","taskQueue","activities","workflows","interModulePresentations"],"mappings":"AAAA,SAAQA,OAAO,EAAEC,OAAO,QAAO,YAAY;AAC3C,SAAQC,aAAa,QAAO,WAAW;AAOvC,SACEC,kBAAkB,EAClBC,wBAAwB,EACxBC,iBAAiB,QAEZ,2BAA2B;AAGlC,SACEC,6BAA6B,EAC7BC,2BAA2B,EAC3BC,sCAAsC,EACtCC,gCAAgC,EAEhCC,qBAAqB,QAChB,6BAA6B;AACpC,SAA4BC,iBAAiB,QAAO,uBAAuB;AAC3E,SAAQC,EAAE,EAAEC,cAAc,EAAEC,eAAe,QAAO,eAAe;AACjE,SAAQC,+BAA+B,QAAO,oBAAoB;AAClE,SACEC,oBAAoB,EACpBC,mBAAmB,EACnBC,iBAAiB,EACjBC,kBAAkB,EAClBC,uBAAuB,EACvBC,iBAAiB,EACjBC,2BAA2B,EAC3BC,sBAAsB,QACjB,yBAAyB;AAChC,SAAQC,sCAAsC,QAAO,gCAAgC;AACrF,SAAQC,6BAA6B,EAAEC,oBAAoB,QAAO,qBAAqB;AAYvF,SACEC,uBAAuB,EACvBC,8BAA8B,EAC9BC,2BAA2B,EAC3BC,oBAAoB,EACpBC,WAAW,EACXC,8BAA8B,QACzB,iBAAiB;AACxB,SACEC,OAAO,EAGPrB,EAAE,EACFsB,sBAAsB,EACtBC,WAAW,EACXC,0BAA0B,EAC1BvB,cAAc,EACdC,eAAe,QACV,eAAe;AACtB,SAAQuB,qBAAqB,QAAO,sCAAsC;AAE1E,MAAMC,cAAcrC,QAAQD,QAAQE,cAAc,YAAYqC,GAAG,IAAI;AACrE,MAAMC,gBAAgBvC,QAAQqC,aAAa;AAE3C,MAAMG,aAAa9B;AAEnB,OAAO,SAAS+B,sBAAsB,EACpCC,KAAK,EACLC,WAAW,EACXC,WAAW,EACXC,IAAI,EACJC,YAAY,EACZC,QAAQ,EACRC,OAAO,EACPC,OAAO,EAUR;IACC,OAAO;QACLC,MAAM;QACNC,UAAU;YAACxC;YAAIC;QAAc;QAC7BwC,QAAQrC,qBAAqB;YAC3B2B;YACAE;YACAC;YACAC;YACAC;YACAC;YACAC;QACF;QACAI,SAASvC;QACTwC,YAAY;YACV;gBAACJ,MAAM;gBAAaK,OAAO1C;gBAAiBF;gBAAI6C,cAAc/C;YAAqB;SACpF;QACDgD,aAAa;YACXjB,WAAWjC,wCAAwCc;YACnDmB,WAAWhC,kCAAkCc;YAC7CkB,WAAWnC,+BAA+BW;YAC1CwB,WAAWlC,6BAA6BW;YACxCuB,WAAWrC,0BAA0BgB;YACrCqB,WAAWpC,mBAAmBgB;YAC9BoB,WAAWtC,oBAAoBgB;SAChC;QACDwC,SAAS;YACP;gBACEC,WAAWlC;gBACXc;gBACAqB,YAAY,IACVpC,8BAA8B;wBAACkB;wBAAOI;wBAAcC;wBAAUC;wBAASC;oBAAO;gBAChFY,WAAW,EAAE;YACf;SACD;QACDC,0BAA0B;YACxBvC,uCAAuC;gBACrCmB;gBACAC;gBACAG;gBACAC;gBACAC;gBACAC;YACF;SACD;IACH;AACF"}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import {dirname, resolve} from 'node:path';\nimport {fileURLToPath} from 'node:url';\nimport type {AnnotationsInterModuleClient} from '@shipfox/annotations-dto/inter-module';\nimport type {AgentInterModuleClient} from '@shipfox/api-agent-dto/inter-module';\nimport type {AuthInterModuleClient} from '@shipfox/api-auth-dto/inter-module';\nimport type {DefinitionsInterModuleClient} from '@shipfox/api-definitions-dto/inter-module';\nimport type {IntegrationsModuleClient} from '@shipfox/api-integration-core-dto/inter-module';\nimport type {ProjectsModuleClient} from '@shipfox/api-projects-dto/inter-module';\nimport {\n RUNNER_JOB_CLAIMED,\n RUNNER_JOB_LEASE_EXPIRED,\n RUNNER_JOB_QUEUED,\n type RunnersEventMap,\n} from '@shipfox/api-runners-dto';\nimport type {RunnersInterModuleClient} from '@shipfox/api-runners-dto/inter-module';\nimport type {SecretsInterModuleClient} from '@shipfox/api-secrets-dto/inter-module';\nimport {\n WORKFLOWS_JOB_EVENT_DELIVERED,\n WORKFLOWS_JOB_STEPS_SETTLED,\n WORKFLOWS_WORKFLOW_RUN_ATTEMPT_CREATED,\n WORKFLOWS_WORKFLOW_RUN_CANCELLED,\n type WorkflowsEventMapDto,\n workflowsEventSchemas,\n} from '@shipfox/api-workflows-dto';\nimport {type ShipfoxModule, subscriberFactory} from '@shipfox/node-module';\nimport {db, migrationsPath, workflowsOutbox} from '#db/index.js';\nimport {registerWorkflowsServiceMetrics} from '#metrics/index.js';\nimport {\n createWorkflowRoutes,\n onJobEventDelivered,\n onJobStepsSettled,\n onRunnerJobClaimed,\n onRunnerJobLeaseExpired,\n onRunnerJobQueued,\n onWorkflowRunAttemptCreated,\n onWorkflowRunCancelled,\n} from '#presentation/index.js';\nimport {createWorkflowsInterModulePresentation} from '#presentation/inter-module.js';\nimport {createOrchestrationActivities, WORKFLOWS_TASK_QUEUE} from '#temporal/index.js';\n\nexport type {\n Job,\n JobListenerEvent,\n JobListenerEventDisposition,\n RunWorkflowParams,\n Step,\n TriggerPayload,\n WorkflowRun,\n WorkflowSourceSnapshot,\n} from '#core/index.js';\nexport {\n DefinitionNotFoundError,\n InterpolationUnresolvableError,\n isPermanentRunWorkflowError,\n ProjectMismatchError,\n runWorkflow,\n WorkflowRunNotCancellableError,\n} from '#core/index.js';\nexport {\n closeDb,\n type DeliverEventToListenerParams,\n type DeliverEventToListenerResult,\n db,\n deliverEventToListener,\n getStepById,\n getStepByIdForJobExecution,\n migrationsPath,\n workflowsOutbox,\n} from '#db/index.js';\nexport {loadRunningLeasedStep} from '#presentation/routes/leased-step.js';\n\nconst packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..');\nconst workflowsPath = resolve(packageRoot, 'dist/temporal/workflows/index.js');\n\nconst subscriber = subscriberFactory<WorkflowsEventMapDto & RunnersEventMap>();\n\nexport function createWorkflowsModule({\n agent,\n definitions,\n annotations,\n auth,\n integrations,\n projects,\n runners,\n secrets,\n}: {\n agent: AgentInterModuleClient;\n definitions: DefinitionsInterModuleClient;\n annotations: AnnotationsInterModuleClient;\n auth: AuthInterModuleClient;\n integrations: IntegrationsModuleClient;\n projects: ProjectsModuleClient;\n runners: RunnersInterModuleClient;\n secrets: SecretsInterModuleClient;\n}): ShipfoxModule {\n return {\n name: 'workflows',\n database: {db, migrationsPath},\n routes: createWorkflowRoutes({\n agent,\n annotations,\n auth,\n integrations,\n projects,\n runners,\n secrets,\n }),\n metrics: registerWorkflowsServiceMetrics,\n publishers: [\n {name: 'workflows', table: workflowsOutbox, db, eventSchemas: workflowsEventSchemas},\n ],\n subscribers: [\n subscriber(WORKFLOWS_WORKFLOW_RUN_ATTEMPT_CREATED, onWorkflowRunAttemptCreated),\n subscriber(WORKFLOWS_WORKFLOW_RUN_CANCELLED, onWorkflowRunCancelled),\n subscriber(WORKFLOWS_JOB_EVENT_DELIVERED, onJobEventDelivered),\n subscriber(WORKFLOWS_JOB_STEPS_SETTLED, onJobStepsSettled),\n subscriber(RUNNER_JOB_LEASE_EXPIRED, onRunnerJobLeaseExpired),\n subscriber(RUNNER_JOB_QUEUED, onRunnerJobQueued),\n subscriber(RUNNER_JOB_CLAIMED, onRunnerJobClaimed),\n ],\n workers: [\n {\n taskQueue: WORKFLOWS_TASK_QUEUE,\n workflowsPath,\n activities: () =>\n createOrchestrationActivities({agent, integrations, projects, runners, secrets}),\n workflows: [],\n },\n ],\n interModulePresentations: [\n createWorkflowsInterModulePresentation({\n agent,\n definitions,\n integrations,\n projects,\n runners,\n secrets,\n }),\n ],\n };\n}\n"],"names":["dirname","resolve","fileURLToPath","RUNNER_JOB_CLAIMED","RUNNER_JOB_LEASE_EXPIRED","RUNNER_JOB_QUEUED","WORKFLOWS_JOB_EVENT_DELIVERED","WORKFLOWS_JOB_STEPS_SETTLED","WORKFLOWS_WORKFLOW_RUN_ATTEMPT_CREATED","WORKFLOWS_WORKFLOW_RUN_CANCELLED","workflowsEventSchemas","subscriberFactory","db","migrationsPath","workflowsOutbox","registerWorkflowsServiceMetrics","createWorkflowRoutes","onJobEventDelivered","onJobStepsSettled","onRunnerJobClaimed","onRunnerJobLeaseExpired","onRunnerJobQueued","onWorkflowRunAttemptCreated","onWorkflowRunCancelled","createWorkflowsInterModulePresentation","createOrchestrationActivities","WORKFLOWS_TASK_QUEUE","DefinitionNotFoundError","InterpolationUnresolvableError","isPermanentRunWorkflowError","ProjectMismatchError","runWorkflow","WorkflowRunNotCancellableError","closeDb","deliverEventToListener","getStepById","getStepByIdForJobExecution","loadRunningLeasedStep","packageRoot","url","workflowsPath","subscriber","createWorkflowsModule","agent","definitions","annotations","auth","integrations","projects","runners","secrets","name","database","routes","metrics","publishers","table","eventSchemas","subscribers","workers","taskQueue","activities","workflows","interModulePresentations"],"mappings":"AAAA,SAAQA,OAAO,EAAEC,OAAO,QAAO,YAAY;AAC3C,SAAQC,aAAa,QAAO,WAAW;AAOvC,SACEC,kBAAkB,EAClBC,wBAAwB,EACxBC,iBAAiB,QAEZ,2BAA2B;AAGlC,SACEC,6BAA6B,EAC7BC,2BAA2B,EAC3BC,sCAAsC,EACtCC,gCAAgC,EAEhCC,qBAAqB,QAChB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1CwB,WAAWlC,6BAA6BW;YACxCuB,WAAWrC,0BAA0BgB;YACrCqB,WAAWpC,mBAAmBgB;YAC9BoB,WAAWtC,oBAAoBgB;SAChC;QACDwC,SAAS;YACP;gBACEC,WAAWlC;gBACXc;gBACAqB,YAAY,IACVpC,8BAA8B;wBAACkB;wBAAOI;wBAAcC;wBAAUC;wBAASC;oBAAO;gBAChFY,WAAW,EAAE;YACf;SACD;QACDC,0BAA0B;YACxBvC,uCAAuC;gBACrCmB;gBACAC;gBACAG;gBACAC;gBACAC;gBACAC;YACF;SACD;IACH;AACF"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { AgentInterModuleClient } from '@shipfox/api-agent-dto/inter-module';
|
|
2
2
|
import type { DefinitionsInterModuleClient } from '@shipfox/api-definitions-dto/inter-module';
|
|
3
|
-
import type { IntegrationsModuleClient } from '@shipfox/api-integration-core-dto';
|
|
4
|
-
import type { ProjectsModuleClient } from '@shipfox/api-projects-dto';
|
|
3
|
+
import type { IntegrationsModuleClient } from '@shipfox/api-integration-core-dto/inter-module';
|
|
4
|
+
import type { ProjectsModuleClient } from '@shipfox/api-projects-dto/inter-module';
|
|
5
5
|
import type { RunnersInterModuleClient } from '@shipfox/api-runners-dto/inter-module';
|
|
6
6
|
import type { SecretsInterModuleClient } from '@shipfox/api-secrets-dto/inter-module';
|
|
7
7
|
import { workflowsInterModuleContract } from '@shipfox/api-workflows-dto/inter-module';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"inter-module.d.ts","sourceRoot":"","sources":["../../src/presentation/inter-module.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"inter-module.d.ts","sourceRoot":"","sources":["../../src/presentation/inter-module.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAC,sBAAsB,EAAC,MAAM,qCAAqC,CAAC;AAChF,OAAO,KAAK,EAAC,4BAA4B,EAAC,MAAM,2CAA2C,CAAC;AAC5F,OAAO,KAAK,EAAC,wBAAwB,EAAC,MAAM,gDAAgD,CAAC;AAC7F,OAAO,KAAK,EAAC,oBAAoB,EAAC,MAAM,wCAAwC,CAAC;AACjF,OAAO,KAAK,EAAC,wBAAwB,EAAC,MAAM,uCAAuC,CAAC;AACpF,OAAO,KAAK,EAAC,wBAAwB,EAAC,MAAM,uCAAuC,CAAC;AACpF,OAAO,EAAC,4BAA4B,EAAC,MAAM,yCAAyC,CAAC;AACrF,OAAO,EAGL,KAAK,uBAAuB,EAC7B,MAAM,uBAAuB,CAAC;AAc/B,wBAAgB,sCAAsC,CAAC,MAAM,EAAE;IAC7D,KAAK,EAAE,sBAAsB,CAAC;IAC9B,WAAW,EAAE,4BAA4B,CAAC;IAC1C,OAAO,EAAE,IAAI,CAAC,wBAAwB,EAAE,yBAAyB,CAAC,CAAC;IACnE,OAAO,EAAE,wBAAwB,CAAC;IAClC,YAAY,EAAE,wBAAwB,CAAC;IACvC,QAAQ,EAAE,oBAAoB,CAAC;CAChC,GAAG,uBAAuB,CAAC,OAAO,4BAA4B,CAAC,CA+D/D;AAED,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,OAAO,EAAE,YAAY,EAAE,MAAM,GAAG,OAAO,CA8BlF"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { materializedAgentStepConfigSchema } from '@shipfox/api-agent-dto';
|
|
2
2
|
import { workflowsInterModuleContract } from '@shipfox/api-workflows-dto/inter-module';
|
|
3
3
|
import { createInterModuleKnownError, defineInterModulePresentation } from '@shipfox/inter-module';
|
|
4
|
+
import { DEFAULT_HARNESS, harnessSchema } from '@shipfox/workflow-document';
|
|
4
5
|
import { InvalidJobRunnerLabelsError } from '#core/errors.js';
|
|
5
6
|
import { AgentConfigUnresolvableError, AgentIntegrationMaterializationError, DefinitionNotFoundError, InterpolationUnresolvableError, ProjectMismatchError, runWorkflow } from '#core/index.js';
|
|
6
7
|
import { getJobScope, getStepById, getStepByIdForJobExecution } from '#db/index.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/presentation/inter-module.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"sources":["../../src/presentation/inter-module.ts"],"sourcesContent":["import {materializedAgentStepConfigSchema} from '@shipfox/api-agent-dto';\nimport type {AgentInterModuleClient} from '@shipfox/api-agent-dto/inter-module';\nimport type {DefinitionsInterModuleClient} from '@shipfox/api-definitions-dto/inter-module';\nimport type {IntegrationsModuleClient} from '@shipfox/api-integration-core-dto/inter-module';\nimport type {ProjectsModuleClient} from '@shipfox/api-projects-dto/inter-module';\nimport type {RunnersInterModuleClient} from '@shipfox/api-runners-dto/inter-module';\nimport type {SecretsInterModuleClient} from '@shipfox/api-secrets-dto/inter-module';\nimport {workflowsInterModuleContract} from '@shipfox/api-workflows-dto/inter-module';\nimport {\n createInterModuleKnownError,\n defineInterModulePresentation,\n type InterModulePresentation,\n} from '@shipfox/inter-module';\nimport {DEFAULT_HARNESS, harnessSchema} from '@shipfox/workflow-document';\nimport {InvalidJobRunnerLabelsError} from '#core/errors.js';\nimport {\n AgentConfigUnresolvableError,\n AgentIntegrationMaterializationError,\n DefinitionNotFoundError,\n InterpolationUnresolvableError,\n ProjectMismatchError,\n runWorkflow,\n} from '#core/index.js';\nimport {getJobScope, getStepById, getStepByIdForJobExecution} from '#db/index.js';\nimport {deliverEventToListener} from '#db/job-listener-events.js';\n\nexport function createWorkflowsInterModulePresentation(params: {\n agent: AgentInterModuleClient;\n definitions: DefinitionsInterModuleClient;\n secrets: Pick<SecretsInterModuleClient, 'getVariablesByNamespace'>;\n runners: RunnersInterModuleClient;\n integrations: IntegrationsModuleClient;\n projects: ProjectsModuleClient;\n}): InterModulePresentation<typeof workflowsInterModuleContract> {\n return defineInterModulePresentation(workflowsInterModuleContract, {\n startRunFromTrigger: async (input) => {\n try {\n const run = await runWorkflow(\n params.definitions,\n {\n agent: params.agent,\n workspaceId: input.workspaceId,\n projectId: input.projectId,\n definitionId: input.definitionId,\n triggerPayload: input.triggerPayload,\n inputs: input.inputs,\n triggerIdempotencyKey: input.idempotencyKey,\n integrations: params.integrations,\n projects: params.projects,\n },\n {secrets: params.secrets},\n );\n return {id: run.id, name: run.name};\n } catch (error) {\n throw toStartRunKnownError(error, input.definitionId);\n }\n },\n deliverEventToJobListener: async (input) =>\n await deliverEventToListener({...input, receivedAt: new Date(input.receivedAt)}),\n getStepLogContext: async ({stepId}) => {\n const step = await getStepById(stepId);\n const parsed = harnessSchema.safeParse(step?.config.harness);\n return {harness: parsed.success ? parsed.data : DEFAULT_HARNESS};\n },\n getLeasedAgentToolContext: async (input) => {\n const method = workflowsInterModuleContract.methods.getLeasedAgentToolContext;\n const {active: leaseIsActive} = await params.runners.getLeaseState({\n jobId: input.jobId,\n jobExecutionId: input.jobExecutionId,\n runnerSessionId: input.runnerSessionId,\n });\n if (!leaseIsActive) throw createInterModuleKnownError(method, 'lease-not-active', {});\n\n const step = await getStepByIdForJobExecution({\n stepId: input.stepId,\n jobExecutionId: input.jobExecutionId,\n });\n if (!step) throw createInterModuleKnownError(method, 'step-not-found', {});\n\n const scope = await getJobScope(input.jobId);\n if (!scope) throw createInterModuleKnownError(method, 'job-not-found', {});\n if (step.currentAttempt !== input.attempt) {\n throw createInterModuleKnownError(method, 'step-attempt-mismatch', {});\n }\n if (step.status !== 'running')\n throw createInterModuleKnownError(method, 'step-not-running', {});\n if (step.type !== 'agent')\n throw createInterModuleKnownError(method, 'leased-step-not-agent', {});\n\n const config = materializedAgentStepConfigSchema.safeParse(step.config);\n if (!config.success) {\n throw createInterModuleKnownError(method, 'agent-step-config-invalid', {});\n }\n return {workspaceId: scope.workspaceId, integrations: config.data.integrations ?? []};\n },\n });\n}\n\nexport function toStartRunKnownError(error: unknown, definitionId: string): unknown {\n const method = workflowsInterModuleContract.methods.startRunFromTrigger;\n if (error instanceof DefinitionNotFoundError) {\n return createInterModuleKnownError(method, 'definition-not-found', {definitionId});\n }\n if (error instanceof ProjectMismatchError) {\n return createInterModuleKnownError(method, 'project-mismatch', {});\n }\n if (error instanceof AgentConfigUnresolvableError) {\n return createInterModuleKnownError(method, 'agent-config-unresolvable', {\n definitionId: error.definitionId,\n });\n }\n if (error instanceof AgentIntegrationMaterializationError) {\n return createInterModuleKnownError(method, 'agent-integration-materialization-failed', {});\n }\n if (error instanceof InterpolationUnresolvableError) {\n return createInterModuleKnownError(method, 'interpolation-unresolvable', {\n definitionId: error.definitionId,\n field: error.field,\n source: error.source,\n ...(error.envKey === undefined ? {} : {envKey: error.envKey}),\n });\n }\n if (error instanceof InvalidJobRunnerLabelsError) {\n return createInterModuleKnownError(method, 'invalid-job-runner-labels', {\n labels: [...error.labels],\n });\n }\n return error;\n}\n"],"names":["materializedAgentStepConfigSchema","workflowsInterModuleContract","createInterModuleKnownError","defineInterModulePresentation","DEFAULT_HARNESS","harnessSchema","InvalidJobRunnerLabelsError","AgentConfigUnresolvableError","AgentIntegrationMaterializationError","DefinitionNotFoundError","InterpolationUnresolvableError","ProjectMismatchError","runWorkflow","getJobScope","getStepById","getStepByIdForJobExecution","deliverEventToListener","createWorkflowsInterModulePresentation","params","startRunFromTrigger","input","run","definitions","agent","workspaceId","projectId","definitionId","triggerPayload","inputs","triggerIdempotencyKey","idempotencyKey","integrations","projects","secrets","id","name","error","toStartRunKnownError","deliverEventToJobListener","receivedAt","Date","getStepLogContext","stepId","step","parsed","safeParse","config","harness","success","data","getLeasedAgentToolContext","method","methods","active","leaseIsActive","runners","getLeaseState","jobId","jobExecutionId","runnerSessionId","scope","currentAttempt","attempt","status","type","field","source","envKey","undefined","labels"],"mappings":"AAAA,SAAQA,iCAAiC,QAAO,yBAAyB;AAOzE,SAAQC,4BAA4B,QAAO,0CAA0C;AACrF,SACEC,2BAA2B,EAC3BC,6BAA6B,QAExB,wBAAwB;AAC/B,SAAQC,eAAe,EAAEC,aAAa,QAAO,6BAA6B;AAC1E,SAAQC,2BAA2B,QAAO,kBAAkB;AAC5D,SACEC,4BAA4B,EAC5BC,oCAAoC,E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AAwB;YAACzB;QAAY;IAClF;IACA,IAAIU,iBAAiBzB,sBAAsB;QACzC,OAAOT,4BAA4BiD,QAAQ,oBAAoB,CAAC;IAClE;IACA,IAAIf,iBAAiB7B,8BAA8B;QACjD,OAAOL,4BAA4BiD,QAAQ,6BAA6B;YACtEzB,cAAcU,MAAMV,YAAY;QAClC;IACF;IACA,IAAIU,iBAAiB5B,sCAAsC;QACzD,OAAON,4BAA4BiD,QAAQ,4CAA4C,CAAC;IAC1F;IACA,IAAIf,iBAAiB1B,gCAAgC;QACnD,OAAOR,4BAA4BiD,QAAQ,8BAA8B;YACvEzB,cAAcU,MAAMV,YAAY;YAChCuC,OAAO7B,MAAM6B,KAAK;YAClBC,QAAQ9B,MAAM8B,MAAM;YACpB,GAAI9B,MAAM+B,MAAM,KAAKC,YAAY,CAAC,IAAI;gBAACD,QAAQ/B,MAAM+B,MAAM;YAAA,CAAC;QAC9D;IACF;IACA,IAAI/B,iBAAiB9B,6BAA6B;QAChD,OAAOJ,4BAA4BiD,QAAQ,6BAA6B;YACtEkB,QAAQ;mBAAIjC,MAAMiC,MAAM;aAAC;QAC3B;IACF;IACA,OAAOjC;AACT"}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import type { ProjectsModuleClient } from '@shipfox/api-projects-dto';
|
|
1
|
+
import type { ProjectsModuleClient } from '@shipfox/api-projects-dto/inter-module';
|
|
2
2
|
export declare function cancelRunRoute(projects: ProjectsModuleClient): import("@shipfox/node-fastify").RouteDefinition;
|
|
3
3
|
//# sourceMappingURL=cancel-run.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cancel-run.d.ts","sourceRoot":"","sources":["../../../src/presentation/routes/cancel-run.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,oBAAoB,EAAC,MAAM,
|
|
1
|
+
{"version":3,"file":"cancel-run.d.ts","sourceRoot":"","sources":["../../../src/presentation/routes/cancel-run.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,oBAAoB,EAAC,MAAM,wCAAwC,CAAC;AASjF,wBAAgB,cAAc,CAAC,QAAQ,EAAE,oBAAoB,mDA8B5D"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/presentation/routes/cancel-run.ts"],"sourcesContent":["import type {ProjectsModuleClient} from '@shipfox/api-projects-dto';\nimport {workflowRunDtoSchema} from '@shipfox/api-workflows-dto';\nimport {ClientError, defineRoute} from '@shipfox/node-fastify';\nimport {z} from 'zod';\nimport {WorkflowRunNotCancellableError, WorkflowRunNotFoundError} from '#core/errors.js';\nimport {cancelWorkflowRun} from '#db/index.js';\nimport {toRunDto} from '#presentation/dto/index.js';\nimport {requireAccessibleRun} from './require-accessible-run.js';\n\nexport function cancelRunRoute(projects: ProjectsModuleClient) {\n return defineRoute({\n method: 'POST',\n path: '/:id/cancel',\n description: 'Cancel an in-progress workflow run',\n schema: {\n params: z.object({\n id: z.string().uuid(),\n }),\n response: {\n 200: workflowRunDtoSchema,\n },\n },\n errorHandler: (error) => {\n if (error instanceof WorkflowRunNotCancellableError) {\n throw new ClientError(error.message, 'run-already-finished', {status: 409});\n }\n if (error instanceof WorkflowRunNotFoundError) {\n throw new ClientError('Run not found', 'not-found', {status: 404});\n }\n throw error;\n },\n handler: async (request) => {\n const {id} = request.params;\n const run = await requireAccessibleRun({request, id, projects});\n\n const cancelled = await cancelWorkflowRun({workflowRunId: run.id});\n return toRunDto(cancelled);\n },\n });\n}\n"],"names":["workflowRunDtoSchema","ClientError","defineRoute","z","WorkflowRunNotCancellableError","WorkflowRunNotFoundError","cancelWorkflowRun","toRunDto","requireAccessibleRun","cancelRunRoute","projects","method","path","description","schema","params","object","id","string","uuid","response","errorHandler","error","message","status","handler","request","run","cancelled","workflowRunId"],"mappings":"AACA,SAAQA,oBAAoB,QAAO,6BAA6B;AAChE,SAAQC,WAAW,EAAEC,WAAW,QAAO,wBAAwB;AAC/D,SAAQC,CAAC,QAAO,MAAM;AACtB,SAAQC,8BAA8B,EAAEC,wBAAwB,QAAO,kBAAkB;AACzF,SAAQC,iBAAiB,QAAO,eAAe;AAC/C,SAAQC,QAAQ,QAAO,6BAA6B;AACpD,SAAQC,oBAAoB,QAAO,8BAA8B;AAEjE,OAAO,SAASC,eAAeC,QAA8B;IAC3D,OAAOR,YAAY;QACjBS,QAAQ;QACRC,MAAM;QACNC,aAAa;QACbC,QAAQ;YACNC,QAAQZ,EAAEa,MAAM,CAAC;gBACfC,IAAId,EAAEe,MAAM,GAAGC,IAAI;YACrB;YACAC,UAAU;gBACR,KAAKpB;YACP;QACF;QACAqB,cAAc,CAACC;YACb,IAAIA,iBAAiBlB,gCAAgC;gBACnD,MAAM,IAAIH,YAAYqB,MAAMC,OAAO,EAAE,wBAAwB;oBAACC,QAAQ;gBAAG;YAC3E;YACA,IAAIF,iBAAiBjB,0BAA0B;gBAC7C,MAAM,IAAIJ,YAAY,iBAAiB,aAAa;oBAACuB,QAAQ;gBAAG;YAClE;YACA,MAAMF;QACR;QACAG,SAAS,OAAOC;YACd,MAAM,EAACT,EAAE,EAAC,GAAGS,QAAQX,MAAM;YAC3B,MAAMY,MAAM,MAAMnB,qBAAqB;gBAACkB;gBAAST;gBAAIP;YAAQ;YAE7D,MAAMkB,YAAY,MAAMtB,kBAAkB;gBAACuB,eAAeF,IAAIV,EAAE;YAAA;YAChE,OAAOV,SAASqB;QAClB;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../src/presentation/routes/cancel-run.ts"],"sourcesContent":["import type {ProjectsModuleClient} from '@shipfox/api-projects-dto/inter-module';\nimport {workflowRunDtoSchema} from '@shipfox/api-workflows-dto';\nimport {ClientError, defineRoute} from '@shipfox/node-fastify';\nimport {z} from 'zod';\nimport {WorkflowRunNotCancellableError, WorkflowRunNotFoundError} from '#core/errors.js';\nimport {cancelWorkflowRun} from '#db/index.js';\nimport {toRunDto} from '#presentation/dto/index.js';\nimport {requireAccessibleRun} from './require-accessible-run.js';\n\nexport function cancelRunRoute(projects: ProjectsModuleClient) {\n return defineRoute({\n method: 'POST',\n path: '/:id/cancel',\n description: 'Cancel an in-progress workflow run',\n schema: {\n params: z.object({\n id: z.string().uuid(),\n }),\n response: {\n 200: workflowRunDtoSchema,\n },\n },\n errorHandler: (error) => {\n if (error instanceof WorkflowRunNotCancellableError) {\n throw new ClientError(error.message, 'run-already-finished', {status: 409});\n }\n if (error instanceof WorkflowRunNotFoundError) {\n throw new ClientError('Run not found', 'not-found', {status: 404});\n }\n throw error;\n },\n handler: async (request) => {\n const {id} = request.params;\n const run = await requireAccessibleRun({request, id, projects});\n\n const cancelled = await cancelWorkflowRun({workflowRunId: run.id});\n return toRunDto(cancelled);\n },\n });\n}\n"],"names":["workflowRunDtoSchema","ClientError","defineRoute","z","WorkflowRunNotCancellableError","WorkflowRunNotFoundError","cancelWorkflowRun","toRunDto","requireAccessibleRun","cancelRunRoute","projects","method","path","description","schema","params","object","id","string","uuid","response","errorHandler","error","message","status","handler","request","run","cancelled","workflowRunId"],"mappings":"AACA,SAAQA,oBAAoB,QAAO,6BAA6B;AAChE,SAAQC,WAAW,EAAEC,WAAW,QAAO,wBAAwB;AAC/D,SAAQC,CAAC,QAAO,MAAM;AACtB,SAAQC,8BAA8B,EAAEC,wBAAwB,QAAO,kBAAkB;AACzF,SAAQC,iBAAiB,QAAO,eAAe;AAC/C,SAAQC,QAAQ,QAAO,6BAA6B;AACpD,SAAQC,oBAAoB,QAAO,8BAA8B;AAEjE,OAAO,SAASC,eAAeC,QAA8B;IAC3D,OAAOR,YAAY;QACjBS,QAAQ;QACRC,MAAM;QACNC,aAAa;QACbC,QAAQ;YACNC,QAAQZ,EAAEa,MAAM,CAAC;gBACfC,IAAId,EAAEe,MAAM,GAAGC,IAAI;YACrB;YACAC,UAAU;gBACR,KAAKpB;YACP;QACF;QACAqB,cAAc,CAACC;YACb,IAAIA,iBAAiBlB,gCAAgC;gBACnD,MAAM,IAAIH,YAAYqB,MAAMC,OAAO,EAAE,wBAAwB;oBAACC,QAAQ;gBAAG;YAC3E;YACA,IAAIF,iBAAiBjB,0BAA0B;gBAC7C,MAAM,IAAIJ,YAAY,iBAAiB,aAAa;oBAACuB,QAAQ;gBAAG;YAClE;YACA,MAAMF;QACR;QACAG,SAAS,OAAOC;YACd,MAAM,EAACT,EAAE,EAAC,GAAGS,QAAQX,MAAM;YAC3B,MAAMY,MAAM,MAAMnB,qBAAqB;gBAACkB;gBAAST;gBAAIP;YAAQ;YAE7D,MAAMkB,YAAY,MAAMtB,kBAAkB;gBAACuB,eAAeF,IAAIV,EAAE;YAAA;YAChE,OAAOV,SAASqB;QAClB;IACF;AACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { type IntegrationsModuleClient } from '@shipfox/api-integration-core-dto';
|
|
2
|
-
import type { ProjectsModuleClient } from '@shipfox/api-projects-dto';
|
|
1
|
+
import { type IntegrationsModuleClient } from '@shipfox/api-integration-core-dto/inter-module';
|
|
2
|
+
import type { ProjectsModuleClient } from '@shipfox/api-projects-dto/inter-module';
|
|
3
3
|
import type { RunnersInterModuleClient } from '@shipfox/api-runners-dto/inter-module';
|
|
4
4
|
export declare function createCheckoutTokenRoute(clients: {
|
|
5
5
|
runners: RunnersInterModuleClient;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"checkout-token.d.ts","sourceRoot":"","sources":["../../../src/presentation/routes/checkout-token.ts"],"names":[],"mappings":"AACA,OAAO,EACL,KAAK,wBAAwB,EAE9B,MAAM,
|
|
1
|
+
{"version":3,"file":"checkout-token.d.ts","sourceRoot":"","sources":["../../../src/presentation/routes/checkout-token.ts"],"names":[],"mappings":"AACA,OAAO,EACL,KAAK,wBAAwB,EAE9B,MAAM,gDAAgD,CAAC;AACxD,OAAO,KAAK,EAAC,oBAAoB,EAAC,MAAM,wCAAwC,CAAC;AACjF,OAAO,KAAK,EAAC,wBAAwB,EAAC,MAAM,uCAAuC,CAAC;AAYpF,wBAAgB,wBAAwB,CAAC,OAAO,EAAE;IAChD,OAAO,EAAE,wBAAwB,CAAC;IAClC,YAAY,EAAE,wBAAwB,CAAC;IACvC,QAAQ,EAAE,oBAAoB,CAAC;CAChC,mDAkGA"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { requireLeasedJobContext } from '@shipfox/api-auth-context';
|
|
2
|
-
import { integrationsInterModuleContract } from '@shipfox/api-integration-core-dto';
|
|
2
|
+
import { integrationsInterModuleContract } from '@shipfox/api-integration-core-dto/inter-module';
|
|
3
3
|
import { checkoutTokenResponseSchema } from '@shipfox/api-workflows-dto';
|
|
4
4
|
import { isInterModuleKnownError } from '@shipfox/inter-module';
|
|
5
5
|
import { ClientError, defineRoute } from '@shipfox/node-fastify';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/presentation/routes/checkout-token.ts"],"sourcesContent":["import {requireLeasedJobContext} from '@shipfox/api-auth-context';\nimport {\n type IntegrationsModuleClient,\n integrationsInterModuleContract,\n} from '@shipfox/api-integration-core-dto';\nimport type {ProjectsModuleClient} from '@shipfox/api-projects-dto';\nimport type {RunnersInterModuleClient} from '@shipfox/api-runners-dto/inter-module';\nimport {checkoutTokenResponseSchema} from '@shipfox/api-workflows-dto';\nimport {isInterModuleKnownError} from '@shipfox/inter-module';\nimport {ClientError, defineRoute} from '@shipfox/node-fastify';\nimport {createJobCheckoutSpec} from '#core/checkout.js';\nimport {\n CheckoutIntentUnresolvedError,\n JobNotFoundError,\n WorkflowRunNotFoundError,\n} from '#core/errors.js';\nimport {toCheckoutTokenDto} from '#presentation/dto/checkout-token.js';\n\nexport function createCheckoutTokenRoute(clients: {\n runners: RunnersInterModuleClient;\n integrations: IntegrationsModuleClient;\n projects: ProjectsModuleClient;\n}) {\n return defineRoute({\n method: 'POST',\n path: '/checkout-token',\n description:\n \"Exchanges the runner's job lease for short-lived, read-only checkout credentials for the job's repository. The job is identified by the access token, so no job ID is needed. The checkout target is resolved server-side from the job's run and project; no credential material is stored on the job or run. Returns the repository URL, ref, and (when the provider needs auth) a short-lived credential that expires soon.\",\n schema: {response: {200: checkoutTokenResponseSchema}},\n errorHandler: (error) => {\n const known = isInterModuleKnownError(\n integrationsInterModuleContract.methods.createCheckoutSpec,\n error,\n )\n ? error\n : undefined;\n if (error instanceof JobNotFoundError)\n throw new ClientError(error.message, 'job-not-found', {status: 404});\n if (error instanceof WorkflowRunNotFoundError)\n throw new ClientError(error.message, 'run-not-found', {status: 404});\n if (error instanceof CheckoutIntentUnresolvedError)\n throw new ClientError(error.message, 'checkout-unavailable', {status: 404});\n if (known?.code === 'connection-not-found')\n throw new ClientError(\n 'Integration connection not found',\n 'integration-connection-not-found',\n {\n status: 404,\n },\n );\n if (known?.code === 'connection-inactive')\n throw new ClientError(\n 'Integration connection is not active',\n 'integration-connection-inactive',\n {\n status: 422,\n },\n );\n if (known?.code === 'connection-workspace-mismatch')\n throw new ClientError(\n 'Integration connection does not belong to this workspace',\n 'forbidden',\n {status: 403},\n );\n if (known?.code === 'provider-unavailable')\n throw new ClientError(\n 'Integration provider is unavailable',\n 'integration-provider-unavailable',\n {\n status: 422,\n },\n );\n if (known?.code === 'capability-unavailable')\n throw new ClientError(\n 'Integration capability is unavailable',\n 'integration-capability-unavailable',\n {\n status: 422,\n },\n );\n if (known?.code === 'checkout-unsupported')\n throw new ClientError(\n 'Integration checkout is unsupported',\n 'integration-checkout-unsupported',\n {\n status: 422,\n },\n );\n if (known?.code === 'provider-failure') {\n const status =\n known.details.reason === 'rate-limited'\n ? 429\n : known.details.reason === 'timeout' || known.details.reason === 'provider-unavailable'\n ? 503\n : 422;\n throw new ClientError('Integration provider request failed', known.details.reason, {\n details: {retry_after_seconds: known.details.retryAfterSeconds},\n status,\n });\n }\n throw error;\n },\n handler: async (request, reply) => {\n const leasedJob = requireLeasedJobContext(request);\n const {active: leaseIsActive} = await clients.runners.getLeaseState({\n jobId: leasedJob.jobId,\n jobExecutionId: leasedJob.jobExecutionId,\n runnerSessionId: leasedJob.runnerSessionId,\n });\n if (!leaseIsActive)\n throw new ClientError('Job lease is no longer active', 'lease-not-active', {status: 404});\n const checkout = await createJobCheckoutSpec({\n jobId: leasedJob.jobId,\n integrations: clients.integrations,\n projects: clients.projects,\n });\n reply.header('cache-control', 'no-store');\n return toCheckoutTokenDto(checkout.spec, {persist: checkout.persistCredentials});\n },\n });\n}\n"],"names":["requireLeasedJobContext","integrationsInterModuleContract","checkoutTokenResponseSchema","isInterModuleKnownError","ClientError","defineRoute","createJobCheckoutSpec","CheckoutIntentUnresolvedError","JobNotFoundError","WorkflowRunNotFoundError","toCheckoutTokenDto","createCheckoutTokenRoute","clients","method","path","description","schema","response","errorHandler","error","known","methods","createCheckoutSpec","undefined","message","status","code","details","reason","retry_after_seconds","retryAfterSeconds","handler","request","reply","leasedJob","active","leaseIsActive","runners","getLeaseState","jobId","jobExecutionId","runnerSessionId","checkout","integrations","projects","header","spec","persist","persistCredentials"],"mappings":"AAAA,SAAQA,uBAAuB,QAAO,4BAA4B;AAClE,SAEEC,+BAA+B,QAC1B,
|
|
1
|
+
{"version":3,"sources":["../../../src/presentation/routes/checkout-token.ts"],"sourcesContent":["import {requireLeasedJobContext} from '@shipfox/api-auth-context';\nimport {\n type IntegrationsModuleClient,\n integrationsInterModuleContract,\n} from '@shipfox/api-integration-core-dto/inter-module';\nimport type {ProjectsModuleClient} from '@shipfox/api-projects-dto/inter-module';\nimport type {RunnersInterModuleClient} from '@shipfox/api-runners-dto/inter-module';\nimport {checkoutTokenResponseSchema} from '@shipfox/api-workflows-dto';\nimport {isInterModuleKnownError} from '@shipfox/inter-module';\nimport {ClientError, defineRoute} from '@shipfox/node-fastify';\nimport {createJobCheckoutSpec} from '#core/checkout.js';\nimport {\n CheckoutIntentUnresolvedError,\n JobNotFoundError,\n WorkflowRunNotFoundError,\n} from '#core/errors.js';\nimport {toCheckoutTokenDto} from '#presentation/dto/checkout-token.js';\n\nexport function createCheckoutTokenRoute(clients: {\n runners: RunnersInterModuleClient;\n integrations: IntegrationsModuleClient;\n projects: ProjectsModuleClient;\n}) {\n return defineRoute({\n method: 'POST',\n path: '/checkout-token',\n description:\n \"Exchanges the runner's job lease for short-lived, read-only checkout credentials for the job's repository. The job is identified by the access token, so no job ID is needed. The checkout target is resolved server-side from the job's run and project; no credential material is stored on the job or run. Returns the repository URL, ref, and (when the provider needs auth) a short-lived credential that expires soon.\",\n schema: {response: {200: checkoutTokenResponseSchema}},\n errorHandler: (error) => {\n const known = isInterModuleKnownError(\n integrationsInterModuleContract.methods.createCheckoutSpec,\n error,\n )\n ? error\n : undefined;\n if (error instanceof JobNotFoundError)\n throw new ClientError(error.message, 'job-not-found', {status: 404});\n if (error instanceof WorkflowRunNotFoundError)\n throw new ClientError(error.message, 'run-not-found', {status: 404});\n if (error instanceof CheckoutIntentUnresolvedError)\n throw new ClientError(error.message, 'checkout-unavailable', {status: 404});\n if (known?.code === 'connection-not-found')\n throw new ClientError(\n 'Integration connection not found',\n 'integration-connection-not-found',\n {\n status: 404,\n },\n );\n if (known?.code === 'connection-inactive')\n throw new ClientError(\n 'Integration connection is not active',\n 'integration-connection-inactive',\n {\n status: 422,\n },\n );\n if (known?.code === 'connection-workspace-mismatch')\n throw new ClientError(\n 'Integration connection does not belong to this workspace',\n 'forbidden',\n {status: 403},\n );\n if (known?.code === 'provider-unavailable')\n throw new ClientError(\n 'Integration provider is unavailable',\n 'integration-provider-unavailable',\n {\n status: 422,\n },\n );\n if (known?.code === 'capability-unavailable')\n throw new ClientError(\n 'Integration capability is unavailable',\n 'integration-capability-unavailable',\n {\n status: 422,\n },\n );\n if (known?.code === 'checkout-unsupported')\n throw new ClientError(\n 'Integration checkout is unsupported',\n 'integration-checkout-unsupported',\n {\n status: 422,\n },\n );\n if (known?.code === 'provider-failure') {\n const status =\n known.details.reason === 'rate-limited'\n ? 429\n : known.details.reason === 'timeout' || known.details.reason === 'provider-unavailable'\n ? 503\n : 422;\n throw new ClientError('Integration provider request failed', known.details.reason, {\n details: {retry_after_seconds: known.details.retryAfterSeconds},\n status,\n });\n }\n throw error;\n },\n handler: async (request, reply) => {\n const leasedJob = requireLeasedJobContext(request);\n const {active: leaseIsActive} = await clients.runners.getLeaseState({\n jobId: leasedJob.jobId,\n jobExecutionId: leasedJob.jobExecutionId,\n runnerSessionId: leasedJob.runnerSessionId,\n });\n if (!leaseIsActive)\n throw new ClientError('Job lease is no longer active', 'lease-not-active', {status: 404});\n const checkout = await createJobCheckoutSpec({\n jobId: leasedJob.jobId,\n integrations: clients.integrations,\n projects: clients.projects,\n });\n reply.header('cache-control', 'no-store');\n return toCheckoutTokenDto(checkout.spec, {persist: checkout.persistCredentials});\n },\n });\n}\n"],"names":["requireLeasedJobContext","integrationsInterModuleContract","checkoutTokenResponseSchema","isInterModuleKnownError","ClientError","defineRoute","createJobCheckoutSpec","CheckoutIntentUnresolvedError","JobNotFoundError","WorkflowRunNotFoundError","toCheckoutTokenDto","createCheckoutTokenRoute","clients","method","path","description","schema","response","errorHandler","error","known","methods","createCheckoutSpec","undefined","message","status","code","details","reason","retry_after_seconds","retryAfterSeconds","handler","request","reply","leasedJob","active","leaseIsActive","runners","getLeaseState","jobId","jobExecutionId","runnerSessionId","checkout","integrations","projects","header","spec","persist","persistCredentials"],"mappings":"AAAA,SAAQA,uBAAuB,QAAO,4BAA4B;AAClE,SAEEC,+BAA+B,QAC1B,iDAAiD;AAGxD,SAAQC,2BAA2B,QAAO,6BAA6B;AACvE,SAAQC,uBAAuB,QAAO,wBAAwB;AAC9D,SAAQC,WAAW,EAAEC,WAAW,QAAO,wBAAwB;AAC/D,SAAQC,qBAAqB,QAAO,oBAAoB;AACxD,SACEC,6BAA6B,EAC7BC,gBAAgB,EAChBC,wBAAwB,QACnB,kBAAkB;AACzB,SAAQC,kBAAkB,QAAO,sCAAsC;AAEvE,OAAO,SAASC,yBAAyBC,OAIxC;IACC,OAAOP,YAAY;QACjBQ,QAAQ;QACRC,MAAM;QACNC,aACE;QACFC,QAAQ;YAACC,UAAU;gBAAC,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AACG,iBAAiB;oBAAA;oBAC9DL;gBACF;YACF;YACA,MAAMN;QACR;QACAY,SAAS,OAAOC,SAASC;YACvB,MAAMC,YAAYlC,wBAAwBgC;YAC1C,MAAM,EAACG,QAAQC,aAAa,EAAC,GAAG,MAAMxB,QAAQyB,OAAO,CAACC,aAAa,CAAC;gBAClEC,OAAOL,UAAUK,KAAK;gBACtBC,gBAAgBN,UAAUM,cAAc;gBACxCC,iBAAiBP,UAAUO,eAAe;YAC5C;YACA,IAAI,CAACL,eACH,MAAM,IAAIhC,YAAY,iCAAiC,oBAAoB;gBAACqB,QAAQ;YAAG;YACzF,MAAMiB,WAAW,MAAMpC,sBAAsB;gBAC3CiC,OAAOL,UAAUK,KAAK;gBACtBI,cAAc/B,QAAQ+B,YAAY;gBAClCC,UAAUhC,QAAQgC,QAAQ;YAC5B;YACAX,MAAMY,MAAM,CAAC,iBAAiB;YAC9B,OAAOnC,mBAAmBgC,SAASI,IAAI,EAAE;gBAACC,SAASL,SAASM,kBAAkB;YAAA;QAChF;IACF;AACF"}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import type { ProjectsModuleClient } from '@shipfox/api-projects-dto';
|
|
1
|
+
import type { ProjectsModuleClient } from '@shipfox/api-projects-dto/inter-module';
|
|
2
2
|
export declare function getRunAggregatesRoute(projects: ProjectsModuleClient): import("@shipfox/node-fastify").RouteDefinition;
|
|
3
3
|
//# sourceMappingURL=get-run-aggregates.d.ts.map
|