@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 451 lines 17 KB
Raw
1 import * as glacier from "@distilled.cloud/aws/glacier";
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, diffTags, hasAlchemyTags } from "alchemy/Tags";
8 import * as Data from "effect/Data";
9 import * as Effect from "effect/Effect";
10 import * as Schedule from "effect/Schedule";
11 import * as Stream from "effect/Stream";
12 import type { Providers } from "../Providers.ts";
13
14 // Glacier's REST API takes the AWS account ID as a path segment; `-` means
15 // "the account that signed the request".
16 const ACCOUNT = "-";
17
18 export interface VaultNotificationConfigProps {
19 /**
20 * ARN of the SNS topic that Amazon S3 Glacier publishes job-completion
21 * notifications to.
22 */
23 snsTopic: string;
24 /**
25 * Job-completion events to publish. Valid values are
26 * `ArchiveRetrievalCompleted` and `InventoryRetrievalCompleted`.
27 */
28 events: string[];
29 }
30
31 export interface VaultProps {
32 /**
33 * Name of the vault. 1-255 characters; allowed characters are a-z, A-Z,
34 * 0-9, `_` (underscore), `-` (hyphen), and `.` (period). Changing the
35 * name replaces the vault.
36 * @default ${app}-${stage}-${id}
37 */
38 vaultName?: string;
39 /**
40 * Notification configuration publishing job-completion events to an SNS
41 * topic. Removing the prop deletes the vault's notification
42 * configuration.
43 */
44 notificationConfig?: VaultNotificationConfigProps;
45 /**
46 * Vault access policy (a resource-based IAM policy document), provided
47 * as a JSON string or a plain object. Removing the prop deletes the
48 * vault's access policy.
49 */
50 accessPolicy?: string | Record<string, any>;
51 /**
52 * Vault lock policy (an IAM policy document enforcing compliance
53 * controls), provided as a JSON string or a plain object. Setting it
54 * initiates the vault lock, leaving it in the `InProgress` state — the
55 * policy is in effect but can still be changed or removed for 24 hours.
56 * Alchemy never calls `CompleteVaultLock`, so the lock is never made
57 * immutable by this resource. Removing the prop aborts an in-progress
58 * lock.
59 */
60 lockPolicy?: string | Record<string, any>;
61 /**
62 * Tags to apply to the vault (up to 10). Merged with internal Alchemy
63 * tags.
64 */
65 tags?: Record<string, string>;
66 }
67
68 export interface Vault extends Resource<
69 "AWS.Glacier.Vault",
70 VaultProps,
71 {
72 /** The name of the vault. */
73 vaultName: string;
74 /** The ARN of the vault. */
75 vaultArn: string;
76 /** ISO-8601 timestamp of when the vault was created. */
77 creationDate: string;
78 },
79 never,
80 Providers
81 > {}
82
83 /**
84 * An Amazon S3 Glacier vault — a container for archives in the original
85 * (vault-based) S3 Glacier service.
86 *
87 * Vault creation is idempotent and free; storage is billed per archive.
88 * A vault must be empty to be deleted, which is always the case for vaults
89 * that only ever held configuration.
90 * ### Creating Vaults
91 * **Example:** Basic Vault
92 * ```typescript
93 * import * as Glacier from "@alchemy.run/aws/Glacier";
94 *
95 * const vault = yield* Glacier.Vault("Backups");
96 * ```
97 *
98 * **Example:** Vault with Tags
99 * ```typescript
100 * const vault = yield* Glacier.Vault("Backups", {
101 * tags: { team: "storage" },
102 * });
103 * ```
104 *
105 * ### Notifications
106 * **Example:** Publish job-completion events to SNS
107 * ```typescript
108 * const topic = yield* SNS.Topic("VaultEvents");
109 * const vault = yield* Glacier.Vault("Backups", {
110 * notificationConfig: {
111 * snsTopic: topic.topicArn,
112 * events: ["ArchiveRetrievalCompleted", "InventoryRetrievalCompleted"],
113 * },
114 * });
115 * ```
116 *
117 * ### Access Control
118 * **Example:** Vault access policy
119 * ```typescript
120 * const vault = yield* Glacier.Vault("Backups", {
121 * accessPolicy: {
122 * Version: "2012-10-17",
123 * Statement: [{
124 * Sid: "deny-archive-deletes",
125 * Effect: "Deny",
126 * Principal: "*",
127 * Action: ["glacier:DeleteArchive"],
128 * Resource: ["arn:aws:glacier:us-east-1:123456789012:vaults/backups"],
129 * }],
130 * },
131 * });
132 * ```
133 *
134 * **Example:** Vault lock policy (left in-progress, never completed)
135 * ```typescript
136 * const vault = yield* Glacier.Vault("Compliance", {
137 * lockPolicy: {
138 * Version: "2012-10-17",
139 * Statement: [{
140 * Sid: "deny-archive-deletes",
141 * Effect: "Deny",
142 * Principal: "*",
143 * Action: ["glacier:DeleteArchive"],
144 * Resource: ["arn:aws:glacier:us-east-1:123456789012:vaults/compliance"],
145 * }],
146 * },
147 * });
148 * ```
149 *
150 * @resource
151 */
152 export const Vault = Resource<Vault>("AWS.Glacier.Vault");
153
154 /**
155 * Raised when the desired `lockPolicy` differs from (or removes) a vault
156 * lock that is already in the `Locked` state. A locked vault lock policy is
157 * immutable — it can never be changed or removed.
158 */
159 export class GlacierVaultLockImmutable extends Data.TaggedError("GlacierVaultLockImmutable")<{
160 message: string;
161 }> {}
162
163 /**
164 * Raised when DescribeVault returns a vault record missing its ARN or
165 * creation date — never expected from the live API.
166 */
167 export class GlacierVaultIncomplete extends Data.TaggedError("GlacierVaultIncomplete")<{
168 message: string;
169 }> {}
170
171 // Explicitly-typed pipeable retry helper. Inlining `Effect.retry` in a
172 // provider lifecycle op leaks `Retry.Return`'s conditional into declaration
173 // emit and widens the provider layer to `unknown` R for every consumer of
174 // `AWS.providers()`.
175 const retryWhileVaultNotFound = <A, E extends { readonly _tag: string }, R>(
176 self: Effect.Effect<A, E, R>,
177 ): Effect.Effect<A, E, R> =>
178 Effect.retry(self, {
179 while: (e) => e._tag === "ResourceNotFoundException",
180 schedule: Schedule.max([Schedule.fixed(1000), Schedule.recurs(10)]),
181 });
182
183 const toPolicyString = (policy: string | Record<string, any> | undefined): string | undefined =>
184 policy === undefined ? undefined : typeof policy === "string" ? policy : JSON.stringify(policy);
185
186 // Structural comparison for policy documents: AWS may re-serialize the
187 // stored policy, so compare parsed shapes rather than raw strings. Falls
188 // back to raw string equality if either side is not valid JSON.
189 const samePolicy = (left: string, right: string): boolean => {
190 if (left === right) return true;
191 try {
192 return JSON.stringify(JSON.parse(left)) === JSON.stringify(JSON.parse(right));
193 } catch {
194 return false;
195 }
196 };
197
198 const sameStringSet = (left: readonly string[], right: readonly string[]): boolean => {
199 if (left.length !== right.length) return false;
200 const sortedLeft = [...left].sort();
201 const sortedRight = [...right].sort();
202 return sortedLeft.every((value, i) => value === sortedRight[i]);
203 };
204
205 export const VaultProvider = () =>
206 Provider.effect(
207 Vault,
208 Effect.gen(function* () {
209 const createVaultName = Effect.fn(function* (id: string, props: VaultProps) {
210 return props.vaultName ?? (yield* createPhysicalName({ id, maxLength: 255 }));
211 });
212
213 const describeVault = (vaultName: string) =>
214 glacier
215 .describeVault({ accountId: ACCOUNT, vaultName })
216 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
217
218 const readVaultTags = (vaultName: string) =>
219 glacier.listTagsForVault({ accountId: ACCOUNT, vaultName }).pipe(
220 Effect.map((r) => (r.Tags ?? {}) as Record<string, string>),
221 Effect.orElseSucceed(() => ({}) as Record<string, string>),
222 );
223
224 return Vault.Provider.of({
225 stables: ["vaultName", "vaultArn", "creationDate"],
226
227 // Enumerate every vault in the ambient account/region. Vaults whose
228 // list entry is missing identifying fields (never expected from the
229 // live API) are dropped.
230 list: () =>
231 Effect.gen(function* () {
232 const pages = yield* glacier.listVaults
233 .pages({ accountId: ACCOUNT })
234 .pipe(Stream.runCollect);
235 return Array.from(pages)
236 .flatMap((page) => page.VaultList ?? [])
237 .flatMap((vault) =>
238 vault.VaultName !== undefined &&
239 vault.VaultARN !== undefined &&
240 vault.CreationDate !== undefined
241 ? [
242 {
243 vaultName: vault.VaultName,
244 vaultArn: vault.VaultARN,
245 creationDate: vault.CreationDate,
246 },
247 ]
248 : [],
249 );
250 }),
251
252 read: Effect.fn(function* ({ id, olds, output }) {
253 const vaultName = output?.vaultName ?? (yield* createVaultName(id, olds ?? {}));
254 const found = yield* describeVault(vaultName);
255 if (found?.VaultARN === undefined) return undefined;
256 const attrs = {
257 vaultName,
258 vaultArn: found.VaultARN,
259 creationDate: found.CreationDate ?? "",
260 };
261 const tags = yield* readVaultTags(vaultName);
262 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
263 }),
264
265 diff: Effect.fn(function* ({ id, news, olds }) {
266 if (!isResolved(news)) return undefined;
267 const oldName = yield* createVaultName(id, olds ?? {});
268 const newName = yield* createVaultName(id, news);
269 if (oldName !== newName) {
270 return { action: "replace" } as const;
271 }
272 // undefined → default update path (reconcile syncs the rest)
273 }),
274
275 reconcile: Effect.fn(function* ({ id, news, output, session }) {
276 const props = news ?? {};
277 const vaultName = output?.vaultName ?? (yield* createVaultName(id, props));
278 const internalTags = yield* createInternalTags(id);
279
280 // 1. OBSERVE — cloud state is authoritative; output is only a
281 // name cache.
282 let live = yield* describeVault(vaultName);
283
284 // 2. ENSURE — CreateVault is an idempotent PUT; re-observe for the
285 // full record (create only returns a Location header). A brief
286 // bounded retry covers read-after-create consistency.
287 if (live === undefined) {
288 yield* glacier.createVault({ accountId: ACCOUNT, vaultName });
289 live = yield* glacier
290 .describeVault({ accountId: ACCOUNT, vaultName })
291 .pipe(retryWhileVaultNotFound);
292 }
293 if (live.VaultARN === undefined || live.CreationDate === undefined) {
294 return yield* new GlacierVaultIncomplete({
295 message: `DescribeVault for '${vaultName}' returned no VaultARN/CreationDate`,
296 });
297 }
298
299 // 3a. SYNC notification configuration — observed vs desired.
300 const observedNotifications = yield* glacier
301 .getVaultNotifications({ accountId: ACCOUNT, vaultName })
302 .pipe(
303 Effect.map((r) => r.vaultNotificationConfig),
304 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
305 );
306 const desiredNotifications = props.notificationConfig;
307 if (desiredNotifications !== undefined) {
308 const inSync =
309 observedNotifications !== undefined &&
310 observedNotifications.SNSTopic === desiredNotifications.snsTopic &&
311 sameStringSet(observedNotifications.Events ?? [], desiredNotifications.events);
312 if (!inSync) {
313 yield* glacier.setVaultNotifications({
314 accountId: ACCOUNT,
315 vaultName,
316 vaultNotificationConfig: {
317 SNSTopic: desiredNotifications.snsTopic,
318 Events: desiredNotifications.events,
319 },
320 });
321 }
322 } else if (observedNotifications !== undefined) {
323 yield* glacier
324 .deleteVaultNotifications({ accountId: ACCOUNT, vaultName })
325 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
326 }
327
328 // 3b. SYNC access policy — observed vs desired.
329 const observedPolicy = yield* glacier
330 .getVaultAccessPolicy({ accountId: ACCOUNT, vaultName })
331 .pipe(
332 Effect.map((r) => r.policy?.Policy),
333 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
334 );
335 const desiredPolicy = toPolicyString(props.accessPolicy);
336 if (desiredPolicy !== undefined) {
337 if (observedPolicy === undefined || !samePolicy(observedPolicy, desiredPolicy)) {
338 yield* glacier.setVaultAccessPolicy({
339 accountId: ACCOUNT,
340 vaultName,
341 policy: { Policy: desiredPolicy },
342 });
343 }
344 } else if (observedPolicy !== undefined) {
345 yield* glacier
346 .deleteVaultAccessPolicy({ accountId: ACCOUNT, vaultName })
347 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
348 }
349
350 // 3c. SYNC vault lock — observed vs desired. An `InProgress` lock
351 // can be aborted and re-initiated; a `Locked` lock is immutable
352 // forever, so any drift from the desired state is surfaced as a
353 // typed failure rather than silently ignored.
354 const observedLock = yield* glacier
355 .getVaultLock({ accountId: ACCOUNT, vaultName })
356 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
357 const desiredLock = toPolicyString(props.lockPolicy);
358 if (desiredLock !== undefined) {
359 if (observedLock === undefined) {
360 yield* glacier.initiateVaultLock({
361 accountId: ACCOUNT,
362 vaultName,
363 policy: { Policy: desiredLock },
364 });
365 } else if (
366 observedLock.Policy === undefined ||
367 !samePolicy(observedLock.Policy, desiredLock)
368 ) {
369 if (observedLock.State === "Locked") {
370 return yield* new GlacierVaultLockImmutable({
371 message: `Vault '${vaultName}' lock is in the Locked state; its lock policy can never be changed.`,
372 });
373 }
374 // InProgress with a different policy: abort and re-initiate.
375 yield* glacier
376 .abortVaultLock({ accountId: ACCOUNT, vaultName })
377 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
378 yield* glacier.initiateVaultLock({
379 accountId: ACCOUNT,
380 vaultName,
381 policy: { Policy: desiredLock },
382 });
383 }
384 } else if (observedLock !== undefined) {
385 if (observedLock.State === "Locked") {
386 return yield* new GlacierVaultLockImmutable({
387 message: `Vault '${vaultName}' lock is in the Locked state; it can never be removed.`,
388 });
389 }
390 yield* glacier
391 .abortVaultLock({ accountId: ACCOUNT, vaultName })
392 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
393 }
394
395 // 3d. SYNC tags — diff against OBSERVED cloud tags so adoption
396 // converges.
397 const observedTags = yield* readVaultTags(vaultName);
398 const desiredTags: Record<string, string> = {
399 ...props.tags,
400 ...internalTags,
401 };
402 const { upsert, removed } = diffTags(observedTags, desiredTags);
403 if (upsert.length > 0) {
404 yield* glacier.addTagsToVault({
405 accountId: ACCOUNT,
406 vaultName,
407 Tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value])),
408 });
409 }
410 if (removed.length > 0) {
411 yield* glacier.removeTagsFromVault({
412 accountId: ACCOUNT,
413 vaultName,
414 TagKeys: removed,
415 });
416 }
417
418 // 4. RETURN fresh Attributes.
419 yield* session.note(vaultName);
420 return {
421 vaultName,
422 vaultArn: live.VaultARN,
423 creationDate: live.CreationDate,
424 };
425 }),
426
427 // Idempotent delete. An in-progress vault lock is aborted first so a
428 // lock policy that denies deletes cannot strand the vault; deleting
429 // an already-deleted vault is not an error.
430 delete: Effect.fn(function* ({ output }) {
431 const lock = yield* glacier
432 .getVaultLock({
433 accountId: ACCOUNT,
434 vaultName: output.vaultName,
435 })
436 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
437 if (lock !== undefined && lock.State !== "Locked") {
438 yield* glacier
439 .abortVaultLock({
440 accountId: ACCOUNT,
441 vaultName: output.vaultName,
442 })
443 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
444 }
445 yield* glacier
446 .deleteVault({ accountId: ACCOUNT, vaultName: output.vaultName })
447 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
448 }),
449 });
450 }),
451 );