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

main
ts 278 lines 8.72 KB
Raw
1 import * as discoveryengine from "@distilled.cloud/gcp/discoveryengine_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 * 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 parentOf,
13 parseResourceName,
14 rfc1035,
15 sameJson,
16 toPhysical,
17 withSchemaVersion,
18 } from "./internal.ts";
19 import { waitForOperation } from "./operations.ts";
20
21 export type CollectionsDataStoresSchemaProps = {
22 /**
23 * Parent data store resource name. Immutable — changing it replaces
24 * the schema.
25 */
26 dataStore: string;
27 /**
28 * Schema id (RFC-1034, max 63 characters). If omitted, a unique id is
29 * generated. Immutable — changing it replaces the schema.
30 */
31 schemaId?: string;
32 /**
33 * JSON Schema document.
34 */
35 jsonSchema?: string;
36 /**
37 * Structured schema representation.
38 */
39 structSchema?: Record<string, unknown>;
40 };
41
42 export type CollectionsDataStoresSchema = Resource<
43 "GCP.DiscoveryEngine.CollectionsDataStoresSchema",
44 CollectionsDataStoresSchemaProps,
45 {
46 /** Full resource name. */
47 name: string;
48 /** Schema id. */
49 schemaId: string;
50 /** Parent data store resource name. */
51 dataStore: string;
52 /** Project id. */
53 project: string;
54 /** Location id. */
55 location: string;
56 /** JSON Schema document. */
57 jsonSchema: string | undefined;
58 /** Structured schema. */
59 structSchema: Record<string, unknown> | undefined;
60 },
61 never,
62 Providers
63 >;
64
65 /**
66 * A Discovery Engine schema on a collection data store.
67 *
68 * Without labels, ownership rests on the deterministic id: `read` reports a
69 * resource it finds without prior state as unowned (adopt it with `--adopt`).
70 * Parent and schema id are immutable. Schema contents update in place.
71 *
72 * ### Creating a Schema
73 * **Example:** Custom schema on a store without a default schema
74 * ```typescript
75 * const store = yield* GCP.DiscoveryEngine.CollectionsDataStore("Docs", {
76 * skipDefaultSchemaCreation: true,
77 * });
78 * const schema = yield* GCP.DiscoveryEngine.CollectionsDataStoresSchema(
79 * "Fields",
80 * {
81 * dataStore: store.name,
82 * jsonSchema: JSON.stringify({
83 * type: "object",
84 * properties: { title: { type: "string" } },
85 * }),
86 * },
87 * );
88 * ```
89 *
90 * @resource
91 * @category DiscoveryEngine
92 */
93 export const CollectionsDataStoresSchema = Resource<CollectionsDataStoresSchema>(
94 "GCP.DiscoveryEngine.CollectionsDataStoresSchema",
95 );
96
97 export class CollectionsDataStoresSchemaNotResolved extends Data.TaggedError(
98 "GCP.DiscoveryEngine.CollectionsDataStoresSchemaNotResolved",
99 )<{
100 resourceName: string;
101 }> {}
102
103 export class CollectionsDataStoresSchemaStillExists extends Data.TaggedError(
104 "GCP.DiscoveryEngine.CollectionsDataStoresSchemaStillExists",
105 )<{
106 resourceName: string;
107 }> {}
108
109 const toAttrs = (schema: discoveryengine.GoogleCloudDiscoveryengineV1Schema, project: string) => {
110 const name = schema.name ?? "";
111 const parsed = parseResourceName(name, "schemas");
112 return {
113 name,
114 schemaId: parsed.id,
115 dataStore: parentOf(name, "schemas"),
116 project: parsed.project || project,
117 location: parsed.location,
118 jsonSchema: schema.jsonSchema,
119 structSchema: schema.structSchema as Record<string, unknown> | undefined,
120 };
121 };
122
123 const resourceName = (dataStore: string, schemaId: string) => `${dataStore}/schemas/${schemaId}`;
124
125 const getByName = (name: string) =>
126 name.length === 0
127 ? Effect.undefined
128 : discoveryengine
129 .getProjectsLocationsCollectionsDataStoresSchemas({ name })
130 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
131
132 const waitUntilExists = (name: string) =>
133 getByName(name).pipe(
134 Effect.flatMap((schema) =>
135 schema
136 ? Effect.succeed(schema)
137 : Effect.fail(new CollectionsDataStoresSchemaNotResolved({ resourceName: name })),
138 ),
139 Effect.retry({
140 while: (error) => error._tag === "GCP.DiscoveryEngine.CollectionsDataStoresSchemaNotResolved",
141 times: 8,
142 schedule: Schedule.spaced("1 second"),
143 }),
144 );
145
146 const waitUntilGone = (name: string) =>
147 getByName(name).pipe(
148 Effect.flatMap((schema) =>
149 schema === undefined
150 ? Effect.void
151 : Effect.fail(new CollectionsDataStoresSchemaStillExists({ resourceName: name })),
152 ),
153 Effect.retry({
154 while: (error) => error._tag === "GCP.DiscoveryEngine.CollectionsDataStoresSchemaStillExists",
155 times: 10,
156 schedule: Schedule.spaced("2 seconds"),
157 }),
158 );
159
160 export const CollectionsDataStoresSchemaProvider = () =>
161 Provider.succeed(CollectionsDataStoresSchema, {
162 stables: ["name", "schemaId", "dataStore", "project", "location"],
163
164 diff: Effect.fn(function* ({ news, olds, output }) {
165 if (!isResolved(news)) return undefined;
166 const previousParent = olds?.dataStore ?? output?.dataStore;
167 const previousId = olds?.schemaId ?? output?.schemaId;
168 if (
169 (previousParent !== undefined && news.dataStore !== previousParent) ||
170 (previousId !== undefined && news.schemaId !== undefined && news.schemaId !== previousId)
171 ) {
172 return {
173 action: "replace" as const,
174 deleteFirst:
175 previousParent === news.dataStore &&
176 previousId !== undefined &&
177 news.schemaId === previousId,
178 };
179 }
180 return undefined;
181 }),
182
183 read: Effect.fn(function* ({ id, olds, output }) {
184 const env = yield* GcpEnvironment.current;
185 const dataStore = olds?.dataStore ?? output?.dataStore;
186 const schemaId = yield* toPhysical(
187 id,
188 olds?.schemaId,
189 output?.schemaId,
190 (name) => rfc1035(name, 32),
191 32,
192 );
193 const name =
194 output?.name ?? (dataStore !== undefined ? resourceName(dataStore, schemaId) : undefined);
195 if (name === undefined) return undefined;
196 const existing = yield* getByName(name);
197 if (existing === undefined) return undefined;
198 const attrs = toAttrs(existing, env.project);
199 // No labels field: without prior state it may not be ours.
200 return output !== undefined ? attrs : Unowned(attrs);
201 }),
202
203 reconcile: Effect.fn(function* ({ id, news, output }) {
204 const env = yield* GcpEnvironment.current;
205 const schemaId = yield* toPhysical(
206 id,
207 news.schemaId,
208 output?.schemaId,
209 (name) => rfc1035(name, 32),
210 32,
211 );
212 const name = resourceName(news.dataStore, schemaId);
213 const jsonSchema = withSchemaVersion(news.jsonSchema);
214
215 let current = yield* getByName(output?.name ?? name);
216
217 if (current === undefined) {
218 const created = yield* discoveryengine
219 .createProjectsLocationsCollectionsDataStoresSchemas({
220 parent: news.dataStore,
221 schemaId,
222 body: {
223 jsonSchema,
224 structSchema: news.structSchema,
225 },
226 })
227 .pipe(
228 Effect.retry({
229 while: (error) => error._tag === "DataStoreNotReady",
230 times: 8,
231 schedule: Schedule.spaced("5 seconds"),
232 }),
233 Effect.catchTag("Conflict", () => Effect.undefined),
234 );
235 if (created !== undefined) {
236 yield* waitForOperation(created);
237 }
238 current = yield* waitUntilExists(name);
239 }
240
241 if (current === undefined) {
242 return yield* new CollectionsDataStoresSchemaNotResolved({ resourceName: name });
243 }
244
245 const resource = current.name ?? name;
246 const jsonChanged = (current.jsonSchema ?? "") !== jsonSchema;
247 const structChanged = !sameJson(current.structSchema, news.structSchema);
248
249 if (jsonChanged || structChanged) {
250 const patched = yield* discoveryengine.patchProjectsLocationsCollectionsDataStoresSchemas({
251 name: resource,
252 body: {
253 name: resource,
254 jsonSchema,
255 structSchema: news.structSchema,
256 },
257 });
258 yield* waitForOperation(patched);
259 current = yield* waitUntilExists(resource);
260 }
261
262 return toAttrs(current, env.project);
263 }),
264
265 delete: Effect.fn(function* ({ output }) {
266 const existing = yield* getByName(output.name);
267 if (existing === undefined) return;
268 const operation = yield* discoveryengine
269 .deleteProjectsLocationsCollectionsDataStoresSchemas({
270 name: output.name,
271 })
272 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
273 if (operation !== undefined) {
274 yield* waitForOperation(operation, { notFoundOk: true });
275 }
276 yield* waitUntilGone(output.name);
277 }),
278 });