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

main
ts 175 lines 6.08 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 type { Providers } from "../Providers.ts";
9
10 export interface NamespaceProps {
11 /**
12 * ARN of the table bucket that owns the namespace. Changing it replaces
13 * the namespace.
14 */
15 tableBucket: string;
16 /**
17 * Name of the namespace. Must be 1-255 characters of lowercase letters,
18 * numbers, and underscores, beginning with a letter or number. Changing
19 * the name replaces the namespace.
20 * @default a deterministic name derived from the app, stage, and logical ID
21 */
22 namespace?: string;
23 }
24
25 export interface Namespace extends Resource<
26 "AWS.S3Tables.Namespace",
27 NamespaceProps,
28 {
29 tableBucketArn: string;
30 namespace: string;
31 namespaceId: string | undefined;
32 createdAt: Date;
33 createdBy: string;
34 ownerAccountId: string;
35 },
36 never,
37 Providers
38 > {}
39
40 /**
41 * A namespace within an Amazon S3 Tables {@link TableBucket} — a logical
42 * grouping of {@link Table}s, equivalent to a database in an Iceberg catalog.
43 * ### Creating Namespaces
44 * **Example:** Basic Namespace
45 * ```typescript
46 * import * as S3Tables from "@alchemy.run/aws/S3Tables";
47 *
48 * const bucket = yield* S3Tables.TableBucket("Analytics");
49 * const ns = yield* S3Tables.Namespace("Events", {
50 * tableBucket: bucket.tableBucketArn,
51 * });
52 * ```
53 *
54 * **Example:** Named Namespace
55 * ```typescript
56 * const ns = yield* S3Tables.Namespace("Events", {
57 * tableBucket: bucket.tableBucketArn,
58 * namespace: "raw_events",
59 * });
60 * ```
61 *
62 * @resource
63 */
64 export const Namespace = Resource<Namespace>("AWS.S3Tables.Namespace");
65
66 const createNamespaceName = (id: string, props: { namespace?: string | undefined }) =>
67 Effect.gen(function* () {
68 if (props.namespace) {
69 return props.namespace;
70 }
71 // Namespace names allow lowercase letters, numbers, and underscores only —
72 // no hyphens — so translate the DNS-style physical name. Namespace names
73 // must not start with the reserved prefix `aws`.
74 const base = yield* createPhysicalName({
75 id,
76 maxLength: 60,
77 lowercase: true,
78 forbiddenPrefixes: ["aws"],
79 });
80 return base.replaceAll("-", "_");
81 });
82
83 export const NamespaceProvider = () =>
84 Provider.succeed(Namespace, {
85 stables: ["tableBucketArn", "namespace"],
86 // Namespaces are scoped to a parent table bucket; there is no ambient
87 // enumeration without a bucket ARN, so the engine drives lifecycle from
88 // state alone.
89 list: () => Effect.succeed([]),
90 read: Effect.fn(function* ({ id, olds, output }) {
91 const tableBucketArn = output?.tableBucketArn ?? olds?.tableBucket;
92 if (typeof tableBucketArn !== "string") return undefined;
93 const namespace = output?.namespace ?? (yield* createNamespaceName(id, olds ?? {}));
94 return yield* s3tables.getNamespace({ tableBucketARN: tableBucketArn, namespace }).pipe(
95 Effect.map((n): Namespace["Attributes"] => ({
96 tableBucketArn,
97 namespace: n.namespace[0] ?? namespace,
98 namespaceId: n.namespaceId,
99 createdAt: n.createdAt,
100 createdBy: n.createdBy,
101 ownerAccountId: n.ownerAccountId,
102 })),
103 Effect.catchTag("NotFoundException", () => Effect.undefined),
104 );
105 }),
106 diff: Effect.fn(function* ({ id, news, olds }) {
107 if (!isResolved(news)) return;
108 if (news.tableBucket !== olds?.tableBucket) {
109 return { action: "replace" } as const;
110 }
111 const oldName = yield* createNamespaceName(id, olds ?? {});
112 const newName = yield* createNamespaceName(id, news);
113 if (oldName !== newName) {
114 return { action: "replace" } as const;
115 }
116 }),
117 reconcile: Effect.fn(function* ({ id, news, output, session }) {
118 const tableBucketArn = news.tableBucket as string;
119 const namespace = output?.namespace ?? (yield* createNamespaceName(id, news));
120
121 // Observe — read live state; the namespace may have been removed
122 // out-of-band even if `output` cached it.
123 let ns = yield* s3tables.getNamespace({ tableBucketARN: tableBucketArn, namespace }).pipe(
124 Effect.map((n) => n),
125 Effect.catchTag("NotFoundException", () => Effect.undefined),
126 );
127
128 // Ensure — create if missing, tolerating a concurrent create.
129 if (ns === undefined) {
130 yield* s3tables
131 .createNamespace({
132 tableBucketARN: tableBucketArn,
133 namespace: [namespace],
134 })
135 .pipe(
136 Effect.asVoid,
137 Effect.catchTag("ConflictException", () => Effect.void),
138 );
139 // Eventual consistency: getNamespace can briefly 404 a namespace that
140 // createNamespace just returned.
141 ns = yield* s3tables.getNamespace({ tableBucketARN: tableBucketArn, namespace }).pipe(
142 Effect.retry({
143 while: (e) => e._tag === "NotFoundException",
144 schedule: Schedule.max([Schedule.exponential(500), Schedule.recurs(8)]),
145 }),
146 );
147 }
148
149 yield* session.note(namespace);
150 return {
151 tableBucketArn,
152 namespace: ns.namespace[0] ?? namespace,
153 namespaceId: ns.namespaceId,
154 createdAt: ns.createdAt,
155 createdBy: ns.createdBy,
156 ownerAccountId: ns.ownerAccountId,
157 };
158 }),
159 delete: Effect.fn(function* ({ output }) {
160 yield* s3tables
161 .deleteNamespace({
162 tableBucketARN: output.tableBucketArn,
163 namespace: output.namespace,
164 })
165 .pipe(
166 // Table deletes are eventually consistent; a namespace delete that
167 // races them reports ConflictException — ride out the window.
168 Effect.retry({
169 while: (e) => e._tag === "ConflictException",
170 schedule: Schedule.max([Schedule.exponential(500), Schedule.recurs(8)]),
171 }),
172 Effect.catchTag("NotFoundException", () => Effect.void),
173 );
174 }),
175 });