@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 206 lines 6.59 KB
Raw
1 import type * as Duration from "effect/Duration";
2 import * as Effect from "effect/Effect";
3 import type * as Stream from "effect/Stream";
4 import { consumeBusEvents, type EventRecord } from "../EventBridge/EventSource.ts";
5 import type { AutoScalingGroup } from "./AutoScalingGroup.ts";
6 import {
7 LifecycleHook,
8 normalizeTransition,
9 type LifecycleActionResult,
10 type LifecycleTransition,
11 } from "./LifecycleHook.ts";
12
13 /**
14 * The `detail` payload EC2 Auto Scaling delivers to EventBridge when an instance
15 * enters a lifecycle wait state.
16 */
17 export interface LifecycleActionDetail {
18 /**
19 * Token identifying this specific lifecycle action; pass it to
20 * `complete`/`heartbeat` on the {@link CompleteLifecycleAction} binding.
21 */
22 LifecycleActionToken: string;
23 /**
24 * Name of the Auto Scaling Group the instance belongs to.
25 */
26 AutoScalingGroupName: string;
27 /**
28 * Name of the lifecycle hook that paused the instance.
29 */
30 LifecycleHookName: string;
31 /**
32 * ID of the EC2 instance in the wait state.
33 */
34 EC2InstanceId: string;
35 /**
36 * The paused transition (e.g. `autoscaling:EC2_INSTANCE_LAUNCHING`).
37 */
38 LifecycleTransition: string;
39 /**
40 * Metadata configured on the hook via `notificationMetadata`.
41 */
42 NotificationMetadata?: string;
43 /**
44 * Where the instance is coming from (e.g. `EC2` or `WarmPool`).
45 */
46 Origin?: string;
47 /**
48 * Where the instance is headed (e.g. `AutoScalingGroup` or `WarmPool`).
49 */
50 Destination?: string;
51 }
52
53 /** A lifecycle-action EventBridge event delivered to the handler. */
54 export type LifecycleActionEvent = EventRecord<LifecycleActionDetail>;
55
56 export interface LifecycleHookEventSourceProps {
57 /**
58 * Logical id prefix for the backing hook + EventBridge rule. Defaults to the
59 * Auto Scaling Group's logical id.
60 */
61 id?: string;
62 /**
63 * Physical name for the lifecycle hook. If omitted, a deterministic name is
64 * generated.
65 */
66 lifecycleHookName?: string;
67 /**
68 * Instance state transition to pause on.
69 */
70 lifecycleTransition: LifecycleTransition;
71 /**
72 * Maximum time an instance stays paused before `defaultResult` applies,
73 * e.g. `"5 minutes"` or `Duration.seconds(300)` (whole seconds on the
74 * wire).
75 * @default "1 hour"
76 */
77 heartbeatTimeout?: Duration.Input;
78 /**
79 * Action taken when the hook times out.
80 * @default "ABANDON"
81 */
82 defaultResult?: LifecycleActionResult;
83 /**
84 * Metadata delivered with the lifecycle event.
85 */
86 notificationMetadata?: string;
87 }
88
89 const detailTypeFor = (transition: string): string =>
90 transition === "autoscaling:EC2_INSTANCE_LAUNCHING"
91 ? "EC2 Instance-launch Lifecycle Action"
92 : "EC2 Instance-terminate Lifecycle Action";
93
94 /**
95 * Pause an Auto Scaling instance transition and deliver the lifecycle event to
96 * the host Function. Creates the backing {@link LifecycleHook} on `group` (so
97 * instances actually pause) and subscribes the Function to the matching
98 * `aws.autoscaling` EventBridge events. Pair with
99 * {@link CompleteLifecycleAction} to signal `CONTINUE` / `ABANDON` from the
100 * handler.
101 *
102 * The EventBridge pattern matches every lifecycle action of this transition in
103 * the account; inspect `event.detail.AutoScalingGroupName` /
104 * `event.detail.LifecycleHookName` in the handler if multiple groups share the
105 * Function.
106 *
107 * ### Draining Instances
108 * **Example:** Signal CONTINUE when an instance is about to terminate
109 * ```typescript
110 * const lifecycle = yield* CompleteLifecycleAction(group);
111 * yield* consumeLifecycleActions(
112 * group,
113 * { lifecycleTransition: "TERMINATING", heartbeatTimeout: "300 seconds" },
114 * (events) =>
115 * Stream.runForEach(events, (event) =>
116 * lifecycle
117 * .complete({
118 * LifecycleHookName: event.detail.LifecycleHookName,
119 * LifecycleActionToken: event.detail.LifecycleActionToken,
120 * LifecycleActionResult: "CONTINUE",
121 * })
122 * .pipe(Effect.orDie),
123 * ),
124 * );
125 * ```
126 *
127 * **Example:** Register the event source inside a Lambda Function
128 * ```typescript
129 * import * as AWS from "@alchemy.run/aws";
130 * import {
131 * CompleteLifecycleAction,
132 * CompleteLifecycleActionHttp,
133 * consumeLifecycleActions,
134 * } from "@alchemy.run/aws/AutoScaling";
135 *
136 * export class DrainFunction extends AWS.Lambda.Function<AWS.Lambda.Function>()(
137 * "DrainFunction",
138 * ) {}
139 *
140 * export default DrainFunction.make(
141 * { main: import.meta.url },
142 * Effect.gen(function* () {
143 * const lifecycle = yield* CompleteLifecycleAction(group);
144 *
145 * // creates the LifecycleHook on the group and subscribes this Function
146 * // to the matching EventBridge lifecycle events
147 * yield* consumeLifecycleActions(
148 * group,
149 * { lifecycleTransition: "TERMINATING" },
150 * (events) =>
151 * Stream.runForEach(events, (event) =>
152 * lifecycle
153 * .complete({
154 * LifecycleHookName: event.detail.LifecycleHookName,
155 * LifecycleActionToken: event.detail.LifecycleActionToken,
156 * LifecycleActionResult: "CONTINUE",
157 * })
158 * .pipe(Effect.orDie),
159 * ),
160 * );
161 *
162 * return {};
163 * }).pipe(
164 * Effect.provide(
165 * Layer.mergeAll(AWS.Lambda.EventSource, CompleteLifecycleActionHttp),
166 * ),
167 * ),
168 * );
169 * ```
170 */
171 export const consumeLifecycleActions = <StreamReq = never, Req = never>(
172 group: AutoScalingGroup,
173 props: LifecycleHookEventSourceProps,
174 process: (
175 events: Stream.Stream<LifecycleActionEvent, never, StreamReq>,
176 ) => Effect.Effect<void, never, Req>,
177 ) =>
178 Effect.gen(function* () {
179 const transition = normalizeTransition(props.lifecycleTransition);
180 const idPrefix = props.id ?? group.LogicalId;
181
182 // Create the hook so instances actually pause and emit lifecycle events.
183 const hook = yield* LifecycleHook(`${idPrefix}-LifecycleHook`, {
184 autoScalingGroup: group,
185 lifecycleHookName: props.lifecycleHookName,
186 lifecycleTransition: props.lifecycleTransition,
187 heartbeatTimeout: props.heartbeatTimeout,
188 defaultResult: props.defaultResult,
189 notificationMetadata: props.notificationMetadata,
190 });
191
192 // Subscribe the host Function to the matching lifecycle events. The pattern
193 // uses only literal `source` + `detail-type` so it round-trips through both
194 // the deploy-time rule and the runtime matcher (Output values cannot appear
195 // in the pattern — they don't resolve inside the deployed bundle).
196 yield* consumeBusEvents(
197 `${idPrefix}-LifecycleEvents`,
198 {
199 source: ["aws.autoscaling"],
200 "detail-type": [detailTypeFor(transition)],
201 },
202 process,
203 );
204
205 return hook;
206 });