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

main
ts 308 lines 10.7 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 type InspectConfig = dlp.GooglePrivacyDlpV2InspectConfig;
34
35 export type OrganizationsLocationsInspectTemplateProps = {
36 /**
37 * Template id (the `{inspectTemplate}` segment of
38 * `organizations/{organization}/locations/{location}/inspectTemplates/{inspectTemplate}`).
39 * If omitted, a unique id is generated. Letters, digits, hyphens, and
40 * underscores; max 100 characters. Immutable — changing it replaces
41 * the template.
42 */
43 templateId?: string;
44 /**
45 * Parent organization (`organizations/{organization}` or the numeric
46 * id). Defaults to `GOOGLE_ORGANIZATION_ID` or the project's Resource
47 * Manager ancestor. Immutable — changing it replaces the template.
48 */
49 organization?: string;
50 /**
51 * Processing location (`us-central1`, `global`, `us`, …). Immutable —
52 * changing it replaces the template.
53 * @default "global"
54 */
55 location?: string;
56 /**
57 * Human-readable display name (max 256 characters).
58 */
59 displayName?: string;
60 /**
61 * Human-readable description (max 256 characters). Inspect templates
62 * have no labels field, so Alchemy ownership is stored in a
63 * `[alchemy …]` prefix and stripped from attributes.
64 */
65 description?: string;
66 /**
67 * Inspection configuration applied when this template is used.
68 */
69 inspectConfig: InspectConfig;
70 /**
71 * Allow limited-availability built-in infoTypes in `inspectConfig`.
72 * @default false
73 */
74 allowLimitedAvailabilityInfoTypes?: boolean;
75 };
76
77 export type OrganizationsLocationsInspectTemplate = Resource<
78 "GCP.DLP.OrganizationsLocationsInspectTemplate",
79 OrganizationsLocationsInspectTemplateProps,
80 {
81 /** Full resource name. */
82 name: string;
83 /** Template id (last path segment). */
84 templateId: string;
85 /** Organization resource name. */
86 organization: string;
87 /** Organization id. */
88 organizationId: string;
89 /** Location id. */
90 location: string;
91 /** Project id of the deploying stack. */
92 project: string;
93 /** User display name. */
94 displayName: string | undefined;
95 /** User description with the Alchemy ownership prefix stripped. */
96 description: string | undefined;
97 /** Inspection configuration. */
98 inspectConfig: InspectConfig | undefined;
99 /** Whether limited-availability infoTypes are allowed. */
100 allowLimitedAvailabilityInfoTypes: boolean;
101 /** RFC3339 creation timestamp. */
102 createTime: string | undefined;
103 /** RFC3339 last-update timestamp. */
104 updateTime: string | undefined;
105 },
106 never,
107 Providers
108 >;
109
110 /**
111 * A location-scoped Sensitive Data Protection inspect template on an
112 * organization.
113 *
114 * Templates have no labels field — Alchemy stamps ownership into the
115 * description so `list` / nuke can find them. Template id, organization,
116 * and location are identity. Display name, description, and inspect
117 * config update in place.
118 *
119 * ### Creating a Location Inspect Template
120 * **Example:** Detect phone numbers in us-central1
121 * ```typescript
122 * const template = yield* GCP.DLP.OrganizationsLocationsInspectTemplate(
123 * "Phones",
124 * {
125 * location: "us-central1",
126 * inspectConfig: {
127 * infoTypes: [{ name: "PHONE_NUMBER" }],
128 * includeQuote: true,
129 * },
130 * },
131 * );
132 * ```
133 *
134 * @resource
135 * @category DLP
136 */
137 export const OrganizationsLocationsInspectTemplate =
138 Resource<OrganizationsLocationsInspectTemplate>("GCP.DLP.OrganizationsLocationsInspectTemplate");
139
140 const resourceName = (organization: string, location: string, templateId: string) =>
141 `${organizationLocationParent(organization, location)}/inspectTemplates/${templateId}`;
142
143 const toAttrs = (
144 template: dlp.GooglePrivacyDlpV2InspectTemplate,
145 organization: string,
146 project: string,
147 ) => {
148 const name = template.name ?? "";
149 const parsed = parseName(name, "inspectTemplates");
150 const ownership = parseOwnership(template.description);
151 return {
152 name,
153 templateId: parsed.id || lastSegment(name),
154 organization,
155 organizationId: organizationIdOf(organization),
156 location: parsed.location || DEFAULT_LOCATION,
157 project,
158 displayName: template.displayName,
159 description: ownership.text,
160 inspectConfig: template.inspectConfig,
161 allowLimitedAvailabilityInfoTypes: template.allowLimitedAvailabilityInfoTypes === true,
162 createTime: template.createTime,
163 updateTime: template.updateTime,
164 };
165 };
166
167 const getByName = (name: string) =>
168 name.length === 0
169 ? Effect.undefined
170 : dlp
171 .getOrganizationsLocationsInspectTemplates({ name })
172 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
173
174 const listAt = (parent: string, organization: string, project: string) =>
175 dlp.listOrganizationsLocationsInspectTemplates.pages({ parent, pageSize: 100 }).pipe(
176 Stream.flatMap((page) => Stream.fromIterable(page.inspectTemplates ?? [])),
177 Stream.filter((template) => hasOwnershipMarker(template.description)),
178 Stream.map((template) => toAttrs(template, organization, project)),
179 Stream.runCollect,
180 Effect.map((chunk) => Array.from(chunk)),
181 Effect.catchTag("NotFound", () => Effect.succeed([])),
182 );
183
184 export const OrganizationsLocationsInspectTemplateProvider = () =>
185 Provider.succeed(OrganizationsLocationsInspectTemplate, {
186 stables: [
187 "name",
188 "templateId",
189 "organization",
190 "organizationId",
191 "location",
192 "project",
193 "createTime",
194 ],
195
196 diff: Effect.fn(function* ({ news, olds, output }) {
197 if (!isResolved(news)) return undefined;
198 const previousLocation = normalizeLocation(olds?.location ?? output?.location);
199 const nextLocation = normalizeLocation(news.location ?? olds?.location ?? output?.location);
200 return (
201 replaceOn(olds?.templateId ?? output?.templateId, news.templateId) ??
202 replaceOn(olds?.organization ?? output?.organization, news.organization) ??
203 replaceOn(previousLocation, nextLocation)
204 );
205 }),
206
207 read: Effect.fn(function* ({ id, olds, output }) {
208 const env = yield* GcpEnvironment.current;
209 const organization = yield* resolveOrganization(
210 olds?.organization ?? output?.organization,
211 output?.organization,
212 );
213 const location = normalizeLocation(olds?.location ?? output?.location);
214 const templateId = yield* toPhysicalId(id, olds?.templateId, output?.templateId);
215 const name = output?.name ?? resourceName(organization, location, templateId);
216 const existing = yield* getByName(name);
217 if (existing === undefined) return undefined;
218 const attrs = toAttrs(existing, organization, env.project);
219 return (yield* ownedByAlchemy(id, existing.description)) ? attrs : Unowned(attrs);
220 }),
221
222 list: () =>
223 Effect.gen(function* () {
224 const env = yield* GcpEnvironment.current;
225 const organization = yield* tryResolveOrganization();
226 if (organization === undefined) return [];
227 const pages = yield* Effect.forEach(
228 locationParentsOf(organization, env.region),
229 (parent) => listAt(parent, organization, env.project),
230 { concurrency: 3 },
231 );
232 return pages.flat();
233 }),
234
235 reconcile: Effect.fn(function* ({ id, news, output }) {
236 const env = yield* GcpEnvironment.current;
237 const organization = yield* resolveOrganization(news.organization, output?.organization);
238 const location = normalizeLocation(news.location ?? output?.location);
239 const templateId = yield* toPhysicalId(id, news.templateId, output?.templateId);
240 const parent = organizationLocationParent(organization, location);
241 const name = resourceName(organization, location, templateId);
242 const ownership = yield* createInternalLabels(id);
243 const description = encodeDescription(ownership, news.description);
244 const displayName = news.displayName;
245 const inspectConfig = news.inspectConfig;
246 const allowLimitedAvailabilityInfoTypes = news.allowLimitedAvailabilityInfoTypes === true;
247
248 let current = yield* getByName(output?.name ?? name);
249
250 if (current === undefined) {
251 const created = yield* dlp
252 .createOrganizationsLocationsInspectTemplates({
253 parent,
254 body: {
255 templateId,
256 inspectTemplate: {
257 displayName,
258 description,
259 inspectConfig,
260 allowLimitedAvailabilityInfoTypes,
261 },
262 },
263 })
264 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
265 current = created ?? undefined;
266 }
267
268 if (current === undefined) {
269 return yield* new DlpNotResolved({ resourceName: name });
270 }
271
272 const currentName = current.name ?? name;
273 const displayChanged = !sameText(current.displayName, displayName);
274 const descriptionChanged = !sameText(current.description, description);
275 const configChanged = fingerprint(current.inspectConfig) !== fingerprint(inspectConfig);
276 const limitedChanged =
277 (current.allowLimitedAvailabilityInfoTypes === true) !== allowLimitedAvailabilityInfoTypes;
278 const updateMask = updateMaskOf(
279 displayChanged ? "displayName" : undefined,
280 descriptionChanged ? "description" : undefined,
281 configChanged ? "inspectConfig" : undefined,
282 limitedChanged ? "allowLimitedAvailabilityInfoTypes" : undefined,
283 );
284
285 if (updateMask.length > 0) {
286 current = yield* dlp.patchOrganizationsLocationsInspectTemplates({
287 name: currentName,
288 body: {
289 updateMask,
290 inspectTemplate: {
291 displayName,
292 description,
293 inspectConfig,
294 allowLimitedAvailabilityInfoTypes,
295 },
296 },
297 });
298 }
299
300 return toAttrs(current, organization, env.project);
301 }),
302
303 delete: Effect.fn(function* ({ output }) {
304 yield* dlp
305 .deleteOrganizationsLocationsInspectTemplates({ name: output.name })
306 .pipe(Effect.catchTag("NotFound", () => Effect.void));
307 }),
308 });