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

main
ts 304 lines 9.88 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 { GcpEnvironment } from "../Environment.ts";
9 import type { Providers } from "../Providers.ts";
10 import {
11 DEFAULT_BRANCH,
12 MAX_DOCUMENT_ID_LENGTH,
13 branchParent,
14 parentOf,
15 parseResourceName,
16 rfc1035,
17 sameJson,
18 toPhysical,
19 } from "./internal.ts";
20
21 export type DocumentContent = {
22 /** MIME type of `rawBytes` or the object at `uri`. */
23 mimeType?: string;
24 /** GCS URI (`gs://bucket/path`). */
25 uri?: string;
26 /** Base64-encoded bytes. Max 1,000,000 bytes. */
27 rawBytes?: string;
28 };
29
30 export type CollectionsDataStoresBranchesDocumentProps = {
31 /**
32 * Parent data store resource name
33 * `projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}`.
34 * Immutable — changing it replaces the document.
35 */
36 dataStore: string;
37 /**
38 * Branch id. Immutable.
39 * @default "default_branch"
40 */
41 branchId?: string;
42 /**
43 * Document id (RFC-1034, max 128 characters). If omitted, a unique id
44 * is generated. Immutable — changing it replaces the document.
45 */
46 documentId?: string;
47 /**
48 * JSON document payload. Must conform to the data store schema.
49 */
50 jsonData?: string;
51 /**
52 * Structured document payload.
53 */
54 structData?: Record<string, unknown>;
55 /**
56 * Unstructured content. Required when the parent data store uses
57 * `CONTENT_REQUIRED`.
58 */
59 content?: DocumentContent;
60 /**
61 * Parent document id (RFC-1034, max 63 characters).
62 */
63 parentDocumentId?: string;
64 /**
65 * Schema id in the same data store.
66 */
67 schemaId?: string;
68 };
69
70 export type CollectionsDataStoresBranchesDocument = Resource<
71 "GCP.DiscoveryEngine.CollectionsDataStoresBranchesDocument",
72 CollectionsDataStoresBranchesDocumentProps,
73 {
74 /** Full resource name. */
75 name: string;
76 /** Document id. */
77 documentId: string;
78 /** Parent data store resource name. */
79 dataStore: string;
80 /** Branch id. */
81 branchId: string;
82 /** Project id. */
83 project: string;
84 /** Location id. */
85 location: string;
86 /** JSON payload. */
87 jsonData: string | undefined;
88 /** Structured payload. */
89 structData: Record<string, unknown> | undefined;
90 /** Unstructured content. */
91 content: DocumentContent | undefined;
92 /** Parent document id. */
93 parentDocumentId: string | undefined;
94 /** Schema id. */
95 schemaId: string | undefined;
96 /** Last index time. */
97 indexTime: string | undefined;
98 },
99 never,
100 Providers
101 >;
102
103 /**
104 * A Discovery Engine document under a collection data store branch.
105 *
106 * Without labels, ownership rests on the deterministic id: `read` reports a
107 * resource it finds without prior state as unowned (adopt it with `--adopt`).
108 * Parent data store, branch, and document id are immutable. Payload fields
109 * update in place.
110 *
111 * ### Creating a Document
112 * **Example:** JSON document on the default branch
113 * ```typescript
114 * const store = yield* GCP.DiscoveryEngine.CollectionsDataStore("Docs", {});
115 * const doc = yield* GCP.DiscoveryEngine.CollectionsDataStoresBranchesDocument(
116 * "Intro",
117 * {
118 * dataStore: store.name,
119 * jsonData: JSON.stringify({ title: "Getting started" }),
120 * },
121 * );
122 * ```
123 *
124 * @resource
125 * @category DiscoveryEngine
126 */
127 export const CollectionsDataStoresBranchesDocument =
128 Resource<CollectionsDataStoresBranchesDocument>(
129 "GCP.DiscoveryEngine.CollectionsDataStoresBranchesDocument",
130 );
131
132 export class CollectionsDataStoresBranchesDocumentNotResolved extends Data.TaggedError(
133 "GCP.DiscoveryEngine.CollectionsDataStoresBranchesDocumentNotResolved",
134 )<{
135 resourceName: string;
136 }> {}
137
138 const contentOf = (
139 content: discoveryengine.GoogleCloudDiscoveryengineV1DocumentContent | undefined,
140 ): DocumentContent | undefined =>
141 content === undefined
142 ? undefined
143 : {
144 mimeType: content.mimeType,
145 uri: content.uri,
146 rawBytes: content.rawBytes,
147 };
148
149 const toAttrs = (
150 document: discoveryengine.GoogleCloudDiscoveryengineV1Document,
151 project: string,
152 ) => {
153 const name = document.name ?? "";
154 const parsed = parseResourceName(name, "documents");
155 const branches = parseResourceName(name, "branches");
156 return {
157 name,
158 documentId: document.id ?? parsed.id,
159 dataStore: parentOf(name, "branches"),
160 branchId: branches.id,
161 project: parsed.project || project,
162 location: parsed.location,
163 jsonData: document.jsonData,
164 structData: document.structData as Record<string, unknown> | undefined,
165 content: contentOf(document.content),
166 parentDocumentId: document.parentDocumentId,
167 schemaId: document.schemaId,
168 indexTime: document.indexTime,
169 };
170 };
171
172 const resourceName = (dataStore: string, branchId: string, documentId: string) =>
173 `${branchParent(dataStore, branchId)}/documents/${documentId}`;
174
175 const getByName = (name: string) =>
176 name.length === 0
177 ? Effect.undefined
178 : discoveryengine
179 .getProjectsLocationsCollectionsDataStoresBranchesDocuments({ name })
180 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
181
182 export const CollectionsDataStoresBranchesDocumentProvider = () =>
183 Provider.succeed(CollectionsDataStoresBranchesDocument, {
184 stables: ["name", "documentId", "dataStore", "branchId", "project", "location"],
185
186 diff: Effect.fn(function* ({ news, olds, output }) {
187 if (!isResolved(news)) return undefined;
188 const previousParent = olds?.dataStore ?? output?.dataStore;
189 const previousBranch = olds?.branchId ?? output?.branchId ?? DEFAULT_BRANCH;
190 const nextBranch = news.branchId ?? previousBranch;
191 const previousId = olds?.documentId ?? output?.documentId;
192 if (
193 (previousParent !== undefined && news.dataStore !== previousParent) ||
194 previousBranch !== nextBranch ||
195 (previousId !== undefined &&
196 news.documentId !== undefined &&
197 news.documentId !== previousId)
198 ) {
199 return {
200 action: "replace" as const,
201 deleteFirst:
202 previousParent === news.dataStore &&
203 previousBranch === nextBranch &&
204 previousId !== undefined &&
205 news.documentId === previousId,
206 };
207 }
208 return undefined;
209 }),
210
211 read: Effect.fn(function* ({ id, olds, output }) {
212 const env = yield* GcpEnvironment.current;
213 const dataStore = olds?.dataStore ?? output?.dataStore;
214 const branchId = olds?.branchId ?? output?.branchId ?? DEFAULT_BRANCH;
215 const documentId = yield* toPhysical(
216 id,
217 olds?.documentId,
218 output?.documentId,
219 (name) => rfc1035(name, MAX_DOCUMENT_ID_LENGTH),
220 MAX_DOCUMENT_ID_LENGTH,
221 );
222 const name =
223 output?.name ??
224 (dataStore !== undefined ? resourceName(dataStore, branchId, documentId) : undefined);
225 if (name === undefined) return undefined;
226 const existing = yield* getByName(name);
227 if (existing === undefined) return undefined;
228 const attrs = toAttrs(existing, env.project);
229 // No labels field: without prior state it may not be ours.
230 return output !== undefined ? attrs : Unowned(attrs);
231 }),
232
233 reconcile: Effect.fn(function* ({ id, news, output }) {
234 const env = yield* GcpEnvironment.current;
235 const branchId = news.branchId ?? output?.branchId ?? DEFAULT_BRANCH;
236 const documentId = yield* toPhysical(
237 id,
238 news.documentId,
239 output?.documentId,
240 (name) => rfc1035(name, MAX_DOCUMENT_ID_LENGTH),
241 MAX_DOCUMENT_ID_LENGTH,
242 );
243 const name = resourceName(news.dataStore, branchId, documentId);
244 const jsonData = news.jsonData;
245 const parent = branchParent(news.dataStore, branchId);
246
247 let current = yield* getByName(output?.name ?? name);
248
249 if (current === undefined) {
250 const created = yield* discoveryengine
251 .createProjectsLocationsCollectionsDataStoresBranchesDocuments({
252 parent,
253 documentId,
254 body: {
255 jsonData,
256 structData: news.structData,
257 content: news.content,
258 parentDocumentId: news.parentDocumentId,
259 schemaId: news.schemaId,
260 },
261 })
262 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
263 current = created ?? undefined;
264 }
265
266 if (current === undefined) {
267 return yield* new CollectionsDataStoresBranchesDocumentNotResolved({
268 resourceName: name,
269 });
270 }
271
272 const resource = current.name ?? name;
273 const jsonChanged = jsonData !== undefined && (current.jsonData ?? "") !== jsonData;
274 const structChanged = !sameJson(current.structData, news.structData);
275 const contentChanged = !sameJson(contentOf(current.content), news.content);
276 const parentChanged = (current.parentDocumentId ?? "") !== (news.parentDocumentId ?? "");
277 const schemaChanged = (current.schemaId ?? "") !== (news.schemaId ?? "");
278
279 if (jsonChanged || structChanged || contentChanged || parentChanged || schemaChanged) {
280 current =
281 yield* discoveryengine.patchProjectsLocationsCollectionsDataStoresBranchesDocuments({
282 name: resource,
283 body: {
284 name: resource,
285 jsonData,
286 structData: news.structData,
287 content: news.content,
288 parentDocumentId: news.parentDocumentId,
289 schemaId: news.schemaId,
290 },
291 });
292 }
293
294 return toAttrs(current, env.project);
295 }),
296
297 delete: Effect.fn(function* ({ output }) {
298 yield* discoveryengine
299 .deleteProjectsLocationsCollectionsDataStoresBranchesDocuments({
300 name: output.name,
301 })
302 .pipe(Effect.catchTag("NotFound", () => Effect.void));
303 }),
304 });