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

main
ts 286 lines 10 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 Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import { GcpEnvironment } from "../Environment.ts";
9 import { createInternalLabels } from "../Labels.ts";
10 import type { Providers } from "../Providers.ts";
11 import {
12 collectPages,
13 encodeOwnership,
14 hasOwnershipMarker,
15 jsonEqual,
16 lastSegment,
17 locationOf,
18 locationParent,
19 normalizeLocation,
20 ownedByAlchemy,
21 parseOwnership,
22 replaceOnIdentity,
23 toResourceId,
24 updateMaskOf,
25 } from "./internal.ts";
26
27 type InspectConfig = dlp.GooglePrivacyDlpV2InspectConfig;
28
29 export type LocationsInspectTemplateProps = {
30 /**
31 * Template id (the `{inspectTemplate}` segment of
32 * `projects/{project}/locations/{location}/inspectTemplates/{inspectTemplate}`).
33 * If omitted, a unique name is generated. Must match `[a-zA-Z0-9_-]+` and
34 * is at most 100 characters. Immutable — changing it replaces the
35 * template.
36 */
37 templateId?: string;
38 /**
39 * Processing location (`us-central1`, `global`, …). Immutable —
40 * changing it replaces the template.
41 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
42 */
43 location?: string;
44 /**
45 * Display name (max 256 characters).
46 */
47 displayName?: string;
48 /**
49 * Human-readable description (max 256 characters). Inspect templates
50 * have no labels field, so Alchemy ownership is stored in a
51 * `[alchemy …]` prefix and stripped from attributes.
52 */
53 description?: string;
54 /**
55 * Inspection configuration (info types, likelihood, quotes, limits).
56 */
57 inspectConfig?: InspectConfig;
58 /**
59 * Allow limited-availability built-in info types in `inspectConfig`.
60 * @default false
61 */
62 allowLimitedAvailabilityInfoTypes?: boolean;
63 };
64
65 export type LocationsInspectTemplate = Resource<
66 "GCP.DLP.LocationsInspectTemplate",
67 LocationsInspectTemplateProps,
68 {
69 /** Full resource name `projects/{project}/locations/{location}/inspectTemplates/{id}`. */
70 name: string;
71 /** Template id (last path segment). */
72 templateId: string;
73 /** Location id. */
74 location: string;
75 /** Project id. */
76 project: string;
77 /** Display name. */
78 displayName: string | undefined;
79 /** User description with the Alchemy ownership prefix stripped. */
80 description: string | undefined;
81 /** Inspection configuration. */
82 inspectConfig: InspectConfig | undefined;
83 /** Whether limited-availability info types are allowed. */
84 allowLimitedAvailabilityInfoTypes: boolean;
85 /** RFC3339 creation timestamp. */
86 createTime: string | undefined;
87 /** RFC3339 last-update timestamp. */
88 updateTime: string | undefined;
89 },
90 never,
91 Providers
92 >;
93
94 /**
95 * A regional Cloud DLP inspect template
96 * (`projects.locations.inspectTemplates`).
97 *
98 * Inspect templates have no labels field, so Alchemy stamps ownership
99 * into the description for `list` / nuke. Location and id are identity —
100 * changing them replaces the template. Display name, description, and
101 * inspect config update in place.
102 *
103 * ### Creating an Inspect Template
104 * **Example:** Email detector
105 * ```typescript
106 * const template = yield* GCP.DLP.LocationsInspectTemplate("Email", {
107 * displayName: "email",
108 * description: "detect email addresses",
109 * inspectConfig: { infoTypes: [{ name: "EMAIL_ADDRESS" }] },
110 * });
111 * ```
112 *
113 * ### Updating an Inspect Template
114 * **Example:** Raise the likelihood threshold
115 * ```typescript
116 * const template = yield* GCP.DLP.LocationsInspectTemplate("Email", {
117 * displayName: "email",
118 * description: "detect email addresses v2",
119 * inspectConfig: {
120 * infoTypes: [{ name: "EMAIL_ADDRESS" }],
121 * minLikelihood: "LIKELY",
122 * includeQuote: true,
123 * },
124 * });
125 * ```
126 *
127 * @resource
128 * @category DLP
129 */
130 export const LocationsInspectTemplate = Resource<LocationsInspectTemplate>(
131 "GCP.DLP.LocationsInspectTemplate",
132 );
133
134 export class LocationsInspectTemplateNotResolved extends Data.TaggedError(
135 "GCP.DLP.LocationsInspectTemplateNotResolved",
136 )<{
137 resourceName: string;
138 }> {}
139
140 const resourceName = (project: string, location: string, templateId: string) =>
141 `${locationParent(project, location)}/inspectTemplates/${templateId}`;
142
143 const toAttrs = (
144 template: dlp.GooglePrivacyDlpV2InspectTemplate,
145 project: string,
146 region: string,
147 ) => {
148 const name = template.name ?? "";
149 const parsed = parseOwnership(template.description);
150 return {
151 name,
152 templateId: lastSegment(name),
153 location: locationOf(name, region),
154 project,
155 displayName: template.displayName,
156 description: parsed.text,
157 inspectConfig: template.inspectConfig,
158 allowLimitedAvailabilityInfoTypes: template.allowLimitedAvailabilityInfoTypes === true,
159 createTime: template.createTime,
160 updateTime: template.updateTime,
161 };
162 };
163
164 const getByName = (name: string) =>
165 name.length === 0
166 ? Effect.undefined
167 : dlp
168 .getProjectsLocationsInspectTemplates({ name })
169 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
170
171 export const LocationsInspectTemplateProvider = () =>
172 Provider.succeed(LocationsInspectTemplate, {
173 stables: ["name", "templateId", "location", "project", "createTime"],
174
175 diff: Effect.fn(function* ({ news, olds, output }) {
176 if (!isResolved(news)) return undefined;
177 const env = yield* GcpEnvironment.current;
178 const previousId = olds?.templateId ?? output?.templateId;
179 const idChanged =
180 previousId !== undefined && news.templateId !== undefined && news.templateId !== previousId;
181 const previousLocation = olds?.location ?? output?.location;
182 const locationChanged =
183 previousLocation !== undefined &&
184 normalizeLocation(news.location ?? previousLocation, env.region) !==
185 normalizeLocation(previousLocation, env.region);
186 return replaceOnIdentity(idChanged || locationChanged);
187 }),
188
189 read: Effect.fn(function* ({ id, olds, output }) {
190 const env = yield* GcpEnvironment.current;
191 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
192 const templateId = yield* toResourceId(id, olds?.templateId, output?.templateId);
193 const name = output?.name ?? resourceName(env.project, location, templateId);
194 const existing = yield* getByName(name);
195 if (existing === undefined) return undefined;
196 const attrs = toAttrs(existing, env.project, env.region);
197 return (yield* ownedByAlchemy(id, existing.description)) ? attrs : Unowned(attrs);
198 }),
199
200 list: () =>
201 Effect.gen(function* () {
202 const env = yield* GcpEnvironment.current;
203 const items = yield* collectPages(
204 dlp.listProjectsLocationsInspectTemplates.pages({
205 parent: locationParent(env.project, env.region),
206 pageSize: 100,
207 }),
208 (page) => page.inspectTemplates,
209 ).pipe(
210 Effect.catchTag("NotFound", () =>
211 Effect.succeed([] as dlp.GooglePrivacyDlpV2InspectTemplate[]),
212 ),
213 );
214 return items
215 .filter((template) => hasOwnershipMarker(template.description))
216 .map((template) => toAttrs(template, env.project, env.region));
217 }),
218
219 reconcile: Effect.fn(function* ({ id, news, output }) {
220 const env = yield* GcpEnvironment.current;
221 const location = normalizeLocation(news.location ?? output?.location, env.region);
222 const templateId = yield* toResourceId(id, news.templateId, output?.templateId);
223 const name = resourceName(env.project, location, templateId);
224 const ownership = yield* createInternalLabels(id);
225 const description = encodeOwnership(ownership, news.description);
226 const allowLimitedAvailabilityInfoTypes = news.allowLimitedAvailabilityInfoTypes === true;
227
228 let current = yield* getByName(output?.name ?? name);
229
230 if (current === undefined) {
231 const created = yield* dlp
232 .createProjectsLocationsInspectTemplates({
233 parent: locationParent(env.project, location),
234 body: {
235 templateId,
236 inspectTemplate: {
237 displayName: news.displayName,
238 description,
239 inspectConfig: news.inspectConfig,
240 allowLimitedAvailabilityInfoTypes,
241 },
242 },
243 })
244 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
245 current = created ?? undefined;
246 }
247
248 if (current === undefined) {
249 return yield* new LocationsInspectTemplateNotResolved({ resourceName: name });
250 }
251
252 const displayChanged = !jsonEqual(current.displayName, news.displayName);
253 const descriptionChanged = (current.description ?? "") !== description;
254 const configChanged = !jsonEqual(current.inspectConfig, news.inspectConfig);
255 const limitedChanged =
256 (current.allowLimitedAvailabilityInfoTypes === true) !== allowLimitedAvailabilityInfoTypes;
257
258 if (displayChanged || descriptionChanged || configChanged || limitedChanged) {
259 current = yield* dlp.patchProjectsLocationsInspectTemplates({
260 name: current.name ?? name,
261 body: {
262 updateMask: updateMaskOf(
263 displayChanged ? "displayName" : undefined,
264 descriptionChanged ? "description" : undefined,
265 configChanged ? "inspectConfig" : undefined,
266 limitedChanged ? "allowLimitedAvailabilityInfoTypes" : undefined,
267 ),
268 inspectTemplate: {
269 displayName: news.displayName,
270 description,
271 inspectConfig: news.inspectConfig,
272 allowLimitedAvailabilityInfoTypes,
273 },
274 },
275 });
276 }
277
278 return toAttrs(current, env.project, env.region);
279 }),
280
281 delete: Effect.fn(function* ({ output }) {
282 yield* dlp
283 .deleteProjectsLocationsInspectTemplates({ name: output.name })
284 .pipe(Effect.catchTag("NotFound", () => Effect.void));
285 }),
286 });