@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, 06:00 UTC

main
ts 232 lines 7.77 KB
Raw
1 import * as personalize from "@distilled.cloud/aws/personalize";
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 type { Providers } from "../Providers.ts";
10
11 export interface SchemaProps {
12 /**
13 * Name of the schema. If omitted, a unique name is generated from the app,
14 * stage, and logical ID. Changing the name replaces the schema.
15 */
16 name?: string;
17 /**
18 * The Avro schema definition, as a JSON string, describing the fields of the
19 * dataset this schema applies to. Immutable — changing it replaces the
20 * schema.
21 *
22 * @example
23 * ```json
24 * {
25 * "type": "record",
26 * "name": "Interactions",
27 * "namespace": "com.amazonaws.personalize.schema",
28 * "fields": [
29 * { "name": "USER_ID", "type": "string" },
30 * { "name": "ITEM_ID", "type": "string" },
31 * { "name": "TIMESTAMP", "type": "long" }
32 * ],
33 * "version": "1.0"
34 * }
35 * ```
36 */
37 schema: string;
38 /**
39 * The domain of a domain-specific dataset group this schema belongs to
40 * (`ECOMMERCE` or `VIDEO_ON_DEMAND`). Omit for a custom (non-domain) schema.
41 * Immutable — changing it replaces the schema.
42 */
43 domain?: string;
44 }
45
46 export interface Schema extends Resource<
47 "AWS.Personalize.Schema",
48 SchemaProps,
49 {
50 /**
51 * ARN of the schema.
52 */
53 schemaArn: string;
54 /**
55 * Name of the schema.
56 */
57 name: string;
58 /**
59 * Avro schema definition as a JSON string.
60 */
61 schema: string;
62 /**
63 * Domain of the schema (`ECOMMERCE` or `VIDEO_ON_DEMAND`) when it is a
64 * domain schema.
65 */
66 domain: string | undefined;
67 },
68 never,
69 Providers
70 > {}
71
72 /**
73 * An Amazon Personalize schema — an Avro definition that describes the fields
74 * of a dataset (Interactions, Items, Users, …). Schemas are immutable once
75 * created; changing any property replaces the schema.
76 *
77 * ### Creating a Schema
78 * **Example:** Interactions Schema
79 * ```typescript
80 * const schema = yield* Personalize.Schema("Interactions", {
81 * schema: JSON.stringify({
82 * type: "record",
83 * name: "Interactions",
84 * namespace: "com.amazonaws.personalize.schema",
85 * fields: [
86 * { name: "USER_ID", type: "string" },
87 * { name: "ITEM_ID", type: "string" },
88 * { name: "TIMESTAMP", type: "long" },
89 * ],
90 * version: "1.0",
91 * }),
92 * });
93 * ```
94 *
95 * @resource
96 */
97 export const Schema = Resource<Schema>("AWS.Personalize.Schema");
98
99 export const SchemaProvider = () =>
100 Provider.effect(
101 Schema,
102 Effect.gen(function* () {
103 const createName = Effect.fn(function* (id: string, props: SchemaProps) {
104 return props.name ?? (yield* createPhysicalName({ id, maxLength: 63 }));
105 });
106
107 /** Describe a schema by ARN; typed not-found → undefined. */
108 const describe = Effect.fn(function* (schemaArn: string) {
109 const response = yield* personalize
110 .describeSchema({ schemaArn })
111 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
112 return response?.schema;
113 });
114
115 /** Find an existing schema's ARN by its (deterministic) name. */
116 const findArnByName = Effect.fn(function* (name: string) {
117 const pages = yield* personalize.listSchemas.pages({}).pipe(Stream.runCollect);
118 return Array.from(pages)
119 .flatMap((page) => page.schemas ?? [])
120 .find((summary) => summary.name === name)?.schemaArn;
121 });
122
123 return {
124 stables: ["schemaArn", "name"],
125
126 diff: Effect.fn(function* ({ id, olds, news }) {
127 if (!isResolved(news)) return undefined;
128 const oldName = yield* createName(id, olds);
129 const newName = yield* createName(id, news);
130 // Schemas are entirely immutable — any change replaces.
131 if (
132 oldName !== newName ||
133 (olds.schema ?? undefined) !== (news.schema ?? undefined) ||
134 (olds.domain ?? undefined) !== (news.domain ?? undefined)
135 ) {
136 return { action: "replace" } as const;
137 }
138 }),
139
140 read: Effect.fn(function* ({ output }) {
141 if (!output?.schemaArn) return undefined;
142 const schema = yield* describe(output.schemaArn);
143 if (schema === undefined) return undefined;
144 return {
145 schemaArn: schema.schemaArn!,
146 name: schema.name!,
147 schema: schema.schema!,
148 domain: schema.domain,
149 };
150 }),
151
152 reconcile: Effect.fn(function* ({ id, news, output, session }) {
153 const name = yield* createName(id, news);
154
155 // 1. Observe — cloud state is authoritative; output is an ARN cache.
156 let schema =
157 output?.schemaArn !== undefined ? yield* describe(output.schemaArn) : undefined;
158
159 // 2. Ensure — schemas are immutable, so only create when missing.
160 // A crashed prior run may have left a same-named schema behind
161 // with no persisted state — adopt it by name.
162 if (schema === undefined) {
163 const arn = yield* personalize
164 .createSchema({
165 name,
166 schema: news.schema,
167 domain: news.domain,
168 })
169 .pipe(
170 Effect.map((created) => created.schemaArn!),
171 Effect.catchTag("ResourceAlreadyExistsException", (error) =>
172 findArnByName(name).pipe(
173 Effect.flatMap((existing) =>
174 existing === undefined ? Effect.fail(error) : Effect.succeed(existing),
175 ),
176 ),
177 ),
178 );
179 schema = yield* describe(arn);
180 }
181
182 yield* session.note(schema!.schemaArn!);
183 return {
184 schemaArn: schema!.schemaArn!,
185 name: schema!.name!,
186 schema: schema!.schema!,
187 domain: schema!.domain,
188 };
189 }),
190
191 delete: Effect.fn(function* ({ output }) {
192 yield* personalize.deleteSchema({ schemaArn: output.schemaArn }).pipe(
193 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
194 // A schema still referenced by a dataset rejects deletion. The
195 // engine deletes dependent datasets first, but dataset deletion is
196 // asynchronous (DELETE PENDING) and may be draining concurrently
197 // (e.g. via a dataset group's child cascade) — retry bounded while
198 // the referencing datasets finish deleting.
199 Effect.retry({
200 while: (e) => e._tag === "ResourceInUseException",
201 schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(40)]),
202 }),
203 );
204 }),
205
206 list: () =>
207 personalize.listSchemas.pages({}).pipe(
208 Stream.runCollect,
209 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.schemas ?? [])),
210 Effect.flatMap(
211 Effect.forEach(
212 (summary) =>
213 describe(summary.schemaArn!).pipe(
214 Effect.map((s) =>
215 s
216 ? {
217 schemaArn: s.schemaArn!,
218 name: s.name!,
219 schema: s.schema!,
220 domain: s.domain,
221 }
222 : undefined,
223 ),
224 ),
225 { concurrency: 4 },
226 ),
227 ),
228 Effect.map((items) => items.filter((item) => item !== undefined)),
229 ),
230 };
231 }),
232 );