Skip to content

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
wants to merge 12 commits into from
Closed
Show file tree
Hide file tree
Changes from 3 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
13 changes: 13 additions & 0 deletions packages/rule-engine/eslint.config.js
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,
];
36 changes: 36 additions & 0 deletions packages/rule-engine/package.json
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"
}
5 changes: 5 additions & 0 deletions packages/rule-engine/src/index.ts
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";
72 changes: 72 additions & 0 deletions packages/rule-engine/src/rule-engine.ts
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];
}
}
97 changes: 97 additions & 0 deletions packages/rule-engine/src/rules/approval-required-rule.ts
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(

Check failure on line 36 in packages/rule-engine/src/rules/approval-required-rule.ts

View workflow job for this annotation

GitHub Actions / Lint

Async method 'filter' has no 'await' expression
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];

Check failure on line 67 in packages/rule-engine/src/rules/approval-required-rule.ts

View workflow job for this annotation

GitHub Actions / Lint

Unnecessary optional chain on a non-nullish value

// 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 };
}
}
162 changes: 162 additions & 0 deletions packages/rule-engine/src/rules/gradual-rollout-rule.ts
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);

Check failure on line 55 in packages/rule-engine/src/rules/gradual-rollout-rule.ts

View workflow job for this annotation

GitHub Actions / Lint

'cutoffTime' is assigned a value but never used. Allowed unused vars must match /^_/u

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 };
}
}
Loading
Loading