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

main
ts 351 lines 12.7 KB
Raw
1 import * as cloudsearch from "@distilled.cloud/gcp/cloudsearch_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 findSearchApplicationByDisplayName,
12 getSearchApplication,
13 ignoreMissing,
14 jsonEqual,
15 MAX_DISPLAY_NAME_LENGTH,
16 operationResourceName,
17 sameBoolean,
18 sameText,
19 searchApplicationIdOf,
20 toGeneratedName,
21 toSearchApplicationName,
22 updateMaskOf,
23 waitForOperation,
24 waitUntilExists,
25 } from "./internal.ts";
26
27 export type DataSourceRestriction = cloudsearch.DataSourceRestriction;
28 export type SortOptions = cloudsearch.SortOptions;
29 export type QueryInterpretationConfig = cloudsearch.QueryInterpretationConfig;
30 export type ScoringConfig = cloudsearch.ScoringConfig;
31 export type SourceConfig = cloudsearch.SourceConfig;
32 export type FacetOptions = cloudsearch.FacetOptions;
33
34 export type SettingsSearchapplicationProps = {
35 /**
36 * Search application id (`{application_id}` or
37 * `searchapplications/{application_id}`). Server assigned on create.
38 * Immutable — changing it replaces the application.
39 */
40 searchApplicationId?: string;
41 /**
42 * Display name (max 300 characters). Without state Alchemy finds the
43 * application by this name.
44 * @default a unique name generated from the stack, stage, and logical id
45 */
46 displayName?: string;
47 /**
48 * Enable audit logging for query APIs.
49 * @default false
50 */
51 enableAuditLog?: boolean;
52 /**
53 * Return thumbnail URIs with search results when available.
54 * @default false
55 */
56 returnResultThumbnailUrls?: boolean;
57 /**
58 * Sources this application may search (max 10).
59 */
60 dataSourceRestrictions?: DataSourceRestriction[];
61 /**
62 * Default sort for search results.
63 */
64 defaultSortOptions?: SortOptions;
65 /**
66 * Default query-interpretation options.
67 */
68 queryInterpretationConfig?: QueryInterpretationConfig;
69 /**
70 * Ranking configuration.
71 */
72 scoringConfig?: ScoringConfig;
73 /**
74 * Per-source scoring and crowding configuration.
75 */
76 sourceConfig?: SourceConfig[];
77 /**
78 * Default facet fields. Sources listed here must also appear in
79 * `dataSourceRestrictions`.
80 */
81 defaultFacetOptions?: FacetOptions[];
82 };
83
84 export type SettingsSearchapplication = Resource<
85 "GCP.CloudSearch.SettingsSearchapplication",
86 SettingsSearchapplicationProps,
87 {
88 /** Full resource name `searchapplications/{application_id}`. */
89 name: string;
90 /** Search application id (last path segment). */
91 searchApplicationId: string;
92 /** Project id used when the application was reconciled. */
93 project: string;
94 /** User-facing display name with the Alchemy prefix stripped. */
95 displayName: string | undefined;
96 /** Whether query audit logging is enabled. */
97 enableAuditLog: boolean;
98 /** Whether result thumbnail URIs are returned. */
99 returnResultThumbnailUrls: boolean;
100 /** Restricted data sources. */
101 dataSourceRestrictions: DataSourceRestriction[];
102 /** Default sort options. */
103 defaultSortOptions: SortOptions | undefined;
104 /** Query interpretation config. */
105 queryInterpretationConfig: QueryInterpretationConfig | undefined;
106 /** Scoring config. */
107 scoringConfig: ScoringConfig | undefined;
108 /** Per-source config. */
109 sourceConfig: SourceConfig[];
110 /** Default facet options. */
111 defaultFacetOptions: FacetOptions[];
112 /** Server-reported in-flight operation ids. */
113 operationIds: string[];
114 },
115 never,
116 Providers
117 >;
118
119 /**
120 * A Cloud Search search application.
121 *
122 * Search applications have no labels field, so without state Alchemy finds
123 * one by `displayName` and reports it unowned unless the name is
124 * generated. The server-assigned application id is identity — changing
125 * `searchApplicationId` replaces the application. Display name, audit
126 * logging, sources, scoring, and facet options update in place. Admin
127 * credentials are required.
128 *
129 * ### Creating a Search Application
130 * **Example:** Generated name
131 * ```typescript
132 * const app = yield* GCP.CloudSearch.SettingsSearchapplication(
133 * "Intranet",
134 * {},
135 * );
136 * ```
137 *
138 * **Example:** Named application with audit logging
139 * ```typescript
140 * const app = yield* GCP.CloudSearch.SettingsSearchapplication(
141 * "Intranet",
142 * {
143 * displayName: "Intranet",
144 * enableAuditLog: true,
145 * },
146 * );
147 * ```
148 *
149 * ### Updating a Search Application
150 * Change props on the same logical id; the engine keeps the physical id.
151 *
152 * **Example:** Rename and enable result thumbnails
153 * ```typescript
154 * const app = yield* GCP.CloudSearch.SettingsSearchapplication(
155 * "Intranet",
156 * {
157 * displayName: "Company search",
158 * returnResultThumbnailUrls: true,
159 * },
160 * );
161 * ```
162 *
163 * @resource
164 * @category CloudSearch
165 */
166 export const SettingsSearchapplication = Resource<SettingsSearchapplication>(
167 "GCP.CloudSearch.SettingsSearchapplication",
168 );
169
170 export class SettingsSearchapplicationNotResolved extends Data.TaggedError(
171 "GCP.CloudSearch.SettingsSearchapplicationNotResolved",
172 )<{
173 resourceName: string;
174 }> {}
175
176 const toAttrs = (app: cloudsearch.SearchApplication, project: string) => {
177 const name = app.name ?? "";
178 return {
179 name,
180 searchApplicationId: searchApplicationIdOf(name),
181 project,
182 displayName: app.displayName,
183 enableAuditLog: app.enableAuditLog === true,
184 returnResultThumbnailUrls: app.returnResultThumbnailUrls === true,
185 dataSourceRestrictions: app.dataSourceRestrictions ?? [],
186 defaultSortOptions: app.defaultSortOptions,
187 queryInterpretationConfig: app.queryInterpretationConfig,
188 scoringConfig: app.scoringConfig,
189 sourceConfig: app.sourceConfig ?? [],
190 defaultFacetOptions: app.defaultFacetOptions ?? [],
191 operationIds: app.operationIds ?? [],
192 };
193 };
194
195 const lookupName = (searchApplicationId: string | undefined, existingName: string | undefined) => {
196 if (searchApplicationId !== undefined && searchApplicationId.length > 0) {
197 return toSearchApplicationName(searchApplicationId);
198 }
199 if (existingName !== undefined && existingName.length > 0) {
200 return toSearchApplicationName(existingName);
201 }
202 return "";
203 };
204
205 export const SettingsSearchapplicationProvider = () =>
206 Provider.succeed(SettingsSearchapplication, {
207 stables: ["name", "searchApplicationId", "project"],
208
209 diff: Effect.fn(function* ({ news, olds, output }) {
210 if (!isResolved(news)) return undefined;
211 const previous = olds?.searchApplicationId ?? output?.searchApplicationId ?? output?.name;
212 if (
213 previous !== undefined &&
214 news.searchApplicationId !== undefined &&
215 toSearchApplicationName(news.searchApplicationId) !== toSearchApplicationName(previous) &&
216 news.searchApplicationId !== output?.searchApplicationId &&
217 toSearchApplicationName(news.searchApplicationId) !== output?.name
218 ) {
219 return { action: "replace" as const, deleteFirst: false };
220 }
221 return undefined;
222 }),
223
224 read: Effect.fn(function* ({ id, olds, output }) {
225 const env = yield* GcpEnvironment.current;
226 const name = lookupName(
227 olds?.searchApplicationId ?? output?.searchApplicationId,
228 output?.name,
229 );
230 let existing = yield* getSearchApplication(name);
231 if (existing !== undefined) return toAttrs(existing, env.project);
232 if (olds === undefined) return undefined;
233 const generated = yield* toGeneratedName(id, undefined, undefined);
234 const displayName = olds.displayName ?? generated;
235 const found = yield* findSearchApplicationByDisplayName(displayName);
236 if (found === undefined) return undefined;
237 const attrs = toAttrs(found, env.project);
238 // A generated display name is unique to this stack, stage and id.
239 return displayName === generated ? attrs : Unowned(attrs);
240 }),
241
242 reconcile: Effect.fn(function* ({ id, news, output }) {
243 const env = yield* GcpEnvironment.current;
244 const displayName = (yield* toGeneratedName(id, news.displayName, output?.displayName)).slice(
245 0,
246 MAX_DISPLAY_NAME_LENGTH,
247 );
248 const name = lookupName(news.searchApplicationId, output?.name);
249 const desiredEnableAuditLog = news.enableAuditLog === true;
250 const desiredThumbnails = news.returnResultThumbnailUrls === true;
251 const desiredRestrictions = news.dataSourceRestrictions ?? [];
252 const desiredSourceConfig = news.sourceConfig ?? [];
253 const desiredFacets = news.defaultFacetOptions ?? [];
254 const desired: cloudsearch.SearchApplication = {
255 displayName,
256 enableAuditLog: desiredEnableAuditLog,
257 returnResultThumbnailUrls: desiredThumbnails,
258 dataSourceRestrictions: desiredRestrictions,
259 defaultSortOptions: news.defaultSortOptions,
260 queryInterpretationConfig: news.queryInterpretationConfig,
261 scoringConfig: news.scoringConfig,
262 sourceConfig: desiredSourceConfig,
263 defaultFacetOptions: desiredFacets,
264 };
265
266 let current = yield* getSearchApplication(name);
267 if (current === undefined) {
268 current = yield* findSearchApplicationByDisplayName(displayName);
269 }
270
271 if (current === undefined) {
272 const created = yield* cloudsearch
273 .createSettingsSearchapplications({ body: desired })
274 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
275 if (created !== undefined) {
276 const done = yield* waitForOperation(created);
277 const createdName = operationResourceName(done);
278 if (createdName !== undefined) {
279 current = yield* waitUntilExists(getSearchApplication(createdName), createdName).pipe(
280 Effect.catchTag("GCP.CloudSearch.ResourceNotResolved", () => Effect.undefined),
281 );
282 }
283 }
284 if (current === undefined) {
285 current = yield* findSearchApplicationByDisplayName(displayName);
286 }
287 }
288
289 if (current === undefined) {
290 return yield* new SettingsSearchapplicationNotResolved({
291 resourceName: name || displayName,
292 });
293 }
294
295 const resourceName = current.name ?? name;
296 const displayChanged = !sameText(current.displayName, displayName);
297 const auditChanged = !sameBoolean(current.enableAuditLog, desiredEnableAuditLog);
298 const thumbnailsChanged = !sameBoolean(current.returnResultThumbnailUrls, desiredThumbnails);
299 const restrictionsChanged = !jsonEqual(
300 current.dataSourceRestrictions ?? [],
301 desiredRestrictions,
302 );
303 const sortChanged = !jsonEqual(current.defaultSortOptions, news.defaultSortOptions);
304 const interpretationChanged = !jsonEqual(
305 current.queryInterpretationConfig,
306 news.queryInterpretationConfig,
307 );
308 const scoringChanged = !jsonEqual(current.scoringConfig, news.scoringConfig);
309 const sourceConfigChanged = !jsonEqual(current.sourceConfig ?? [], desiredSourceConfig);
310 const facetsChanged = !jsonEqual(current.defaultFacetOptions ?? [], desiredFacets);
311
312 const updateMask = updateMaskOf(
313 displayChanged ? "displayName" : undefined,
314 auditChanged ? "enableAuditLog" : undefined,
315 thumbnailsChanged ? "returnResultThumbnailUrls" : undefined,
316 restrictionsChanged ? "dataSourceRestrictions" : undefined,
317 sortChanged ? "defaultSortOptions" : undefined,
318 interpretationChanged ? "queryInterpretationConfig" : undefined,
319 scoringChanged ? "scoringConfig" : undefined,
320 sourceConfigChanged ? "sourceConfig" : undefined,
321 facetsChanged ? "defaultFacetOptions" : undefined,
322 );
323
324 if (updateMask.length > 0) {
325 const patched = yield* cloudsearch.patchSettingsSearchapplications({
326 name: toSearchApplicationName(resourceName),
327 updateMask,
328 body: desired,
329 });
330 yield* waitForOperation(patched);
331 const refreshed = yield* waitUntilExists(getSearchApplication(resourceName), resourceName);
332 current = refreshed;
333 }
334
335 return toAttrs(current, env.project);
336 }),
337
338 delete: Effect.fn(function* ({ output }) {
339 if (output.name.length === 0 && output.searchApplicationId.length === 0) {
340 return;
341 }
342 const name = toSearchApplicationName(output.name || output.searchApplicationId);
343 const operation = yield* cloudsearch
344 .deleteSettingsSearchapplications({ name })
345 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
346 if (operation !== undefined) {
347 yield* waitForOperation(operation, { notFoundOk: true });
348 }
349 yield* ignoreMissing(cloudsearch.deleteSettingsSearchapplications({ name }));
350 }),
351 });