@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 272 lines 8.79 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 decodeDataId,
14 encodeDataId,
15 expandParent,
16 hasOwnedDataId,
17 listAlchemyConsentStores,
18 normalizeLocation,
19 parseResourceName,
20 retryTransient,
21 sameJson,
22 sameText,
23 updateMaskOf,
24 waitUntilGone,
25 } from "./internal.ts";
26
27 export type DatasetsConsentStoresUserDataMappingProps = {
28 /**
29 * Parent consent store. Full name
30 * `.../consentStores/{consentStore}` or the store id (combined with
31 * `dataset` and `location`). Immutable — changing it replaces the
32 * mapping.
33 */
34 consentStore: string;
35 /**
36 * Parent dataset used when `consentStore` is a bare id.
37 */
38 dataset?: string;
39 /**
40 * Region used when `consentStore` is a bare id.
41 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
42 */
43 location?: string;
44 /**
45 * User UUID supplied by the client.
46 */
47 userId: string;
48 /**
49 * Unique identifier for the mapped resource. User data mappings have
50 * no labels field, so Alchemy prefixes `dataId` with `alc-{id}-` and
51 * strips it from attributes.
52 */
53 dataId: string;
54 /**
55 * Single-valued resource attributes.
56 */
57 resourceAttributes?: healthcare.Attribute[];
58 };
59
60 export type DatasetsConsentStoresUserDataMapping = Resource<
61 "GCP.Healthcare.DatasetsConsentStoresUserDataMapping",
62 DatasetsConsentStoresUserDataMappingProps,
63 {
64 /** Full resource name `.../userDataMappings/{userDataMapping}`. */
65 name: string;
66 /** Server-assigned mapping id. */
67 userDataMappingId: string;
68 /** Parent consent store resource name. */
69 consentStore: string;
70 /** Project id. */
71 project: string;
72 /** Location id. */
73 location: string;
74 /** User id. */
75 userId: string | undefined;
76 /** Mapped resource id with the Alchemy prefix stripped. */
77 dataId: string | undefined;
78 /** Resource attributes. */
79 resourceAttributes: healthcare.Attribute[] | undefined;
80 /** Whether the mapping is archived. */
81 archived: boolean;
82 /** RFC3339 archive time. */
83 archiveTime: string | undefined;
84 },
85 never,
86 Providers
87 >;
88
89 /**
90 * Maps a resource to a user and consent attributes.
91 *
92 * Mapping ids are server-assigned. `userId`, `dataId`, and resource
93 * attributes update in place. Ownership is stamped into `dataId`.
94 *
95 * ### Creating a User Data Mapping
96 * **Example:** Map a FHIR resource to a user
97 * ```typescript
98 * const mapping = yield* GCP.Healthcare.DatasetsConsentStoresUserDataMapping(
99 * "Chart",
100 * {
101 * consentStore: store.name,
102 * userId: "user-123",
103 * dataId: "Patient/abc",
104 * },
105 * );
106 * ```
107 *
108 * @resource
109 * @category Healthcare
110 */
111 export const DatasetsConsentStoresUserDataMapping = Resource<DatasetsConsentStoresUserDataMapping>(
112 "GCP.Healthcare.DatasetsConsentStoresUserDataMapping",
113 );
114
115 export class DatasetsConsentStoresUserDataMappingNotResolved extends Data.TaggedError(
116 "GCP.Healthcare.DatasetsConsentStoresUserDataMappingNotResolved",
117 )<{
118 resourceName: string;
119 }> {}
120
121 const storeOf = (
122 consentStore: string,
123 project: string,
124 location: string,
125 dataset: string | undefined,
126 ) => {
127 if (consentStore.includes("/")) return consentStore.replace(/\/+$/, "");
128 if (dataset === undefined) {
129 return expandParent(consentStore, project, location, "consentStores");
130 }
131 const datasetName = expandParent(dataset, project, location, "datasets");
132 return `${datasetName}/consentStores/${consentStore}`;
133 };
134
135 const toAttrs = (mapping: healthcare.UserDataMapping, project: string, region: string) => {
136 const name = mapping.name ?? "";
137 const parsed = parseResourceName(name, "userDataMappings", region);
138 return {
139 name,
140 userDataMappingId: parsed.id,
141 consentStore: parsed.parent,
142 project: parsed.project || project,
143 location: parsed.location,
144 userId: mapping.userId,
145 dataId: decodeDataId(mapping.dataId),
146 resourceAttributes: mapping.resourceAttributes,
147 archived: mapping.archived === true,
148 archiveTime: mapping.archiveTime,
149 };
150 };
151
152 const getByName = (name: string) =>
153 name.length === 0
154 ? Effect.undefined
155 : healthcare
156 .getProjectsLocationsDatasetsConsentStoresUserDataMappings({ name })
157 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
158
159 export const DatasetsConsentStoresUserDataMappingProvider = () =>
160 Provider.succeed(DatasetsConsentStoresUserDataMapping, {
161 stables: ["name", "userDataMappingId", "consentStore", "project", "location"],
162
163 diff: Effect.fn(function* ({ news, olds, output }) {
164 if (!isResolved(news)) return undefined;
165 const env = yield* GcpEnvironment.current;
166 const previousParent = olds?.consentStore ?? output?.consentStore;
167 const nextParent = storeOf(
168 news.consentStore,
169 env.project,
170 normalizeLocation(news.location ?? output?.location, env.region),
171 news.dataset,
172 );
173 if (previousParent !== undefined && previousParent !== nextParent) {
174 return { action: "replace" as const, deleteFirst: false };
175 }
176 return undefined;
177 }),
178
179 read: Effect.fn(function* ({ output }) {
180 const env = yield* GcpEnvironment.current;
181 const existing = yield* getByName(output?.name ?? "");
182 if (existing === undefined) return undefined;
183 const attrs = toAttrs(existing, env.project, env.region);
184 return hasOwnedDataId(existing.dataId) ? attrs : Unowned(attrs);
185 }),
186
187 list: () =>
188 Effect.gen(function* () {
189 const env = yield* GcpEnvironment.current;
190 const stores = yield* listAlchemyConsentStores(env.project, env.region);
191 const mappings = yield* Effect.forEach(
192 stores,
193 (store) =>
194 collectPages(
195 healthcare.listProjectsLocationsDatasetsConsentStoresUserDataMappings.pages({
196 parent: store.name ?? "",
197 pageSize: 1000,
198 }),
199 (page) => page.userDataMappings,
200 ),
201 { concurrency: 4 },
202 );
203 return mappings
204 .flat()
205 .filter((mapping) => hasOwnedDataId(mapping.dataId))
206 .map((mapping) => toAttrs(mapping, env.project, env.region));
207 }),
208
209 reconcile: Effect.fn(function* ({ id, news, output }) {
210 const env = yield* GcpEnvironment.current;
211 const location = normalizeLocation(news.location ?? output?.location, env.region);
212 const consentStore = storeOf(news.consentStore, env.project, location, news.dataset);
213 const ownership = yield* createInternalLabels(id);
214 const dataId = encodeDataId(ownership, news.dataId);
215
216 let current = yield* getByName(output?.name ?? "");
217
218 if (current === undefined) {
219 current = yield* retryTransient(
220 healthcare.createProjectsLocationsDatasetsConsentStoresUserDataMappings({
221 parent: consentStore,
222 body: {
223 userId: news.userId,
224 dataId,
225 resourceAttributes: news.resourceAttributes,
226 },
227 }),
228 );
229 }
230
231 if (current === undefined) {
232 return yield* new DatasetsConsentStoresUserDataMappingNotResolved({
233 resourceName: consentStore,
234 });
235 }
236
237 const currentName = current.name ?? output?.name ?? "";
238 const userChanged = !sameText(current.userId, news.userId);
239 const dataChanged = !sameText(current.dataId, dataId);
240 const attrsChanged = !sameJson(current.resourceAttributes, news.resourceAttributes);
241
242 if (userChanged || dataChanged || attrsChanged) {
243 current = yield* retryTransient(
244 healthcare.patchProjectsLocationsDatasetsConsentStoresUserDataMappings({
245 name: currentName,
246 updateMask: updateMaskOf(
247 userChanged ? "userId" : undefined,
248 dataChanged ? "dataId" : undefined,
249 attrsChanged ? "resourceAttributes" : undefined,
250 ),
251 body: {
252 userId: news.userId,
253 dataId,
254 resourceAttributes: news.resourceAttributes,
255 },
256 }),
257 );
258 }
259
260 return toAttrs(current, env.project, env.region);
261 }),
262
263 delete: Effect.fn(function* ({ output }) {
264 if (!output.name) return;
265 yield* retryTransient(
266 healthcare.deleteProjectsLocationsDatasetsConsentStoresUserDataMappings({
267 name: output.name,
268 }),
269 ).pipe(Effect.catchTag("NotFound", () => Effect.void));
270 yield* waitUntilGone(getByName(output.name), output.name);
271 }),
272 });