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

main
ts 342 lines 11.3 KB
Raw
1 import * as ssm from "@distilled.cloud/gcp/securesourcemanager_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 Effect from "effect/Effect";
7 import { GcpEnvironment } from "../Environment.ts";
8 import { hasAlchemyLabels } from "../Labels.ts";
9 import type { Providers } from "../Providers.ts";
10 import {
11 catchMissing,
12 collectPages,
13 expandName,
14 fieldMask,
15 fingerprint,
16 forEachRepository,
17 hasTargetUriOwnership,
18 normalizeLocation,
19 PAGE_SIZE,
20 parseName,
21 parseTargetUriOwnership,
22 replaceOnIdentity,
23 ResourceNotResolved,
24 retryConflict,
25 rfc1035,
26 sameText,
27 stripAlchemyQuery,
28 toPhysicalId,
29 waitForOperation,
30 waitUntilExists,
31 waitUntilGone,
32 } from "./internal.ts";
33
34 export type HookEvent = ssm.HookEventsItemEnum | (string & {});
35
36 export type RepositoriesHookProps = {
37 /**
38 * Parent repository. Full name
39 * `projects/{project}/locations/{location}/repositories/{repository}`
40 * or the repository id (combined with `location`). Immutable —
41 * changing it replaces the hook.
42 */
43 repository: string;
44 /**
45 * Region used when `repository` is a bare id.
46 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
47 */
48 location?: string;
49 /**
50 * Hook id (the `{hook}` segment). If omitted, a unique RFC1035 name is
51 * generated. Immutable — changing it replaces the hook.
52 */
53 hookId?: string;
54 /**
55 * Target URI that receives webhook payloads, sent as given. Hooks have
56 * no labels, so ownership rests on the hook id (generated ids embed the
57 * stack, stage, and logical id).
58 */
59 targetUri: string;
60 /**
61 * Events that fire the hook (`PUSH`, `PULL_REQUEST`).
62 */
63 events?: HookEvent[];
64 /**
65 * When true, the hook exists but does not send traffic.
66 * @default false
67 */
68 disabled?: boolean;
69 /**
70 * Sensitive query string appended to `targetUri` by the service.
71 */
72 sensitiveQueryString?: string;
73 /**
74 * Push-event filter. Empty or `*` reports every branch.
75 */
76 pushOption?: {
77 /** Glob of branches that trigger the hook. */
78 branchFilter?: string;
79 };
80 };
81
82 export type RepositoriesHook = Resource<
83 "GCP.SecureSourceManager.RepositoriesHook",
84 RepositoriesHookProps,
85 {
86 /** Full resource name. */
87 name: string;
88 /** Hook id (last path segment). */
89 hookId: string;
90 /** Parent repository resource name. */
91 repository: string;
92 /** Project id. */
93 project: string;
94 /** Location id. */
95 location: string;
96 /** Target URI with Alchemy ownership query parameters stripped. */
97 targetUri: string;
98 /** Events that fire the hook. */
99 events: HookEvent[];
100 /** Whether the hook is disabled. */
101 disabled: boolean;
102 /** Push-event filter. */
103 pushOption:
104 | {
105 branchFilter: string | undefined;
106 }
107 | undefined;
108 /** Server-generated resource uid. */
109 uid: string | undefined;
110 /** RFC3339 creation timestamp. */
111 createTime: string | undefined;
112 /** RFC3339 last-update timestamp. */
113 updateTime: string | undefined;
114 },
115 never,
116 Providers
117 >;
118
119 /**
120 * A Secure Source Manager repository webhook.
121 *
122 * Changing `hookId`, `repository`, or `location` replaces the hook.
123 * Target URI, events, disabled flag, and push options update in place.
124 * Ownership for `list` / nuke is stamped into `targetUri` query
125 * parameters (hooks have no labels field).
126 *
127 * ### Creating a Hook
128 * **Example:** Push webhook
129 * ```typescript
130 * const hook = yield* GCP.SecureSourceManager.RepositoriesHook("Notify", {
131 * repository: repo.name,
132 * targetUri: "https://example.com/hooks/ssm",
133 * events: ["PUSH"],
134 * });
135 * ```
136 *
137 * **Example:** Named hook with a branch filter
138 * ```typescript
139 * const hook = yield* GCP.SecureSourceManager.RepositoriesHook("Notify", {
140 * repository: repo.name,
141 * hookId: "prod-push",
142 * targetUri: "https://example.com/hooks/ssm",
143 * events: ["PUSH", "PULL_REQUEST"],
144 * pushOption: { branchFilter: "main" },
145 * });
146 * ```
147 *
148 * ### Updating a Hook
149 * Re-declare the same logical id with changed props; the engine keeps the
150 * physical resource and updates it in place.
151 *
152 * **Example:** Disable and retarget
153 * ```typescript
154 * const hook = yield* GCP.SecureSourceManager.RepositoriesHook("Notify", {
155 * repository: repo.name,
156 * targetUri: "https://example.com/hooks/ssm-v2",
157 * events: ["PUSH"],
158 * disabled: true,
159 * });
160 * ```
161 *
162 * @resource
163 * @category SecureSourceManager
164 */
165 export const RepositoriesHook = Resource<RepositoriesHook>(
166 "GCP.SecureSourceManager.RepositoriesHook",
167 );
168
169 const resourceName = (repository: string, hookId: string) => `${repository}/hooks/${hookId}`;
170
171 const toEvents = (
172 events: readonly (ssm.HookEventsItemEnum | (string & {}))[] | undefined,
173 ): HookEvent[] => [...(events ?? [])].slice().sort();
174
175 const toAttrs = (item: ssm.Hook, project: string, region: string) => {
176 const name = item.name ?? "";
177 const parsed = parseName(name, "hooks", region);
178 return {
179 name,
180 hookId: parsed.id,
181 repository: parsed.parent,
182 project: parsed.project || project,
183 location: parsed.location,
184 targetUri: stripAlchemyQuery(item.targetUri ?? ""),
185 events: toEvents(item.events),
186 disabled: item.disabled === true,
187 pushOption:
188 item.pushOption === undefined ? undefined : { branchFilter: item.pushOption.branchFilter },
189 uid: item.uid,
190 createTime: item.createTime,
191 updateTime: item.updateTime,
192 };
193 };
194
195 const getByName = (name: string) =>
196 name.length === 0
197 ? Effect.undefined
198 : catchMissing(ssm.getProjectsLocationsRepositoriesHooks({ name }));
199
200 const listOnRepository = (repository: string) =>
201 collectPages(
202 ssm.listProjectsLocationsRepositoriesHooks.pages({
203 parent: repository,
204 pageSize: PAGE_SIZE,
205 }),
206 (page) => page.hooks,
207 );
208
209 const listOwned = (project: string, region: string) =>
210 forEachRepository(project, region, (repository) =>
211 listOnRepository(repository).pipe(
212 Effect.map((items) => items.filter((item) => hasTargetUriOwnership(item.targetUri))),
213 ),
214 );
215
216 export const RepositoriesHookProvider = () =>
217 Provider.succeed(RepositoriesHook, {
218 stables: ["name", "hookId", "repository", "project", "location", "uid", "createTime"],
219
220 diff: Effect.fn(function* ({ news, olds, output }) {
221 if (!isResolved(news)) return undefined;
222 const env = yield* GcpEnvironment.current;
223 const location = normalizeLocation(
224 news.location ?? olds?.location ?? output?.location,
225 env.region,
226 );
227 return replaceOnIdentity({
228 previousId: olds?.hookId ?? output?.hookId,
229 nextId: news.hookId ? rfc1035(news.hookId, "hook") : (olds?.hookId ?? output?.hookId),
230 previousLocation: normalizeLocation(olds?.location ?? output?.location, env.region),
231 nextLocation: location,
232 previousParent: olds?.repository ?? output?.repository,
233 nextParent: expandName(news.repository, env.project, location, "repositories"),
234 });
235 }),
236
237 read: Effect.fn(function* ({ id, olds, output }) {
238 const env = yield* GcpEnvironment.current;
239 const hookId = yield* toPhysicalId(id, olds?.hookId, output?.hookId, "hook");
240 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
241 const repository = expandName(
242 olds?.repository ?? output?.repository ?? "",
243 env.project,
244 location,
245 "repositories",
246 );
247 const name = output?.name ?? (repository.length > 0 ? resourceName(repository, hookId) : "");
248 const existing = yield* getByName(name);
249 if (existing === undefined) return undefined;
250 const attrs = toAttrs(existing, env.project, env.region);
251 // A generated id embeds stack/stage/logical id, so finding it means we
252 // created it; an explicit id could name anyone's hook. Hooks created
253 // before ownership moved off the URI still carry query markers.
254 const owned =
255 output !== undefined ||
256 olds?.hookId === undefined ||
257 (yield* hasAlchemyLabels(id, parseTargetUriOwnership(existing.targetUri)));
258 return owned ? attrs : Unowned(attrs);
259 }),
260
261 list: () =>
262 Effect.gen(function* () {
263 const env = yield* GcpEnvironment.current;
264 const items = yield* listOwned(env.project, env.region);
265 return items.map((item: ssm.Hook) => toAttrs(item, env.project, env.region));
266 }),
267
268 reconcile: Effect.fn(function* ({ id, news, output }) {
269 const env = yield* GcpEnvironment.current;
270 const hookId = yield* toPhysicalId(id, news.hookId, output?.hookId, "hook");
271 const location = normalizeLocation(news.location ?? output?.location, env.region);
272 const repository = expandName(news.repository, env.project, location, "repositories");
273 const name = resourceName(repository, hookId);
274 const targetUri = news.targetUri;
275 const events = toEvents(news.events);
276
277 let current = yield* getByName(output?.name ?? name);
278
279 if (current === undefined) {
280 const created = yield* ssm
281 .createProjectsLocationsRepositoriesHooks({
282 parent: repository,
283 hookId,
284 body: {
285 targetUri,
286 events: events.length > 0 ? events : undefined,
287 disabled: news.disabled === true ? true : undefined,
288 sensitiveQueryString: news.sensitiveQueryString,
289 pushOption: news.pushOption,
290 },
291 })
292 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
293 if (created !== undefined) {
294 yield* waitForOperation(created);
295 }
296 current = yield* waitUntilExists(getByName(name), name);
297 }
298
299 if (current === undefined) {
300 return yield* new ResourceNotResolved({ resourceName: name });
301 }
302
303 const mask = fieldMask([
304 !sameText(current.targetUri, targetUri) && "targetUri",
305 fingerprint(toEvents(current.events)) !== fingerprint(events) && "events",
306 (current.disabled === true) !== (news.disabled === true) && "disabled",
307 !sameText(current.sensitiveQueryString, news.sensitiveQueryString) &&
308 "sensitiveQueryString",
309 fingerprint(current.pushOption) !== fingerprint(news.pushOption) && "pushOption",
310 ]);
311
312 if (mask.length > 0) {
313 const operation = yield* ssm.patchProjectsLocationsRepositoriesHooks({
314 name: current.name ?? name,
315 updateMask: mask,
316 body: {
317 targetUri,
318 events,
319 disabled: news.disabled === true,
320 sensitiveQueryString: news.sensitiveQueryString,
321 pushOption: news.pushOption,
322 },
323 });
324 yield* waitForOperation(operation);
325 current = yield* waitUntilExists(getByName(current.name ?? name), current.name ?? name);
326 }
327
328 return toAttrs(current, env.project, env.region);
329 }),
330
331 delete: Effect.fn(function* ({ output }) {
332 const operation = yield* retryConflict(
333 ssm
334 .deleteProjectsLocationsRepositoriesHooks({ name: output.name })
335 .pipe(Effect.catchTag("NotFound", () => Effect.undefined)),
336 );
337 if (operation !== undefined) {
338 yield* waitForOperation(operation, { notFoundOk: true });
339 }
340 yield* waitUntilGone(getByName(output.name), output.name);
341 }),
342 });