From 5358eded46219751905946aa0d6f33d6bb989cbc Mon Sep 17 00:00:00 2001 From: Aditya Choudhari <48932219+adityachoudhari26@users.noreply.github.com> Date: Sun, 20 Oct 2024 18:41:13 -0700 Subject: [PATCH] fix: Optimize job policy query (#153) --- apps/jobs/src/policy-checker/index.ts | 31 +++++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/apps/jobs/src/policy-checker/index.ts b/apps/jobs/src/policy-checker/index.ts index 0994807b..5aa67af3 100644 --- a/apps/jobs/src/policy-checker/index.ts +++ b/apps/jobs/src/policy-checker/index.ts @@ -1,4 +1,4 @@ -import { eq } from "@ctrlplane/db"; +import { and, eq, isNull, or } from "@ctrlplane/db"; import { db } from "@ctrlplane/db/client"; import * as schema from "@ctrlplane/db/schema"; import { @@ -9,11 +9,38 @@ import { import { JobStatus } from "@ctrlplane/validators/jobs"; export const run = async () => { + const isPassingApprovalGate = or( + isNull(schema.environment.policyId), + eq(schema.environmentPolicy.approvalRequirement, "automatic"), + eq(schema.environmentPolicyApproval.status, "approved"), + ); + const releaseJobTriggers = await db .select() .from(schema.releaseJobTrigger) .innerJoin(schema.job, eq(schema.releaseJobTrigger.jobId, schema.job.id)) - .where(eq(schema.job.status, JobStatus.Pending)) + .innerJoin( + schema.environment, + eq(schema.releaseJobTrigger.environmentId, schema.environment.id), + ) + .leftJoin( + schema.environmentPolicy, + eq(schema.environment.policyId, schema.environmentPolicy.id), + ) + .leftJoin( + schema.environmentPolicyApproval, + and( + eq( + schema.environmentPolicyApproval.policyId, + schema.environmentPolicy.id, + ), + eq( + schema.environmentPolicyApproval.releaseId, + schema.releaseJobTrigger.releaseId, + ), + ), + ) + .where(and(eq(schema.job.status, JobStatus.Pending), isPassingApprovalGate)) .then((rows) => rows.map((row) => row.release_job_trigger)); if (releaseJobTriggers.length === 0) return;