@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 261 lines 8.01 KB
Raw
1 import * as pubsub from "@distilled.cloud/gcp/pubsub_v1";
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 Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import * as Stream from "effect/Stream";
9 import { GcpEnvironment } from "../Environment.ts";
10 import type { Providers } from "../Providers.ts";
11
12 export type SchemaType = "AVRO" | "PROTOCOL_BUFFER";
13
14 export type SchemaProps = {
15 /**
16 * Schema id (the `{schema}` segment of `projects/{project}/schemas/{schema}`).
17 * If omitted, a unique name is generated from the stack, stage, and
18 * logical id. Must start with a letter and be 3-255 characters.
19 * Immutable — changing it replaces the schema.
20 */
21 schemaId?: string;
22 /**
23 * Schema definition language. Immutable — changing it replaces the schema.
24 */
25 type: SchemaType;
26 /**
27 * Schema definition. Must be a valid Avro JSON schema or Protocol Buffer
28 * file matching `type`. Updates commit a new revision (Pub/Sub allows
29 * up to 20 revisions per schema).
30 */
31 definition: string;
32 };
33
34 export type Schema = Resource<
35 "GCP.PubSub.Schema",
36 SchemaProps,
37 {
38 /** Full resource name `projects/{project}/schemas/{schema}`. */
39 name: string;
40 /** Schema id (last path segment). */
41 schemaId: string;
42 /** Project id. */
43 project: string;
44 /** Schema definition language. */
45 type: string | undefined;
46 /** Schema definition (latest revision). */
47 definition: string | undefined;
48 /** Latest revision id. */
49 revisionId: string | undefined;
50 /** RFC3339 timestamp when the latest revision was created. */
51 revisionCreateTime: string | undefined;
52 },
53 never,
54 Providers
55 >;
56
57 /**
58 * A Google Cloud Pub/Sub schema used to validate published messages.
59 *
60 * Pub/Sub schemas have no labels field. Ownership is by resource name;
61 * `list` returns every schema in the project so `pnpm nuke:gcp` can
62 * clean leaked test schemas.
63 *
64 * ### Creating a Schema
65 * **Example:** Generated name (Avro)
66 * ```typescript
67 * const schema = yield* GCP.PubSub.Schema("Events", {
68 * type: "AVRO",
69 * definition: JSON.stringify({
70 * type: "record",
71 * name: "Event",
72 * fields: [{ name: "id", type: "string" }],
73 * }),
74 * });
75 * ```
76 *
77 * **Example:** Explicit id and Protocol Buffer definition
78 * ```typescript
79 * const schema = yield* GCP.PubSub.Schema("Events", {
80 * schemaId: "order-events",
81 * type: "PROTOCOL_BUFFER",
82 * definition: 'syntax = "proto3";\nmessage Event { string id = 1; }',
83 * });
84 * ```
85 *
86 * ### Updating a Schema
87 * Change `definition` on the same logical id; the schema keeps its name and
88 * a new revision is committed.
89 *
90 * **Example:** Commit a compatible Avro revision
91 * ```typescript
92 * const schema = yield* GCP.PubSub.Schema("Events", {
93 * type: "AVRO",
94 * definition: JSON.stringify({
95 * type: "record",
96 * name: "Event",
97 * fields: [
98 * { name: "id", type: "string" },
99 * { name: "count", type: "int", default: 0 },
100 * ],
101 * }),
102 * });
103 * ```
104 *
105 * @resource
106 * @category PubSub
107 */
108 export const Schema = Resource<Schema>("GCP.PubSub.Schema");
109
110 export class SchemaNotResolved extends Data.TaggedError("GCP.PubSub.SchemaNotResolved")<{
111 resourceName: string;
112 }> {}
113
114 const canonicalName = (name: string) => name.split("@")[0] ?? name;
115
116 const schemaIdOf = (name: string) => {
117 const withoutRevision = canonicalName(name);
118 return withoutRevision.split("/").pop() ?? withoutRevision;
119 };
120
121 const resourceName = (project: string, schemaId: string) =>
122 `projects/${project}/schemas/${schemaId}`;
123
124 const toId = (id: string, schemaId: string | undefined, existing?: string) =>
125 Effect.gen(function* () {
126 if (schemaId !== undefined) return schemaId;
127 if (existing !== undefined) return existing;
128 const generated = yield* createPhysicalName({
129 id,
130 maxLength: 255,
131 lowercase: true,
132 });
133 return /^[a-z]/.test(generated) ? generated : `s${generated}`.slice(0, 255);
134 });
135
136 const toAttrs = (schema: pubsub.Pubsub_Schema, project: string) => {
137 const name = canonicalName(schema.name ?? "");
138 return {
139 name,
140 schemaId: schemaIdOf(name),
141 project,
142 type: schema.type,
143 definition: schema.definition,
144 revisionId: schema.revisionId,
145 revisionCreateTime: schema.revisionCreateTime,
146 };
147 };
148
149 const getByName = (name: string) =>
150 pubsub
151 .getProjectsSchemas({ name: canonicalName(name), view: "FULL" })
152 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
153
154 const definitionsEqual = (left: string | undefined, right: string | undefined) => {
155 const a = (left ?? "").trim();
156 const b = (right ?? "").trim();
157 if (a === b) return true;
158 try {
159 return JSON.stringify(JSON.parse(a)) === JSON.stringify(JSON.parse(b));
160 } catch {
161 return false;
162 }
163 };
164
165 export const SchemaProvider = () =>
166 Provider.succeed(Schema, {
167 stables: ["name", "schemaId", "project"],
168
169 diff: Effect.fn(function* ({ news, olds, output }) {
170 if (!isResolved(news)) return undefined;
171 const previousId = olds?.schemaId ?? output?.schemaId;
172 const nextId = news.schemaId ?? previousId;
173 const nameChanged =
174 previousId !== undefined && news.schemaId !== undefined && news.schemaId !== previousId;
175 const previousType = olds?.type ?? output?.type;
176 const typeChanged = previousType !== undefined && previousType !== news.type;
177 if (nameChanged) {
178 return { action: "replace" as const, deleteFirst: false };
179 }
180 if (typeChanged) {
181 return {
182 action: "replace" as const,
183 deleteFirst: nextId !== undefined && nextId === previousId,
184 };
185 }
186 return undefined;
187 }),
188
189 read: Effect.fn(function* ({ id, olds, output }) {
190 const env = yield* GcpEnvironment.current;
191 const schemaId = yield* toId(id, olds?.schemaId, output?.schemaId);
192 const name = canonicalName(output?.name ?? resourceName(env.project, schemaId));
193 const existing = yield* getByName(name);
194 if (existing === undefined) return undefined;
195 return toAttrs(existing, env.project);
196 }),
197
198 list: () =>
199 Effect.gen(function* () {
200 const env = yield* GcpEnvironment.current;
201 return yield* pubsub.listProjectsSchemas
202 .pages({
203 parent: `projects/${env.project}`,
204 pageSize: 1000,
205 view: "FULL",
206 })
207 .pipe(
208 Stream.flatMap((page) => Stream.fromIterable(page.schemas ?? [])),
209 Stream.map((schema) => toAttrs(schema, env.project)),
210 Stream.runCollect,
211 Effect.map((chunk) => Array.from(chunk)),
212 );
213 }),
214
215 reconcile: Effect.fn(function* ({ id, news, output }) {
216 const env = yield* GcpEnvironment.current;
217 const schemaId = yield* toId(id, news.schemaId, output?.schemaId);
218 const name = resourceName(env.project, schemaId);
219
220 let current = yield* getByName(name);
221
222 if (current === undefined) {
223 const created = yield* pubsub
224 .createProjectsSchemas({
225 parent: `projects/${env.project}`,
226 schemaId,
227 body: {
228 type: news.type,
229 definition: news.definition,
230 },
231 })
232 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
233 current = created ?? undefined;
234 }
235
236 if (current === undefined) {
237 return yield* new SchemaNotResolved({ resourceName: name });
238 }
239
240 if (!definitionsEqual(current.definition, news.definition)) {
241 current = yield* pubsub.commitProjectsSchemas({
242 name,
243 body: {
244 schema: {
245 name,
246 type: news.type,
247 definition: news.definition,
248 },
249 },
250 });
251 }
252
253 return toAttrs(current, env.project);
254 }),
255
256 delete: Effect.fn(function* ({ output }) {
257 yield* pubsub
258 .deleteProjectsSchemas({ name: canonicalName(output.name) })
259 .pipe(Effect.catchTag("NotFound", () => Effect.void));
260 }),
261 });