@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 211 lines 7.46 KB
Raw
1 import * as cloudfront from "@distilled.cloud/aws/cloudfront";
2 import { isResolved } from "alchemy/Diff";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Effect from "effect/Effect";
7 import * as Option from "effect/Option";
8 import * as Schedule from "effect/Schedule";
9 import * as Stream from "effect/Stream";
10 import type { Providers } from "../Providers.ts";
11
12 export interface KeyValueStoreProps {
13 /**
14 * KeyValueStore name. If omitted, a deterministic name is generated.
15 */
16 name?: string;
17 /**
18 * Optional store comment.
19 */
20 comment?: string;
21 }
22
23 export interface KeyValueStore extends Resource<
24 "AWS.CloudFront.KeyValueStore",
25 KeyValueStoreProps,
26 {
27 /**
28 * KeyValueStore ID.
29 */
30 keyValueStoreId: string;
31 /**
32 * Store ARN.
33 */
34 keyValueStoreArn: string;
35 /**
36 * Store name.
37 */
38 keyValueStoreName: string;
39 /**
40 * Current comment.
41 */
42 comment: string;
43 },
44 never,
45 Providers
46 > {}
47
48 /**
49 * A CloudFront KeyValueStore for edge metadata.
50 *
51 * KeyValueStores can be associated with CloudFront Functions and are useful for
52 * routing metadata or other small edge-time lookup tables.
53 * ### Creating KeyValueStores
54 * **Example:** Basic Store
55 * ```typescript
56 * const store = yield* KeyValueStore("RouterStore", {
57 * comment: "Route metadata",
58 * });
59 * ```
60 *
61 * @resource
62 */
63 export const KeyValueStore = Resource<KeyValueStore>("AWS.CloudFront.KeyValueStore");
64
65 export const KeyValueStoreProvider = () =>
66 Provider.effect(
67 KeyValueStore,
68 Effect.gen(function* () {
69 const getByName = Effect.fn(function* (name: string) {
70 const store = yield* cloudfront.listKeyValueStores.pages({}).pipe(
71 Stream.map((page) => page.KeyValueStoreList?.Items ?? []),
72 Stream.flattenIterable,
73 Stream.filter((item) => item.Name === name),
74 Stream.runHead,
75 Effect.map(Option.getOrUndefined),
76 );
77 if (!store?.Name) {
78 return undefined;
79 }
80 return yield* cloudfront
81 .describeKeyValueStore({ Name: store.Name })
82 .pipe(Effect.catchTag("EntityNotFound", () => Effect.undefined));
83 });
84
85 return {
86 stables: ["keyValueStoreId", "keyValueStoreArn", "keyValueStoreName"],
87 diff: Effect.fn(function* ({ id, olds, news: _news }) {
88 if (!isResolved(_news)) return undefined;
89 const news = _news as typeof olds;
90 if ((yield* createName(id, olds ?? {})) !== (yield* createName(id, news))) {
91 return { action: "replace" } as const;
92 }
93 }),
94 read: Effect.fn(function* ({ id, olds, output }) {
95 const name = output?.keyValueStoreName ?? (yield* createName(id, olds ?? {}));
96 const current = yield* cloudfront
97 .describeKeyValueStore({ Name: name })
98 .pipe(Effect.catchTag("EntityNotFound", () => getByName(name)));
99 if (!current?.KeyValueStore) {
100 return undefined;
101 }
102 return toAttrs(current.KeyValueStore, name);
103 }),
104 // CloudFront is global; `listKeyValueStores` enumerates every store in
105 // the account.
106 list: () =>
107 cloudfront.listKeyValueStores.pages({}).pipe(
108 Stream.runCollect,
109 Effect.map((chunk) =>
110 Array.from(chunk).flatMap((page) =>
111 (page.KeyValueStoreList?.Items ?? []).map((store) => toAttrs(store, store.Name)),
112 ),
113 ),
114 ),
115 reconcile: Effect.fn(function* ({ id, news, output, session }) {
116 const name = output?.keyValueStoreName ?? (yield* createName(id, news));
117
118 // Observe — describe the store, falling back to a list lookup
119 // by name. Trust live state, not stale `olds`.
120 const observed = yield* cloudfront
121 .describeKeyValueStore({ Name: name })
122 .pipe(Effect.catchTag("EntityNotFound", () => getByName(name)));
123
124 // Ensure — create the store if it's missing. Tolerate
125 // `EntityAlreadyExists` (race with a peer reconciler).
126 if (!observed?.KeyValueStore) {
127 const created = yield* cloudfront
128 .createKeyValueStore({ Name: name, Comment: news.comment })
129 .pipe(
130 Effect.catchTag("EntityAlreadyExists", () =>
131 getByName(name).pipe(
132 Effect.flatMap((existing) =>
133 existing
134 ? Effect.succeed(existing)
135 : Effect.die(
136 `CloudFront KeyValueStore '${name}' already exists but could not be recovered`,
137 ),
138 ),
139 ),
140 ),
141 );
142 if (!created.KeyValueStore) {
143 return yield* Effect.die("createKeyValueStore returned no key value store");
144 }
145 yield* session.note(created.KeyValueStore.Id);
146 return toAttrs(created.KeyValueStore, name);
147 }
148
149 // Sync — patch the observed comment via `updateKeyValueStore`
150 // using the freshly observed ETag.
151 const updated = yield* cloudfront.updateKeyValueStore({
152 Name: observed.KeyValueStore.Name,
153 Comment: news.comment ?? "",
154 IfMatch: observed.ETag!,
155 });
156 if (!updated.KeyValueStore) {
157 return yield* Effect.die("updateKeyValueStore returned no key value store");
158 }
159 yield* session.note(updated.KeyValueStore.Id);
160 return toAttrs(updated.KeyValueStore, observed.KeyValueStore.Name);
161 }),
162 delete: Effect.fn(
163 function* ({ output }) {
164 const current = yield* cloudfront
165 .describeKeyValueStore({ Name: output.keyValueStoreName })
166 .pipe(Effect.catchTag("EntityNotFound", () => Effect.undefined));
167
168 const etag = current?.ETag;
169 if (!etag) {
170 yield* Effect.logInfo(
171 `CloudFront KeyValueStore delete: ${output.keyValueStoreName} already absent`,
172 );
173 return;
174 }
175
176 yield* Effect.logInfo(
177 `CloudFront KeyValueStore delete: deleting ${output.keyValueStoreName} with etag=${etag}`,
178 );
179 yield* cloudfront
180 .deleteKeyValueStore({ Name: output.keyValueStoreName, IfMatch: etag })
181 .pipe(Effect.catchTag("EntityNotFound", () => Effect.void));
182 },
183 Effect.retry({
184 // KV writes can invalidate the control-plane ETag before Describe
185 // catches up. Retry the entire read/delete pair with a fresh ETag.
186 while: (error) => error._tag === "PreconditionFailed",
187 schedule: Schedule.spaced("500 millis"),
188 times: 8,
189 }),
190 ),
191 };
192 }),
193 );
194
195 const createName = (id: string, props: KeyValueStoreProps) =>
196 props.name
197 ? Effect.succeed(props.name)
198 : createPhysicalName({ id, maxLength: 64, lowercase: true });
199
200 // Status, last-modified time and ETag change on their own (provisioning
201 // finishes, every key write bumps them), so they are not attributes: drift
202 // would never read a store as unchanged.
203 const toAttrs = (
204 store: cloudfront.KeyValueStore,
205 fallbackName: string,
206 ): KeyValueStore["Attributes"] => ({
207 keyValueStoreId: store.Id,
208 keyValueStoreArn: store.ARN,
209 keyValueStoreName: store.Name || fallbackName,
210 comment: store.Comment ?? "",
211 });