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

main
ts 294 lines 10.1 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 Stream from "effect/Stream";
9 import { GcpEnvironment } from "../Environment.ts";
10 import type { Providers } from "../Providers.ts";
11 import { expandDataStore, matchesUriPattern, parseResourceName } from "./internal.ts";
12 import { waitForOperation } from "./operations.ts";
13
14 export type DataStoresSiteSearchEngineTargetSiteProps = {
15 /**
16 * Parent Data Store resource name
17 * `projects/{project}/locations/{location}/dataStores/{dataStore}`.
18 * The data store must use `PUBLIC_WEBSITE` content. Immutable —
19 * changing it replaces the target site.
20 */
21 dataStore: string;
22 /**
23 * User-provided URI pattern from which the generated URI pattern is
24 * derived (for example `www.example.com`). Identifies the target site
25 * within the data store. Changing it replaces the site.
26 */
27 providedUriPattern: string;
28 /**
29 * When true, match the provided URI pattern exactly. Immutable —
30 * changing it replaces the target site.
31 * @default false
32 */
33 exactMatch?: boolean;
34 /**
35 * Whether the site is included or excluded (`INCLUDE`, `EXCLUDE`).
36 * @default "INCLUDE"
37 */
38 type?: string;
39 };
40
41 export type DataStoresSiteSearchEngineTargetSite = Resource<
42 "GCP.DiscoveryEngine.DataStoresSiteSearchEngineTargetSite",
43 DataStoresSiteSearchEngineTargetSiteProps,
44 {
45 /** Full resource name `.../siteSearchEngine/targetSites/{targetSite}`. */
46 name: string;
47 /** Target site id (last path segment). Server-assigned on create. */
48 targetSiteId: string;
49 /** Parent data store resource name. */
50 dataStore: string;
51 /** Project id. */
52 project: string;
53 /** Location id. */
54 location: string;
55 /** User-provided URI pattern. */
56 providedUriPattern: string | undefined;
57 /** System-generated URI pattern. */
58 generatedUriPattern: string | undefined;
59 /** Root domain of the provided URI pattern. */
60 rootDomainUri: string | undefined;
61 /** Whether the URI pattern is an exact match. */
62 exactMatch: boolean;
63 /** Include or exclude. */
64 type: string | undefined;
65 /** Indexing status. */
66 indexingStatus: string | undefined;
67 /** RFC3339 last-update timestamp. */
68 updateTime: string | undefined;
69 },
70 never,
71 Providers
72 >;
73
74 /**
75 * A Vertex AI Search TargetSite under a Data Store site search engine.
76 *
77 * Its id is assigned by the API, so only a recorded resource can be read
78 * back. The target site id is server-assigned. Parent and exact-match flag
79 * are immutable; type updates in place (LRO).
80 *
81 * ### Creating a Target Site
82 * **Example:** Include a site
83 * ```typescript
84 * const site = yield* GCP.DiscoveryEngine.DataStoresSiteSearchEngineTargetSite(
85 * "Docs",
86 * {
87 * dataStore: dataStore.name,
88 * providedUriPattern: "www.example.com/docs",
89 * type: "INCLUDE",
90 * },
91 * );
92 * ```
93 *
94 * ### Updating a Target Site
95 * **Example:** Exclude the site
96 * ```typescript
97 * // Same logical id as before; only the changed props differ.
98 * const site = yield* GCP.DiscoveryEngine.DataStoresSiteSearchEngineTargetSite(
99 * "Docs",
100 * {
101 * dataStore: dataStore.name,
102 * providedUriPattern: "www.example.com/docs",
103 * type: "EXCLUDE",
104 * },
105 * );
106 * ```
107 *
108 * @resource
109 * @category DiscoveryEngine
110 */
111 export const DataStoresSiteSearchEngineTargetSite = Resource<DataStoresSiteSearchEngineTargetSite>(
112 "GCP.DiscoveryEngine.DataStoresSiteSearchEngineTargetSite",
113 );
114
115 export class DataStoresSiteSearchEngineTargetSiteNotResolved extends Data.TaggedError(
116 "GCP.DiscoveryEngine.DataStoresSiteSearchEngineTargetSiteNotResolved",
117 )<{
118 resourceName: string;
119 }> {}
120
121 const siteSearchEngine = (dataStore: string) => `${dataStore}/siteSearchEngine`;
122
123 const toAttrs = (
124 site: discoveryengine.GoogleCloudDiscoveryengineV1TargetSite,
125 project: string,
126 pattern?: string,
127 ) => {
128 const name = site.name ?? "";
129 const parsed = parseResourceName(name, "targetSites");
130 return {
131 name,
132 targetSiteId: parsed.id,
133 dataStore: parsed.dataStore,
134 project: parsed.project || project,
135 location: parsed.location,
136 providedUriPattern: site.providedUriPattern ?? pattern ?? site.generatedUriPattern,
137 generatedUriPattern: site.generatedUriPattern,
138 rootDomainUri: site.rootDomainUri,
139 exactMatch: site.exactMatch === true,
140 type: site.type,
141 indexingStatus: site.indexingStatus,
142 updateTime: site.updateTime,
143 };
144 };
145
146 const getByName = (name: string) =>
147 name.length === 0
148 ? Effect.undefined
149 : discoveryengine
150 .getProjectsLocationsDataStoresSiteSearchEngineTargetSites({ name })
151 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
152
153 const listAtParent = (parent: string) =>
154 discoveryengine.listProjectsLocationsDataStoresSiteSearchEngineTargetSites
155 .pages({ parent, pageSize: 100 })
156 .pipe(
157 Stream.flatMap((page) => Stream.fromIterable(page.targetSites ?? [])),
158 Stream.runCollect,
159 Effect.map((chunk) => Array.from(chunk)),
160 Effect.catchTag("NotFound", () => Effect.succeed([])),
161 );
162
163 const findByPattern = (uri: string, parent: string | undefined, hinted?: string) =>
164 Effect.gen(function* () {
165 if (hinted !== undefined && hinted.length > 0) {
166 const existing = yield* getByName(hinted);
167 if (existing !== undefined) return existing;
168 }
169 if (parent === undefined) return undefined;
170 const sites = yield* listAtParent(parent);
171 return sites.find((site) => matchesUriPattern(site, uri));
172 });
173
174 export const DataStoresSiteSearchEngineTargetSiteProvider = () =>
175 Provider.succeed(DataStoresSiteSearchEngineTargetSite, {
176 stables: [
177 "name",
178 "targetSiteId",
179 "dataStore",
180 "project",
181 "location",
182 "providedUriPattern",
183 "exactMatch",
184 ],
185
186 diff: Effect.fn(function* ({ news, olds, output }) {
187 if (!isResolved(news)) return undefined;
188 const previousParent = olds?.dataStore ?? output?.dataStore;
189 if (previousParent !== undefined && news.dataStore !== previousParent) {
190 return { action: "replace" as const, deleteFirst: false };
191 }
192 const previousExact = olds?.exactMatch ?? output?.exactMatch ?? false;
193 const nextExact = news.exactMatch ?? previousExact;
194 if (previousExact !== nextExact) {
195 return { action: "replace" as const, deleteFirst: true };
196 }
197 const previousUri = olds?.providedUriPattern ?? output?.providedUriPattern;
198 if (
199 previousUri !== undefined &&
200 news.providedUriPattern !== undefined &&
201 news.providedUriPattern !== previousUri
202 ) {
203 return { action: "replace" as const, deleteFirst: true };
204 }
205 const previousType = olds?.type ?? output?.type ?? "INCLUDE";
206 const nextType = news.type ?? previousType;
207 if (previousType !== nextType) {
208 return { action: "replace" as const, deleteFirst: true };
209 }
210 return undefined;
211 }),
212
213 read: Effect.fn(function* ({ olds, output, previous }) {
214 const env = yield* GcpEnvironment.current;
215 const parent = olds?.dataStore
216 ? expandDataStore(olds.dataStore, env.project, output?.location ?? "global")
217 : undefined;
218 const uri = olds?.providedUriPattern ?? output?.providedUriPattern;
219 const existing =
220 uri === undefined
221 ? undefined
222 : yield* findByPattern(uri, parent ? siteSearchEngine(parent) : undefined, output?.name);
223 if (existing === undefined) return undefined;
224 const attrs = toAttrs(existing, env.project, uri);
225 // No labels field: without prior state it may not be ours.
226 return output !== undefined ? attrs : unownedUnlessPrevious(attrs, previous, "name");
227 }),
228
229 reconcile: Effect.fn(function* ({ news, output }) {
230 const env = yield* GcpEnvironment.current;
231 const parent = expandDataStore(news.dataStore, env.project, output?.location ?? "global");
232 const engine = siteSearchEngine(parent);
233 const providedUriPattern = news.providedUriPattern;
234 const exactMatch = news.exactMatch === true;
235 const type = news.type ?? "INCLUDE";
236
237 let current = yield* findByPattern(providedUriPattern, engine, output?.name);
238
239 if (current === undefined) {
240 const created = yield* discoveryengine
241 .createProjectsLocationsDataStoresSiteSearchEngineTargetSites({
242 parent: engine,
243 body: {
244 providedUriPattern,
245 exactMatch,
246 type,
247 },
248 })
249 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
250 if (created !== undefined) {
251 yield* waitForOperation(created);
252 }
253 current = yield* findByPattern(providedUriPattern, engine);
254 }
255
256 if (current === undefined) {
257 return yield* new DataStoresSiteSearchEngineTargetSiteNotResolved({
258 resourceName: output?.name ?? `${engine}/targetSites`,
259 });
260 }
261
262 const typeChanged = news.type !== undefined && (current.type ?? "INCLUDE") !== type;
263
264 if (typeChanged) {
265 const patched =
266 yield* discoveryengine.patchProjectsLocationsDataStoresSiteSearchEngineTargetSites({
267 name: current.name ?? "",
268 body: {
269 name: current.name,
270 providedUriPattern,
271 exactMatch,
272 type,
273 },
274 });
275 yield* waitForOperation(patched);
276 current = (yield* getByName(current.name ?? "")) ?? current;
277 }
278
279 return toAttrs(current, env.project, providedUriPattern);
280 }),
281
282 delete: Effect.fn(function* ({ output }) {
283 const existing = yield* getByName(output.name);
284 if (existing === undefined) return;
285 const operation = yield* discoveryengine
286 .deleteProjectsLocationsDataStoresSiteSearchEngineTargetSites({
287 name: output.name,
288 })
289 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
290 if (operation !== undefined) {
291 yield* waitForOperation(operation, { notFoundOk: true });
292 }
293 }),
294 });