-
Notifications
You must be signed in to change notification settings - Fork 9
init new policy engine #411
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
d509871
init new policy engine
jsbroks 1be908c
rename from policy -> rule
jsbroks c1162f7
clean up policies
jsbroks 6c36946
add version cooldown rule
jsbroks a443e43
refactor options to be passed in
jsbroks 9293104
add version selector roles
jsbroks 72fde50
add more docs to grad rollouts
jsbroks f434b33
add maintenance window code tests
jsbroks 2a216b7
clean up
jsbroks ccd3798
more templating
jsbroks beee929
add more checks
jsbroks 74abecd
clean up
jsbroks File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,150 @@ | ||
import type { | ||
DeploymentResourceContext, | ||
Release, | ||
} from "@ctrlplane/rule-engine"; | ||
import type { RuleEngineEvaluationEvent } from "@ctrlplane/validators/events"; | ||
import { Worker } from "bullmq"; | ||
import { Mutex } from "redis-semaphore"; | ||
|
||
import { and, desc, eq, sql, takeFirstOrNull } from "@ctrlplane/db"; | ||
import { db } from "@ctrlplane/db/client"; | ||
import * as schema from "@ctrlplane/db/schema"; | ||
import { | ||
Releases, | ||
RuleEngine, | ||
VersionCooldownRule, | ||
} from "@ctrlplane/rule-engine"; | ||
import { Channel } from "@ctrlplane/validators/events"; | ||
|
||
import { redis } from "../redis.js"; | ||
|
||
const createDeploymentResourceContext = ({ | ||
resourceId, | ||
deploymentId, | ||
environmentId, | ||
}: RuleEngineEvaluationEvent) => { | ||
return db | ||
.select({ | ||
desiredReleaseId: schema.resourceDesiredRelease.desiredReleaseId, | ||
deployment: schema.deployment, | ||
environment: schema.environment, | ||
resource: schema.resource, | ||
}) | ||
.from(schema.resourceDesiredRelease) | ||
.innerJoin( | ||
schema.deployment, | ||
eq(schema.resourceDesiredRelease.deploymentId, schema.deployment.id), | ||
) | ||
.innerJoin( | ||
schema.environment, | ||
eq(schema.resourceDesiredRelease.environmentId, schema.environment.id), | ||
) | ||
.innerJoin( | ||
schema.resource, | ||
eq(schema.resourceDesiredRelease.resourceId, schema.resource.id), | ||
) | ||
.where( | ||
and( | ||
eq(schema.resourceDesiredRelease.resourceId, resourceId), | ||
eq(schema.resourceDesiredRelease.environmentId, environmentId), | ||
eq(schema.resourceDesiredRelease.deploymentId, deploymentId), | ||
), | ||
) | ||
.then(takeFirstOrNull); | ||
}; | ||
|
||
const getReleaseCandidates = async ( | ||
ctx: DeploymentResourceContext, | ||
): Promise<Release[]> => { | ||
return db | ||
.select({ | ||
id: schema.release.id, | ||
createdAt: schema.release.createdAt, | ||
version: schema.deploymentVersion, | ||
variables: sql<Record<string, unknown>>`COALESCE(jsonb_object_agg( | ||
${schema.releaseVariable.key}, | ||
${schema.releaseVariable.value} | ||
) FILTER (WHERE ${schema.releaseVariable.key} IS NOT NULL), '{}'::jsonb)`.as( | ||
"variables", | ||
), | ||
}) | ||
.from(schema.release) | ||
.where( | ||
and( | ||
eq(schema.release.id, ctx.resource.id), | ||
eq(schema.release.environmentId, ctx.environment.id), | ||
eq(schema.release.deploymentId, ctx.deployment.id), | ||
), | ||
) | ||
.innerJoin( | ||
schema.deploymentVersion, | ||
eq(schema.release.versionId, schema.deploymentVersion.id), | ||
) | ||
.leftJoin( | ||
schema.releaseVariable, | ||
and( | ||
eq(schema.release.id, schema.releaseVariable.releaseId), | ||
eq(schema.releaseVariable.sensitive, false), | ||
), | ||
) | ||
.groupBy( | ||
schema.release.id, | ||
schema.release.createdAt, | ||
schema.deploymentVersion.id, | ||
) | ||
.orderBy(desc(schema.release.createdAt)) | ||
.limit(100) | ||
.then((releases) => | ||
releases.map((r) => ({ | ||
...r, | ||
version: { | ||
...r.version, | ||
metadata: {} as Record<string, string>, | ||
}, | ||
})), | ||
); | ||
}; | ||
|
||
const versionCooldownRule = () => | ||
new VersionCooldownRule({ | ||
cooldownMinutes: 1440, | ||
getLastSuccessfulDeploymentTime: () => new Date(), | ||
}); | ||
|
||
export const createRuleEngineEvaluationWorker = () => | ||
new Worker<RuleEngineEvaluationEvent>( | ||
Channel.RuleEngineEvaluation, | ||
async (job) => { | ||
const { resourceId, deploymentId, environmentId } = job.data; | ||
|
||
const key = `rule-engine-evaluation:${resourceId}-${deploymentId}-${environmentId}`; | ||
const mutex = new Mutex(redis, key); | ||
|
||
await mutex.acquire(); | ||
try { | ||
const ctx = await createDeploymentResourceContext(job.data); | ||
if (ctx == null) | ||
throw new Error( | ||
"Resource desired release not found. Could not build context.", | ||
); | ||
|
||
const allReleaseCandidates = await getReleaseCandidates(ctx); | ||
|
||
const releases = Releases.from(allReleaseCandidates); | ||
if (releases.isEmpty()) return; | ||
|
||
const ruleEngine = new RuleEngine([versionCooldownRule()]); | ||
const result = await ruleEngine.evaluate(releases, ctx); | ||
|
||
console.log(result); | ||
} finally { | ||
await mutex.release(); | ||
} | ||
}, | ||
{ | ||
connection: redis, | ||
removeOnComplete: { age: 1 * 60 * 60, count: 5000 }, | ||
removeOnFail: { age: 12 * 60 * 60, count: 5000 }, | ||
concurrency: 10, | ||
}, | ||
); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
import { | ||
boolean, | ||
json, | ||
pgTable, | ||
text, | ||
timestamp, | ||
uniqueIndex, | ||
uuid, | ||
} from "drizzle-orm/pg-core"; | ||
|
||
import { deploymentVersion } from "./deployment-version.js"; | ||
import { deployment } from "./deployment.js"; | ||
import { environment } from "./environment.js"; | ||
import { job } from "./job.js"; | ||
import { resource } from "./resource.js"; | ||
|
||
export const release = pgTable("release", { | ||
id: uuid("id").primaryKey().defaultRandom(), | ||
|
||
versionId: uuid("version_id") | ||
.notNull() | ||
.references(() => deploymentVersion.id, { onDelete: "cascade" }), | ||
resourceId: uuid("resource_id") | ||
.notNull() | ||
.references(() => resource.id, { onDelete: "cascade" }), | ||
deploymentId: uuid("deployment_id") | ||
.notNull() | ||
.references(() => deployment.id, { onDelete: "cascade" }), | ||
environmentId: uuid("environment_id") | ||
.references(() => environment.id, { onDelete: "cascade" }) | ||
.notNull(), | ||
|
||
createdAt: timestamp("created_at", { withTimezone: true }) | ||
.notNull() | ||
.defaultNow(), | ||
}); | ||
|
||
export const releaseVariable = pgTable( | ||
"release_variable", | ||
{ | ||
id: uuid("id").primaryKey().defaultRandom(), | ||
releaseId: uuid("release_id") | ||
.notNull() | ||
.references(() => release.id, { onDelete: "cascade" }), | ||
key: text("key").notNull(), | ||
value: json("value").notNull(), | ||
sensitive: boolean("sensitive").notNull().default(false), | ||
}, | ||
(t) => ({ uniq: uniqueIndex().on(t.releaseId, t.key) }), | ||
); | ||
|
||
export const releaseJob = pgTable("release_job", { | ||
id: uuid("id").primaryKey().defaultRandom(), | ||
releaseId: uuid("release_id") | ||
.notNull() | ||
.references(() => release.id, { onDelete: "cascade" }), | ||
jobId: uuid("job_id") | ||
.notNull() | ||
.references(() => job.id, { onDelete: "cascade" }), | ||
createdAt: timestamp("created_at", { withTimezone: true }) | ||
.notNull() | ||
.defaultNow(), | ||
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Review the fixed return value for
getLastSuccessfulDeploymentTime
.Currently, it always returns the current time, which can nullify the cooldown logic. Consider fetching the actual last successful deployment time to correctly enforce the cooldown period.
📝 Committable suggestion