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

main
ts 295 lines 9.72 KB
Raw
1 import * as datacatalog from "@distilled.cloud/gcp/datacatalog_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 * as Schedule from "effect/Schedule";
8 import { GcpEnvironment } from "../Environment.ts";
9 import { isTransientGcpError } from "../Errors.ts";
10 import { createInternalLabels } from "../Labels.ts";
11 import type { Providers } from "../Providers.ts";
12 import {
13 DatacatalogNotResolved,
14 collectPages,
15 emptyOnMissing,
16 encodeOwnership,
17 findOwned,
18 hasOwnershipMarker,
19 ignoreGone,
20 listAtLocation,
21 locationParent,
22 missingGet,
23 normalizeLocation,
24 ownedByAlchemy,
25 parseName,
26 parseOwnership,
27 replaceOnIdentity,
28 retryTransient,
29 sameStringList,
30 sameText,
31 toDisplayName,
32 updateMaskOf,
33 type TaxonomyActivatedPolicyType,
34 } from "./internal.ts";
35
36 export type { TaxonomyActivatedPolicyType };
37
38 export type TaxonomyProps = {
39 /**
40 * Region (`us-central1`, `us`, …). Immutable — changing it replaces
41 * the taxonomy. Policy Tag Manager assigns the taxonomy id; it is not
42 * chosen by the caller.
43 * @default the stack's GCP region (`GCP.Region`, profile region, `us-central1`)
44 */
45 location?: string;
46 /**
47 * User-defined display name. Unique within an organization. Letters,
48 * numbers, underscores, dashes, and spaces; max 200 bytes. If omitted,
49 * a unique name is generated from the stack, stage, and logical id.
50 */
51 displayName?: string;
52 /**
53 * Human-readable description (max 2000 bytes). Taxonomies have no
54 * labels field, so Alchemy ownership is stored in a `[alchemy …]`
55 * prefix and stripped from attributes.
56 */
57 description?: string;
58 /**
59 * Policy types activated on this taxonomy
60 * (`FINE_GRAINED_ACCESS_CONTROL`).
61 */
62 activatedPolicyTypes?: TaxonomyActivatedPolicyType[];
63 };
64
65 export type Taxonomy = Resource<
66 "GCP.DataCatalog.Taxonomy",
67 TaxonomyProps,
68 {
69 /** Full resource name. */
70 name: string;
71 /** Server-assigned taxonomy id (last path segment). */
72 taxonomyId: string;
73 /** Project id. */
74 project: string;
75 /** Location id. */
76 location: string;
77 /** Display name. */
78 displayName: string | undefined;
79 /** User description (Alchemy ownership marker stripped). */
80 description: string | undefined;
81 /** Activated policy types. */
82 activatedPolicyTypes: string[];
83 /** Number of policy tags in this taxonomy. */
84 policyTagCount: number | undefined;
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 Data Catalog taxonomy — a hierarchy of policy tags used to classify
96 * data (for example PII vs financials).
97 *
98 * Taxonomy ids are assigned by Policy Tag Manager. Location is
99 * immutable. Display name, description, and activated policy types
100 * update in place. Taxonomies have no labels; Alchemy stamps
101 * `alchemy-stack` / `alchemy-stage` / `alchemy-id` into the description
102 * so `list` and `pnpm nuke:gcp` can identify owned taxonomies.
103 *
104 * ### Creating a Taxonomy
105 * **Example:** Generated display name
106 * ```typescript
107 * const taxonomy = yield* GCP.DataCatalog.Taxonomy("Pii", {
108 * description: "sensitivity classes",
109 * });
110 * ```
111 *
112 * **Example:** Fine-grained access control
113 * ```typescript
114 * const taxonomy = yield* GCP.DataCatalog.Taxonomy("Pii", {
115 * displayName: "PII",
116 * activatedPolicyTypes: ["FINE_GRAINED_ACCESS_CONTROL"],
117 * });
118 * ```
119 *
120 * ### Updating a Taxonomy
121 * **Example:** Description
122 * ```typescript
123 * // Same logical id, changed props: the engine updates it in place.
124 * const taxonomy = yield* GCP.DataCatalog.Taxonomy("Pii", {
125 * displayName: "PII",
126 * description: "sensitivity classes v2",
127 * activatedPolicyTypes: ["FINE_GRAINED_ACCESS_CONTROL"],
128 * });
129 * ```
130 *
131 * @resource
132 * @category DataCatalog
133 */
134 export const Taxonomy = Resource<Taxonomy>("GCP.DataCatalog.Taxonomy");
135
136 const toAttrs = (
137 taxonomy: datacatalog.GoogleCloudDatacatalogV1Taxonomy,
138 project: string,
139 region: string,
140 ) => {
141 const name = taxonomy.name ?? "";
142 const parsed = parseName(name, "taxonomies", region);
143 const ownership = parseOwnership(taxonomy.description);
144 return {
145 name,
146 taxonomyId: parsed.id,
147 project: parsed.project || project,
148 location: parsed.location,
149 displayName: taxonomy.displayName,
150 description: ownership.text,
151 activatedPolicyTypes: [...(taxonomy.activatedPolicyTypes ?? [])],
152 policyTagCount: taxonomy.policyTagCount,
153 createTime: taxonomy.taxonomyTimestamps?.createTime,
154 updateTime: taxonomy.taxonomyTimestamps?.updateTime,
155 };
156 };
157
158 const getByName = missingGet(datacatalog.getProjectsLocationsTaxonomies);
159
160 const listTaxonomiesAt = (
161 parent: string,
162 ): Effect.Effect<
163 datacatalog.GoogleCloudDatacatalogV1Taxonomy[],
164 datacatalog.ListProjectsLocationsTaxonomiesError,
165 datacatalog.GcpOpContext
166 > =>
167 emptyOnMissing(
168 collectPages(
169 datacatalog.listProjectsLocationsTaxonomies.pages({
170 parent,
171 pageSize: 1000,
172 }),
173 (page) => page.taxonomies,
174 ),
175 );
176
177 const listOwned = (project: string, region: string) =>
178 listAtLocation(project, region, listTaxonomiesAt).pipe(
179 Effect.map((items) => items.filter((item) => hasOwnershipMarker(item.description))),
180 );
181
182 const observe = (id: string, name: string | undefined, project: string, location: string) =>
183 Effect.gen(function* () {
184 if (name !== undefined && name.length > 0) {
185 const existing = yield* getByName(name);
186 if (existing !== undefined) return existing;
187 }
188 const candidates = yield* listTaxonomiesAt(locationParent(project, location));
189 return yield* findOwned(candidates, id, (item) => item.description);
190 });
191
192 export const TaxonomyProvider = () =>
193 Provider.succeed(Taxonomy, {
194 stables: ["name", "taxonomyId", "project", "location", "createTime"],
195
196 diff: Effect.fn(function* ({ news, olds, output }) {
197 if (!isResolved(news)) return undefined;
198 const env = yield* GcpEnvironment.current;
199 return replaceOnIdentity({
200 previousLocation: normalizeLocation(olds?.location ?? output?.location, env.region),
201 nextLocation: normalizeLocation(
202 news.location ?? olds?.location ?? output?.location,
203 env.region,
204 ),
205 });
206 }),
207
208 read: Effect.fn(function* ({ id, olds, output }) {
209 const env = yield* GcpEnvironment.current;
210 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
211 const existing = yield* observe(id, output?.name, env.project, location);
212 if (existing === undefined) return undefined;
213 const attrs = toAttrs(existing, env.project, env.region);
214 return (yield* ownedByAlchemy(id, existing.description)) ? attrs : Unowned(attrs);
215 }),
216
217 list: () =>
218 Effect.gen(function* () {
219 const env = yield* GcpEnvironment.current;
220 const items = yield* listOwned(env.project, env.region);
221 return items.map((item) => toAttrs(item, env.project, env.region));
222 }),
223
224 reconcile: Effect.fn(function* ({ id, news, output }) {
225 const env = yield* GcpEnvironment.current;
226 const location = normalizeLocation(news.location ?? output?.location, env.region);
227 const parent = locationParent(env.project, location);
228 const ownership = yield* createInternalLabels(id);
229 const description = encodeOwnership(ownership, news.description);
230 const displayName = yield* toDisplayName(id, news.displayName, output?.displayName);
231 const activatedPolicyTypes = news.activatedPolicyTypes;
232
233 let current = yield* observe(id, output?.name, env.project, location);
234
235 if (current === undefined) {
236 const created = yield* retryTransient(
237 datacatalog.createProjectsLocationsTaxonomies({
238 parent,
239 body: {
240 displayName,
241 description,
242 activatedPolicyTypes,
243 },
244 }),
245 ).pipe(Effect.catchTag("Conflict", () => Effect.undefined));
246 current = created ?? (yield* observe(id, undefined, env.project, location));
247 }
248
249 if (current === undefined) {
250 return yield* new DatacatalogNotResolved({
251 resourceName: output?.name ?? `${parent}/taxonomies`,
252 });
253 }
254
255 const currentName = current.name ?? output?.name ?? "";
256 const displayChanged = !sameText(current.displayName, displayName);
257 const descriptionChanged = (current.description ?? "") !== description;
258 const policyChanged =
259 activatedPolicyTypes !== undefined &&
260 !sameStringList(current.activatedPolicyTypes, activatedPolicyTypes);
261
262 if (displayChanged || descriptionChanged || policyChanged) {
263 current = yield* retryTransient(
264 datacatalog.patchProjectsLocationsTaxonomies({
265 name: currentName,
266 updateMask: updateMaskOf(
267 displayChanged ? "display_name" : undefined,
268 descriptionChanged ? "description" : undefined,
269 policyChanged ? "activated_policy_types" : undefined,
270 ),
271 body: {
272 name: currentName,
273 displayName,
274 description,
275 activatedPolicyTypes,
276 },
277 }),
278 );
279 }
280
281 return toAttrs(current, env.project, env.region);
282 }),
283
284 delete: Effect.fn(function* ({ output }) {
285 yield* ignoreGone(
286 datacatalog.deleteProjectsLocationsTaxonomies({ name: output.name }).pipe(
287 Effect.retry({
288 while: (error) => error._tag === "Conflict" || isTransientGcpError(error),
289 times: 8,
290 schedule: Schedule.exponential("500 millis"),
291 }),
292 ),
293 );
294 }),
295 });