Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 50 additions & 1 deletion apps/event-worker/src/workers/evaluate-release-target.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
import type { Tx } from "@ctrlplane/db";
import _ from "lodash";

import { and, desc, eq, sql, takeFirst } from "@ctrlplane/db";
import {
and,
desc,
eq,
inArray,
sql,
takeFirst,
takeFirstOrNull,
} from "@ctrlplane/db";
import { db } from "@ctrlplane/db/client";
import { createReleaseJob } from "@ctrlplane/db/queries";
import * as schema from "@ctrlplane/db/schema";
Expand All @@ -11,6 +19,7 @@ import {
VariableReleaseManager,
VersionReleaseManager,
} from "@ctrlplane/rule-engine";
import { JobStatus } from "@ctrlplane/validators/jobs";

const tracer = trace.getTracer("evaluate-release-target");
const withSpan = makeWithSpan(tracer);
Expand Down Expand Up @@ -72,6 +81,40 @@ const handleVariableRelease = withSpan(
},
);

const getReleaseTargetIdFromRelease = async (releaseId: string) =>
db
.select({ releaseTargetId: schema.versionRelease.releaseTargetId })
.from(schema.release)
.innerJoin(
schema.versionRelease,
eq(schema.release.versionReleaseId, schema.versionRelease.id),
)
.where(eq(schema.release.id, releaseId))
.then(takeFirst)
.then(({ releaseTargetId }) => releaseTargetId);

const getActiveJobForReleaseTarget = async (releaseTargetId: string) =>
db
.select()
.from(schema.job)
.innerJoin(schema.releaseJob, eq(schema.releaseJob.jobId, schema.job.id))
.innerJoin(
schema.release,
eq(schema.release.id, schema.releaseJob.releaseId),
)
.innerJoin(
schema.versionRelease,
eq(schema.release.versionReleaseId, schema.versionRelease.id),
)
.where(
and(
eq(schema.versionRelease.releaseTargetId, releaseTargetId),
inArray(schema.job.status, [JobStatus.Pending, JobStatus.InProgress]),
),
)
.limit(1)
.then(takeFirstOrNull);

/**
* Worker that evaluates a release target and creates necessary releases and jobs
* Only runs in development environment
Expand Down Expand Up @@ -166,6 +209,12 @@ export const evaluateReleaseTargetWorker = createWorker(

if (existingReleaseJob != null && !skipDuplicateCheck) return;

// Check if the release target already has an active job (pending or in progress)
const releaseTargetId = await getReleaseTargetIdFromRelease(release.id);
const activeJobForReleaseTarget =
await getActiveJobForReleaseTarget(releaseTargetId);
if (activeJobForReleaseTarget != null) return;

// If no job exists yet, create one and dispatch it
const newReleaseJob = await db.transaction(async (tx) =>
createReleaseJob(tx, release),
Expand Down
77 changes: 65 additions & 12 deletions packages/job-dispatch/src/job-update.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
import type { Tx } from "@ctrlplane/db";

import { eq, sql, takeFirst } from "@ctrlplane/db";
import { desc, eq, sql, takeFirst, takeFirstOrNull } from "@ctrlplane/db";
import { db } from "@ctrlplane/db/client";
import { createReleaseJob } from "@ctrlplane/db/queries";
import * as schema from "@ctrlplane/db/schema";
import { logger } from "@ctrlplane/logger";
import { ReservedMetadataKey } from "@ctrlplane/validators/conditions";
import { exitedStatus, JobStatus } from "@ctrlplane/validators/jobs";

import { onJobCompletion } from "./job-creation.js";
import { onJobFailure } from "./job-failure.js";

const log = logger.child({ module: "job-update" });

const updateJobMetadata = async (
Expand Down Expand Up @@ -83,6 +81,52 @@ const getCompletedAt = (
return null;
};

const getIsJobJustCompleted = (
previousStatus: JobStatus,
newStatus: JobStatus,
) => {
const isPreviousStatusExited = exitedStatus.includes(previousStatus);
const isNewStatusExited = exitedStatus.includes(newStatus);
return !isPreviousStatusExited && isNewStatusExited;
};

const getReleaseTargetFromJob = (jobId: string) =>
db
.select()
.from(schema.releaseJob)
.innerJoin(
schema.release,
eq(schema.releaseJob.releaseId, schema.release.id),
)
.innerJoin(
schema.versionRelease,
eq(schema.release.versionReleaseId, schema.versionRelease.id),
)
.innerJoin(
schema.releaseTarget,
eq(schema.versionRelease.releaseTargetId, schema.releaseTarget.id),
)
.where(eq(schema.job.id, jobId))
.then(takeFirstOrNull)
.then((result) => result?.release_target ?? null);

Comment on lines +93 to +112
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Incorrect WHERE clause – schema.job not joined, causes invalid SQL

The query filters with eq(schema.job.id, jobId) while the job table is not part of the FROM … JOIN chain. At runtime most SQL engines will raise “column reference ‘job.id’ is ambiguous / missing FROM-clause entry”.

Fix by filtering on the joined releaseJob.jobId, or join the job table explicitly:

-    .where(eq(schema.job.id, jobId))
+    .where(eq(schema.releaseJob.jobId, jobId))

or

+    .innerJoin(schema.job, eq(schema.releaseJob.jobId, schema.job.id))
+    .where(eq(schema.job.id, jobId))

Without this fix updateJob will always fail when it reaches getReleaseTargetFromJob, preventing automatic chaining of jobs.

const getLatestReleaseForReleaseTarget = (releaseTargetId: string) =>
db
.select()
.from(schema.release)
.innerJoin(
schema.versionRelease,
eq(schema.release.versionReleaseId, schema.versionRelease.id),
)
.leftJoin(
schema.releaseJob,
eq(schema.releaseJob.releaseId, schema.release.id),
)
.orderBy(desc(schema.release.createdAt))
.limit(1)
.where(eq(schema.versionRelease.releaseTargetId, releaseTargetId))
.then(takeFirstOrNull);

export const updateJob = async (
db: Tx,
jobId: string,
Expand Down Expand Up @@ -112,15 +156,24 @@ export const updateJob = async (
if (metadata != null)
await updateJobMetadata(jobId, jobBeforeUpdate.metadata, metadata);

const isJobFailure =
data.status === JobStatus.Failure &&
jobBeforeUpdate.status !== JobStatus.Failure;
if (isJobFailure) await onJobFailure(updatedJob);
const isJobJustCompleted = getIsJobJustCompleted(
jobBeforeUpdate.status as JobStatus,
updatedJob.status as JobStatus,
);
if (!isJobJustCompleted) return updatedJob;

const isJobCompletion =
data.status === JobStatus.Successful &&
jobBeforeUpdate.status !== JobStatus.Successful;
if (isJobCompletion) await onJobCompletion(updatedJob);
const releaseTarget = await getReleaseTargetFromJob(jobId);
if (releaseTarget == null) {
log.warn(`Release target not found for job: ${jobId}`);
return updatedJob;
}

const latestRelease = await getLatestReleaseForReleaseTarget(
releaseTarget.id,
);
if (latestRelease == null || latestRelease.release_job != null)
return updatedJob;
await createReleaseJob(db, latestRelease.release);

return updatedJob;
};
Loading