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

main
ts 333 lines 11.6 KB
Raw
1 import * as healthcare from "@distilled.cloud/gcp/healthcare_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 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 expandParent,
15 hasOwnershipMarker,
16 listAlchemyConsentStores,
17 normalizeLocation,
18 ownedByAlchemy,
19 parseOwnership,
20 parseResourceName,
21 replaceOnIdentity,
22 retryTransient,
23 sameJson,
24 sameText,
25 toPhysicalSnake,
26 updateMaskOf,
27 waitUntilGone,
28 } from "./internal.ts";
29
30 export type DatasetsConsentStoresAttributeDefinitionProps = {
31 /**
32 * Parent consent store. Full name
33 * `.../consentStores/{consentStore}` or the store id (combined with
34 * `dataset` and `location`). Immutable — changing it replaces the
35 * definition.
36 */
37 consentStore: string;
38 /**
39 * Parent dataset used when `consentStore` is a bare id.
40 */
41 dataset?: string;
42 /**
43 * Region used when `consentStore` is a bare id.
44 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
45 */
46 location?: string;
47 /**
48 * Attribute definition id. Must match letters, digits, and
49 * underscores; cannot be a CEL reserved keyword. Immutable — changing
50 * it replaces the definition.
51 */
52 attributeDefinitionId?: string;
53 /**
54 * Attribute category. Immutable — changing it replaces the definition.
55 */
56 category: healthcare.AttributeDefinitionCategoryEnum | (string & {});
57 /**
58 * Allowed values. The list can only be expanded after creation.
59 */
60 allowedValues: string[];
61 /**
62 * Human-readable description. Attribute definitions have no labels
63 * field, so Alchemy ownership is stored in a `[alchemy …]` prefix and
64 * stripped from attributes.
65 */
66 description?: string;
67 /**
68 * Default values applied to Consents that omit this attribute.
69 */
70 consentDefaultValues?: string[];
71 /**
72 * Default value applied to User data mappings (RESOURCE category).
73 */
74 dataMappingDefaultValue?: string;
75 };
76
77 export type DatasetsConsentStoresAttributeDefinition = Resource<
78 "GCP.Healthcare.DatasetsConsentStoresAttributeDefinition",
79 DatasetsConsentStoresAttributeDefinitionProps,
80 {
81 /** Full resource name `.../attributeDefinitions/{attributeDefinition}`. */
82 name: string;
83 /** Attribute definition id. */
84 attributeDefinitionId: string;
85 /** Parent consent store resource name. */
86 consentStore: string;
87 /** Project id. */
88 project: string;
89 /** Location id. */
90 location: string;
91 /** Attribute category. */
92 category: string;
93 /** Allowed values. */
94 allowedValues: string[];
95 /** Description with the Alchemy ownership prefix stripped. */
96 description: string | undefined;
97 /** Default Consent values. */
98 consentDefaultValues: string[] | undefined;
99 /** Default User data mapping value. */
100 dataMappingDefaultValue: string | undefined;
101 },
102 never,
103 Providers
104 >;
105
106 /**
107 * A client-defined consent attribute in a consent store.
108 *
109 * Consent store, id, and category are immutable. Allowed values can only
110 * grow. Description, consent defaults, and data-mapping default update
111 * in place. Ownership is stamped into `description`.
112 *
113 * ### Creating an Attribute Definition
114 * **Example:** Resource attribute
115 * ```typescript
116 * const attr = yield* GCP.Healthcare.DatasetsConsentStoresAttributeDefinition(
117 * "DataType",
118 * {
119 * consentStore: store.name,
120 * category: "RESOURCE",
121 * allowedValues: ["fhir", "dicom"],
122 * description: "data modality",
123 * },
124 * );
125 * ```
126 *
127 * @resource
128 * @category Healthcare
129 */
130 export const DatasetsConsentStoresAttributeDefinition =
131 Resource<DatasetsConsentStoresAttributeDefinition>(
132 "GCP.Healthcare.DatasetsConsentStoresAttributeDefinition",
133 );
134
135 export class DatasetsConsentStoresAttributeDefinitionNotResolved extends Data.TaggedError(
136 "GCP.Healthcare.DatasetsConsentStoresAttributeDefinitionNotResolved",
137 )<{
138 resourceName: string;
139 }> {}
140
141 const storeOf = (
142 consentStore: string,
143 project: string,
144 location: string,
145 dataset: string | undefined,
146 ) => {
147 if (consentStore.includes("/")) return consentStore.replace(/\/+$/, "");
148 if (dataset === undefined) {
149 return expandParent(consentStore, project, location, "consentStores");
150 }
151 const datasetName = expandParent(dataset, project, location, "datasets");
152 return `${datasetName}/consentStores/${consentStore}`;
153 };
154
155 const resourceName = (consentStore: string, attributeDefinitionId: string) =>
156 `${consentStore}/attributeDefinitions/${attributeDefinitionId}`;
157
158 const toAttrs = (definition: healthcare.AttributeDefinition, project: string, region: string) => {
159 const name = definition.name ?? "";
160 const parsed = parseResourceName(name, "attributeDefinitions", region);
161 const ownership = parseOwnership(definition.description);
162 return {
163 name,
164 attributeDefinitionId: parsed.id,
165 consentStore: parsed.parent,
166 project: parsed.project || project,
167 location: parsed.location,
168 category: definition.category ?? "CATEGORY_UNSPECIFIED",
169 allowedValues: definition.allowedValues ?? [],
170 description: ownership.text,
171 consentDefaultValues: definition.consentDefaultValues,
172 dataMappingDefaultValue: definition.dataMappingDefaultValue,
173 };
174 };
175
176 const getByName = (name: string) =>
177 name.length === 0
178 ? Effect.undefined
179 : healthcare
180 .getProjectsLocationsDatasetsConsentStoresAttributeDefinitions({
181 name,
182 })
183 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
184
185 export const DatasetsConsentStoresAttributeDefinitionProvider = () =>
186 Provider.succeed(DatasetsConsentStoresAttributeDefinition, {
187 stables: ["name", "attributeDefinitionId", "consentStore", "project", "location", "category"],
188
189 diff: Effect.fn(function* ({ news, olds, output }) {
190 if (!isResolved(news)) return undefined;
191 const env = yield* GcpEnvironment.current;
192 const previousCategory = olds?.category ?? output?.category;
193 const extra = previousCategory !== undefined && previousCategory !== news.category;
194 return replaceOnIdentity({
195 previousId: olds?.attributeDefinitionId ?? output?.attributeDefinitionId,
196 nextId: news.attributeDefinitionId,
197 previousParent: olds?.consentStore ?? output?.consentStore,
198 nextParent: storeOf(
199 news.consentStore,
200 env.project,
201 normalizeLocation(news.location ?? output?.location, env.region),
202 news.dataset,
203 ),
204 extra,
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 attributeDefinitionId = yield* toPhysicalSnake(
212 id,
213 olds?.attributeDefinitionId,
214 output?.attributeDefinitionId,
215 );
216 const consentStore =
217 olds?.consentStore !== undefined
218 ? storeOf(olds.consentStore, env.project, location, olds.dataset)
219 : (output?.consentStore ?? "");
220 const name =
221 output?.name ??
222 (consentStore.length > 0 ? resourceName(consentStore, attributeDefinitionId) : "");
223 const existing = yield* getByName(name);
224 if (existing === undefined) return undefined;
225 const attrs = toAttrs(existing, env.project, env.region);
226 return (yield* ownedByAlchemy(id, existing.description)) ? attrs : Unowned(attrs);
227 }),
228
229 list: () =>
230 Effect.gen(function* () {
231 const env = yield* GcpEnvironment.current;
232 const stores = yield* listAlchemyConsentStores(env.project, env.region);
233 const definitions = yield* Effect.forEach(
234 stores,
235 (store) =>
236 collectPages(
237 healthcare.listProjectsLocationsDatasetsConsentStoresAttributeDefinitions.pages({
238 parent: store.name ?? "",
239 pageSize: 1000,
240 }),
241 (page) => page.attributeDefinitions,
242 ),
243 { concurrency: 4 },
244 );
245 return definitions
246 .flat()
247 .filter((definition) => hasOwnershipMarker(definition.description))
248 .map((definition) => toAttrs(definition, env.project, env.region));
249 }),
250
251 reconcile: Effect.fn(function* ({ id, news, output }) {
252 const env = yield* GcpEnvironment.current;
253 const location = normalizeLocation(news.location ?? output?.location, env.region);
254 const consentStore = storeOf(news.consentStore, env.project, location, news.dataset);
255 const attributeDefinitionId = yield* toPhysicalSnake(
256 id,
257 news.attributeDefinitionId,
258 output?.attributeDefinitionId,
259 );
260 const name = output?.name ?? resourceName(consentStore, attributeDefinitionId);
261 const ownership = yield* createInternalLabels(id);
262 const description = encodeOwnership(ownership, news.description);
263
264 let current = yield* getByName(name);
265
266 if (current === undefined) {
267 const created = yield* retryTransient(
268 healthcare.createProjectsLocationsDatasetsConsentStoresAttributeDefinitions({
269 parent: consentStore,
270 attributeDefinitionId,
271 body: {
272 category: news.category,
273 allowedValues: news.allowedValues,
274 description,
275 consentDefaultValues: news.consentDefaultValues,
276 dataMappingDefaultValue: news.dataMappingDefaultValue,
277 },
278 }),
279 ).pipe(Effect.catchTag("Conflict", () => getByName(name)));
280 current = created ?? undefined;
281 }
282
283 if (current === undefined) {
284 return yield* new DatasetsConsentStoresAttributeDefinitionNotResolved({
285 resourceName: name,
286 });
287 }
288
289 const currentName = current.name ?? name;
290 const descriptionChanged = !sameText(current.description, description);
291 const allowedChanged = !sameJson(current.allowedValues, news.allowedValues);
292 const consentDefaultChanged = !sameJson(
293 current.consentDefaultValues,
294 news.consentDefaultValues,
295 );
296 const mappingDefaultChanged = !sameText(
297 current.dataMappingDefaultValue,
298 news.dataMappingDefaultValue,
299 );
300
301 if (descriptionChanged || allowedChanged || consentDefaultChanged || mappingDefaultChanged) {
302 current = yield* retryTransient(
303 healthcare.patchProjectsLocationsDatasetsConsentStoresAttributeDefinitions({
304 name: currentName,
305 updateMask: updateMaskOf(
306 descriptionChanged ? "description" : undefined,
307 allowedChanged ? "allowedValues" : undefined,
308 consentDefaultChanged ? "consentDefaultValues" : undefined,
309 mappingDefaultChanged ? "dataMappingDefaultValue" : undefined,
310 ),
311 body: {
312 description,
313 allowedValues: news.allowedValues,
314 consentDefaultValues: news.consentDefaultValues,
315 dataMappingDefaultValue: news.dataMappingDefaultValue,
316 },
317 }),
318 );
319 }
320
321 return toAttrs(current, env.project, env.region);
322 }),
323
324 delete: Effect.fn(function* ({ output }) {
325 if (!output.name) return;
326 yield* retryTransient(
327 healthcare.deleteProjectsLocationsDatasetsConsentStoresAttributeDefinitions({
328 name: output.name,
329 }),
330 ).pipe(Effect.catchTag("NotFound", () => Effect.void));
331 yield* waitUntilGone(getByName(output.name), output.name);
332 }),
333 });