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

main
ts 259 lines 8.84 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 DEFAULT_LOCATION,
13 collectPages,
14 encodeOwnership,
15 hasOwnershipMarker,
16 jsonEqual,
17 lastSegment,
18 locationOf,
19 locationParent,
20 normalizeLocation,
21 ownedByAlchemy,
22 parseOwnership,
23 projectOf,
24 replaceOnIdentity,
25 sameText,
26 toResourceId,
27 updateMaskOf,
28 } from "./internal.ts";
29
30 export type LocationsDeidentifyTemplateProps = {
31 /**
32 * Template id (the `{deidentifyTemplate}` segment of
33 * `projects/{project}/locations/{location}/deidentifyTemplates/{id}`).
34 * If omitted, a unique name is generated. Must match `[a-zA-Z0-9_-]+`
35 * and is at most 100 characters. Immutable — changing it replaces the
36 * template.
37 */
38 templateId?: string;
39 /**
40 * Processing location (`global`, `us`, `us-central1`, …). Immutable —
41 * changing it replaces the template.
42 * @default "global"
43 */
44 location?: string;
45 /**
46 * Display name (max 256 characters).
47 */
48 displayName?: string;
49 /**
50 * Human-readable description (max 256 characters). Deidentify templates
51 * have no labels field, so Alchemy ownership is stored in a
52 * `[alchemy …]` prefix and stripped from attributes.
53 */
54 description?: string;
55 /**
56 * De-identify configuration applied when this template is referenced.
57 */
58 deidentifyConfig?: dlp.GooglePrivacyDlpV2DeidentifyConfig;
59 };
60
61 export type LocationsDeidentifyTemplate = Resource<
62 "GCP.DLP.LocationsDeidentifyTemplate",
63 LocationsDeidentifyTemplateProps,
64 {
65 /** Full resource name. */
66 name: string;
67 /** Template id (last path segment). */
68 templateId: string;
69 /** Location id. */
70 location: string;
71 /** Project id. */
72 project: string;
73 /** Display name. */
74 displayName: string | undefined;
75 /** User description with the Alchemy ownership prefix stripped. */
76 description: string | undefined;
77 /** De-identify configuration. */
78 deidentifyConfig: dlp.GooglePrivacyDlpV2DeidentifyConfig | undefined;
79 /** RFC3339 creation timestamp. */
80 createTime: string | undefined;
81 /** RFC3339 last-update timestamp. */
82 updateTime: string | undefined;
83 },
84 never,
85 Providers
86 >;
87
88 /**
89 * A location-scoped Cloud DLP de-identify template.
90 *
91 * Templates have no labels field, so Alchemy stamps ownership into the
92 * description for `list` / nuke. Location and template id are identity —
93 * changing them replaces the template. Display name, description, and
94 * de-identify config update in place.
95 *
96 * ### Creating a Location Deidentify Template
97 * **Example:** Redact emails in `global`
98 * ```typescript
99 * const template = yield* GCP.DLP.LocationsDeidentifyTemplate("Emails", {
100 * location: "global",
101 * displayName: "redact emails",
102 * deidentifyConfig: {
103 * infoTypeTransformations: {
104 * transformations: [
105 * {
106 * infoTypes: [{ name: "EMAIL_ADDRESS" }],
107 * primitiveTransformation: { replaceWithInfoTypeConfig: {} },
108 * },
109 * ],
110 * },
111 * },
112 * });
113 * ```
114 *
115 * @resource
116 * @category DLP
117 */
118 export const LocationsDeidentifyTemplate = Resource<LocationsDeidentifyTemplate>(
119 "GCP.DLP.LocationsDeidentifyTemplate",
120 );
121
122 export class LocationsDeidentifyTemplateNotResolved extends Data.TaggedError(
123 "GCP.DLP.LocationsDeidentifyTemplateNotResolved",
124 )<{
125 resourceName: string;
126 }> {}
127
128 const resourceName = (project: string, location: string, templateId: string) =>
129 `${locationParent(project, location)}/deidentifyTemplates/${templateId}`;
130
131 const toAttrs = (template: dlp.GooglePrivacyDlpV2DeidentifyTemplate, project: string) => {
132 const name = template.name ?? "";
133 const parsed = parseOwnership(template.description);
134 return {
135 name,
136 templateId: lastSegment(name),
137 location: locationOf(name),
138 project: projectOf(name) || project,
139 displayName: template.displayName,
140 description: parsed.text,
141 deidentifyConfig: template.deidentifyConfig,
142 createTime: template.createTime,
143 updateTime: template.updateTime,
144 };
145 };
146
147 const getByName = (name: string) =>
148 name.length === 0
149 ? Effect.undefined
150 : dlp
151 .getProjectsLocationsDeidentifyTemplates({ name })
152 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
153
154 export const LocationsDeidentifyTemplateProvider = () =>
155 Provider.succeed(LocationsDeidentifyTemplate, {
156 stables: ["name", "templateId", "location", "project", "createTime"],
157
158 diff: Effect.fn(function* ({ news, olds, output }) {
159 if (!isResolved(news)) return undefined;
160 const previousId = olds?.templateId ?? output?.templateId;
161 const idChanged =
162 previousId !== undefined && news.templateId !== undefined && news.templateId !== previousId;
163 const previousLocation = olds?.location ?? output?.location;
164 const locationChanged =
165 previousLocation !== undefined &&
166 news.location !== undefined &&
167 normalizeLocation(news.location) !== normalizeLocation(previousLocation);
168 return replaceOnIdentity(idChanged || locationChanged);
169 }),
170
171 read: Effect.fn(function* ({ id, olds, output }) {
172 const env = yield* GcpEnvironment.current;
173 const templateId = yield* toResourceId(id, olds?.templateId, output?.templateId);
174 const location = normalizeLocation(olds?.location ?? output?.location);
175 const name = output?.name ?? resourceName(env.project, location, templateId);
176 const existing = yield* getByName(name);
177 if (existing === undefined) return undefined;
178 const attrs = toAttrs(existing, env.project);
179 return (yield* ownedByAlchemy(id, existing.description)) ? attrs : Unowned(attrs);
180 }),
181
182 list: () =>
183 Effect.gen(function* () {
184 const env = yield* GcpEnvironment.current;
185 const items = yield* collectPages(
186 dlp.listProjectsLocationsDeidentifyTemplates.pages({
187 parent: locationParent(env.project, DEFAULT_LOCATION),
188 pageSize: 100,
189 }),
190 (page) => page.deidentifyTemplates,
191 ).pipe(
192 Effect.catchTag("NotFound", () =>
193 Effect.succeed([] as dlp.GooglePrivacyDlpV2DeidentifyTemplate[]),
194 ),
195 );
196 return items
197 .filter((template) => hasOwnershipMarker(template.description))
198 .map((template) => toAttrs(template, env.project));
199 }),
200
201 reconcile: Effect.fn(function* ({ id, news, output }) {
202 const env = yield* GcpEnvironment.current;
203 const location = normalizeLocation(news.location ?? output?.location ?? DEFAULT_LOCATION);
204 const templateId = yield* toResourceId(id, news.templateId, output?.templateId);
205 const name = resourceName(env.project, location, templateId);
206 const ownership = yield* createInternalLabels(id);
207 const description = encodeOwnership(ownership, news.description);
208 const body: dlp.GooglePrivacyDlpV2DeidentifyTemplate = {
209 displayName: news.displayName,
210 description,
211 deidentifyConfig: news.deidentifyConfig,
212 };
213
214 let current = yield* getByName(output?.name ?? name);
215
216 if (current === undefined) {
217 const created = yield* dlp
218 .createProjectsLocationsDeidentifyTemplates({
219 parent: locationParent(env.project, location),
220 body: {
221 templateId,
222 deidentifyTemplate: body,
223 },
224 })
225 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
226 current = created ?? undefined;
227 }
228
229 if (current === undefined) {
230 return yield* new LocationsDeidentifyTemplateNotResolved({ resourceName: name });
231 }
232
233 const displayChanged = !sameText(current.displayName, news.displayName);
234 const descriptionChanged = (current.description ?? "") !== description;
235 const configChanged = !jsonEqual(current.deidentifyConfig, news.deidentifyConfig);
236
237 if (displayChanged || descriptionChanged || configChanged) {
238 current = yield* dlp.patchProjectsLocationsDeidentifyTemplates({
239 name: current.name ?? name,
240 body: {
241 deidentifyTemplate: body,
242 updateMask: updateMaskOf(
243 displayChanged ? "displayName" : undefined,
244 descriptionChanged ? "description" : undefined,
245 configChanged ? "deidentifyConfig" : undefined,
246 ),
247 },
248 });
249 }
250
251 return toAttrs(current, env.project);
252 }),
253
254 delete: Effect.fn(function* ({ output }) {
255 yield* dlp
256 .deleteProjectsLocationsDeidentifyTemplates({ name: output.name })
257 .pipe(Effect.catchTag("NotFound", () => Effect.void));
258 }),
259 });