@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, 06:00 UTC

main
ts 414 lines 15.4 KB
Raw
1 import * as cloudhsm from "@distilled.cloud/aws/cloudhsm-v2";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { createInternalTags, createTagsList, diffTags, hasAlchemyTags } from "alchemy/Tags";
7 import { toWireDays } 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 * as Stream from "effect/Stream";
13 import { reapLogGroupsByPrefix } from "../Logs/reapLogGroups.ts";
14 import type { Providers } from "../Providers.ts";
15 import { findClusterById, sameStringSet, toTagRecord } from "./internal.ts";
16
17 export class CloudHSMV2ClusterNotReady extends Data.TaggedError("CloudHSMV2ClusterNotReady")<{
18 readonly message: string;
19 readonly cause?: unknown;
20 }> {}
21
22 export class CloudHSMV2ClusterUnexpectedResponse extends Data.TaggedError(
23 "CloudHSMV2ClusterUnexpectedResponse",
24 )<{
25 readonly message: string;
26 readonly cause?: unknown;
27 }> {}
28
29 export interface ClusterProps {
30 /**
31 * Type of HSM the cluster hosts, e.g. `"hsm2m.medium"` (current
32 * generation) or `"hsm1.medium"` (legacy). Changing the HSM type replaces
33 * the cluster.
34 */
35 hsmType: string;
36 /**
37 * IDs of the subnets the cluster's HSMs may be placed into. Each subnet
38 * must be in a different Availability Zone of the same VPC. Changing the
39 * subnets replaces the cluster.
40 */
41 subnetIds: string[];
42 /**
43 * ID (or, cross-account, the full ARN) of a cluster backup to restore the
44 * new cluster from. Changing the source backup replaces the cluster.
45 */
46 sourceBackupId?: string;
47 /**
48 * IP address type of the cluster's endpoints — `"IPV4"` or `"DUALSTACK"`.
49 * Changing the network type replaces the cluster.
50 * @default "IPV4"
51 */
52 networkType?: cloudhsm.NetworkType;
53 /**
54 * Whether the cluster runs in `"FIPS"` or `"NON_FIPS"` mode. Required by
55 * AWS for `hsm2m.*` HSM types, so Alchemy sends `"FIPS"` when omitted
56 * (legacy `hsm1.*` clusters are FIPS-only and omit it). Changing the mode
57 * replaces the cluster.
58 * @default "FIPS"
59 */
60 mode?: cloudhsm.ClusterMode;
61 /**
62 * How long automatic backups of the cluster are retained (e.g. `"30 days"`
63 * or `Duration.days(30)`; a bare number is milliseconds). Converted to
64 * whole days on the wire. Updated in place via ModifyCluster.
65 * @default 90 days
66 */
67 backupRetention?: Duration.Input;
68 /**
69 * User-defined tags for the cluster.
70 */
71 tags?: Record<string, string>;
72 }
73
74 export interface Cluster extends Resource<
75 "AWS.CloudHSMV2.Cluster",
76 ClusterProps,
77 {
78 /**
79 * The unique identifier of the cluster.
80 */
81 clusterId: string;
82 /**
83 * Current state of the cluster (e.g. `UNINITIALIZED`, `ACTIVE`).
84 */
85 state: string;
86 /**
87 * The type of HSM in the cluster (e.g. `hsm2m.medium`).
88 */
89 hsmType: string;
90 /**
91 * The FIPS mode of the cluster (`FIPS` or `NON_FIPS`).
92 */
93 mode: string | undefined;
94 /**
95 * The network type of the cluster (`IPV4` or `DUALSTACK`).
96 */
97 networkType: string | undefined;
98 /**
99 * The VPC the cluster's HSMs live in.
100 */
101 vpcId: string | undefined;
102 /**
103 * The security group CloudHSM created for the cluster's ENIs.
104 */
105 securityGroup: string | undefined;
106 /**
107 * The subnets (one per AZ) the cluster spans.
108 */
109 subnetIds: string[];
110 /**
111 * The certificate signing request to sign when initializing the cluster
112 * (present while `UNINITIALIZED`).
113 */
114 clusterCsr: string | undefined;
115 /**
116 * How many days backups are retained.
117 */
118 backupRetentionDays: number | undefined;
119 /**
120 * Current tags on the cluster.
121 */
122 tags: Record<string, string>;
123 },
124 never,
125 Providers
126 > {}
127
128 /**
129 * An AWS CloudHSM cluster — a fleet of FIPS-validated, single-tenant
130 * hardware security modules (HSMs) inside your VPC.
131 *
132 * A fresh cluster provisions to the `UNINITIALIZED` state in a few minutes
133 * and holds no HSMs; add {@link Hsm} resources to place HSMs into its
134 * subnets' Availability Zones (each HSM is billed hourly). Activating the
135 * cluster (signing the cluster CSR and calling InitializeCluster) is an
136 * offline certificate-authority ceremony that stays out of band — the
137 * `clusterCsr` attribute exposes the CSR to sign.
138 * ### Creating a Cluster
139 * **Example:** Cluster Spanning Two Availability Zones
140 * ```typescript
141 * const cluster = yield* Cluster("HsmCluster", {
142 * hsmType: "hsm2m.medium",
143 * subnetIds: [subnetA.subnetId, subnetB.subnetId],
144 * });
145 * ```
146 *
147 * **Example:** Non-FIPS Cluster with Custom Backup Retention
148 * ```typescript
149 * const cluster = yield* Cluster("HsmCluster", {
150 * hsmType: "hsm2m.medium",
151 * subnetIds: [subnetA.subnetId, subnetB.subnetId],
152 * mode: "NON_FIPS",
153 * backupRetention: "30 days",
154 * });
155 * ```
156 *
157 * ### Adding HSMs
158 * **Example:** Cluster with One HSM
159 * ```typescript
160 * const cluster = yield* Cluster("HsmCluster", {
161 * hsmType: "hsm2m.medium",
162 * subnetIds: [subnetA.subnetId, subnetB.subnetId],
163 * });
164 * const hsm = yield* Hsm("Primary", {
165 * clusterId: cluster.clusterId,
166 * availabilityZone: "us-west-2a",
167 * });
168 * ```
169 *
170 * @resource
171 */
172 export const Cluster = Resource<Cluster>("AWS.CloudHSMV2.Cluster");
173
174 /** Cluster states that mean "gone" for reconciliation purposes. */
175 const isGone = (cluster: cloudhsm.Cluster | undefined) =>
176 cluster === undefined || cluster.State === "DELETED" || cluster.State === "DELETE_IN_PROGRESS";
177
178 export const ClusterProvider = () =>
179 Provider.effect(
180 Cluster,
181 Effect.gen(function* () {
182 // Read the observed tags for a cluster. A cluster mid-transition can
183 // transiently reject listTags; treat failure as "no observed tags" so
184 // tag reconciliation re-runs on the next pass.
185 const readClusterTags = Effect.fn(function* (clusterId: string) {
186 const response = yield* cloudhsm
187 .listTags({ ResourceId: clusterId })
188 .pipe(Effect.orElseSucceed(() => undefined));
189 return toTagRecord(response?.TagList);
190 });
191
192 // CloudHSM clusters have no caller-chosen name — the id is
193 // auto-assigned. When we have no cached id (state persistence failed
194 // mid-reconcile), recover ownership by scanning for the cluster
195 // carrying our alchemy tags.
196 const findClusterByAlchemyTags = Effect.fn(function* (id: string) {
197 const pages = yield* cloudhsm.describeClusters.pages({}).pipe(Stream.runCollect);
198 for (const page of pages) {
199 for (const cluster of page.Clusters ?? []) {
200 if (isGone(cluster)) continue;
201 if (yield* hasAlchemyTags(id, toTagRecord(cluster.TagList))) {
202 return cluster;
203 }
204 }
205 }
206 return undefined;
207 });
208
209 // Bounded settle wait: creation and modification park the cluster in a
210 // *_IN_PROGRESS state; the cluster itself settles in a few minutes
211 // (budget 10 min = 40 * 15s).
212 const waitUntilSettled = Effect.fn(function* (clusterId: string) {
213 const policy = Schedule.max([Schedule.fixed("15 seconds"), Schedule.recurs(40)]);
214 return yield* findClusterById(clusterId).pipe(
215 Effect.flatMap((cluster) => {
216 if (cluster === undefined) {
217 return Effect.fail(
218 new CloudHSMV2ClusterNotReady({
219 message: `CloudHSM cluster '${clusterId}' not found`,
220 }),
221 );
222 }
223 if (cluster.State?.endsWith("_IN_PROGRESS")) {
224 return Effect.fail(
225 new CloudHSMV2ClusterNotReady({
226 message: `CloudHSM cluster '${clusterId}' still settling (state: ${cluster.State})`,
227 }),
228 );
229 }
230 return Effect.succeed(cluster);
231 }),
232 Effect.retry({ schedule: policy }),
233 );
234 });
235
236 const toAttrs = Effect.fn(function* (cluster: cloudhsm.Cluster) {
237 if (!cluster.ClusterId) {
238 return yield* new CloudHSMV2ClusterUnexpectedResponse({
239 message: "CloudHSM cluster is missing its ClusterId",
240 });
241 }
242 return {
243 clusterId: cluster.ClusterId,
244 state: cluster.State ?? "UNINITIALIZED",
245 hsmType: cluster.HsmType ?? "",
246 mode: cluster.Mode,
247 networkType: cluster.NetworkType,
248 vpcId: cluster.VpcId,
249 securityGroup: cluster.SecurityGroup,
250 subnetIds: Object.values(cluster.SubnetMapping ?? {}).filter(
251 (s): s is string => s !== undefined,
252 ),
253 clusterCsr: cluster.Certificates?.ClusterCsr,
254 backupRetentionDays:
255 cluster.BackupRetentionPolicy?.Value !== undefined
256 ? Number(cluster.BackupRetentionPolicy.Value)
257 : undefined,
258 tags: toTagRecord(cluster.TagList),
259 };
260 });
261
262 return {
263 stables: ["clusterId", "vpcId", "securityGroup"],
264
265 diff: Effect.fn(function* ({ olds, news }) {
266 if (!isResolved(news)) return undefined;
267 const n = news ?? { hsmType: "", subnetIds: [] };
268 const o = olds ?? { hsmType: "", subnetIds: [] };
269 // Create-only properties force a replacement.
270 if (n.hsmType !== o.hsmType) {
271 return { action: "replace" } as const;
272 }
273 if (!sameStringSet(n.subnetIds, o.subnetIds)) {
274 return { action: "replace" } as const;
275 }
276 if (n.sourceBackupId !== o.sourceBackupId) {
277 return { action: "replace" } as const;
278 }
279 if ((n.networkType ?? "IPV4") !== (o.networkType ?? "IPV4")) {
280 return { action: "replace" } as const;
281 }
282 if ((n.mode ?? undefined) !== (o.mode ?? undefined)) {
283 return { action: "replace" } as const;
284 }
285 }),
286
287 read: Effect.fn(function* ({ id, output }) {
288 const cluster = output?.clusterId
289 ? yield* findClusterById(output.clusterId)
290 : yield* findClusterByAlchemyTags(id);
291 if (cluster === undefined || cluster.State === "DELETED") {
292 return undefined;
293 }
294 const attrs = yield* toAttrs(cluster);
295 return (yield* hasAlchemyTags(id, attrs.tags)) ? attrs : Unowned(attrs);
296 }),
297
298 reconcile: Effect.fn(function* ({ id, news, output, session }) {
299 const props = news!;
300 const internalTags = yield* createInternalTags(id);
301 const desiredTags = { ...internalTags, ...props.tags };
302 const backupRetentionDays = toWireDays(props.backupRetention);
303
304 // 1. Observe — cloud state is authoritative; output is only an id
305 // cache. Without one, recover by alchemy tags (crash recovery /
306 // adoption both land here).
307 let observed = output?.clusterId
308 ? yield* findClusterById(output.clusterId)
309 : yield* findClusterByAlchemyTags(id);
310
311 // 2. Ensure — create if missing (or terminally deleted).
312 if (isGone(observed)) {
313 const created = yield* cloudhsm.createCluster({
314 HsmType: props.hsmType,
315 SubnetIds: props.subnetIds,
316 SourceBackupId: props.sourceBackupId,
317 NetworkType: props.networkType,
318 // hsm2m.* types require an explicit Mode ("Mode is a required
319 // argument for this hsm type"); default to FIPS as documented.
320 // Legacy hsm1.* types predate the parameter and are FIPS-only.
321 Mode: props.mode ?? (props.hsmType.startsWith("hsm1") ? undefined : "FIPS"),
322 BackupRetentionPolicy:
323 backupRetentionDays !== undefined
324 ? { Type: "DAYS", Value: String(backupRetentionDays) }
325 : undefined,
326 TagList: createTagsList(desiredTags),
327 });
328 observed = created.Cluster;
329 }
330 const clusterId = observed?.ClusterId;
331 if (!clusterId) {
332 return yield* new CloudHSMV2ClusterUnexpectedResponse({
333 message: "CreateCluster returned no ClusterId",
334 });
335 }
336
337 // Creation/modification park the cluster in *_IN_PROGRESS; wait
338 // (bounded) so subsequent modify calls do not race the transition.
339 observed = yield* waitUntilSettled(clusterId);
340
341 // 3. Sync backup retention — diff OBSERVED policy against desired.
342 if (
343 backupRetentionDays !== undefined &&
344 String(backupRetentionDays) !== observed.BackupRetentionPolicy?.Value
345 ) {
346 yield* cloudhsm.modifyCluster({
347 ClusterId: clusterId,
348 BackupRetentionPolicy: {
349 Type: "DAYS",
350 Value: String(backupRetentionDays),
351 },
352 });
353 observed = yield* waitUntilSettled(clusterId);
354 }
355
356 // 3b. Sync tags — diff against OBSERVED cloud tags.
357 const observedTags = yield* readClusterTags(clusterId);
358 const { removed, upsert } = diffTags(observedTags, desiredTags);
359 if (upsert.length > 0) {
360 yield* cloudhsm.tagResource({
361 ResourceId: clusterId,
362 TagList: upsert,
363 });
364 }
365 if (removed.length > 0) {
366 yield* cloudhsm.untagResource({
367 ResourceId: clusterId,
368 TagKeyList: removed,
369 });
370 }
371
372 yield* session.note(clusterId);
373 return yield* toAttrs(observed);
374 }),
375
376 delete: Effect.fn(function* ({ output }) {
377 const clusterId = output.clusterId;
378 const observed = yield* findClusterById(clusterId);
379 if (isGone(observed)) return;
380 // Before a cluster can be deleted all of its HSMs must be gone;
381 // HSM deletion initiated by dependent resources may still be
382 // propagating, which surfaces as CloudHsmInvalidRequestException.
383 // Bounded retry through that window (10 min = 40 * 15s).
384 yield* cloudhsm.deleteCluster({ ClusterId: clusterId }).pipe(
385 Effect.retry({
386 while: (e) => e._tag === "CloudHsmInvalidRequestException",
387 schedule: Schedule.max([Schedule.fixed("15 seconds"), Schedule.recurs(40)]),
388 }),
389 Effect.catchTag("CloudHsmResourceNotFoundException", () => Effect.void),
390 );
391 // CloudHSM writes audit logs to `/aws/cloudhsm/<clusterId>` and
392 // never deletes the group. Wait (bounded) for the deletion to
393 // finish so no late flush recreates it, then reap it.
394 yield* findClusterById(clusterId).pipe(
395 Effect.repeat({
396 schedule: Schedule.max([Schedule.fixed("10 seconds"), Schedule.recurs(18)]),
397 until: (cluster) => cluster === undefined || cluster.State === "DELETED",
398 }),
399 Effect.catch(() => Effect.void),
400 );
401 yield* reapLogGroupsByPrefix(`/aws/cloudhsm/${clusterId}`);
402 }),
403
404 list: () =>
405 Effect.gen(function* () {
406 const pages = yield* cloudhsm.describeClusters.pages({}).pipe(Stream.runCollect);
407 const clusters = Array.from(pages)
408 .flatMap((page) => page.Clusters ?? [])
409 .filter((cluster) => cluster.ClusterId !== undefined && cluster.State !== "DELETED");
410 return yield* Effect.forEach(clusters, (cluster) => toAttrs(cluster));
411 }),
412 };
413 }),
414 );