@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 467 lines 14.8 KB
Raw
1 import * as firebasedataconnect from "@distilled.cloud/gcp/firebasedataconnect_v1";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { tagRecord } from "alchemy/Tags";
7 import * as Effect from "effect/Effect";
8 import * as Schedule from "effect/Schedule";
9 import { GcpEnvironment } from "../Environment.ts";
10 import { createInternalLabels, diffLabels, hasAlchemyLabels, toLabels } from "../Labels.ts";
11 import type { Providers } from "../Providers.ts";
12 import {
13 DEFAULT_SCHEMA_ID,
14 expandParent,
15 fieldMask,
16 fingerprint,
17 listAtNested,
18 listLabeledPages,
19 normalizeLocation,
20 parseName,
21 replaceOnIdentity,
22 ResourceNotResolved,
23 retryStaleEtag,
24 sameText,
25 stringMap,
26 userLabels,
27 waitForDeleteOperation,
28 waitForOperation,
29 waitUntilExists,
30 waitUntilGone,
31 waitUntilReady,
32 } from "./internal.ts";
33
34 export type File = {
35 /** File contents (GraphQL SDL). */
36 content?: string;
37 /**
38 * Path relative to the Data Connect workspace, for example
39 * `schema.gql`.
40 */
41 path?: string;
42 };
43
44 export type Source = {
45 /** GraphQL source files that make up the schema. */
46 files?: File[];
47 };
48
49 export type CloudSqlInstance = {
50 /**
51 * Cloud SQL instance resource name
52 * `projects/{project}/locations/{location}/instances/{instance}`.
53 */
54 instance?: string;
55 };
56
57 export type HttpGraphql = {
58 /** HTTP GraphQL endpoint URI. */
59 uri?: string;
60 /** Request timeout, for example `"3.5s"`. */
61 timeout?: string;
62 };
63
64 export type PostgreSql = {
65 /** Cloud SQL instance used as the Postgres backend. */
66 cloudSql?: CloudSqlInstance;
67 /**
68 * When true, no Postgres instance is linked. Do not set `database`
69 * or `schemaValidation` together with `unlinked`.
70 */
71 unlinked?: boolean;
72 /** PostgreSQL database name. */
73 database?: string;
74 /**
75 * How much PostgreSQL schema validation to run before deploying
76 * (`NONE`, `STRICT`, `COMPATIBLE`).
77 */
78 schemaValidation?: firebasedataconnect.PostgreSqlSchemaValidationEnum | (string & {});
79 /**
80 * Additive-only PostgreSQL schema migration before deploy
81 * (`MIGRATE_COMPATIBLE`).
82 */
83 schemaMigration?: firebasedataconnect.PostgreSqlSchemaMigrationEnum | (string & {});
84 /**
85 * PostgreSQL schema name.
86 * @default "public"
87 */
88 schema?: string;
89 };
90
91 export type Datasource = {
92 /** HTTP GraphQL webhook backend. */
93 httpGraphql?: HttpGraphql;
94 /** PostgreSQL (Cloud SQL or unlinked) backend. */
95 postgresql?: PostgreSql;
96 };
97
98 export type ServicesSchemaProps = {
99 /**
100 * Parent Data Connect service. Full name
101 * `projects/{project}/locations/{location}/services/{service}` or the
102 * service id (combined with `location`). Immutable — changing it
103 * replaces the schema.
104 */
105 service: string;
106 /**
107 * Region used when `service` is a bare id.
108 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
109 */
110 location?: string;
111 /**
112 * Schema id. The API currently only accepts `main`. Immutable —
113 * changing it replaces the schema.
114 * @default "main"
115 */
116 schemaId?: string;
117 /**
118 * GraphQL SDL source files. Required.
119 */
120 source: Source;
121 /**
122 * Data sources linked by this schema. Required. Use
123 * `{ postgresql: { unlinked: true } }` when no Cloud SQL instance is
124 * attached, or `{ postgresql: { database, cloudSql } }` to link one.
125 */
126 datasources: Datasource[];
127 /**
128 * Human-readable name. 63 character limit.
129 */
130 displayName?: string;
131 /**
132 * User annotations (preserved by external tools).
133 */
134 annotations?: Record<string, string>;
135 /**
136 * User labels. Alchemy ownership labels are merged in automatically.
137 */
138 labels?: Record<string, string>;
139 };
140
141 export type ServicesSchema = Resource<
142 "GCP.FirebaseDataConnect.ServicesSchema",
143 ServicesSchemaProps,
144 {
145 /** Full resource name. */
146 name: string;
147 /** Schema id (`main`). */
148 schemaId: string;
149 /** Parent service name. */
150 service: string;
151 /** Project id. */
152 project: string;
153 /** Location id. */
154 location: string;
155 /** GraphQL source files. */
156 source: Source | undefined;
157 /** Linked data sources. */
158 datasources: Datasource[] | undefined;
159 /** Human-readable name. */
160 displayName: string | undefined;
161 /** True while Data Connect is compiling or deploying the schema. */
162 reconciling: boolean;
163 /** True when the Postgres backend is ephemeral in-memory storage. */
164 ephemeral: boolean;
165 /** User annotations. */
166 annotations: Record<string, string>;
167 /** User labels (Alchemy ownership labels stripped). */
168 labels: Record<string, string>;
169 /** Server-generated resource uid. */
170 uid: string | undefined;
171 /** RFC3339 creation timestamp. */
172 createTime: string | undefined;
173 /** RFC3339 last-update timestamp. */
174 updateTime: string | undefined;
175 /** Server-computed etag. */
176 etag: string | undefined;
177 },
178 never,
179 Providers
180 >;
181
182 /**
183 * The application schema of a Firebase Data Connect service. Only
184 * `schemas/main` is supported — one schema per service.
185 *
186 * Changing `service`, `location`, or `schemaId` replaces the schema.
187 * Source, datasources, display name, labels, and annotations update in
188 * place. Delete fails while connectors still exist; destroy connectors
189 * first (or delete the parent service with `force`).
190 *
191 * ### Creating a Schema
192 * **Example:** Unlinked Postgres schema
193 * ```typescript
194 * const service = yield* GCP.FirebaseDataConnect.Service("App", {});
195 * const schema = yield* GCP.FirebaseDataConnect.ServicesSchema("Main", {
196 * service: service.name,
197 * source: {
198 * files: [{
199 * path: "schema.gql",
200 * content: "type Note @table { title: String! }",
201 * }],
202 * },
203 * datasources: [{ postgresql: { unlinked: true } }],
204 * labels: { env: "test" },
205 * });
206 * ```
207 *
208 * **Example:** Cloud SQL Postgres
209 * ```typescript
210 * const schema = yield* GCP.FirebaseDataConnect.ServicesSchema("Main", {
211 * service: service.name,
212 * source: {
213 * files: [{
214 * path: "schema.gql",
215 * content: "type Movie @table { title: String! }",
216 * }],
217 * },
218 * datasources: [{
219 * postgresql: {
220 * database: "fdcdb",
221 * cloudSql: { instance: sqlInstance.name },
222 * schemaValidation: "NONE",
223 * schemaMigration: "MIGRATE_COMPATIBLE",
224 * },
225 * }],
226 * });
227 * ```
228 *
229 * ### Updating a Schema
230 * **Example:** New GraphQL types
231 * ```typescript
232 * const schema = yield* GCP.FirebaseDataConnect.ServicesSchema("Main", {
233 * service: service.name,
234 * source: {
235 * files: [{
236 * path: "schema.gql",
237 * content: "type Note @table { title: String! body: String }",
238 * }],
239 * },
240 * datasources: [{ postgresql: { unlinked: true } }],
241 * displayName: "notes v2",
242 * });
243 * ```
244 *
245 * @resource
246 * @category FirebaseDataConnect
247 */
248 export const ServicesSchema = Resource<ServicesSchema>("GCP.FirebaseDataConnect.ServicesSchema");
249
250 const resourceName = (service: string, schemaId: string) => `${service}/schemas/${schemaId}`;
251
252 const toFile = (value: firebasedataconnect.File): File => ({
253 content: value.content,
254 path: value.path,
255 });
256
257 const toSource = (value: firebasedataconnect.Source | undefined): Source | undefined =>
258 value === undefined ? undefined : { files: value.files?.map(toFile) };
259
260 const toDatasource = (value: firebasedataconnect.Datasource): Datasource => ({
261 httpGraphql: value.httpGraphql
262 ? { uri: value.httpGraphql.uri, timeout: value.httpGraphql.timeout }
263 : undefined,
264 postgresql: value.postgresql
265 ? {
266 cloudSql: value.postgresql.cloudSql
267 ? { instance: value.postgresql.cloudSql.instance }
268 : undefined,
269 unlinked: value.postgresql.unlinked,
270 database: value.postgresql.database,
271 schemaValidation: value.postgresql.schemaValidation,
272 schemaMigration: value.postgresql.schemaMigration,
273 schema: value.postgresql.schema,
274 }
275 : undefined,
276 });
277
278 const toAttrs = (
279 item: firebasedataconnect.Firebasedataconnect_Schema,
280 project: string,
281 region: string,
282 ): ServicesSchema["Attributes"] => {
283 const name = item.name ?? "";
284 const parsed = parseName(name, "schemas", region);
285 return {
286 name,
287 schemaId: parsed.id,
288 service: parsed.parent,
289 project: parsed.project || project,
290 location: parsed.location,
291 source: toSource(item.source),
292 datasources: item.datasources?.map(toDatasource),
293 displayName: item.displayName,
294 reconciling: item.reconciling === true,
295 ephemeral: item.datasources?.some((ds) => ds.postgresql?.ephemeral === true) === true,
296 annotations: stringMap(item.annotations),
297 labels: userLabels(item.labels),
298 uid: item.uid,
299 createTime: item.createTime,
300 updateTime: item.updateTime,
301 etag: item.etag,
302 };
303 };
304
305 const getByName = (name: string) =>
306 firebasedataconnect
307 .getProjectsLocationsServicesSchemas({ name })
308 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
309
310 const listOwned = (project: string) =>
311 listAtNested(project, "services/-", (parent) =>
312 listLabeledPages(
313 firebasedataconnect.listProjectsLocationsServicesSchemas.pages({
314 parent,
315 pageSize: 1000,
316 }),
317 (page) => page.schemas,
318 (item) => item.labels,
319 ),
320 );
321
322 const schemaIdOf = (value: string | undefined) =>
323 value === undefined || value.length === 0 ? DEFAULT_SCHEMA_ID : value;
324
325 export const ServicesSchemaProvider = () =>
326 Provider.succeed(ServicesSchema, {
327 stables: ["name", "schemaId", "service", "project", "location", "uid", "createTime"],
328
329 diff: Effect.fn(function* ({ news, olds, output }) {
330 if (!isResolved(news)) return undefined;
331 const env = yield* GcpEnvironment.current;
332 const location = normalizeLocation(
333 news.location ?? olds?.location ?? output?.location,
334 env.region,
335 );
336 const previousLocation = normalizeLocation(olds?.location ?? output?.location, env.region);
337 const previousParent =
338 (olds?.service ?? output?.service)
339 ? expandParent(
340 olds?.service ?? output?.service ?? "",
341 env.project,
342 previousLocation,
343 "services",
344 )
345 : undefined;
346 const nextParent = expandParent(news.service, env.project, location, "services");
347 return replaceOnIdentity({
348 previousId: olds?.schemaId ?? output?.schemaId,
349 nextId: schemaIdOf(news.schemaId ?? olds?.schemaId ?? output?.schemaId),
350 previousLocation,
351 nextLocation: location,
352 previousParent,
353 nextParent,
354 });
355 }),
356
357 read: Effect.fn(function* ({ id, olds, output }) {
358 const env = yield* GcpEnvironment.current;
359 const schemaId = schemaIdOf(olds?.schemaId ?? output?.schemaId);
360 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
361 const service =
362 output?.service ??
363 (olds?.service ? expandParent(olds.service, env.project, location, "services") : undefined);
364 const name = output?.name ?? (service ? resourceName(service, schemaId) : undefined);
365 if (name === undefined) return undefined;
366 const existing = yield* getByName(name);
367 if (existing === undefined) return undefined;
368 const attrs = toAttrs(existing, env.project, env.region);
369 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
370 }),
371
372 list: () =>
373 Effect.gen(function* () {
374 const env = yield* GcpEnvironment.current;
375 const items = yield* listOwned(env.project);
376 return items.map((item) => toAttrs(item, env.project, env.region));
377 }),
378
379 reconcile: Effect.fn(function* ({ id, news, output }) {
380 const env = yield* GcpEnvironment.current;
381 const schemaId = schemaIdOf(news.schemaId ?? output?.schemaId);
382 const location = normalizeLocation(news.location ?? output?.location, env.region);
383 const service = expandParent(news.service, env.project, location, "services");
384 const name = resourceName(service, schemaId);
385 const desiredLabels = {
386 ...toLabels(news.labels),
387 ...(yield* createInternalLabels(id)),
388 };
389 const desiredAnnotations = news.annotations ?? {};
390 const body: firebasedataconnect.Firebasedataconnect_Schema = {
391 source: news.source,
392 datasources: news.datasources,
393 displayName: news.displayName,
394 annotations: desiredAnnotations,
395 labels: desiredLabels,
396 };
397
398 let current = yield* getByName(output?.name ?? name);
399
400 if (current === undefined) {
401 const created = yield* firebasedataconnect
402 .createProjectsLocationsServicesSchemas({
403 parent: service,
404 schemaId,
405 body,
406 })
407 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
408 if (created !== undefined) {
409 yield* waitForOperation(created);
410 }
411 current = yield* waitUntilExists(getByName(name), name);
412 }
413
414 if (current === undefined) {
415 return yield* new ResourceNotResolved({ resourceName: name });
416 }
417
418 const observedLabels = tagRecord(current.labels);
419 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
420 const mask = fieldMask([
421 (upsert.length > 0 || removed.length > 0) && "labels",
422 fingerprint(stringMap(current.annotations)) !== fingerprint(desiredAnnotations) &&
423 "annotations",
424 !sameText(current.displayName, news.displayName) && "displayName",
425 fingerprint(toSource(current.source)) !== fingerprint(news.source) && "source",
426 fingerprint(current.datasources?.map(toDatasource)) !== fingerprint(news.datasources) &&
427 "datasources",
428 ]);
429
430 if (mask.length > 0) {
431 const patchName = current.name ?? name;
432 yield* retryStaleEtag(
433 firebasedataconnect
434 .patchProjectsLocationsServicesSchemas({
435 name: patchName,
436 updateMask: mask,
437 body,
438 })
439 .pipe(Effect.flatMap((operation) => waitForOperation(operation))),
440 );
441 current = yield* waitUntilExists(getByName(current.name ?? name), current.name ?? name);
442 }
443
444 current = yield* waitUntilReady(getByName(current.name ?? name), current.name ?? name);
445 return toAttrs(current, env.project, env.region);
446 }),
447
448 delete: Effect.fn(function* ({ output }) {
449 const operation = yield* firebasedataconnect
450 .deleteProjectsLocationsServicesSchemas({
451 name: output.name,
452 force: true,
453 })
454 .pipe(
455 Effect.retry({
456 while: (error) => error._tag === "Conflict",
457 times: 8,
458 schedule: Schedule.spaced("2 seconds"),
459 }),
460 Effect.catchTag("NotFound", () => Effect.undefined),
461 );
462 if (operation !== undefined) {
463 yield* waitForDeleteOperation(operation);
464 }
465 yield* waitUntilGone(getByName(output.name), output.name);
466 }),
467 });