@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 279 lines 9.47 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 { tagRecord } from "alchemy/Tags";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import { GcpEnvironment } from "../Environment.ts";
10 import { createInternalLabels, diffLabels, hasAlchemyLabels, toLabels } from "../Labels.ts";
11 import type { Providers } from "../Providers.ts";
12 import {
13 collectPages,
14 expandParent,
15 forEachDataset,
16 hasAlchemyLabelMap,
17 normalizeLocation,
18 parseResourceName,
19 replaceOnIdentity,
20 retryTransient,
21 sameText,
22 toPhysicalId,
23 updateMaskOf,
24 userLabels,
25 waitUntilGone,
26 } from "./internal.ts";
27
28 export type DatasetsConsentStoreProps = {
29 /**
30 * Parent dataset. Full name
31 * `projects/{project}/locations/{location}/datasets/{dataset}` or the
32 * dataset id (combined with `location`). Immutable — changing it
33 * replaces the consent store.
34 */
35 dataset: string;
36 /**
37 * Region used when `dataset` is a bare id.
38 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
39 */
40 location?: string;
41 /**
42 * Consent store id. Must match letters, numbers, underscores, hyphens,
43 * and periods; 1-256 characters. Immutable — changing it replaces the
44 * store.
45 */
46 consentStoreId?: string;
47 /**
48 * User labels. Alchemy ownership labels are merged in automatically.
49 */
50 labels?: Record<string, string>;
51 /**
52 * Default TTL for Consents created in this store (e.g. `"86400s"`).
53 * Must be at least 24 hours. Updating this does not change existing
54 * consents.
55 */
56 defaultConsentTtl?: string;
57 /**
58 * If true, `UpdateConsent` creates the Consent when it is missing.
59 * @default false
60 */
61 enableConsentCreateOnUpdate?: boolean;
62 };
63
64 export type DatasetsConsentStore = Resource<
65 "GCP.Healthcare.DatasetsConsentStore",
66 DatasetsConsentStoreProps,
67 {
68 /** Full resource name `.../datasets/{dataset}/consentStores/{consentStore}`. */
69 name: string;
70 /** Consent store id. */
71 consentStoreId: string;
72 /** Parent dataset resource name. */
73 dataset: string;
74 /** Project id. */
75 project: string;
76 /** Location id. */
77 location: string;
78 /** User labels (Alchemy ownership labels stripped). */
79 labels: Record<string, string>;
80 /** Default consent TTL. */
81 defaultConsentTtl: string | undefined;
82 /** Whether UpdateConsent creates missing Consents. */
83 enableConsentCreateOnUpdate: boolean;
84 },
85 never,
86 Providers
87 >;
88
89 /**
90 * A Cloud Healthcare consent store inside a dataset.
91 *
92 * Dataset, store id, and location are immutable. Labels, default TTL, and
93 * `enableConsentCreateOnUpdate` update in place.
94 *
95 * ### Creating a Consent Store
96 * **Example:** Store with labels
97 * ```typescript
98 * const store = yield* GCP.Healthcare.DatasetsConsentStore("Consents", {
99 * dataset: dataset.name,
100 * labels: { env: "test" },
101 * });
102 * ```
103 *
104 * **Example:** Named store that creates consents on update
105 * ```typescript
106 * const store = yield* GCP.Healthcare.DatasetsConsentStore("Consents", {
107 * dataset: dataset.name,
108 * consentStoreId: "clinic-consents",
109 * enableConsentCreateOnUpdate: true,
110 * });
111 * ```
112 *
113 * @resource
114 * @category Healthcare
115 */
116 export const DatasetsConsentStore = Resource<DatasetsConsentStore>(
117 "GCP.Healthcare.DatasetsConsentStore",
118 );
119
120 export class DatasetsConsentStoreNotResolved extends Data.TaggedError(
121 "GCP.Healthcare.DatasetsConsentStoreNotResolved",
122 )<{
123 resourceName: string;
124 }> {}
125
126 const datasetOf = (dataset: string, project: string, location: string) =>
127 expandParent(dataset, project, location, "datasets");
128
129 const resourceName = (dataset: string, consentStoreId: string) =>
130 `${dataset}/consentStores/${consentStoreId}`;
131
132 const toAttrs = (store: healthcare.ConsentStore, project: string, region: string) => {
133 const name = store.name ?? "";
134 const parsed = parseResourceName(name, "consentStores", region);
135 return {
136 name,
137 consentStoreId: parsed.id,
138 dataset: parsed.parent,
139 project: parsed.project || project,
140 location: parsed.location,
141 labels: userLabels(store.labels),
142 defaultConsentTtl: store.defaultConsentTtl,
143 enableConsentCreateOnUpdate: store.enableConsentCreateOnUpdate === true,
144 };
145 };
146
147 const getByName = (name: string) =>
148 name.length === 0
149 ? Effect.undefined
150 : healthcare
151 .getProjectsLocationsDatasetsConsentStores({ name })
152 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
153
154 export const DatasetsConsentStoreProvider = () =>
155 Provider.succeed(DatasetsConsentStore, {
156 stables: ["name", "consentStoreId", "dataset", "project", "location"],
157
158 diff: Effect.fn(function* ({ news, olds, output }) {
159 if (!isResolved(news)) return undefined;
160 const env = yield* GcpEnvironment.current;
161 const previousParent = olds?.dataset ?? output?.dataset;
162 const nextParent = datasetOf(
163 news.dataset,
164 env.project,
165 normalizeLocation(news.location ?? output?.location, env.region),
166 );
167 return replaceOnIdentity({
168 previousId: olds?.consentStoreId ?? output?.consentStoreId,
169 nextId: news.consentStoreId,
170 previousParent,
171 nextParent,
172 });
173 }),
174
175 read: Effect.fn(function* ({ id, olds, output }) {
176 const env = yield* GcpEnvironment.current;
177 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
178 const consentStoreId = yield* toPhysicalId(id, olds?.consentStoreId, output?.consentStoreId);
179 const dataset =
180 olds?.dataset !== undefined
181 ? datasetOf(olds.dataset, env.project, location)
182 : (output?.dataset ?? "");
183 const name =
184 output?.name ?? (dataset.length > 0 ? resourceName(dataset, consentStoreId) : "");
185 const existing = yield* getByName(name);
186 if (existing === undefined) return undefined;
187 const attrs = toAttrs(existing, env.project, env.region);
188 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
189 }),
190
191 list: () =>
192 Effect.gen(function* () {
193 const env = yield* GcpEnvironment.current;
194 const stores = yield* forEachDataset(env.project, env.region, (parent) =>
195 collectPages(
196 healthcare.listProjectsLocationsDatasetsConsentStores.pages({
197 parent,
198 pageSize: 1000,
199 }),
200 (page) => page.consentStores,
201 ),
202 );
203 return stores
204 .filter((store) => hasAlchemyLabelMap(store.labels))
205 .map((store) => toAttrs(store, env.project, env.region));
206 }),
207
208 reconcile: Effect.fn(function* ({ id, news, output }) {
209 const env = yield* GcpEnvironment.current;
210 const location = normalizeLocation(news.location ?? output?.location, env.region);
211 const dataset = datasetOf(news.dataset, env.project, location);
212 const consentStoreId = yield* toPhysicalId(id, news.consentStoreId, output?.consentStoreId);
213 const name = output?.name ?? resourceName(dataset, consentStoreId);
214 const desiredLabels = {
215 ...toLabels(news.labels),
216 ...(yield* createInternalLabels(id)),
217 };
218
219 let current = yield* getByName(name);
220
221 if (current === undefined) {
222 const created = yield* retryTransient(
223 healthcare.createProjectsLocationsDatasetsConsentStores({
224 parent: dataset,
225 consentStoreId,
226 body: {
227 labels: desiredLabels,
228 defaultConsentTtl: news.defaultConsentTtl,
229 enableConsentCreateOnUpdate: news.enableConsentCreateOnUpdate,
230 },
231 }),
232 ).pipe(Effect.catchTag("Conflict", () => getByName(name)));
233 current = created ?? undefined;
234 }
235
236 if (current === undefined) {
237 return yield* new DatasetsConsentStoreNotResolved({ resourceName: name });
238 }
239
240 const currentName = current.name ?? name;
241 const observedLabels = tagRecord(current.labels);
242 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
243 const labelsChanged = upsert.length > 0 || removed.length > 0;
244 const ttlChanged = !sameText(current.defaultConsentTtl, news.defaultConsentTtl);
245 const createOnUpdateChanged =
246 (current.enableConsentCreateOnUpdate === true) !==
247 (news.enableConsentCreateOnUpdate === true);
248
249 if (labelsChanged || ttlChanged || createOnUpdateChanged) {
250 current = yield* retryTransient(
251 healthcare.patchProjectsLocationsDatasetsConsentStores({
252 name: currentName,
253 updateMask: updateMaskOf(
254 labelsChanged ? "labels" : undefined,
255 ttlChanged ? "defaultConsentTtl" : undefined,
256 createOnUpdateChanged ? "enableConsentCreateOnUpdate" : undefined,
257 ),
258 body: {
259 labels: desiredLabels,
260 defaultConsentTtl: news.defaultConsentTtl,
261 enableConsentCreateOnUpdate: news.enableConsentCreateOnUpdate,
262 },
263 }),
264 );
265 }
266
267 return toAttrs(current, env.project, env.region);
268 }),
269
270 delete: Effect.fn(function* ({ output }) {
271 if (!output.name) return;
272 yield* retryTransient(
273 healthcare.deleteProjectsLocationsDatasetsConsentStores({
274 name: output.name,
275 }),
276 ).pipe(Effect.catchTag("NotFound", () => Effect.void));
277 yield* waitUntilGone(getByName(output.name), output.name);
278 }),
279 });