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

main
ts 250 lines 8.32 KB
Raw
1 import * as discoveryengine from "@distilled.cloud/gcp/discoveryengine_v1";
2 import { unownedUnlessPrevious } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
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 Schedule from "effect/Schedule";
9 import { GcpEnvironment } from "../Environment.ts";
10 import type { Providers } from "../Providers.ts";
11 import {
12 expandDataStore,
13 fingerprint,
14 parseJsonObject,
15 parseResourceName,
16 rfc1035,
17 toPhysical,
18 withSchemaVersion,
19 } from "./internal.ts";
20 import { waitForOperation } from "./operations.ts";
21
22 export type DataStoresSchemaProps = {
23 /**
24 * Parent Data Store resource name
25 * `projects/{project}/locations/{location}/dataStores/{dataStore}`.
26 * Immutable — changing it replaces the schema.
27 */
28 dataStore: string;
29 /**
30 * Schema id (RFC-1034, max 63 characters). If omitted, a unique id is
31 * generated. Immutable — changing it replaces the schema.
32 */
33 schemaId?: string;
34 /**
35 * JSON Schema document.
36 */
37 jsonSchema?: string;
38 /**
39 * Structured schema representation. Ignored when `jsonSchema` is set.
40 */
41 structSchema?: Record<string, unknown>;
42 };
43
44 export type DataStoresSchema = Resource<
45 "GCP.DiscoveryEngine.DataStoresSchema",
46 DataStoresSchemaProps,
47 {
48 /** Full resource name `.../dataStores/{dataStore}/schemas/{schema}`. */
49 name: string;
50 /** Schema id (last path segment). */
51 schemaId: string;
52 /** Parent data store resource name. */
53 dataStore: string;
54 /** Project id. */
55 project: string;
56 /** Location id. */
57 location: string;
58 /** JSON schema document, if set. */
59 jsonSchema: string | undefined;
60 /** Structured schema, if set. */
61 structSchema: Record<string, unknown> | undefined;
62 },
63 never,
64 Providers
65 >;
66
67 /**
68 * A Vertex AI Search Schema attached to a Data Store.
69 *
70 * Without labels, ownership rests on the deterministic id: `read` reports a
71 * resource it finds without prior state as unowned (adopt it with `--adopt`).
72 * Parent and schema id are immutable; the schema document updates in place
73 * (LRO).
74 *
75 * ### Creating a Schema
76 * **Example:** JSON schema
77 * ```typescript
78 * const schema = yield* GCP.DiscoveryEngine.DataStoresSchema("Catalog", {
79 * dataStore: dataStore.name,
80 * jsonSchema: JSON.stringify({
81 * type: "object",
82 * properties: {
83 * title: { type: "string" },
84 * sku: { type: "string" },
85 * },
86 * }),
87 * });
88 * ```
89 *
90 * ### Updating a Schema
91 * **Example:** Add a field
92 * ```typescript
93 * // Same logical id as before; only the changed props differ.
94 * const schema = yield* GCP.DiscoveryEngine.DataStoresSchema("Catalog", {
95 * dataStore: dataStore.name,
96 * jsonSchema: JSON.stringify({
97 * type: "object",
98 * properties: {
99 * title: { type: "string" },
100 * sku: { type: "string" },
101 * price: { type: "number" },
102 * },
103 * }),
104 * });
105 * ```
106 *
107 * @resource
108 * @category DiscoveryEngine
109 */
110 export const DataStoresSchema = Resource<DataStoresSchema>("GCP.DiscoveryEngine.DataStoresSchema");
111
112 export class DataStoresSchemaNotResolved extends Data.TaggedError(
113 "GCP.DiscoveryEngine.DataStoresSchemaNotResolved",
114 )<{
115 resourceName: string;
116 }> {}
117
118 const resourceName = (dataStore: string, schemaId: string) => `${dataStore}/schemas/${schemaId}`;
119
120 const toAttrs = (schema: discoveryengine.GoogleCloudDiscoveryengineV1Schema, project: string) => {
121 const name = schema.name ?? "";
122 const parsed = parseResourceName(name, "schemas");
123 const json = schema.jsonSchema;
124 const obj = parseJsonObject(json);
125 if (obj && "$comment" in obj) {
126 delete obj.$comment;
127 }
128 return {
129 name,
130 schemaId: parsed.id,
131 dataStore: parsed.dataStore,
132 project: parsed.project || project,
133 location: parsed.location,
134 jsonSchema: obj ? JSON.stringify(obj) : json,
135 structSchema: schema.structSchema as Record<string, unknown> | undefined,
136 };
137 };
138
139 const getByName = (name: string) =>
140 name.length === 0
141 ? Effect.undefined
142 : discoveryengine
143 .getProjectsLocationsDataStoresSchemas({ name })
144 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
145
146 export const DataStoresSchemaProvider = () =>
147 Provider.succeed(DataStoresSchema, {
148 stables: ["name", "schemaId", "dataStore", "project", "location"],
149
150 diff: Effect.fn(function* ({ news, olds, output }) {
151 if (!isResolved(news)) return undefined;
152 const previousParent = olds?.dataStore ?? output?.dataStore;
153 if (previousParent !== undefined && news.dataStore !== previousParent) {
154 return { action: "replace" as const, deleteFirst: false };
155 }
156 const previousId = olds?.schemaId ?? output?.schemaId;
157 if (previousId !== undefined && news.schemaId !== undefined && news.schemaId !== previousId) {
158 return { action: "replace" as const, deleteFirst: true };
159 }
160 return undefined;
161 }),
162
163 read: Effect.fn(function* ({ id, olds, output, previous }) {
164 const env = yield* GcpEnvironment.current;
165 const schemaId = yield* toPhysical(id, olds?.schemaId, output?.schemaId, rfc1035);
166 const parent = olds?.dataStore
167 ? expandDataStore(olds.dataStore, env.project, output?.location ?? "global")
168 : undefined;
169 const name = output?.name ?? (parent ? resourceName(parent, schemaId) : "");
170 const existing = yield* getByName(name);
171 if (existing === undefined) return undefined;
172 const attrs = toAttrs(existing, env.project);
173 // No labels field: without prior state it may not be ours.
174 return output !== undefined ? attrs : unownedUnlessPrevious(attrs, previous, "name");
175 }),
176
177 reconcile: Effect.fn(function* ({ id, news, output }) {
178 const env = yield* GcpEnvironment.current;
179 const parent = expandDataStore(news.dataStore, env.project, output?.location ?? "global");
180 const schemaId = yield* toPhysical(id, news.schemaId, output?.schemaId, rfc1035);
181 const name = resourceName(parent, schemaId);
182 const jsonSchema = withSchemaVersion(news.jsonSchema);
183 const body: discoveryengine.GoogleCloudDiscoveryengineV1Schema = {
184 jsonSchema,
185 structSchema: news.jsonSchema === undefined ? news.structSchema : undefined,
186 };
187
188 let current = yield* getByName(output?.name ?? name);
189
190 if (current === undefined) {
191 const created = yield* discoveryengine
192 .createProjectsLocationsDataStoresSchemas({
193 parent,
194 schemaId,
195 body,
196 })
197 .pipe(
198 Effect.retry({
199 while: (error) => error._tag === "DataStoreNotReady",
200 times: 8,
201 schedule: Schedule.spaced("5 seconds"),
202 }),
203 Effect.catchTag("Conflict", () => Effect.undefined),
204 );
205 if (created !== undefined) {
206 yield* waitForOperation(created);
207 }
208 current = yield* getByName(name);
209 }
210
211 if (current === undefined) {
212 return yield* new DataStoresSchemaNotResolved({ resourceName: name });
213 }
214
215 const stripComment = (json: string | undefined) => {
216 const obj = parseJsonObject(json);
217 if (obj && "$comment" in obj) delete obj.$comment;
218 return fingerprint(obj ?? json);
219 };
220 const schemaChanged =
221 stripComment(current.jsonSchema) !== stripComment(jsonSchema) ||
222 (news.jsonSchema === undefined &&
223 fingerprint(current.structSchema) !== fingerprint(news.structSchema));
224
225 if (schemaChanged) {
226 const patched = yield* discoveryengine.patchProjectsLocationsDataStoresSchemas({
227 name: current.name ?? name,
228 body: {
229 ...body,
230 name: current.name ?? name,
231 },
232 });
233 yield* waitForOperation(patched);
234 current = (yield* getByName(current.name ?? name)) ?? current;
235 }
236
237 return toAttrs(current, env.project);
238 }),
239
240 delete: Effect.fn(function* ({ output }) {
241 const existing = yield* getByName(output.name);
242 if (existing === undefined) return;
243 const operation = yield* discoveryengine
244 .deleteProjectsLocationsDataStoresSchemas({ name: output.name })
245 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
246 if (operation !== undefined) {
247 yield* waitForOperation(operation, { notFoundOk: true });
248 }
249 }),
250 });