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

main
ts 314 lines 10.9 KB
Raw
1 import * as cloudfront from "@distilled.cloud/aws/cloudfront";
2 import * as kvs from "@distilled.cloud/aws/cloudfront-keyvaluestore";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Effect from "effect/Effect";
6 import type { HttpClient } from "effect/http/HttpClient";
7 import * as Option from "effect/Option";
8 import * as Stream from "effect/Stream";
9 import type { Credentials } from "../Credentials.ts";
10 import type { Providers } from "../Providers.ts";
11 import type { Region } from "../Region.ts";
12 import {
13 extractValue,
14 getKvsEtag,
15 isKvsPreconditionFailed,
16 cappedKvsRetrySchedule,
17 retryForKvsReadiness,
18 withKvsRegionFn,
19 } from "./common.ts";
20
21 export interface KvRoutesUpdateProps {
22 /** ARN of the CloudFront KeyValueStore. */
23 store: string;
24 /** Namespace prefix. The full key is `{namespace}:{key}`. */
25 namespace: string;
26 /** Key within the namespace (typically "routes"). */
27 key: string;
28 /** The route entry string to add/manage (format: "type,namespace,hostPattern,pathPrefix"). */
29 entry: string;
30 }
31
32 export interface KvRoutesUpdate extends Resource<
33 "AWS.CloudFront.KvRoutesUpdate",
34 KvRoutesUpdateProps,
35 {
36 /**
37 * The ARN of the key value store holding the routes.
38 */
39 store: string;
40 /**
41 * The namespace prefix the routes were written under.
42 */
43 namespace: string;
44 /**
45 * The key the route table was written to.
46 */
47 key: string;
48 /**
49 * The serialized route table value that was written.
50 */
51 entry: string;
52 },
53 never,
54 Providers
55 > {}
56
57 /**
58 * Manages a single route entry in a JSON array stored in a CloudFront KeyValueStore.
59 *
60 * The routes array is stored at key `{namespace}:{key}` and supports automatic
61 * chunking when the serialized array exceeds 1000 characters.
62 * ### Managing Routes
63 * **Example:** Add A Route Entry
64 * ```typescript
65 * const update = yield* KvRoutesUpdate("MyRoute", {
66 * store: store.keyValueStoreArn,
67 * namespace: "app",
68 * key: "routes",
69 * entry: "site,mysite,*,/",
70 * });
71 * ```
72 *
73 * @resource
74 */
75 export const KvRoutesUpdate = Resource<KvRoutesUpdate>("AWS.CloudFront.KvRoutesUpdate");
76
77 const CHUNK_SIZE = 1000;
78
79 export const KvRoutesUpdateProvider = () =>
80 Provider.effect(
81 KvRoutesUpdate,
82 Effect.gen(function* () {
83 const getRoutes = Effect.fn(function* (store: string, fullKey: string) {
84 const res = yield* kvs
85 .getKey({ KvsARN: store, Key: fullKey })
86 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
87
88 if (!res) {
89 return { routes: [] as string[], chunkNum: 1 };
90 }
91
92 const raw = extractValue(res.Value);
93 const parsed = JSON.parse(raw);
94
95 if (parsed && typeof parsed === "object" && "parts" in parsed) {
96 const parts: number = parsed.parts;
97 const chunks: string[] = [];
98 for (let i = 0; i < parts; i++) {
99 const chunkRes = yield* kvs.getKey({
100 KvsARN: store,
101 Key: `${fullKey}:${i}`,
102 });
103 chunks.push(extractValue(chunkRes.Value));
104 }
105 return {
106 routes: JSON.parse(chunks.join("")) as string[],
107 chunkNum: parts,
108 };
109 }
110
111 return { routes: parsed as string[], chunkNum: 1 };
112 });
113
114 const setRoutes = Effect.fn(function* (
115 store: string,
116 etag: string,
117 fullKey: string,
118 routes: string[],
119 oldChunkNum: number,
120 ) {
121 const serialized = JSON.stringify(routes);
122 const puts: kvs.PutKeyRequestListItem[] = [];
123 const deletes: kvs.DeleteKeyRequestListItem[] = [];
124
125 if (serialized.length > CHUNK_SIZE) {
126 const chunkCount = Math.ceil(serialized.length / CHUNK_SIZE);
127 puts.push({
128 Key: fullKey,
129 Value: JSON.stringify({ parts: chunkCount }),
130 });
131 for (let i = 0; i < chunkCount; i++) {
132 puts.push({
133 Key: `${fullKey}:${i}`,
134 Value: serialized.slice(i * CHUNK_SIZE, (i + 1) * CHUNK_SIZE),
135 });
136 }
137 if (oldChunkNum > chunkCount) {
138 for (let i = chunkCount; i < oldChunkNum; i++) {
139 deletes.push({ Key: `${fullKey}:${i}` });
140 }
141 }
142 } else {
143 puts.push({ Key: fullKey, Value: serialized });
144 if (oldChunkNum > 1) {
145 for (let i = 0; i < oldChunkNum; i++) {
146 deletes.push({ Key: `${fullKey}:${i}` });
147 }
148 }
149 }
150
151 yield* kvs.updateKeys({
152 KvsARN: store,
153 IfMatch: etag,
154 Puts: puts.length > 0 ? puts : undefined,
155 Deletes: deletes.length > 0 ? deletes : undefined,
156 });
157 });
158
159 const deleteKey = Effect.fn(function* (
160 store: string,
161 etag: string,
162 fullKey: string,
163 oldChunkNum: number,
164 ) {
165 const deletes: kvs.DeleteKeyRequestListItem[] = [{ Key: fullKey }];
166 if (oldChunkNum > 1) {
167 for (let i = 0; i < oldChunkNum; i++) {
168 deletes.push({ Key: `${fullKey}:${i}` });
169 }
170 }
171 yield* kvs.updateKeys({
172 KvsARN: store,
173 IfMatch: etag,
174 Deletes: deletes,
175 });
176 });
177
178 const deleteOp = (
179 props: KvRoutesUpdateProps,
180 ): Effect.Effect<void, kvs.UpdateKeysError, Credentials | Region | HttpClient> =>
181 Effect.gen(function* () {
182 const fullKey = `${props.namespace}:${props.key}`;
183 const etag = yield* getKvsEtag(props.store);
184 const { routes, chunkNum } = yield* getRoutes(props.store, fullKey);
185 if (!routes.includes(props.entry)) return;
186 const filtered = routes.filter((r) => r !== props.entry);
187 if (filtered.length === 0) {
188 yield* deleteKey(props.store, etag, fullKey, chunkNum);
189 } else {
190 yield* setRoutes(props.store, etag, fullKey, filtered, chunkNum);
191 }
192 }).pipe(
193 Effect.retry({
194 while: (error) =>
195 error._tag === "ValidationException" && isKvsPreconditionFailed(error),
196 schedule: cappedKvsRetrySchedule,
197 }),
198 );
199
200 const upsertEntry = (
201 store: string,
202 fullKey: string,
203 entryToAdd: string,
204 entryToRemove: string | undefined,
205 ): Effect.Effect<void, kvs.UpdateKeysError, HttpClient | Region | Credentials> =>
206 Effect.gen(function* () {
207 const etag = yield* getKvsEtag(store);
208 const { routes, chunkNum } = yield* getRoutes(store, fullKey);
209 const filtered =
210 entryToRemove !== undefined
211 ? routes.filter((r) => r !== entryToRemove)
212 : routes.slice();
213 if (!filtered.includes(entryToAdd)) {
214 filtered.push(entryToAdd);
215 }
216 yield* setRoutes(store, etag, fullKey, filtered, chunkNum);
217 }).pipe(
218 Effect.retry({
219 while: (error) =>
220 error._tag === "ValidationException" && isKvsPreconditionFailed(error),
221 schedule: cappedKvsRetrySchedule,
222 }),
223 );
224
225 return {
226 // Non-listable: this resource is an update operation that manages a
227 // single route entry inside a JSON array stored at a KV store key. It is
228 // keyed entirely by {store, namespace, key, entry}; there is no API that
229 // enumerates individual route-entry updates, so list returns [].
230 list: () => Effect.succeed([]),
231 read: withKvsRegionFn(
232 Effect.fn(function* ({ output }) {
233 if (output === undefined) return undefined;
234 // The managed state is one entry in the route table: report the
235 // update missing when the entry is gone so drift re-adds it.
236 const { routes } = yield* retryForKvsReadiness(
237 getRoutes(output.store, `${output.namespace}:${output.key}`),
238 ).pipe(
239 Effect.catchTag("ResourceNotFoundException", () =>
240 Effect.succeed({ routes: [] as string[] }),
241 ),
242 );
243 return routes.includes(output.entry) ? output : undefined;
244 }),
245 ),
246 reconcile: withKvsRegionFn(
247 Effect.fn(function* ({ news, output }) {
248 return yield* retryForKvsReadiness(
249 Effect.gen(function* () {
250 // Observe — figure out whether the prior entry lived at a
251 // different location. When location changes (or this is
252 // the first reconcile), we strip the old entry from the
253 // old routes array first, then add the new one to the
254 // new array.
255 const movedLocation =
256 output !== undefined &&
257 (output.store !== news.store ||
258 output.namespace !== news.namespace ||
259 output.key !== news.key);
260
261 if (movedLocation) {
262 yield* deleteOp(output);
263 }
264
265 // Sync — append the desired entry to the routes array at
266 // the new location. If the entry was previously at the
267 // same location, drop the old value from the in-memory
268 // array before re-appending so a value change is treated
269 // as upsert-by-replace.
270 const fullKey = `${news.namespace}:${news.key}`;
271 const previousEntry =
272 !movedLocation && output !== undefined ? output.entry : undefined;
273 yield* upsertEntry(news.store, fullKey, news.entry, previousEntry);
274
275 return {
276 store: news.store,
277 namespace: news.namespace,
278 key: news.key,
279 entry: news.entry,
280 };
281 }),
282 );
283 }),
284 ),
285 delete: withKvsRegionFn(
286 Effect.fn(function* ({ output }) {
287 yield* retryForKvsReadiness(
288 deleteOp({
289 store: output.store,
290 namespace: output.namespace,
291 key: output.key,
292 entry: output.entry,
293 }).pipe(
294 Effect.catchTag("ConflictException", (error) =>
295 // The data plane reports ConflictException for deleted stores.
296 // Confirm absence through the control plane before ignoring it.
297 cloudfront.listKeyValueStores.pages({}).pipe(
298 Stream.flatMap((page) =>
299 Stream.fromIterable(page.KeyValueStoreList?.Items ?? []),
300 ),
301 Stream.filter((store) => store.ARN === output.store),
302 Stream.runHead,
303 Effect.flatMap((store) =>
304 Option.isNone(store) ? Effect.void : Effect.fail(error),
305 ),
306 ),
307 ),
308 ),
309 ).pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
310 }),
311 ),
312 };
313 }),
314 );