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

main
ts 288 lines 10 KB
Raw
1 import * as schemas from "@distilled.cloud/aws/schemas";
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 { hasAlchemyTags } from "alchemy/Tags";
8 import * as Effect from "effect/Effect";
9 import * as Schedule from "effect/Schedule";
10 import * as Stream from "effect/Stream";
11 import {
12 normalizePolicyDocument,
13 stringifyPolicyDocument,
14 type PolicyDocument,
15 } from "../IAM/Policy.ts";
16 import type { Providers } from "../Providers.ts";
17 import { syncSchemasTags } from "./internal.ts";
18
19 export interface RegistryProps {
20 /**
21 * Name of the registry. Must match `[a-zA-Z0-9-_.@]+` and be at most 64
22 * characters. If omitted, a unique name is generated. Changing it replaces
23 * the registry.
24 */
25 registryName?: string;
26
27 /**
28 * A description of the registry.
29 */
30 description?: string;
31
32 /**
33 * User tags to attach to the registry.
34 */
35 tags?: Record<string, string>;
36
37 /**
38 * Resource-based policy attached to the registry, granting other AWS
39 * accounts or principals access to the registry and its schemas. Provided
40 * as a structured {@link PolicyDocument} or a raw JSON string. Omitting it
41 * removes any existing resource policy.
42 */
43 policy?: PolicyDocument | string;
44 }
45
46 export interface Registry extends Resource<
47 "AWS.Schemas.Registry",
48 RegistryProps,
49 {
50 /** The name of the registry. */
51 registryName: string;
52 /** The ARN of the registry. */
53 registryArn: string;
54 },
55 never,
56 Providers
57 > {}
58
59 /**
60 * An EventBridge Schema Registry — a named collection of event schemas.
61 * Custom registries hold your own OpenAPI 3 / JSONSchema Draft 4 schema
62 * documents; AWS also maintains the built-in `aws.events` and
63 * `discovered-schemas` registries.
64 *
65 * ### Creating a Registry
66 * **Example:** Basic Registry
67 * ```typescript
68 * const registry = yield* AWS.Schemas.Registry("app-events", {
69 * description: "Schemas for application events",
70 * });
71 * ```
72 *
73 * **Example:** Registry with Tags
74 * ```typescript
75 * const registry = yield* AWS.Schemas.Registry("orders", {
76 * description: "Order lifecycle events",
77 * tags: { team: "payments" },
78 * });
79 * ```
80 *
81 * ### Sharing a Registry
82 * **Example:** Registry with a Resource Policy
83 * ```typescript
84 * const registry = yield* AWS.Schemas.Registry("shared-events", {
85 * policy: {
86 * Version: "2012-10-17",
87 * Statement: [
88 * {
89 * Effect: "Allow",
90 * Principal: { AWS: `arn:aws:iam::${otherAccountId}:root` },
91 * Action: ["schemas:DescribeRegistry", "schemas:SearchSchemas"],
92 * Resource: registryArn,
93 * },
94 * ],
95 * },
96 * });
97 * ```
98 *
99 * ### Adding Schemas
100 * **Example:** Registry with a Schema
101 * ```typescript
102 * const registry = yield* AWS.Schemas.Registry("app-events", {});
103 * const schema = yield* AWS.Schemas.Schema("OrderCreated", {
104 * registryName: registry.registryName,
105 * type: "OpenApi3",
106 * content: JSON.stringify(openApiDocument),
107 * });
108 * ```
109 *
110 * @resource
111 */
112 export const Registry = Resource<Registry>("AWS.Schemas.Registry");
113
114 export const RegistryProvider = () =>
115 Provider.effect(
116 Registry,
117 Effect.gen(function* () {
118 const createName = Effect.fn(function* (id: string, props: RegistryProps) {
119 return props.registryName ?? (yield* createPhysicalName({ id, maxLength: 64 }));
120 });
121
122 const describe = (registryName: string) =>
123 schemas
124 .describeRegistry({ RegistryName: registryName })
125 .pipe(Effect.catchTag("NotFoundException", () => Effect.undefined));
126
127 return Registry.Provider.of({
128 stables: ["registryName", "registryArn"],
129
130 // Top-level, account/region-scoped: enumerate every customer-owned
131 // registry. Scope LOCAL excludes the AWS-managed registries
132 // (aws.events, discovered-schemas).
133 list: () =>
134 schemas.listRegistries.pages({ Scope: "LOCAL" }).pipe(
135 Stream.runCollect,
136 Effect.map((chunk) =>
137 Array.from(chunk).flatMap((page) =>
138 (page.Registries ?? [])
139 .filter((r) => r.RegistryName != null && r.RegistryArn != null)
140 .map((r) => ({
141 registryName: r.RegistryName!,
142 registryArn: r.RegistryArn!,
143 })),
144 ),
145 ),
146 ),
147
148 read: Effect.fn(function* ({ id, olds, output }) {
149 const registryName = output?.registryName ?? (yield* createName(id, olds ?? {}));
150 const found = yield* describe(registryName);
151 if (!found) return undefined;
152 const attrs = {
153 registryName,
154 registryArn: found.RegistryArn!,
155 };
156 return (yield* hasAlchemyTags(id, found.Tags)) ? attrs : Unowned(attrs);
157 }),
158
159 diff: Effect.fn(function* ({ id, news, olds }) {
160 if (!isResolved(news)) return undefined;
161 const oldName = yield* createName(id, olds);
162 const newName = yield* createName(id, news);
163 if (oldName !== newName) return { action: "replace" } as const;
164 return undefined;
165 }),
166
167 reconcile: Effect.fn(function* ({ id, news, output, session }) {
168 const registryName = output?.registryName ?? (yield* createName(id, news));
169
170 // OBSERVE
171 let live = yield* describe(registryName);
172
173 // ENSURE — tolerate the create race as "already exists".
174 if (live === undefined) {
175 yield* schemas
176 .createRegistry({
177 RegistryName: registryName,
178 Description: news.description,
179 })
180 .pipe(Effect.catchTag("ConflictException", () => Effect.void));
181 live = yield* schemas.describeRegistry({
182 RegistryName: registryName,
183 });
184 }
185
186 // SYNC description — diff observed against desired.
187 if ((news.description ?? "") !== (live.Description ?? "")) {
188 yield* schemas.updateRegistry({
189 RegistryName: registryName,
190 Description: news.description ?? "",
191 });
192 }
193
194 // SYNC resource policy — diff observed against desired, comparing
195 // canonicalized documents so a re-deploy of an equivalent policy
196 // (key order, whitespace) is a no-op.
197 const desiredPolicy =
198 news.policy === undefined
199 ? undefined
200 : typeof news.policy === "string"
201 ? news.policy
202 : stringifyPolicyDocument(news.policy);
203 const currentPolicy = yield* schemas
204 .getResourcePolicy({ RegistryName: registryName })
205 .pipe(
206 Effect.map((r) => (r.Policy ? r.Policy : undefined)),
207 Effect.catchTag("NotFoundException", () => Effect.undefined),
208 );
209 const policyDrifted =
210 desiredPolicy === undefined || currentPolicy === undefined
211 ? desiredPolicy !== currentPolicy
212 : normalizePolicyDocument(currentPolicy) !== normalizePolicyDocument(desiredPolicy);
213 if (policyDrifted) {
214 if (desiredPolicy === undefined) {
215 yield* schemas
216 .deleteResourcePolicy({ RegistryName: registryName })
217 .pipe(Effect.catchTag("NotFoundException", () => Effect.void));
218 } else {
219 yield* schemas.putResourcePolicy({
220 RegistryName: registryName,
221 Policy: desiredPolicy,
222 });
223 }
224 }
225
226 // SYNC tags — diff against observed cloud tags.
227 yield* syncSchemasTags(live.RegistryArn!, id, news.tags);
228
229 yield* session.note(registryName);
230 return {
231 registryName,
232 registryArn: live.RegistryArn!,
233 };
234 }),
235
236 delete: Effect.fn(function* ({ output, force }) {
237 const RegistryName = output.registryName;
238 if (force !== true) {
239 yield* schemas
240 .deleteRegistry({ RegistryName })
241 .pipe(Effect.catchTag("NotFoundException", () => Effect.void));
242 return;
243 }
244
245 const purgeAndDelete = Effect.gen(function* () {
246 // Schemas are registry-scoped and globally invisible to nuke.
247 // Only its explicit operator-confirmed force path may remove them
248 // or an attached registry policy.
249 const childSchemas = yield* schemas.listSchemas.items({ RegistryName }).pipe(
250 Stream.runCollect,
251 Effect.map((chunk) => Array.from(chunk)),
252 );
253 yield* Effect.forEach(
254 childSchemas,
255 (schema) =>
256 schema.SchemaName === undefined
257 ? Effect.void
258 : schemas
259 .deleteSchema({
260 RegistryName,
261 SchemaName: schema.SchemaName,
262 })
263 .pipe(Effect.catchTag("NotFoundException", () => Effect.void)),
264 { concurrency: 4, discard: true },
265 );
266 yield* schemas
267 .deleteResourcePolicy({ RegistryName })
268 .pipe(Effect.catchTag("NotFoundException", () => Effect.void));
269 yield* schemas.deleteRegistry({ RegistryName });
270 });
271
272 yield* purgeAndDelete.pipe(
273 // Registry deletion can briefly observe schemas that have already
274 // accepted deletion. Re-list and retry only bounded transient or
275 // dependency-shaped failures.
276 Effect.retry({
277 while: (e) =>
278 e._tag === "BadRequestException" ||
279 e._tag === "InternalServerErrorException" ||
280 e._tag === "ServiceUnavailableException",
281 schedule: Schedule.max([Schedule.exponential(500), Schedule.recurs(8)]),
282 }),
283 Effect.catchTag("NotFoundException", () => Effect.void),
284 );
285 }),
286 });
287 }),
288 );