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

main
ts 320 lines 11.8 KB
Raw
1 import * as autoscaling from "@distilled.cloud/aws/auto-scaling";
2 import { deepEqual, isResolved } from "alchemy/Diff";
3 import type { Input } from "alchemy/Input";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import { toSeconds } from "alchemy/Util/Duration";
8 import * as Data from "effect/Data";
9 import type * as Duration from "effect/Duration";
10 import * as Effect from "effect/Effect";
11 import * as Schedule from "effect/Schedule";
12 import type { Providers } from "../Providers.ts";
13 import type { AutoScalingGroup as AutoScalingGroupResource } from "./AutoScalingGroup.ts";
14
15 export class LifecycleHookUnexpectedResponse extends Data.TaggedError(
16 "LifecycleHookUnexpectedResponse",
17 )<{
18 readonly message: string;
19 readonly cause?: unknown;
20 }> {}
21
22 export type LifecycleHookName = string;
23
24 /**
25 * Lifecycle transition the hook fires on. The friendly `LAUNCHING` /
26 * `TERMINATING` aliases map to the `autoscaling:EC2_INSTANCE_*` transition
27 * strings the API expects.
28 */
29 export type LifecycleTransition =
30 | "LAUNCHING"
31 | "TERMINATING"
32 | "autoscaling:EC2_INSTANCE_LAUNCHING"
33 | "autoscaling:EC2_INSTANCE_TERMINATING";
34
35 export type LifecycleActionResult = "CONTINUE" | "ABANDON";
36
37 export const normalizeTransition = (transition: LifecycleTransition): string =>
38 transition === "LAUNCHING"
39 ? "autoscaling:EC2_INSTANCE_LAUNCHING"
40 : transition === "TERMINATING"
41 ? "autoscaling:EC2_INSTANCE_TERMINATING"
42 : transition;
43
44 export interface LifecycleHookProps {
45 /**
46 * Lifecycle hook name. If omitted, a deterministic name is generated.
47 */
48 lifecycleHookName?: string;
49 /**
50 * Auto Scaling Group to attach the hook to.
51 */
52 autoScalingGroup: Input<string> | AutoScalingGroupResource;
53 /**
54 * Instance state transition the hook pauses on. Use `LAUNCHING` to drain
55 * before an instance enters service, `TERMINATING` to drain before it is
56 * removed.
57 */
58 lifecycleTransition: LifecycleTransition;
59 /**
60 * Maximum time the instance stays in the wait state before the
61 * `defaultResult` is applied, e.g. `"5 minutes"` or
62 * `Duration.seconds(300)` (30 seconds–2 hours on the wire).
63 * @default "1 hour"
64 */
65 heartbeatTimeout?: Duration.Input;
66 /**
67 * Action taken when the hook times out or the ASG is otherwise unable to
68 * respond.
69 * @default "ABANDON"
70 */
71 defaultResult?: LifecycleActionResult;
72 /**
73 * ARN of an SNS topic or SQS queue to notify when the transition occurs.
74 * Omit to receive lifecycle events via EventBridge (the default target).
75 */
76 notificationTargetARN?: string;
77 /**
78 * ARN of the IAM role that permits the ASG to publish to
79 * `notificationTargetARN`. Required when `notificationTargetARN` is set.
80 */
81 roleARN?: string;
82 /**
83 * Arbitrary metadata delivered with the lifecycle notification.
84 */
85 notificationMetadata?: string;
86 }
87
88 export interface LifecycleHook extends Resource<
89 "AWS.AutoScaling.LifecycleHook",
90 LifecycleHookProps,
91 {
92 /**
93 * Name of the lifecycle hook.
94 */
95 lifecycleHookName: LifecycleHookName;
96 /**
97 * Name of the Auto Scaling Group the hook is attached to.
98 */
99 autoScalingGroupName: string;
100 /**
101 * The paused transition (e.g. `autoscaling:EC2_INSTANCE_LAUNCHING`).
102 */
103 lifecycleTransition: string;
104 /**
105 * Seconds an instance stays paused before `defaultResult` applies.
106 */
107 heartbeatTimeout: number;
108 /**
109 * Maximum total seconds an instance can remain in the wait state
110 * (100x heartbeat, capped by AWS).
111 */
112 globalTimeout: number;
113 /**
114 * Action taken when the hook times out (`CONTINUE` or `ABANDON`).
115 */
116 defaultResult: string;
117 /**
118 * SNS/SQS target lifecycle notifications are published to, if any.
119 */
120 notificationTargetARN?: string;
121 /**
122 * IAM role used to publish to the notification target, if any.
123 */
124 roleARN?: string;
125 /**
126 * Metadata delivered with each lifecycle event.
127 */
128 notificationMetadata?: string;
129 },
130 never,
131 Providers
132 > {}
133
134 /**
135 * A lifecycle hook that pauses an Auto Scaling instance in a wait state on
136 * launch or termination so a handler can drain connections, snapshot state, or
137 * warm caches before the transition completes. Pair with
138 * {@link consumeLifecycleActions} to receive the transition events and
139 * {@link CompleteLifecycleAction} to signal `CONTINUE` / `ABANDON`.
140 *
141 * ### Creating a Lifecycle Hook
142 * **Example:** Drain before termination (EventBridge target)
143 * ```typescript
144 * const hook = yield* LifecycleHook("Drain", {
145 * autoScalingGroup: group,
146 * lifecycleTransition: "TERMINATING",
147 * heartbeatTimeout: "300 seconds",
148 * defaultResult: "CONTINUE",
149 * });
150 * ```
151 *
152 * **Example:** Warm caches before an instance enters service
153 * ```typescript
154 * const hook = yield* LifecycleHook("Warm", {
155 * autoScalingGroup: group,
156 * lifecycleTransition: "LAUNCHING",
157 * heartbeatTimeout: "2 minutes",
158 * });
159 * ```
160 *
161 * @resource
162 */
163 export const LifecycleHook = Resource<LifecycleHook>("AWS.AutoScaling.LifecycleHook");
164
165 // Derive the group name from either spelling of `autoScalingGroup`. A whole
166 // AutoScalingGroup resource resolves to its bare Attributes before reaching the
167 // provider — the resource `Type` marker does not survive resolution — so narrow
168 // on the attributes shape, never on `Type`.
169 const toAutoScalingGroupName = (
170 input: LifecycleHookProps["autoScalingGroup"] | undefined,
171 ): string | undefined =>
172 typeof input === "string"
173 ? input
174 : typeof (input as { autoScalingGroupName?: unknown } | undefined)?.autoScalingGroupName ===
175 "string"
176 ? (input as unknown as { autoScalingGroupName: string }).autoScalingGroupName
177 : undefined;
178
179 export const LifecycleHookProvider = () =>
180 Provider.effect(
181 LifecycleHook,
182 Effect.gen(function* () {
183 const toName = (id: string, props: { lifecycleHookName?: string } = {}) =>
184 props.lifecycleHookName
185 ? Effect.succeed(props.lifecycleHookName)
186 : createPhysicalName({ id, maxLength: 255, lowercase: true });
187
188 const describeHook = ({
189 autoScalingGroupName,
190 lifecycleHookName,
191 }: {
192 autoScalingGroupName: string;
193 lifecycleHookName: string;
194 }) =>
195 autoscaling
196 .describeLifecycleHooks({
197 AutoScalingGroupName: autoScalingGroupName,
198 LifecycleHookNames: [lifecycleHookName],
199 } as any)
200 .pipe(
201 Effect.map((result) => result.LifecycleHooks?.[0]),
202 // A deleted/absent Auto Scaling Group surfaces as
203 // `ValidationError: AutoScalingGroup ... not found` (typed
204 // `AutoScalingGroupNotFound` via the auto-scaling patch); treat it
205 // as "hook gone" so refresh/read converge instead of failing.
206 Effect.catchTag("AutoScalingGroupNotFound", () => Effect.undefined),
207 );
208
209 const toAttributes = (hook: autoscaling.LifecycleHook): LifecycleHook["Attributes"] => ({
210 lifecycleHookName: hook.LifecycleHookName!,
211 autoScalingGroupName: hook.AutoScalingGroupName!,
212 lifecycleTransition: hook.LifecycleTransition!,
213 heartbeatTimeout: hook.HeartbeatTimeout ?? 0,
214 globalTimeout: hook.GlobalTimeout ?? 0,
215 defaultResult: hook.DefaultResult ?? "ABANDON",
216 notificationTargetARN: hook.NotificationTargetARN,
217 roleARN: hook.RoleARN,
218 notificationMetadata: hook.NotificationMetadata,
219 });
220
221 return {
222 stables: ["lifecycleHookName", "autoScalingGroupName"],
223 // A lifecycle hook is a sub-resource of its Auto Scaling Group;
224 // `describeLifecycleHooks` requires an AutoScalingGroupName and cannot
225 // enumerate account-wide, so there is no parent-free listing.
226 list: () => Effect.succeed([]),
227 diff: Effect.fn(function* ({ id, olds, news: _news }) {
228 if (!isResolved(_news)) return undefined;
229 const news = _news as typeof olds;
230 const oldName = yield* toName(id, olds ?? {});
231 const newName = yield* toName(id, news ?? {});
232 const oldGroup = toAutoScalingGroupName(olds.autoScalingGroup);
233 const newGroup = toAutoScalingGroupName(news.autoScalingGroup);
234 // Hook name or ASG change → replace (identity fields). Both sides must
235 // be known before forcing a replacement; a half-created row may have
236 // lost an Output-valued `autoScalingGroup`.
237 if (
238 oldName !== newName ||
239 (oldGroup !== undefined && newGroup !== undefined && oldGroup !== newGroup)
240 ) {
241 return { action: "replace", deleteFirst: true } as const;
242 }
243
244 if (!deepEqual(olds, news)) {
245 return {
246 action: "update",
247 stables: ["lifecycleHookName", "autoScalingGroupName"],
248 } as const;
249 }
250 }),
251 read: Effect.fn(function* ({ id, olds, output }) {
252 const autoScalingGroupName =
253 output?.autoScalingGroupName ?? toAutoScalingGroupName(olds?.autoScalingGroup);
254 const lifecycleHookName = output?.lifecycleHookName ?? (yield* toName(id, olds ?? {}));
255 if (!autoScalingGroupName) return undefined;
256 const hook = yield* describeHook({
257 autoScalingGroupName,
258 lifecycleHookName,
259 });
260 return hook ? toAttributes(hook) : undefined;
261 }),
262 reconcile: Effect.fn(function* ({ id, news, output, session }) {
263 const autoScalingGroupName =
264 output?.autoScalingGroupName ?? toAutoScalingGroupName(news.autoScalingGroup);
265 if (!autoScalingGroupName) {
266 return yield* Effect.die(
267 new Error("LifecycleHook requires a resolvable autoScalingGroup name"),
268 );
269 }
270 const lifecycleHookName = output?.lifecycleHookName ?? (yield* toName(id, news));
271
272 // Ensure + Sync — `putLifecycleHook` is the single create-or-update
273 // API. It overwrites the whole hook configuration, so we issue it
274 // unconditionally (idempotent on matching params).
275 yield* autoscaling.putLifecycleHook({
276 LifecycleHookName: lifecycleHookName,
277 AutoScalingGroupName: autoScalingGroupName,
278 LifecycleTransition: normalizeTransition(news.lifecycleTransition),
279 HeartbeatTimeout: toSeconds(news.heartbeatTimeout),
280 DefaultResult: news.defaultResult,
281 NotificationTargetARN: news.notificationTargetARN,
282 RoleARN: news.roleARN,
283 NotificationMetadata: news.notificationMetadata,
284 } as any);
285
286 const hook = yield* describeHook({
287 autoScalingGroupName,
288 lifecycleHookName,
289 }).pipe(
290 Effect.flatMap((hook) =>
291 hook
292 ? Effect.succeed(hook)
293 : Effect.fail(
294 new LifecycleHookUnexpectedResponse({
295 message: `Lifecycle hook '${lifecycleHookName}' was not readable after reconcile`,
296 }),
297 ),
298 ),
299 );
300 yield* session.note(lifecycleHookName);
301 return toAttributes(hook);
302 }),
303 delete: Effect.fn(function* ({ output }) {
304 // `deleteLifecycleHook` is idempotent — a missing hook returns
305 // success. Retry only the transient contention fault.
306 yield* autoscaling
307 .deleteLifecycleHook({
308 AutoScalingGroupName: output.autoScalingGroupName,
309 LifecycleHookName: output.lifecycleHookName,
310 } as any)
311 .pipe(
312 Effect.retry({
313 while: (error) => error._tag === "ResourceContentionFault",
314 schedule: Schedule.max([Schedule.recurs(5), Schedule.exponential("250 millis")]),
315 }),
316 );
317 }),
318 };
319 }),
320 );