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

main
ts 298 lines 10.3 KB
Raw
1 import * as integrations from "@distilled.cloud/gcp/integrations_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 { 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 parseOwnership,
21 sameText,
22 toResourceId,
23 updateMaskOf,
24 } from "./ownership.ts";
25
26 export type IntegrationsVersionsTestCasesProps = {
27 /**
28 * Parent integration version resource name
29 * `projects/{project}/locations/{location}/integrations/{integration}/versions/{version}`.
30 * Immutable — changing it replaces the test case.
31 */
32 version: string;
33 /**
34 * Test case id (the `{testCase}` segment). If omitted, a unique id is
35 * generated. Immutable — changing it replaces the test case.
36 */
37 testCaseId?: string;
38 /**
39 * Location used when `version` is a bare id. Immutable — changing it
40 * replaces the test case.
41 * @default the stack's GCP region (`GCP.Region`, else the profile
42 * region, else `us-central1`)
43 */
44 location?: string;
45 /**
46 * Display name.
47 */
48 displayName?: string;
49 /**
50 * Human-readable description. Test cases have no labels field, so
51 * Alchemy ownership is stored in a `[alchemy …]` prefix and stripped
52 * from attributes.
53 */
54 description?: string;
55 /**
56 * Trigger id in the parent version that starts this test case
57 * (`api_trigger/{name}`).
58 */
59 triggerId: string;
60 };
61
62 export type IntegrationsVersionsTestCases = Resource<
63 "GCP.Integrations.IntegrationsVersionsTestCases",
64 IntegrationsVersionsTestCasesProps,
65 {
66 /** Full resource name. */
67 name: string;
68 /** Test case id (last path segment). */
69 testCaseId: string;
70 /** Parent version resource name. */
71 version: string;
72 /** Location id. */
73 location: string;
74 /** Project id. */
75 project: string;
76 /** Display name. */
77 displayName: string | undefined;
78 /** User description with the Alchemy ownership prefix stripped. */
79 description: string | undefined;
80 /** Trigger id this test case starts from. */
81 triggerId: string | undefined;
82 /** RFC3339 creation timestamp. */
83 createTime: string | undefined;
84 /** RFC3339 last-update timestamp. */
85 updateTime: string | undefined;
86 },
87 never,
88 Providers
89 >;
90
91 /**
92 * A functional test case attached to an Application Integration version.
93 *
94 * Test cases have no labels field — Alchemy stamps ownership into the
95 * description. Parent version and test case id are immutable. Display
96 * name, description, and trigger id update in place.
97 *
98 * ### Creating a Test Case
99 * **Example:** Exercise an API trigger
100 * ```typescript
101 * const testCase = yield* GCP.Integrations.IntegrationsVersionsTestCases("HappyPath", {
102 * version: version.name,
103 * triggerId: "api_trigger/orders",
104 * displayName: "happy-path",
105 * description: "fires the API trigger",
106 * });
107 * ```
108 *
109 * @resource
110 * @category Integrations
111 */
112 export const IntegrationsVersionsTestCases = Resource<IntegrationsVersionsTestCases>(
113 "GCP.Integrations.IntegrationsVersionsTestCases",
114 );
115
116 export class IntegrationsVersionsTestCasesNotResolved extends Data.TaggedError(
117 "GCP.Integrations.IntegrationsVersionsTestCasesNotResolved",
118 )<{
119 resourceName: string;
120 }> {}
121
122 const expandVersion = (value: string, project: string, location: string) =>
123 value.includes("/versions/")
124 ? value
125 : `${locationParent(project, location)}/integrations/${value}/versions/${value}`;
126
127 const resourceName = (version: string, testCaseId: string) => `${version}/testCases/${testCaseId}`;
128
129 const toAttrs = (
130 testCase: integrations.GoogleCloudIntegrationsV1alphaTestCase,
131 project: string,
132 region: string,
133 version: string,
134 ) => {
135 const name = testCase.name ?? "";
136 const parsed = parseOwnership(testCase.description);
137 return {
138 name,
139 testCaseId: lastSegment(name),
140 version,
141 location: locationOf(name, region),
142 project,
143 displayName: testCase.displayName,
144 description: parsed.text,
145 triggerId: testCase.triggerId,
146 createTime: testCase.createTime,
147 updateTime: testCase.updateTime,
148 };
149 };
150
151 const getByName = (name: string) =>
152 name.length === 0
153 ? Effect.undefined
154 : integrations
155 .getProjectsLocationsIntegrationsVersionsTestCases({ name })
156 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
157
158 const listAt = (parent: string, project: string, region: string) =>
159 integrations.listProjectsLocationsIntegrationsVersionsTestCases
160 .pages({ parent, pageSize: 100 })
161 .pipe(
162 Stream.flatMap((page) => Stream.fromIterable(page.testCases ?? [])),
163 Stream.filter((testCase) => hasOwnershipMarker(testCase.description)),
164 Stream.map((testCase) => toAttrs(testCase, project, region, parent)),
165 Stream.runCollect,
166 Effect.map((chunk) => Array.from(chunk)),
167 Effect.catchTag("NotFound", () => Effect.succeed([])),
168 );
169
170 const findOwned = (parent: string, id: string) =>
171 integrations.listProjectsLocationsIntegrationsVersionsTestCases
172 .pages({ parent, pageSize: 100 })
173 .pipe(
174 Stream.flatMap((page) => Stream.fromIterable(page.testCases ?? [])),
175 Stream.filterEffect((testCase) => ownedByAlchemy(id, testCase.description)),
176 Stream.runHead,
177 Effect.map((option) => (option._tag === "Some" ? option.value : undefined)),
178 Effect.catchTag("NotFound", () => Effect.undefined),
179 );
180
181 const listWildcard = (project: string, location: string) =>
182 listAt(`${locationParent(project, location)}/integrations/-/versions/-`, project, location);
183
184 export const IntegrationsVersionsTestCasesProvider = () =>
185 Provider.succeed(IntegrationsVersionsTestCases, {
186 stables: ["name", "testCaseId", "version", "location", "project", "createTime"],
187
188 diff: Effect.fn(function* ({ news, olds, output }) {
189 if (!isResolved(news)) return undefined;
190 const previousVersion = olds?.version ?? output?.version;
191 if (
192 previousVersion !== undefined &&
193 news.version !== previousVersion &&
194 !news.version.endsWith(`/${lastSegment(previousVersion)}`)
195 ) {
196 return { action: "replace" as const, deleteFirst: false };
197 }
198 const previousId = olds?.testCaseId ?? output?.testCaseId;
199 if (
200 previousId !== undefined &&
201 news.testCaseId !== undefined &&
202 news.testCaseId !== previousId
203 ) {
204 return { action: "replace" as const, deleteFirst: true };
205 }
206 return undefined;
207 }),
208
209 read: Effect.fn(function* ({ id, olds, output, previous }) {
210 const env = yield* GcpEnvironment.current;
211 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
212 const version = expandVersion(olds?.version ?? output?.version ?? "", env.project, location);
213 const testCaseId = yield* toResourceId(id, olds?.testCaseId, output?.testCaseId);
214 const name = output?.name ?? resourceName(version, testCaseId);
215 let existing = yield* getByName(name);
216 if (existing === undefined && version.length > 0) {
217 existing = yield* findOwned(version, id);
218 }
219 if (existing === undefined) return undefined;
220 const attrs = toAttrs(existing, env.project, env.region, version);
221 return (yield* ownedByAlchemy(id, existing.description))
222 ? attrs
223 : unownedUnlessPrevious(attrs, previous, "name");
224 }),
225
226 list: () =>
227 Effect.gen(function* () {
228 const env = yield* GcpEnvironment.current;
229 return yield* listWildcard(env.project, env.region);
230 }),
231
232 reconcile: Effect.fn(function* ({ id, news, output }) {
233 const env = yield* GcpEnvironment.current;
234 const location = normalizeLocation(news.location ?? output?.location, env.region);
235 const version = expandVersion(news.version, env.project, location);
236 const testCaseId = yield* toResourceId(id, news.testCaseId, output?.testCaseId);
237 const name = output?.name ?? resourceName(version, testCaseId);
238 const ownership = yield* createInternalLabels(id);
239 const description = encodeOwnership(ownership, news.description);
240 const displayName = news.displayName ?? testCaseId;
241
242 let current = yield* getByName(output?.name ?? name);
243 if (current === undefined) {
244 current = yield* findOwned(version, id);
245 }
246
247 if (current === undefined) {
248 const created = yield* integrations
249 .createProjectsLocationsIntegrationsVersionsTestCases({
250 parent: version,
251 testCaseId,
252 body: {
253 displayName,
254 description,
255 triggerId: news.triggerId,
256 },
257 })
258 .pipe(Effect.catchTag("Conflict", () => findOwned(version, id)));
259 current = created ?? (yield* findOwned(version, id));
260 }
261
262 if (current === undefined) {
263 return yield* new IntegrationsVersionsTestCasesNotResolved({ resourceName: name });
264 }
265
266 const currentName = current.name ?? name;
267 const displayChanged = !sameText(current.displayName, displayName);
268 const descriptionChanged = (current.description ?? "") !== description;
269 const triggerChanged = !sameText(current.triggerId, news.triggerId);
270
271 if (displayChanged || descriptionChanged || triggerChanged) {
272 current = yield* integrations.patchProjectsLocationsIntegrationsVersionsTestCases({
273 name: currentName,
274 updateMask: updateMaskOf(
275 displayChanged ? "display_name" : undefined,
276 descriptionChanged ? "description" : undefined,
277 triggerChanged ? "trigger_id" : undefined,
278 ),
279 body: {
280 name: currentName,
281 displayName,
282 description,
283 triggerId: news.triggerId,
284 },
285 });
286 }
287
288 return toAttrs(current, env.project, env.region, version);
289 }),
290
291 delete: Effect.fn(function* ({ output }) {
292 yield* integrations
293 .deleteProjectsLocationsIntegrationsVersionsTestCases({
294 name: output.name,
295 })
296 .pipe(Effect.catchTag("NotFound", () => Effect.void));
297 }),
298 });