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

main
ts 402 lines 13.6 KB
Raw
1 import * as integrations from "@distilled.cloud/gcp/integrations_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 Stream from "effect/Stream";
9 import { GcpEnvironment } from "../Environment.ts";
10 import { createInternalLabels } from "../Labels.ts";
11 import type { Providers } from "../Providers.ts";
12 import {
13 encodeOwnership,
14 hasOwnershipMarker,
15 lastSegment,
16 locationOf,
17 locationParent,
18 normalizeLocation,
19 ownedByAlchemy,
20 parentOf,
21 parseOwnership,
22 sameText,
23 toResourceId,
24 updateMaskOf,
25 } from "./ownership.ts";
26 import type { TriggerConfig } from "./shared.ts";
27
28 export type IntegrationsVersionProps = {
29 /**
30 * Integration id (the `{integration}` segment of
31 * `projects/{project}/locations/{location}/integrations/{integration}`).
32 * If omitted, a unique id is generated. Immutable — changing it
33 * replaces the version.
34 */
35 integrationId?: string;
36 /**
37 * Version id (the `{version}` segment). Server-assigned on create.
38 * Immutable — changing it replaces the version.
39 */
40 versionId?: string;
41 /**
42 * Location (`us-central1`, …). Immutable — changing it replaces the
43 * version. `US-CENTRAL1` is accepted and normalized to `us-central1`.
44 * @default the stack's GCP region (`GCP.Region`, else the profile
45 * region, else `us-central1`)
46 */
47 location?: string;
48 /**
49 * Human-readable description. Integration versions have no labels
50 * field, so Alchemy ownership is stored in a `[alchemy …]` prefix and
51 * stripped from attributes.
52 */
53 description?: string;
54 /**
55 * User-defined label that annotates this version.
56 */
57 userLabel?: string;
58 /**
59 * Trigger configurations. A draft with no tasks is valid; add an API
60 * trigger to make the version executable.
61 */
62 triggerConfigs?: TriggerConfig[];
63 /**
64 * When true, create a new integration if `integrationId` does not
65 * exist. Ignored on update.
66 * @default true
67 */
68 newIntegration?: boolean;
69 };
70
71 export type IntegrationsVersion = Resource<
72 "GCP.Integrations.IntegrationsVersion",
73 IntegrationsVersionProps,
74 {
75 /** Full resource name `projects/{project}/locations/{location}/integrations/{integration}/versions/{version}`. */
76 name: string;
77 /** Version id (last path segment). */
78 versionId: string;
79 /** Parent integration id. */
80 integrationId: string;
81 /** Parent integration resource name. */
82 integration: string;
83 /** Location id. */
84 location: string;
85 /** Project id. */
86 project: string;
87 /** User description with the Alchemy ownership prefix stripped. */
88 description: string | undefined;
89 /** User-defined version label. */
90 userLabel: string | undefined;
91 /** Trigger configurations. */
92 triggerConfigs: TriggerConfig[] | undefined;
93 /** Server-reported status (`DRAFT`, `ACTIVE`, …). */
94 status: string | undefined;
95 /** Server-reported state. */
96 state: string | undefined;
97 /** Snapshot number. */
98 snapshotNumber: string | undefined;
99 /** RFC3339 creation timestamp. */
100 createTime: string | undefined;
101 /** RFC3339 last-update timestamp. */
102 updateTime: string | undefined;
103 },
104 never,
105 Providers
106 >;
107
108 /**
109 * An Application Integration version (a draft or published snapshot of
110 * an integration).
111 *
112 * Versions have no labels field — Alchemy stamps ownership into the
113 * description. Location, integration id, and version id are immutable.
114 * Description, user label, and trigger configs update in place. Draft
115 * versions cannot be deleted via the versions API; Alchemy deletes the
116 * parent integration instead.
117 *
118 * ### Creating a Version
119 * **Example:** Empty draft with an API trigger
120 * ```typescript
121 * const version = yield* GCP.Integrations.IntegrationsVersion("Orders", {
122 * description: "order workflow",
123 * triggerConfigs: [
124 * {
125 * label: "API Trigger",
126 * triggerType: "API",
127 * triggerNumber: "1",
128 * triggerId: "api_trigger/orders",
129 * properties: { "Trigger name": "orders" },
130 * },
131 * ],
132 * });
133 * ```
134 *
135 * @resource
136 * @category Integrations
137 */
138 export const IntegrationsVersion = Resource<IntegrationsVersion>(
139 "GCP.Integrations.IntegrationsVersion",
140 );
141
142 export class IntegrationsVersionNotResolved extends Data.TaggedError(
143 "GCP.Integrations.IntegrationsVersionNotResolved",
144 )<{
145 resourceName: string;
146 }> {}
147
148 const integrationOf = (name: string) => {
149 const parts = name.split("/");
150 const index = parts.indexOf("integrations");
151 return index >= 0 ? parts.slice(0, index + 2).join("/") : parentOf(name);
152 };
153
154 const integrationIdOf = (name: string) => {
155 const parts = name.split("/");
156 const index = parts.indexOf("integrations");
157 return index >= 0 ? (parts[index + 1] ?? lastSegment(name)) : lastSegment(name);
158 };
159
160 const resourceName = (
161 project: string,
162 location: string,
163 integrationId: string,
164 versionId: string,
165 ) => `${locationParent(project, location)}/integrations/${integrationId}/versions/${versionId}`;
166
167 const triggersOf = (
168 configs: integrations.GoogleCloudIntegrationsV1alphaTriggerConfigList | undefined,
169 ): TriggerConfig[] | undefined => {
170 if (configs === undefined) return undefined;
171 return configs.map((config) => ({
172 label: config.label,
173 triggerType: config.triggerType,
174 triggerNumber: config.triggerNumber,
175 triggerId: config.triggerId,
176 properties: config.properties,
177 description: config.description,
178 }));
179 };
180
181 const toAttrs = (
182 version: integrations.GoogleCloudIntegrationsV1alphaIntegrationVersion,
183 project: string,
184 region: string,
185 ) => {
186 const name = version.name ?? "";
187 const parsed = parseOwnership(version.description);
188 return {
189 name,
190 versionId: lastSegment(name),
191 integrationId: integrationIdOf(name),
192 integration: integrationOf(name),
193 location: locationOf(name, region),
194 project,
195 description: parsed.text,
196 userLabel: version.userLabel,
197 triggerConfigs: triggersOf(version.triggerConfigs),
198 status: version.status,
199 state: version.state,
200 snapshotNumber: version.snapshotNumber,
201 createTime: version.createTime,
202 updateTime: version.updateTime,
203 };
204 };
205
206 const getByName = (name: string) =>
207 name.length === 0
208 ? Effect.undefined
209 : integrations
210 .getProjectsLocationsIntegrationsVersions({ name })
211 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
212
213 const listAt = (parent: string, project: string, region: string) =>
214 integrations.listProjectsLocationsIntegrationsVersions.pages({ parent, pageSize: 100 }).pipe(
215 Stream.flatMap((page) => Stream.fromIterable(page.integrationVersions ?? [])),
216 Stream.filter((version) => hasOwnershipMarker(version.description)),
217 Stream.map((version) => toAttrs(version, project, region)),
218 Stream.runCollect,
219 Effect.map((chunk) => Array.from(chunk)),
220 Effect.catchTag("NotFound", () => Effect.succeed([])),
221 );
222
223 const findOwned = (parent: string, id: string) =>
224 integrations.listProjectsLocationsIntegrationsVersions.pages({ parent, pageSize: 100 }).pipe(
225 Stream.flatMap((page) => Stream.fromIterable(page.integrationVersions ?? [])),
226 Stream.filterEffect((version) => ownedByAlchemy(id, version.description)),
227 Stream.runHead,
228 Effect.map((option) => (option._tag === "Some" ? option.value : undefined)),
229 Effect.catchTag("NotFound", () => Effect.undefined),
230 );
231
232 const deleteIntegration = (name: string) =>
233 name.length === 0
234 ? Effect.void
235 : integrations.deleteProjectsLocationsIntegrations({ name }).pipe(
236 Effect.catchTags({
237 NotFound: () => Effect.void,
238 BadRequest: () => Effect.void,
239 Conflict: () => Effect.void,
240 }),
241 );
242
243 export const IntegrationsVersionProvider = () =>
244 Provider.succeed(IntegrationsVersion, {
245 stables: [
246 "name",
247 "versionId",
248 "integrationId",
249 "integration",
250 "location",
251 "project",
252 "createTime",
253 ],
254
255 diff: Effect.fn(function* ({ news, olds, output }) {
256 if (!isResolved(news)) return undefined;
257 const env = yield* GcpEnvironment.current;
258 const previousLocation = olds?.location ?? output?.location;
259 const nextLocation = normalizeLocation(news.location, previousLocation ?? env.region);
260 if (
261 previousLocation !== undefined &&
262 normalizeLocation(previousLocation, env.region) !== nextLocation
263 ) {
264 return { action: "replace" as const, deleteFirst: false };
265 }
266 const previousIntegration = olds?.integrationId ?? output?.integrationId;
267 if (
268 previousIntegration !== undefined &&
269 news.integrationId !== undefined &&
270 news.integrationId !== previousIntegration
271 ) {
272 return { action: "replace" as const, deleteFirst: false };
273 }
274 const previousId = olds?.versionId ?? output?.versionId;
275 if (
276 previousId !== undefined &&
277 news.versionId !== undefined &&
278 news.versionId !== previousId
279 ) {
280 return { action: "replace" as const, deleteFirst: false };
281 }
282 return undefined;
283 }),
284
285 read: Effect.fn(function* ({ id, olds, output }) {
286 const env = yield* GcpEnvironment.current;
287 const integrationId = yield* toResourceId(id, olds?.integrationId, output?.integrationId);
288 const versionId = olds?.versionId ?? output?.versionId ?? "";
289 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
290 const name =
291 output?.name ??
292 (versionId.length > 0 ? resourceName(env.project, location, integrationId, versionId) : "");
293 let existing = yield* getByName(name);
294 if (existing === undefined) {
295 existing = yield* findOwned(
296 `${locationParent(env.project, location)}/integrations/${integrationId}`,
297 id,
298 );
299 }
300 if (existing === undefined) return undefined;
301 const attrs = toAttrs(existing, env.project, env.region);
302 return (yield* ownedByAlchemy(id, existing.description)) ? attrs : Unowned(attrs);
303 }),
304
305 list: () =>
306 Effect.gen(function* () {
307 const env = yield* GcpEnvironment.current;
308 return yield* listAt(
309 `${locationParent(env.project, env.region)}/integrations/-`,
310 env.project,
311 env.region,
312 );
313 }),
314
315 reconcile: Effect.fn(function* ({ id, news, output }) {
316 const env = yield* GcpEnvironment.current;
317 const location = normalizeLocation(news.location ?? output?.location, env.region);
318 const integrationId = yield* toResourceId(id, news.integrationId, output?.integrationId);
319 const parent = `${locationParent(env.project, location)}/integrations/${integrationId}`;
320 const versionId = news.versionId ?? output?.versionId ?? "";
321 const name =
322 output?.name ??
323 (versionId.length > 0
324 ? resourceName(env.project, location, integrationId, versionId)
325 : parent);
326 const ownership = yield* createInternalLabels(id);
327 const description = encodeOwnership(ownership, news.description);
328 const triggerConfigs = news.triggerConfigs;
329 const newIntegration = news.newIntegration !== false;
330
331 let current = yield* getByName(output?.name ?? (versionId ? name : ""));
332 if (current === undefined) {
333 current = yield* findOwned(parent, id);
334 }
335
336 if (current === undefined) {
337 const tryCreate = (createNew: boolean) =>
338 integrations.createProjectsLocationsIntegrationsVersions({
339 parent,
340 newIntegration: createNew,
341 body: {
342 description,
343 userLabel: news.userLabel,
344 triggerConfigs,
345 },
346 });
347 const created = yield* tryCreate(newIntegration).pipe(
348 Effect.catchTag(["Conflict", "BadRequest"], () =>
349 tryCreate(false).pipe(
350 Effect.catchTag(["Conflict", "BadRequest"], () => findOwned(parent, id)),
351 ),
352 ),
353 );
354 current = created ?? (yield* findOwned(parent, id));
355 }
356
357 if (current === undefined) {
358 return yield* new IntegrationsVersionNotResolved({ resourceName: name });
359 }
360
361 const currentName = current.name ?? name;
362 const descriptionChanged = (current.description ?? "") !== description;
363 const labelChanged = !sameText(current.userLabel, news.userLabel);
364 const triggersChanged = !jsonTriggersEqual(
365 triggersOf(current.triggerConfigs),
366 triggerConfigs,
367 );
368
369 if (descriptionChanged || labelChanged || triggersChanged) {
370 current = yield* integrations.patchProjectsLocationsIntegrationsVersions({
371 name: currentName,
372 updateMask: updateMaskOf(
373 descriptionChanged ? "description" : undefined,
374 labelChanged ? "user_label" : undefined,
375 triggersChanged ? "trigger_configs" : undefined,
376 ),
377 body: {
378 name: currentName,
379 description,
380 userLabel: news.userLabel,
381 triggerConfigs,
382 },
383 });
384 }
385
386 return toAttrs(current, env.project, env.region);
387 }),
388
389 delete: Effect.fn(function* ({ output }) {
390 yield* integrations.deleteProjectsLocationsIntegrationsVersions({ name: output.name }).pipe(
391 Effect.catchTags({
392 NotFound: () => Effect.void,
393 BadRequest: () => Effect.void,
394 Conflict: () => Effect.void,
395 }),
396 );
397 yield* deleteIntegration(output.integration);
398 }),
399 });
400
401 const jsonTriggersEqual = (left: TriggerConfig[] | undefined, right: TriggerConfig[] | undefined) =>
402 JSON.stringify(left ?? null) === JSON.stringify(right ?? null);