The best way to control Claude Code, Codex and more from any computer or phone

main
ts 244 lines 9.06 KB
Raw
1 import * as appconfig from "@distilled.cloud/aws/appconfig";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import { createInternalTags, hasAlchemyTags } from "alchemy/Tags";
8 import { toWireMinutes } from "alchemy/Util/Duration";
9 import type * as Duration from "effect/Duration";
10 import * as Effect from "effect/Effect";
11 import * as Stream from "effect/Stream";
12 import { AWSEnvironment } from "../Environment.ts";
13 import type { Providers } from "../Providers.ts";
14 import { deploymentStrategyArn, readAppConfigTags, syncAppConfigTags } from "./internal.ts";
15
16 export interface DeploymentStrategyProps {
17 /**
18 * Name of the deployment strategy. Must be 1-64 characters. If omitted, a
19 * deterministic physical name is generated. Changing the name replaces the
20 * strategy.
21 */
22 deploymentStrategyName?: string;
23 /**
24 * Total amount of time over which the deployment rolls the configuration
25 * out to targets (e.g. `"10 minutes"` or `Duration.minutes(10)`; a bare
26 * number is milliseconds). Sent to AppConfig as whole minutes.
27 */
28 deploymentDuration: Duration.Input;
29 /**
30 * Percentage of targets to receive a deployed configuration during each
31 * interval.
32 */
33 growthFactor: number;
34 /**
35 * How growth is applied over the deployment. `LINEAR` grows by
36 * `growthFactor` each interval; `EXPONENTIAL` follows `2^(N*growthFactor)`.
37 * @default "LINEAR"
38 */
39 growthType?: "LINEAR" | "EXPONENTIAL";
40 /**
41 * Amount of time AppConfig monitors for alarms before considering the
42 * deployment complete (e.g. `"5 minutes"`). Sent to AppConfig as whole
43 * minutes.
44 * @default 0
45 */
46 finalBakeTime?: Duration.Input;
47 /**
48 * Where to save a copy of the applied configuration. Immutable — changing
49 * it replaces the strategy.
50 * @default "NONE"
51 */
52 replicateTo?: "NONE" | "SSM_DOCUMENT";
53 /**
54 * Description of the deployment strategy.
55 */
56 description?: string;
57 /**
58 * User-defined tags for the deployment strategy.
59 */
60 tags?: Record<string, string>;
61 }
62
63 export interface DeploymentStrategy extends Resource<
64 "AWS.AppConfig.DeploymentStrategy",
65 DeploymentStrategyProps,
66 {
67 deploymentStrategyId: string;
68 deploymentStrategyName: string;
69 deploymentStrategyArn: string;
70 },
71 never,
72 Providers
73 > {}
74
75 /**
76 * An AWS AppConfig deployment strategy — defines how a configuration version
77 * rolls out to an environment: the total duration, the per-interval growth,
78 * and the final bake time during which alarms can trigger a rollback.
79 *
80 * ### Creating a Deployment Strategy
81 * **Example:** All-At-Once (instant, no bake)
82 * ```typescript
83 * const strategy = yield* AppConfig.DeploymentStrategy("Fast", {
84 * deploymentDuration: 0,
85 * growthFactor: 100,
86 * finalBakeTime: 0,
87 * replicateTo: "NONE",
88 * });
89 * ```
90 *
91 * **Example:** Linear rollout over 10 minutes
92 * ```typescript
93 * const strategy = yield* AppConfig.DeploymentStrategy("Linear", {
94 * deploymentDuration: "10 minutes",
95 * growthFactor: 25,
96 * growthType: "LINEAR",
97 * finalBakeTime: "5 minutes",
98 * });
99 * ```
100 *
101 * @resource
102 */
103 export const DeploymentStrategy = Resource<DeploymentStrategy>("AWS.AppConfig.DeploymentStrategy");
104
105 export const DeploymentStrategyProvider = () =>
106 Provider.effect(
107 DeploymentStrategy,
108 Effect.gen(function* () {
109 const toName = (id: string, props: Partial<DeploymentStrategyProps>) =>
110 props.deploymentStrategyName
111 ? Effect.succeed(props.deploymentStrategyName)
112 : createPhysicalName({ id, maxLength: 64 });
113
114 const readStrategy = Effect.fn(function* (deploymentStrategyId: string) {
115 return yield* appconfig
116 .getDeploymentStrategy({ DeploymentStrategyId: deploymentStrategyId })
117 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
118 });
119
120 const findByName = Effect.fn(function* (name: string) {
121 const strategies = yield* appconfig.listDeploymentStrategies.pages({}).pipe(
122 Stream.runCollect,
123 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.Items ?? [])),
124 );
125 return strategies.find((s) => s.Name === name);
126 });
127
128 return {
129 stables: ["deploymentStrategyId", "deploymentStrategyName", "deploymentStrategyArn"],
130
131 diff: Effect.fn(function* ({ id, olds, news }) {
132 if (!isResolved(news)) return undefined;
133 if ((yield* toName(id, olds ?? {})) !== (yield* toName(id, news ?? {}))) {
134 return { action: "replace" } as const;
135 }
136 // ReplicateTo is create-only.
137 if ((olds?.replicateTo ?? "NONE") !== (news?.replicateTo ?? "NONE")) {
138 return { action: "replace" } as const;
139 }
140 }),
141
142 read: Effect.fn(function* ({ id, olds, output }) {
143 const { accountId, region } = yield* AWSEnvironment.current;
144 const strategy = output?.deploymentStrategyId
145 ? yield* readStrategy(output.deploymentStrategyId)
146 : yield* findByName(yield* toName(id, olds ?? {}));
147 if (strategy?.Id === undefined) return undefined;
148 const arn = deploymentStrategyArn(region, accountId, strategy.Id);
149 const attrs = {
150 deploymentStrategyId: strategy.Id,
151 deploymentStrategyName: strategy.Name!,
152 deploymentStrategyArn: arn,
153 };
154 const tags = yield* readAppConfigTags(arn);
155 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
156 }),
157
158 reconcile: Effect.fn(function* ({ id, news, output, session }) {
159 const { accountId, region } = yield* AWSEnvironment.current;
160 const name = output?.deploymentStrategyName ?? (yield* toName(id, news));
161 const internalTags = yield* createInternalTags(id);
162 const desiredTags = { ...internalTags, ...news.tags };
163
164 // 1. Observe.
165 let observed = output?.deploymentStrategyId
166 ? yield* readStrategy(output.deploymentStrategyId)
167 : undefined;
168 if (observed === undefined) {
169 observed = yield* findByName(name);
170 }
171
172 // 2. Ensure.
173 if (observed?.Id === undefined) {
174 observed = yield* appconfig.createDeploymentStrategy({
175 Name: name,
176 Description: news.description,
177 DeploymentDurationInMinutes: toWireMinutes(news.deploymentDuration)!,
178 FinalBakeTimeInMinutes: toWireMinutes(news.finalBakeTime),
179 GrowthFactor: news.growthFactor,
180 GrowthType: news.growthType,
181 ReplicateTo: news.replicateTo ?? "NONE",
182 Tags: desiredTags,
183 });
184 } else {
185 // 3. Sync — everything but Name and ReplicateTo is mutable.
186 observed = yield* appconfig.updateDeploymentStrategy({
187 DeploymentStrategyId: observed.Id,
188 Description: news.description,
189 DeploymentDurationInMinutes: toWireMinutes(news.deploymentDuration),
190 FinalBakeTimeInMinutes: toWireMinutes(news.finalBakeTime),
191 GrowthFactor: news.growthFactor,
192 GrowthType: news.growthType,
193 });
194 }
195
196 const arn = deploymentStrategyArn(region, accountId, observed.Id!);
197
198 // 3b. Sync tags.
199 yield* syncAppConfigTags(arn, desiredTags);
200
201 yield* session.note(name);
202 return {
203 deploymentStrategyId: observed.Id!,
204 deploymentStrategyName: observed.Name ?? name,
205 deploymentStrategyArn: arn,
206 };
207 }),
208
209 delete: Effect.fn(function* ({ output }) {
210 yield* appconfig
211 .deleteDeploymentStrategy({
212 DeploymentStrategyId: output.deploymentStrategyId,
213 })
214 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
215 }),
216
217 list: () =>
218 Effect.gen(function* () {
219 const { accountId, region } = yield* AWSEnvironment.current;
220 const strategies = yield* appconfig.listDeploymentStrategies.pages({}).pipe(
221 Stream.runCollect,
222 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.Items ?? [])),
223 );
224 return strategies.flatMap((s) =>
225 s.Id !== undefined &&
226 s.Name !== undefined &&
227 // AWS-predefined strategies (AppConfig.AllAtOnce,
228 // AppConfig.Linear50PercentEvery30Seconds, ...) are managed by
229 // AWS and cannot be deleted — deleteDeploymentStrategy rejects
230 // them with "Cannot delete predefined Deployment Strategy".
231 !s.Id.startsWith("AppConfig.")
232 ? [
233 {
234 deploymentStrategyId: s.Id,
235 deploymentStrategyName: s.Name,
236 deploymentStrategyArn: deploymentStrategyArn(region, accountId, s.Id),
237 },
238 ]
239 : [],
240 );
241 }),
242 };
243 }),
244 );