-
Notifications
You must be signed in to change notification settings - Fork 8
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 3 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
import baseConfig, { requireJsSuffix } from "@ctrlplane/eslint-config/base"; | ||
|
||
/** @type {import('typescript-eslint').Config} */ | ||
export default [ | ||
{ | ||
ignores: ["dist/**"], | ||
rules: { | ||
"@typescript-eslint/require-await": "off", | ||
}, | ||
}, | ||
...requireJsSuffix, | ||
...baseConfig, | ||
]; |
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,36 @@ | ||
{ | ||
"name": "@ctrlplane/rule-engine", | ||
"private": true, | ||
"version": "0.1.0", | ||
"type": "module", | ||
"exports": { | ||
".": { | ||
"types": "./src/index.ts", | ||
"default": "./dist/index.js" | ||
} | ||
}, | ||
"license": "MIT", | ||
"scripts": { | ||
"build": "tsc", | ||
"dev": "tsc --watch", | ||
"clean": "rm -rf .turbo node_modules", | ||
"format": "prettier --check . --ignore-path ../../.gitignore", | ||
"lint": "eslint", | ||
"typecheck": "tsc --noEmit --emitDeclarationOnly false" | ||
}, | ||
"dependencies": { | ||
"@ctrlplane/db": "workspace:*", | ||
"@ctrlplane/validators": "workspace:*", | ||
"zod": "catalog:" | ||
}, | ||
"devDependencies": { | ||
"@ctrlplane/eslint-config": "workspace:*", | ||
"@ctrlplane/prettier-config": "workspace:*", | ||
"@ctrlplane/tsconfig": "workspace:*", | ||
"@types/node": "catalog:node22", | ||
"eslint": "catalog:", | ||
"prettier": "catalog:", | ||
"typescript": "catalog:" | ||
}, | ||
"prettier": "@ctrlplane/prettier-config" | ||
} |
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,5 @@ | ||
export * from "./types.js"; | ||
export { RuleEngine } from "./rule-engine.js"; | ||
|
||
// Export all rules | ||
export * from "./rules/index.js"; |
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,72 @@ | ||
import type { | ||
DeploymentResourceContext, | ||
DeploymentResourceRule, | ||
DeploymentResourceSelectionResult, | ||
Release, | ||
} from "./types.js"; | ||
|
||
/** | ||
* The engine that applies rules in sequence, then picks a version. | ||
*/ | ||
export class RuleEngine { | ||
constructor(private rules: DeploymentResourceRule[]) {} | ||
|
||
async evaluate( | ||
context: DeploymentResourceContext, | ||
): Promise<DeploymentResourceSelectionResult> { | ||
let candidateReleases = [...context.availableReleases]; | ||
|
||
for (const rule of this.rules) { | ||
const result = await rule.filter(context, candidateReleases); | ||
|
||
// If the rule yields no candidates, we must stop. | ||
if (result.allowedReleases.length === 0) { | ||
return { | ||
allowed: false, | ||
reason: `${rule.name} disqualified all versions. Additional info: ${result.reason ?? ""}`, | ||
}; | ||
} | ||
|
||
candidateReleases = [...result.allowedReleases]; | ||
} | ||
|
||
const chosen = this.selectFinalRelease(context, candidateReleases); | ||
if (!chosen) { | ||
return { | ||
allowed: false, | ||
reason: `No suitable version chosen after applying all rules.`, | ||
}; | ||
} | ||
|
||
return { | ||
allowed: true, | ||
chosenRelease: chosen, | ||
}; | ||
} | ||
|
||
/** | ||
* Tiebreak logic or final selection strategy. | ||
* | ||
* Examples: | ||
* - If a desiredVersion is in the list, pick it | ||
* - Or pick the newest createdAt, etc. | ||
*/ | ||
private selectFinalRelease( | ||
context: DeploymentResourceContext, | ||
candidates: Release[], | ||
): Release | undefined { | ||
// If a desiredVersion is specified and it's still in the candidates, choose | ||
// it: | ||
if ( | ||
context.desiredReleaseId && | ||
candidates.map((r) => r.id).includes(context.desiredReleaseId) | ||
) | ||
return candidates.find((r) => r.id === context.desiredReleaseId); | ||
|
||
// Otherwise pick the newest release. | ||
const sorted = candidates.sort( | ||
(a, b) => b.createdAt.getTime() - a.createdAt.getTime(), | ||
); | ||
return sorted[0]; | ||
} | ||
} |
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,97 @@ | ||
import type { | ||
DeploymentResourceContext, | ||
DeploymentResourceRule, | ||
DeploymentResourceRuleResult, | ||
Release, | ||
} from "../types.js"; | ||
|
||
/** | ||
* A rule that requires explicit approval for specific versions or environments. | ||
* | ||
* This rule ensures that certain deployments can only proceed after receiving | ||
* explicit approval, which can be tracked in release metadata. | ||
* | ||
* @example | ||
* ```ts | ||
* // Require approval for production deployments | ||
* new ApprovalRequiredRule({ | ||
* environmentPattern: /^prod-/, | ||
* approvalMetadataKey: "approved_by" | ||
* }); | ||
* ``` | ||
*/ | ||
export class ApprovalRequiredRule implements DeploymentResourceRule { | ||
public readonly name = "ApprovalRequiredRule"; | ||
|
||
constructor( | ||
private options: { | ||
environmentPattern?: RegExp; | ||
resourcePattern?: RegExp; | ||
versionPattern?: RegExp; | ||
approvalMetadataKey: string; | ||
requiredApprovers?: number; | ||
}, | ||
) {} | ||
|
||
async filter( | ||
ctx: DeploymentResourceContext, | ||
currentCandidates: Release[], | ||
): Promise<DeploymentResourceRuleResult> { | ||
// Skip approval check if deployment environment/resource doesn't match our patterns | ||
if ( | ||
this.options.environmentPattern && | ||
!this.options.environmentPattern.test(ctx.deployment.name) | ||
) { | ||
return { allowedReleases: currentCandidates }; | ||
} | ||
|
||
if ( | ||
this.options.resourcePattern && | ||
!this.options.resourcePattern.test(ctx.resource.name) | ||
) { | ||
return { allowedReleases: currentCandidates }; | ||
} | ||
|
||
// Filter releases that require approval | ||
const filteredReleases = currentCandidates.filter((release) => { | ||
// If we have a version pattern and it doesn't match, no approval needed | ||
if ( | ||
this.options.versionPattern && | ||
!this.options.versionPattern.test(release.version.tag) | ||
) { | ||
return true; | ||
} | ||
|
||
// Check for approval in metadata | ||
const approvalValue = | ||
release.version.metadata?.[this.options.approvalMetadataKey]; | ||
|
||
// If no approval data found, can't deploy | ||
if (!approvalValue) { | ||
return false; | ||
} | ||
|
||
// If we require a specific number of approvers | ||
if (this.options.requiredApprovers) { | ||
// Check if the approval value has multiple approvers (comma-separated list) | ||
const approvers = approvalValue | ||
.split(",") | ||
.map((a) => a.trim()) | ||
.filter(Boolean); | ||
return approvers.length >= this.options.requiredApprovers; | ||
} | ||
|
||
// Otherwise any approval is sufficient | ||
return true; | ||
}); | ||
|
||
if (filteredReleases.length === 0) { | ||
return { | ||
allowedReleases: [], | ||
reason: `Required approval is missing. Deployment to ${ctx.deployment.name}/${ctx.resource.name} requires explicit approval via the '${this.options.approvalMetadataKey}' metadata field.`, | ||
}; | ||
} | ||
|
||
return { allowedReleases: filteredReleases }; | ||
} | ||
} |
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,162 @@ | ||
import { and, count, eq } from "@ctrlplane/db"; | ||
import { db } from "@ctrlplane/db/client"; | ||
import * as schema from "@ctrlplane/db/schema"; | ||
import { JobStatus } from "@ctrlplane/validators/jobs"; | ||
import crypto from "crypto"; | ||
|
||
import type { | ||
DeploymentResourceContext, | ||
DeploymentResourceRule, | ||
DeploymentResourceRuleResult, | ||
Release, | ||
} from "../types.js"; | ||
|
||
/** | ||
* A rule that implements gradual rollout of new versions. | ||
* | ||
* This rule controls the pace of deployment for new versions, ensuring | ||
* that changes are rolled out gradually across resources to limit risk. | ||
* | ||
* @example | ||
* ```ts | ||
* // Limit rollout to max 5 resources every 30 minutes | ||
* new GradualRolloutRule({ | ||
* maxDeploymentsPerTimeWindow: 5, | ||
* timeWindowMinutes: 30 | ||
* }); | ||
* | ||
* // Deterministic rollout with 25% of resources over 24 hours | ||
* new GradualRolloutRule({ | ||
* maxDeploymentsPerTimeWindow: 5, | ||
* timeWindowMinutes: 30, | ||
* deterministicRollout: { | ||
* seed: "my-release-seed", | ||
* percentagePerDay: 25 | ||
* } | ||
* }); | ||
* ``` | ||
*/ | ||
export class GradualRolloutRule implements DeploymentResourceRule { | ||
public readonly name = "GradualRolloutRule"; | ||
|
||
constructor( | ||
private options: { | ||
maxDeploymentsPerTimeWindow: number; | ||
timeWindowMinutes: number; | ||
deterministicRollout?: { | ||
seed: string; | ||
percentagePerDay: number; | ||
}; | ||
}, | ||
) {} | ||
|
||
private async getRecentDeploymentCount(releaseId: string): Promise<number> { | ||
const timeWindowMs = this.options.timeWindowMinutes * 60 * 1000; | ||
const cutoffTime = new Date(Date.now() - timeWindowMs); | ||
|
||
return db | ||
.select({ count: count() }) | ||
.from(schema.job) | ||
.innerJoin( | ||
schema.releaseJobTrigger, | ||
eq(schema.job.id, schema.releaseJobTrigger.jobId), | ||
) | ||
.where( | ||
and( | ||
eq(schema.releaseJobTrigger.versionId, releaseId), | ||
eq(schema.job.status, JobStatus.Successful), | ||
), | ||
) | ||
.then((r) => r[0]?.count ?? 0); | ||
} | ||
|
||
private isResourceEligibleForDeterministicRollout( | ||
resourceId: string, | ||
releaseId: string, | ||
daysSinceRelease: number | ||
): boolean { | ||
if (!this.options.deterministicRollout) return true; | ||
|
||
const { seed, percentagePerDay } = this.options.deterministicRollout; | ||
|
||
// Calculate max percentage based on days since release, capped at 100% | ||
const maxPercentage = Math.min(percentagePerDay * daysSinceRelease, 100); | ||
|
||
// Create a deterministic hash from the resource ID, release ID, and seed | ||
const hash = crypto | ||
.createHash("sha256") | ||
.update(`${resourceId}-${releaseId}-${seed}`) | ||
.digest("hex"); | ||
|
||
// Convert first 4 bytes of hash to a number between 0-100 | ||
const hashValue = parseInt(hash.substring(0, 8), 16) % 100; | ||
|
||
// Resource is eligible if its hash value falls within the allowed percentage | ||
return hashValue < maxPercentage; | ||
} | ||
|
||
private getDaysSinceRelease(release: Release): number { | ||
const releaseDate = release.createdAt; | ||
const now = new Date(); | ||
const msDiff = now.getTime() - releaseDate.getTime(); | ||
return Math.floor(msDiff / (1000 * 60 * 60 * 24)); | ||
} | ||
|
||
async filter( | ||
ctx: DeploymentResourceContext, | ||
currentCandidates: Release[], | ||
): Promise<DeploymentResourceRuleResult> { | ||
// If we don't have the desired release, nothing to do | ||
const desiredRelease = currentCandidates.find( | ||
(r) => r.id === ctx.desiredReleaseId, | ||
); | ||
if (!desiredRelease) { | ||
return { allowedReleases: currentCandidates }; | ||
} | ||
|
||
// Check deterministic rollout eligibility if configured | ||
if (this.options.deterministicRollout) { | ||
const daysSinceRelease = this.getDaysSinceRelease(desiredRelease); | ||
const isEligible = this.isResourceEligibleForDeterministicRollout( | ||
ctx.resource.id, | ||
ctx.desiredReleaseId, | ||
daysSinceRelease | ||
); | ||
|
||
if (!isEligible) { | ||
// Filter out the desired release | ||
const filteredReleases = currentCandidates.filter( | ||
(r) => r.id !== ctx.desiredReleaseId, | ||
); | ||
|
||
const { percentagePerDay } = this.options.deterministicRollout; | ||
const currentPercentage = Math.min(percentagePerDay * daysSinceRelease, 100); | ||
|
||
return { | ||
allowedReleases: filteredReleases, | ||
reason: `Resource not eligible for release yet. Currently at ${currentPercentage}% rollout (${daysSinceRelease} days since release).`, | ||
}; | ||
} | ||
} | ||
|
||
// Get count of recent deployments for this release | ||
const recentDeployments = await this.getRecentDeploymentCount( | ||
ctx.desiredReleaseId, | ||
); | ||
|
||
// Check if we've hit the limit for this time window | ||
if (recentDeployments >= this.options.maxDeploymentsPerTimeWindow) { | ||
// Filter out the desired release | ||
const filteredReleases = currentCandidates.filter( | ||
(r) => r.id !== ctx.desiredReleaseId, | ||
); | ||
|
||
return { | ||
allowedReleases: filteredReleases, | ||
reason: `Gradual rollout limit reached (${recentDeployments}/${this.options.maxDeploymentsPerTimeWindow} deployments in the last ${this.options.timeWindowMinutes} minutes). Please try again later.`, | ||
}; | ||
} | ||
|
||
return { allowedReleases: currentCandidates }; | ||
} | ||
} |
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.
Uh oh!
There was an error while loading. Please reload this page.