Skip to content

Commit

Permalink
fix: Minimum release interval policy (#272)
Browse files Browse the repository at this point in the history
  • Loading branch information
adityachoudhari26 authored Dec 23, 2024
1 parent 3bb6e4b commit aa32fa8
Show file tree
Hide file tree
Showing 10 changed files with 4,854 additions and 54 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,14 @@ import { toast } from "@ctrlplane/ui/toast";
import { api } from "~/trpc/react";
import { useInvalidatePolicy } from "./useInvalidatePolicy";

const isValidDuration = (str: string) => !isNaN(ms(str));
const isValidDuration = (str: string) => {
try {
const duration = ms(str);
return !Number.isNaN(duration) && duration >= 0;
} catch {
return false;
}
};

const schema = z.object({
releaseWindows: z.array(
Expand All @@ -48,6 +55,9 @@ const schema = z.object({
rolloutDuration: z.string().refine(isValidDuration, {
message: "Invalid duration pattern",
}),
minimumReleaseInterval: z.string().refine(isValidDuration, {
message: "Invalid duration pattern",
}),
});

type RolloutAndTimingProps = {
Expand All @@ -62,10 +72,15 @@ export const RolloutAndTiming: React.FC<RolloutAndTimingProps> = ({
isLoading,
}) => {
const rolloutDuration = prettyMilliseconds(environmentPolicy.rolloutDuration);
const form = useForm({
schema,
defaultValues: { ...environmentPolicy, rolloutDuration },
});
const minimumReleaseInterval = prettyMilliseconds(
environmentPolicy.minimumReleaseInterval,
);
const defaultValues = {
...environmentPolicy,
rolloutDuration,
minimumReleaseInterval,
};
const form = useForm({ schema, defaultValues });

const { fields, append, remove } = useFieldArray({
control: form.control,
Expand All @@ -79,8 +94,10 @@ export const RolloutAndTiming: React.FC<RolloutAndTimingProps> = ({
const onSubmit = form.handleSubmit((data) => {
const { releaseWindows, rolloutDuration: durationString } = data;
const rolloutDuration = ms(durationString);
const minimumReleaseInterval = ms(data.minimumReleaseInterval);
const updates = { rolloutDuration, releaseWindows, minimumReleaseInterval };
updatePolicy
.mutateAsync({ id: policyId, data: { rolloutDuration, releaseWindows } })
.mutateAsync({ id: policyId, data: updates })
.then(() => form.reset(data))
.then(() => invalidatePolicy())
.catch((e) => toast.error(e.message));
Expand Down Expand Up @@ -222,7 +239,39 @@ export const RolloutAndTiming: React.FC<RolloutAndTimingProps> = ({
<div className="flex flex-col gap-1">
<div className="flex items-center gap-2">
<span className="text-sm text-muted-foreground">
Spread deployments out over
Roll deployments out over
</span>
<Input
type="string"
{...field}
placeholder="1d"
className="border-b-1 h-6 w-16 text-xs"
/>
</div>
<FormMessage />
</div>
</FormControl>
</FormItem>
)}
/>

<FormField
control={form.control}
name="minimumReleaseInterval"
render={({ field }) => (
<FormItem className="space-y-4">
<div className="flex flex-col gap-1">
<FormLabel>Minimum Release Interval</FormLabel>
<FormDescription>
Setting a minimum release interval will ensure that a certain
amount of time has passed since the last active release.
</FormDescription>
</div>
<FormControl>
<div className="flex flex-col gap-1">
<div className="flex items-center gap-2">
<span className="text-sm text-muted-foreground">
Minimum amount of time between active releases:
</span>
<Input
type="string"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ export const FlowDiagram: React.FC<{
releaseVersion: release.version,
deploymentId: release.deploymentId,
environmentId: env.id,
policyType: policy?.releaseSequencing,
policy,
label: `${env.name} - release sequencing`,
},
};
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type * as SCHEMA from "@ctrlplane/db/schema";
import type {
EnvironmentCondition,
JobCondition,
Expand All @@ -6,8 +7,11 @@ import type {
} from "@ctrlplane/validators/jobs";
import type { ReleaseCondition } from "@ctrlplane/validators/releases";
import type { NodeProps } from "reactflow";
import { useEffect, useState } from "react";
import { IconCheck, IconLoader2, IconMinus, IconX } from "@tabler/icons-react";
import { differenceInMilliseconds } from "date-fns";
import _ from "lodash";
import prettyMilliseconds from "pretty-ms";
import { Handle, Position } from "reactflow";
import colors from "tailwindcss/colors";

Expand All @@ -21,12 +25,14 @@ import {
import { JobFilterType, JobStatus } from "@ctrlplane/validators/jobs";
import { ReleaseFilterType } from "@ctrlplane/validators/releases";

import { EnvironmentPolicyDrawerTab } from "~/app/[workspaceSlug]/(app)/_components/environment-policy-drawer/EnvironmentPolicyDrawer";
import { useReleaseChannelDrawer } from "~/app/[workspaceSlug]/(app)/_components/release-channel-drawer/useReleaseChannelDrawer";
import { useQueryParams } from "~/app/[workspaceSlug]/(app)/_components/useQueryParams";
import { api } from "~/trpc/react";

type ReleaseSequencingNodeProps = NodeProps<{
workspaceId: string;
policyType?: "cancel" | "wait";
policy?: SCHEMA.EnvironmentPolicy;
releaseId: string;
releaseVersion: string;
deploymentId: string;
Expand All @@ -52,8 +58,8 @@ const Waiting: React.FC = () => (
);

const Loading: React.FC = () => (
<div className="animate-spin rounded-full bg-muted-foreground p-0.5 dark:text-black">
<IconLoader2 strokeWidth={3} className="h-3 w-3" />
<div className="rounded-full bg-muted-foreground p-0.5 dark:text-black">
<IconLoader2 strokeWidth={3} className="h-3 w-3 animate-spin" />
</div>
);

Expand Down Expand Up @@ -243,31 +249,122 @@ const ReleaseChannelCheck: React.FC<ReleaseSequencingNodeProps["data"]> = ({
);
};

export const ReleaseSequencingNode: React.FC<ReleaseSequencingNodeProps> = ({
data,
const MinReleaseIntervalCheck: React.FC<ReleaseSequencingNodeProps["data"]> = ({
policy,
deploymentId,
environmentId,
}) => {
return (
<>
<div
className={cn(
"relative w-[250px] space-y-1 rounded-md border px-2 py-1.5 text-sm",
)}
>
<WaitingOnActiveCheck {...data} />
<ReleaseChannelCheck {...data} />
const [timeLeft, setTimeLeft] = useState<number | null>(null);
const { setParams } = useQueryParams();

const { data: latestRelease, isLoading } =
api.release.latest.completed.useQuery(
{ deploymentId, environmentId },
{ enabled: policy != null },
);

useEffect(() => {
if (!latestRelease || !policy?.minimumReleaseInterval) return;

const calculateTimeLeft = () => {
const timePassed = differenceInMilliseconds(
new Date(),
latestRelease.createdAt,
);
return Math.max(0, policy.minimumReleaseInterval - timePassed);
};

setTimeLeft(calculateTimeLeft());

const interval = setInterval(() => {
const remaining = calculateTimeLeft();
setTimeLeft(remaining);

if (remaining <= 0) clearInterval(interval);
}, 1000);

return () => clearInterval(interval);
}, [latestRelease, policy?.minimumReleaseInterval]);

if (policy == null) return null;
const { minimumReleaseInterval } = policy;
if (minimumReleaseInterval === 0) return null;
if (isLoading)
return (
<div className="flex items-center gap-2">
<Loading />
</div>
);

if (latestRelease == null || timeLeft === 0)
return (
<div className="flex items-center gap-2">
<Passing />
<span className="flex items-center gap-1">
Minimum
<Button
variant="link"
onClick={() =>
setParams({
environment_policy_id: policy.id,
tab: EnvironmentPolicyDrawerTab.Rollout,
})
}
className="h-fit px-0 py-0 text-inherit underline-offset-2"
>
release interval
</Button>
passed
</span>
</div>
<Handle
type="target"
className="h-2 w-2 rounded-full border border-neutral-500"
style={{ background: colors.neutral[800] }}
position={Position.Left}
/>
<Handle
type="source"
className="h-2 w-2 rounded-full border border-neutral-500"
style={{ background: colors.neutral[800] }}
position={Position.Right}
/>
</>
);

return (
<div className="flex items-center gap-2">
<Waiting />
<span className="flex items-center gap-1">
<Button
variant="link"
onClick={() =>
setParams({
environment_policy_id: policy.id,
tab: EnvironmentPolicyDrawerTab.Rollout,
})
}
className="h-fit px-0 py-0 text-inherit underline-offset-2"
>
Waiting {prettyMilliseconds(timeLeft ?? 0, { compact: true })}
</Button>
till next release
</span>
</div>
);
};

export const ReleaseSequencingNode: React.FC<ReleaseSequencingNodeProps> = ({
data,
}) => (
<>
<div
className={cn(
"relative w-[250px] space-y-1 rounded-md border px-2 py-1.5 text-sm",
)}
>
<WaitingOnActiveCheck {...data} />
<ReleaseChannelCheck {...data} />
<MinReleaseIntervalCheck {...data} />
</div>
<Handle
type="target"
className="h-2 w-2 rounded-full border border-neutral-500"
style={{ background: colors.neutral[800] }}
position={Position.Left}
/>
<Handle
type="source"
className="h-2 w-2 rounded-full border border-neutral-500"
style={{ background: colors.neutral[800] }}
position={Position.Right}
/>
</>
);
66 changes: 65 additions & 1 deletion packages/api/src/router/release.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ import {
count,
desc,
eq,
exists,
inArray,
notExists,
takeFirst,
takeFirstOrNull,
} from "@ctrlplane/db";
Expand Down Expand Up @@ -36,7 +38,11 @@ import {
isPassingReleaseStringCheckPolicy,
} from "@ctrlplane/job-dispatch";
import { Permission } from "@ctrlplane/validators/auth";
import { jobCondition } from "@ctrlplane/validators/jobs";
import {
activeStatus,
jobCondition,
JobStatus,
} from "@ctrlplane/validators/jobs";
import { releaseCondition } from "@ctrlplane/validators/releases";

import { createTRPCRouter, protectedProcedure } from "../trpc";
Expand Down Expand Up @@ -351,5 +357,63 @@ export const releaseRouter = createTRPCRouter({
),
}),

latest: createTRPCRouter({
completed: protectedProcedure
.input(
z.object({
deploymentId: z.string().uuid(),
environmentId: z.string().uuid(),
}),
)
.meta({
authorizationCheck: ({ canUser, input }) =>
canUser.perform(Permission.ReleaseGet).on({
type: "deployment",
id: input.deploymentId,
}),
})
.query(({ input: { deploymentId, environmentId } }) =>
db
.select()
.from(release)
.innerJoin(environment, eq(environment.id, environmentId))
.where(
and(
eq(release.deploymentId, deploymentId),
exists(
db
.select()
.from(releaseJobTrigger)
.where(
and(
eq(releaseJobTrigger.releaseId, release.id),
eq(releaseJobTrigger.environmentId, environmentId),
),
)
.limit(1),
),
notExists(
db
.select()
.from(releaseJobTrigger)
.innerJoin(job, eq(releaseJobTrigger.jobId, job.id))
.where(
and(
eq(releaseJobTrigger.releaseId, release.id),
eq(releaseJobTrigger.environmentId, environmentId),
inArray(job.status, [...activeStatus, JobStatus.Pending]),
),
)
.limit(1),
),
),
)
.orderBy(desc(release.createdAt))
.limit(1)
.then(takeFirstOrNull)
.then((r) => r?.release ?? null),
),
}),

metadataKeys: releaseMetadataKeysRouter,
});
1 change: 1 addition & 0 deletions packages/db/drizzle/0048_lucky_eddie_brock.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
ALTER TABLE "environment_policy" ADD COLUMN "minimum_release_interval" bigint DEFAULT 0 NOT NULL;
Loading

0 comments on commit aa32fa8

Please sign in to comment.