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

main
ts 339 lines 11.3 KB
Raw
1 import * as dlp from "@distilled.cloud/gcp/dlp_v2";
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 * as Stream from "effect/Stream";
8 import { GcpEnvironment } from "../Environment.ts";
9 import { createInternalLabels } from "../Labels.ts";
10 import type { Providers } from "../Providers.ts";
11 import {
12 DEFAULT_LOCATION,
13 DlpNotResolved,
14 encodeDescription,
15 fingerprint,
16 hasOwnershipMarker,
17 lastSegment,
18 locationParentsOf,
19 organizationLocationParent,
20 normalizeLocation,
21 organizationIdOf,
22 ownedByAlchemy,
23 parseName,
24 parseOwnership,
25 replaceOn,
26 resolveOrganization,
27 sameText,
28 toPhysicalId,
29 tryResolveOrganization,
30 updateMaskOf,
31 } from "./internal.ts";
32
33 export type InspectJobConfig = dlp.GooglePrivacyDlpV2InspectJobConfig;
34 export type JobTriggerTrigger = dlp.GooglePrivacyDlpV2Trigger;
35 export type JobTriggerStatus = dlp.GooglePrivacyDlpV2JobTriggerStatusEnum | (string & {});
36
37 export type OrganizationsLocationsJobTriggerProps = {
38 /**
39 * Trigger id (the `{jobTrigger}` segment of
40 * `organizations/{organization}/locations/{location}/jobTriggers/{jobTrigger}`).
41 * If omitted, a unique id is generated. Letters, digits, hyphens, and
42 * underscores; max 100 characters. Immutable — changing it replaces
43 * the trigger.
44 */
45 triggerId?: string;
46 /**
47 * Parent organization (`organizations/{organization}` or the numeric
48 * id). Defaults to `GOOGLE_ORGANIZATION_ID` or the project's Resource
49 * Manager ancestor. Immutable — changing it replaces the trigger.
50 */
51 organization?: string;
52 /**
53 * Processing location (`us-central1`, `global`, `us`, …). Immutable —
54 * changing it replaces the trigger.
55 * @default "global"
56 */
57 location?: string;
58 /**
59 * Human-readable display name (max 100 characters).
60 */
61 displayName?: string;
62 /**
63 * Human-readable description (max 256 characters). Job triggers have no
64 * labels field, so Alchemy ownership is stored in a `[alchemy …]` prefix
65 * and stripped from attributes.
66 */
67 description?: string;
68 /**
69 * Trigger status. Prefer `PAUSED` unless jobs should run.
70 * @default "PAUSED"
71 */
72 status?: JobTriggerStatus;
73 /**
74 * Events that start a job. At least one trigger is required.
75 */
76 triggers: JobTriggerTrigger[];
77 /**
78 * Inspect job configuration (what to scan and which detectors to run).
79 */
80 inspectJob: InspectJobConfig;
81 };
82
83 export type OrganizationsLocationsJobTrigger = Resource<
84 "GCP.DLP.OrganizationsLocationsJobTrigger",
85 OrganizationsLocationsJobTriggerProps,
86 {
87 /** Full resource name. */
88 name: string;
89 /** Trigger id (last path segment). */
90 triggerId: string;
91 /** Organization resource name. */
92 organization: string;
93 /** Organization id. */
94 organizationId: string;
95 /** Location id. */
96 location: string;
97 /** Project id of the deploying stack. */
98 project: string;
99 /** User display name. */
100 displayName: string | undefined;
101 /** User description with the Alchemy ownership prefix stripped. */
102 description: string | undefined;
103 /** Trigger status. */
104 status: string;
105 /** Triggers that start a job. */
106 triggers: JobTriggerTrigger[];
107 /** Inspect job configuration. */
108 inspectJob: InspectJobConfig | undefined;
109 /** RFC3339 creation timestamp. */
110 createTime: string | undefined;
111 /** RFC3339 last-update timestamp. */
112 updateTime: string | undefined;
113 /** RFC3339 last-run timestamp. */
114 lastRunTime: string | undefined;
115 },
116 never,
117 Providers
118 >;
119
120 /**
121 * An organization-scoped Sensitive Data Protection job trigger that
122 * inspects storage on a schedule.
123 *
124 * Job triggers have no labels field — Alchemy stamps ownership into the
125 * description so `list` / nuke can find them. Trigger id, organization,
126 * and location are identity. Display name, description, status, triggers,
127 * and inspect job update in place. Keep `status` as `PAUSED` unless jobs
128 * should run.
129 *
130 * ### Creating a Job Trigger
131 * **Example:** Daily paused Cloud Storage inspect
132 * ```typescript
133 * const trigger = yield* GCP.DLP.OrganizationsLocationsJobTrigger(
134 * "ScanBucket",
135 * {
136 * status: "PAUSED",
137 * triggers: [
138 * { schedule: { recurrencePeriodDuration: "86400s" } },
139 * ],
140 * inspectJob: {
141 * inspectConfig: { infoTypes: [{ name: "EMAIL_ADDRESS" }] },
142 * storageConfig: {
143 * cloudStorageOptions: {
144 * fileSet: { url: "gs://my-bucket/" },
145 * },
146 * },
147 * },
148 * },
149 * );
150 * ```
151 *
152 * @resource
153 * @category DLP
154 */
155 export const OrganizationsLocationsJobTrigger = Resource<OrganizationsLocationsJobTrigger>(
156 "GCP.DLP.OrganizationsLocationsJobTrigger",
157 );
158
159 const DEFAULT_STATUS = "PAUSED" satisfies JobTriggerStatus;
160
161 const resourceName = (organization: string, location: string, triggerId: string) =>
162 `${organizationLocationParent(organization, location)}/jobTriggers/${triggerId}`;
163
164 const toAttrs = (
165 trigger: dlp.GooglePrivacyDlpV2JobTrigger,
166 organization: string,
167 project: string,
168 ) => {
169 const name = trigger.name ?? "";
170 const parsed = parseName(name, "jobTriggers");
171 const ownership = parseOwnership(trigger.description);
172 return {
173 name,
174 triggerId: parsed.id || lastSegment(name),
175 organization,
176 organizationId: organizationIdOf(organization),
177 location: parsed.location || DEFAULT_LOCATION,
178 project,
179 displayName: trigger.displayName,
180 description: ownership.text,
181 status: trigger.status ?? DEFAULT_STATUS,
182 triggers: trigger.triggers ?? [],
183 inspectJob: trigger.inspectJob,
184 createTime: trigger.createTime,
185 updateTime: trigger.updateTime,
186 lastRunTime: trigger.lastRunTime,
187 };
188 };
189
190 const getByName = (name: string) =>
191 name.length === 0
192 ? Effect.undefined
193 : dlp
194 .getOrganizationsLocationsJobTriggers({ name })
195 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
196
197 const listAt = (parent: string, organization: string, project: string) =>
198 dlp.listOrganizationsLocationsJobTriggers
199 .pages({ parent, pageSize: 100, type: "INSPECT_JOB" })
200 .pipe(
201 Stream.flatMap((page) => Stream.fromIterable(page.jobTriggers ?? [])),
202 Stream.filter((trigger) => hasOwnershipMarker(trigger.description)),
203 Stream.map((trigger) => toAttrs(trigger, organization, project)),
204 Stream.runCollect,
205 Effect.map((chunk) => Array.from(chunk)),
206 Effect.catchTag("NotFound", () => Effect.succeed([])),
207 );
208
209 const statusOf = (value: string | undefined) => value ?? DEFAULT_STATUS;
210
211 export const OrganizationsLocationsJobTriggerProvider = () =>
212 Provider.succeed(OrganizationsLocationsJobTrigger, {
213 stables: [
214 "name",
215 "triggerId",
216 "organization",
217 "organizationId",
218 "location",
219 "project",
220 "createTime",
221 ],
222
223 diff: Effect.fn(function* ({ news, olds, output }) {
224 if (!isResolved(news)) return undefined;
225 const previousLocation = normalizeLocation(olds?.location ?? output?.location);
226 const nextLocation = normalizeLocation(news.location ?? olds?.location ?? output?.location);
227 return (
228 replaceOn(olds?.triggerId ?? output?.triggerId, news.triggerId) ??
229 replaceOn(olds?.organization ?? output?.organization, news.organization) ??
230 replaceOn(previousLocation, nextLocation)
231 );
232 }),
233
234 read: Effect.fn(function* ({ id, olds, output }) {
235 const env = yield* GcpEnvironment.current;
236 const organization = yield* resolveOrganization(
237 olds?.organization ?? output?.organization,
238 output?.organization,
239 );
240 const location = normalizeLocation(olds?.location ?? output?.location);
241 const triggerId = yield* toPhysicalId(id, olds?.triggerId, output?.triggerId);
242 const name = output?.name ?? resourceName(organization, location, triggerId);
243 const existing = yield* getByName(name);
244 if (existing === undefined) return undefined;
245 const attrs = toAttrs(existing, organization, env.project);
246 return (yield* ownedByAlchemy(id, existing.description)) ? attrs : Unowned(attrs);
247 }),
248
249 list: () =>
250 Effect.gen(function* () {
251 const env = yield* GcpEnvironment.current;
252 const organization = yield* tryResolveOrganization();
253 if (organization === undefined) return [];
254 const pages = yield* Effect.forEach(
255 locationParentsOf(organization, env.region),
256 (parent) => listAt(parent, organization, env.project),
257 { concurrency: 3 },
258 );
259 return pages.flat();
260 }),
261
262 reconcile: Effect.fn(function* ({ id, news, output }) {
263 const env = yield* GcpEnvironment.current;
264 const organization = yield* resolveOrganization(news.organization, output?.organization);
265 const location = normalizeLocation(news.location ?? output?.location);
266 const triggerId = yield* toPhysicalId(id, news.triggerId, output?.triggerId);
267 const parent = organizationLocationParent(organization, location);
268 const name = resourceName(organization, location, triggerId);
269 const ownership = yield* createInternalLabels(id);
270 const description = encodeDescription(ownership, news.description);
271 const displayName = news.displayName;
272 const status = statusOf(news.status);
273 const triggers = news.triggers;
274 const inspectJob = news.inspectJob;
275
276 let current = yield* getByName(output?.name ?? name);
277
278 if (current === undefined) {
279 const created = yield* dlp
280 .createOrganizationsLocationsJobTriggers({
281 parent,
282 body: {
283 triggerId,
284 jobTrigger: {
285 displayName,
286 description,
287 status,
288 triggers,
289 inspectJob,
290 },
291 },
292 })
293 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
294 current = created ?? undefined;
295 }
296
297 if (current === undefined) {
298 return yield* new DlpNotResolved({ resourceName: name });
299 }
300
301 const currentName = current.name ?? name;
302 const displayChanged = !sameText(current.displayName, displayName);
303 const descriptionChanged = !sameText(current.description, description);
304 const statusChanged = !sameText(current.status, status);
305 const triggersChanged = fingerprint(current.triggers) !== fingerprint(triggers);
306 const jobChanged = fingerprint(current.inspectJob) !== fingerprint(inspectJob);
307 const updateMask = updateMaskOf(
308 displayChanged ? "displayName" : undefined,
309 descriptionChanged ? "description" : undefined,
310 statusChanged ? "status" : undefined,
311 triggersChanged ? "triggers" : undefined,
312 jobChanged ? "inspectJob" : undefined,
313 );
314
315 if (updateMask.length > 0) {
316 current = yield* dlp.patchOrganizationsLocationsJobTriggers({
317 name: currentName,
318 body: {
319 updateMask,
320 jobTrigger: {
321 displayName,
322 description,
323 status,
324 triggers,
325 inspectJob,
326 },
327 },
328 });
329 }
330
331 return toAttrs(current, organization, env.project);
332 }),
333
334 delete: Effect.fn(function* ({ output }) {
335 yield* dlp
336 .deleteOrganizationsLocationsJobTriggers({ name: output.name })
337 .pipe(Effect.catchTag("NotFound", () => Effect.void));
338 }),
339 });