@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 282 lines 10.3 KB
Raw
1 import * as s3tables from "@distilled.cloud/aws/s3tables";
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 Schedule from "effect/Schedule";
8 import * as Stream from "effect/Stream";
9 import { AWSEnvironment, type AccountID } from "../Environment.ts";
10 import type { Providers } from "../Providers.ts";
11 import type { RegionID } from "../Region.ts";
12
13 export type TableBucketArn = `arn:aws:s3tables:${RegionID}:${AccountID}:bucket/${string}`;
14
15 /**
16 * Server-side encryption configuration for an S3 table bucket. Applied at
17 * create time; changing it replaces the bucket.
18 */
19 export interface TableBucketEncryption {
20 /**
21 * Encryption algorithm. `AES256` uses S3-managed keys (SSE-S3); `aws:kms`
22 * uses AWS KMS (SSE-KMS) and requires `kmsKeyArn`.
23 */
24 sseAlgorithm: "AES256" | "aws:kms";
25 /**
26 * ARN of the KMS key to use when `sseAlgorithm` is `aws:kms`.
27 */
28 kmsKeyArn?: string;
29 }
30
31 export interface TableBucketProps {
32 /**
33 * Name of the table bucket. Must be 3-63 characters, lowercase letters,
34 * numbers, and hyphens, beginning and ending with a letter or number.
35 * Changing the name replaces the bucket.
36 * @default a deterministic name derived from `${app}-${id}-${stage}`
37 */
38 name?: string;
39 /**
40 * Default server-side encryption for tables in this bucket. Applied at
41 * create time; changing it replaces the bucket.
42 */
43 encryptionConfiguration?: TableBucketEncryption;
44 }
45
46 export interface TableBucket extends Resource<
47 "AWS.S3Tables.TableBucket",
48 TableBucketProps,
49 {
50 tableBucketArn: TableBucketArn;
51 name: string;
52 ownerAccountId: string;
53 createdAt: Date;
54 tableBucketId: string | undefined;
55 type: string | undefined;
56 },
57 never,
58 Providers
59 > {}
60
61 /**
62 * An Amazon S3 Tables table bucket — a purpose-built bucket for storing
63 * fully-managed Apache Iceberg tables.
64 *
65 * A table bucket is regional and holds {@link Namespace}s, which in turn hold
66 * {@link Table}s. The bucket name is auto-generated from the app, stage, and
67 * logical ID unless you provide one explicitly.
68 * ### Creating Table Buckets
69 * **Example:** Basic Table Bucket
70 * ```typescript
71 * import * as S3Tables from "@alchemy.run/aws/S3Tables";
72 *
73 * const bucket = yield* S3Tables.TableBucket("Analytics");
74 * ```
75 *
76 * **Example:** Named Table Bucket
77 * ```typescript
78 * const bucket = yield* S3Tables.TableBucket("Analytics", {
79 * name: "my-analytics-tables",
80 * });
81 * ```
82 *
83 * ### Encryption
84 * **Example:** KMS-encrypted Table Bucket
85 * ```typescript
86 * const bucket = yield* S3Tables.TableBucket("Secure", {
87 * encryptionConfiguration: {
88 * sseAlgorithm: "aws:kms",
89 * kmsKeyArn: key.keyArn,
90 * },
91 * });
92 * ```
93 *
94 * @resource
95 */
96 export const TableBucket = Resource<TableBucket>("AWS.S3Tables.TableBucket");
97
98 const createBucketName = (id: string, props: { name?: string | undefined }) =>
99 Effect.gen(function* () {
100 if (props.name) {
101 return props.name;
102 }
103 // Table-bucket names follow S3-bucket DNS rules: lowercase, 3-63 chars,
104 // and must not start with the service-reserved prefixes.
105 return yield* createPhysicalName({
106 id,
107 maxLength: 63,
108 lowercase: true,
109 forbiddenPrefixes: ["xn--", "sthree-", "amzn-s3-demo-", "aws"],
110 });
111 });
112
113 export const TableBucketProvider = () =>
114 Provider.succeed(TableBucket, {
115 stables: ["tableBucketArn", "name", "ownerAccountId"],
116 // Top-level resource — enumerate every table bucket in the ambient
117 // account/region so the engine can detect drift/adoption.
118 list: Effect.fn(function* () {
119 const buckets = yield* s3tables.listTableBuckets.pages({}).pipe(
120 Stream.runCollect,
121 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.tableBuckets ?? [])),
122 );
123 return buckets.map((b): TableBucket["Attributes"] => ({
124 tableBucketArn: b.arn as TableBucketArn,
125 name: b.name,
126 ownerAccountId: b.ownerAccountId,
127 createdAt: b.createdAt,
128 tableBucketId: b.tableBucketId,
129 type: b.type,
130 }));
131 }),
132 read: Effect.fn(function* ({ id, olds, output }) {
133 const { accountId, region } = yield* AWSEnvironment.current;
134 const name = output?.name ?? (yield* createBucketName(id, olds ?? {}));
135 const arn =
136 output?.tableBucketArn ??
137 (`arn:aws:s3tables:${region}:${accountId}:bucket/${name}` as TableBucketArn);
138 return yield* s3tables.getTableBucket({ tableBucketARN: arn }).pipe(
139 Effect.map((b): TableBucket["Attributes"] => ({
140 tableBucketArn: b.arn as TableBucketArn,
141 name: b.name,
142 ownerAccountId: b.ownerAccountId,
143 createdAt: b.createdAt,
144 tableBucketId: b.tableBucketId,
145 type: b.type,
146 })),
147 Effect.catchTag("NotFoundException", () => Effect.undefined),
148 );
149 }),
150 diff: Effect.fn(function* ({ id, news = {}, olds = {} }) {
151 if (!isResolved(news)) return;
152 const oldName = yield* createBucketName(id, olds);
153 const newName = yield* createBucketName(id, news);
154 if (oldName !== newName) {
155 return { action: "replace" } as const;
156 }
157 // Encryption is set at create time and cannot be changed in place.
158 const oldEnc = JSON.stringify(olds.encryptionConfiguration ?? null);
159 const newEnc = JSON.stringify(news.encryptionConfiguration ?? null);
160 if (oldEnc !== newEnc) {
161 return { action: "replace" } as const;
162 }
163 }),
164 reconcile: Effect.fn(function* ({ id, news = {}, output, session }) {
165 const { accountId, region } = yield* AWSEnvironment.current;
166 const name = output?.name ?? (yield* createBucketName(id, news));
167 const arn =
168 output?.tableBucketArn ??
169 (`arn:aws:s3tables:${region}:${accountId}:bucket/${name}` as TableBucketArn);
170
171 // Observe — cloud state is authoritative. `output` is only a cache for
172 // the deterministic ARN; the bucket may have been deleted out-of-band.
173 let bucket = yield* s3tables.getTableBucket({ tableBucketARN: arn }).pipe(
174 Effect.map((b) => b),
175 Effect.catchTag("NotFoundException", () => Effect.undefined),
176 );
177
178 // Ensure — create if missing. Tolerate a concurrent create
179 // (`ConflictException`) as a race and fall through to re-read.
180 if (bucket === undefined) {
181 yield* s3tables
182 .createTableBucket({
183 name,
184 encryptionConfiguration: news.encryptionConfiguration,
185 })
186 .pipe(
187 Effect.asVoid,
188 Effect.catchTag("ConflictException", () => Effect.void),
189 );
190 // The control plane is eventually consistent: `getTableBucket` can
191 // briefly 404 a bucket that `createTableBucket` just returned. Ride
192 // out that propagation window on a bounded schedule.
193 bucket = yield* s3tables.getTableBucket({ tableBucketARN: arn }).pipe(
194 Effect.retry({
195 while: (e) => e._tag === "NotFoundException",
196 schedule: Schedule.max([Schedule.exponential(500), Schedule.recurs(8)]),
197 }),
198 );
199 }
200
201 yield* session.note(bucket.arn);
202 return {
203 tableBucketArn: bucket.arn as TableBucketArn,
204 name: bucket.name,
205 ownerAccountId: bucket.ownerAccountId,
206 createdAt: bucket.createdAt,
207 tableBucketId: bucket.tableBucketId,
208 type: bucket.type,
209 };
210 }),
211 delete: Effect.fn(function* ({ output, force }) {
212 const tableBucketARN = output.tableBucketArn;
213 if (force !== true) {
214 yield* s3tables.deleteTableBucket({ tableBucketARN }).pipe(
215 // Tracked children are normally deleted first, but their deletion
216 // can take a few seconds to propagate. Do not purge untracked data
217 // during ordinary destroy: a persistent Conflict is protective.
218 Effect.retry({
219 while: (e) => e._tag === "ConflictException",
220 schedule: Schedule.max([Schedule.fixed(500), Schedule.recurs(8)]),
221 }),
222 Effect.catchTag("NotFoundException", () => Effect.void),
223 );
224 return;
225 }
226
227 const purgeAndDelete = Effect.gen(function* () {
228 // Nuke explicitly sets force after operator confirmation. It can
229 // discover a top-level bucket even when child state was never saved,
230 // so only this path may purge globally-invisible children.
231 const tables = yield* s3tables.listTables.items({ tableBucketARN }).pipe(
232 Stream.runCollect,
233 Effect.map((chunk) => Array.from(chunk)),
234 Effect.catchTag("NotFoundException", () => Effect.succeed([])),
235 );
236 yield* Effect.forEach(
237 tables,
238 (table) =>
239 s3tables
240 .deleteTable({
241 tableBucketARN,
242 namespace: table.namespace[0]!,
243 name: table.name,
244 })
245 .pipe(Effect.catchTag("NotFoundException", () => Effect.void)),
246 { concurrency: 4, discard: true },
247 );
248
249 const namespaces = yield* s3tables.listNamespaces.items({ tableBucketARN }).pipe(
250 Stream.runCollect,
251 Effect.map((chunk) => Array.from(chunk)),
252 Effect.catchTag("NotFoundException", () => Effect.succeed([])),
253 );
254 yield* Effect.forEach(
255 namespaces,
256 (namespace) =>
257 s3tables
258 .deleteNamespace({
259 tableBucketARN,
260 namespace: namespace.namespace[0]!,
261 })
262 .pipe(Effect.catchTag("NotFoundException", () => Effect.void)),
263 { concurrency: 4, discard: true },
264 );
265
266 yield* s3tables.deleteTableBucket({ tableBucketARN });
267 });
268
269 yield* purgeAndDelete.pipe(
270 // Deletes propagate asynchronously. Re-listing on every bounded retry
271 // also catches children that were briefly absent from a prior list.
272 Effect.retry({
273 while: (e) =>
274 e._tag === "ConflictException" ||
275 e._tag === "TooManyRequestsException" ||
276 e._tag === "InternalServerErrorException",
277 schedule: Schedule.max([Schedule.exponential(500), Schedule.recurs(8)]),
278 }),
279 Effect.catchTag("NotFoundException", () => Effect.void),
280 );
281 }),
282 });