@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 325 lines 11.3 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 datasourceIdOf,
12 findDatasourceByDisplayName,
13 getDatasource,
14 ignoreMissing,
15 jsonEqual,
16 MAX_DISPLAY_NAME_LENGTH,
17 operationResourceName,
18 sameBoolean,
19 sameText,
20 toDatasourceName,
21 toGeneratedName,
22 toShortName,
23 updateMaskOf,
24 waitForOperation,
25 waitUntilExists,
26 } from "./internal.ts";
27
28 export type GSuitePrincipal = cloudsearch.GSuitePrincipal;
29
30 export type SettingsDatasourceProps = {
31 /**
32 * Datasource id (`{source_id}` or `datasources/{source_id}`). Server
33 * assigned on create. Immutable — changing it replaces the datasource.
34 */
35 datasourceId?: string;
36 /**
37 * Display name (max 300 characters). Without state Alchemy finds the
38 * datasource by this name.
39 * @default a unique name generated from the stack, stage, and logical id
40 */
41 displayName?: string;
42 /**
43 * Short operator name used as `source:<value>`. Alphanumeric, max 32
44 * characters, unique across datasources. Cannot start with `google` or
45 * equal a reserved Workspace source (mail, gmail, docs, drive, …).
46 */
47 shortName?: string;
48 /**
49 * Reject Indexing API writes while still serving previously indexed
50 * items.
51 * @default false
52 */
53 disableModifications?: boolean;
54 /**
55 * Disable serving search and assist results from this source.
56 * @default false
57 */
58 disableServing?: boolean;
59 /**
60 * Whether users can request thumbnail URIs for indexed items.
61 * @default false
62 */
63 returnThumbnailUrls?: boolean;
64 /**
65 * Service accounts allowed to index this source.
66 */
67 indexingServiceAccounts?: string[];
68 /**
69 * Datasource-level item visibility (union of users and groups).
70 */
71 itemsVisibility?: GSuitePrincipal[];
72 };
73
74 export type SettingsDatasource = Resource<
75 "GCP.CloudSearch.SettingsDatasource",
76 SettingsDatasourceProps,
77 {
78 /** Full resource name `datasources/{source_id}`. */
79 name: string;
80 /** Datasource id (last path segment). */
81 datasourceId: string;
82 /** Project id used when the datasource was reconciled. */
83 project: string;
84 /** User-facing display name with the Alchemy prefix stripped. */
85 displayName: string | undefined;
86 /** Short operator name. */
87 shortName: string | undefined;
88 /** Whether indexing writes are rejected. */
89 disableModifications: boolean;
90 /** Whether serving is disabled. */
91 disableServing: boolean;
92 /** Whether thumbnail URIs may be requested. */
93 returnThumbnailUrls: boolean;
94 /** Indexing service accounts. */
95 indexingServiceAccounts: string[];
96 /** Datasource-level visibility. */
97 itemsVisibility: GSuitePrincipal[];
98 /** Server-reported in-flight operation ids. */
99 operationIds: string[];
100 },
101 never,
102 Providers
103 >;
104
105 /**
106 * A Cloud Search datasource.
107 *
108 * Cloud Search datasources have no labels field, so without state Alchemy
109 * finds one by `displayName` and reports it unowned unless the name is
110 * generated. The server-assigned datasource id is identity — changing
111 * `datasourceId` replaces the source. Display name, short name, serving
112 * flags, indexing accounts, and visibility update in place. Admin
113 * credentials are required.
114 *
115 * ### Creating a Datasource
116 * **Example:** Generated name
117 * ```typescript
118 * const source = yield* GCP.CloudSearch.SettingsDatasource("Wiki", {});
119 * ```
120 *
121 * **Example:** Explicit display name and short name
122 * ```typescript
123 * const source = yield* GCP.CloudSearch.SettingsDatasource("Wiki", {
124 * displayName: "Wiki",
125 * shortName: "wiki",
126 * returnThumbnailUrls: true,
127 * });
128 * ```
129 *
130 * ### Updating a Datasource
131 * Change props on the same logical id; the engine keeps the physical id.
132 *
133 * **Example:** Rename and disable serving
134 * ```typescript
135 * const source = yield* GCP.CloudSearch.SettingsDatasource("Wiki", {
136 * displayName: "Knowledge base",
137 * shortName: "wiki",
138 * disableServing: true,
139 * });
140 * ```
141 *
142 * @resource
143 * @category CloudSearch
144 */
145 export const SettingsDatasource = Resource<SettingsDatasource>(
146 "GCP.CloudSearch.SettingsDatasource",
147 );
148
149 export class SettingsDatasourceNotResolved extends Data.TaggedError(
150 "GCP.CloudSearch.SettingsDatasourceNotResolved",
151 )<{
152 resourceName: string;
153 }> {}
154
155 const toAttrs = (source: cloudsearch.DataSource, project: string) => {
156 const name = source.name ?? "";
157 return {
158 name,
159 datasourceId: datasourceIdOf(name),
160 project,
161 displayName: source.displayName,
162 shortName: source.shortName,
163 disableModifications: source.disableModifications === true,
164 disableServing: source.disableServing === true,
165 returnThumbnailUrls: source.returnThumbnailUrls === true,
166 indexingServiceAccounts: source.indexingServiceAccounts ?? [],
167 itemsVisibility: source.itemsVisibility ?? [],
168 operationIds: source.operationIds ?? [],
169 };
170 };
171
172 const lookupName = (datasourceId: string | undefined, existingName: string | undefined) => {
173 if (datasourceId !== undefined && datasourceId.length > 0) {
174 return toDatasourceName(datasourceId);
175 }
176 if (existingName !== undefined && existingName.length > 0) {
177 return toDatasourceName(existingName);
178 }
179 return "";
180 };
181
182 export const SettingsDatasourceProvider = () =>
183 Provider.succeed(SettingsDatasource, {
184 stables: ["name", "datasourceId", "project"],
185
186 diff: Effect.fn(function* ({ news, olds, output }) {
187 if (!isResolved(news)) return undefined;
188 const previous = olds?.datasourceId ?? output?.datasourceId ?? output?.name;
189 if (
190 previous !== undefined &&
191 news.datasourceId !== undefined &&
192 toDatasourceName(news.datasourceId) !== toDatasourceName(previous) &&
193 news.datasourceId !== output?.datasourceId &&
194 toDatasourceName(news.datasourceId) !== output?.name
195 ) {
196 return { action: "replace" as const, deleteFirst: false };
197 }
198 return undefined;
199 }),
200
201 read: Effect.fn(function* ({ id, olds, output }) {
202 const env = yield* GcpEnvironment.current;
203 const name = lookupName(olds?.datasourceId ?? output?.datasourceId, output?.name);
204 let existing = yield* getDatasource(name);
205 if (existing !== undefined) return toAttrs(existing, env.project);
206 if (olds === undefined) return undefined;
207 const generated = yield* toGeneratedName(id, undefined, undefined);
208 const displayName = olds.displayName ?? generated;
209 const found = yield* findDatasourceByDisplayName(displayName);
210 if (found === undefined) return undefined;
211 const attrs = toAttrs(found, env.project);
212 // A generated display name is unique to this stack, stage and id.
213 return displayName === generated ? attrs : Unowned(attrs);
214 }),
215
216 reconcile: Effect.fn(function* ({ id, news, output }) {
217 const env = yield* GcpEnvironment.current;
218 const displayName = (yield* toGeneratedName(id, news.displayName, output?.displayName)).slice(
219 0,
220 MAX_DISPLAY_NAME_LENGTH,
221 );
222 const name = lookupName(news.datasourceId, output?.name);
223
224 let current = yield* getDatasource(name);
225 if (current === undefined) {
226 current = yield* findDatasourceByDisplayName(displayName);
227 }
228
229 const shortName = yield* toShortName(
230 id,
231 news.shortName,
232 current?.shortName ?? output?.shortName,
233 );
234 const desiredDisableModifications = news.disableModifications === true;
235 const desiredDisableServing = news.disableServing === true;
236 const desiredReturnThumbnailUrls = news.returnThumbnailUrls === true;
237 const desiredAccounts = news.indexingServiceAccounts ?? [];
238 const desiredVisibility = news.itemsVisibility ?? [];
239 const desired: cloudsearch.DataSource = {
240 displayName,
241 shortName,
242 disableModifications: desiredDisableModifications,
243 disableServing: desiredDisableServing,
244 returnThumbnailUrls: desiredReturnThumbnailUrls,
245 indexingServiceAccounts: desiredAccounts,
246 itemsVisibility: desiredVisibility,
247 };
248
249 if (current === undefined) {
250 const created = yield* cloudsearch
251 .createSettingsDatasources({ body: desired })
252 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
253 if (created !== undefined) {
254 const done = yield* waitForOperation(created);
255 const createdName = operationResourceName(done);
256 if (createdName !== undefined) {
257 current = yield* waitUntilExists(getDatasource(createdName), createdName).pipe(
258 Effect.catchTag("GCP.CloudSearch.ResourceNotResolved", () => Effect.undefined),
259 );
260 }
261 }
262 if (current === undefined) {
263 current = yield* findDatasourceByDisplayName(displayName);
264 }
265 }
266
267 if (current === undefined) {
268 return yield* new SettingsDatasourceNotResolved({
269 resourceName: name || displayName,
270 });
271 }
272
273 const resourceName = current.name ?? name;
274 const displayChanged = !sameText(current.displayName, displayName);
275 const shortNameChanged = !sameText(current.shortName, shortName);
276 const modificationsChanged = !sameBoolean(
277 current.disableModifications,
278 desiredDisableModifications,
279 );
280 const servingChanged = !sameBoolean(current.disableServing, desiredDisableServing);
281 const thumbnailsChanged = !sameBoolean(
282 current.returnThumbnailUrls,
283 desiredReturnThumbnailUrls,
284 );
285 const accountsChanged = !jsonEqual(current.indexingServiceAccounts ?? [], desiredAccounts);
286 const visibilityChanged = !jsonEqual(current.itemsVisibility ?? [], desiredVisibility);
287
288 const updateMask = updateMaskOf(
289 displayChanged ? "displayName" : undefined,
290 shortNameChanged ? "shortName" : undefined,
291 modificationsChanged ? "disableModifications" : undefined,
292 servingChanged ? "disableServing" : undefined,
293 thumbnailsChanged ? "returnThumbnailUrls" : undefined,
294 accountsChanged ? "indexingServiceAccounts" : undefined,
295 visibilityChanged ? "itemsVisibility" : undefined,
296 );
297
298 if (updateMask.length > 0) {
299 const patched = yield* cloudsearch.patchSettingsDatasources({
300 name: toDatasourceName(resourceName),
301 updateMask,
302 body: desired,
303 });
304 yield* waitForOperation(patched);
305 const refreshed = yield* waitUntilExists(getDatasource(resourceName), resourceName);
306 current = refreshed;
307 }
308
309 return toAttrs(current, env.project);
310 }),
311
312 delete: Effect.fn(function* ({ output }) {
313 if (output.name.length === 0 && output.datasourceId.length === 0) {
314 return;
315 }
316 const name = toDatasourceName(output.name || output.datasourceId);
317 const operation = yield* cloudsearch
318 .deleteSettingsDatasources({ name })
319 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
320 if (operation !== undefined) {
321 yield* waitForOperation(operation, { notFoundOk: true });
322 }
323 yield* ignoreMissing(cloudsearch.deleteSettingsDatasources({ name }));
324 }),
325 });