@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 346 lines 11 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 {
11 createInternalLabels,
12 diffLabels,
13 hasAlchemyLabels,
14 stripInternalLabels,
15 toLabels,
16 } from "../Labels.ts";
17 import type { Providers } from "../Providers.ts";
18 import {
19 decodeHl7,
20 encodeHl7,
21 hasAlchemyLabelMap,
22 lastSegment,
23 listRegionDatasets,
24 listHl7V2Stores,
25 listMessages,
26 parentOf,
27 retryTransient,
28 sameText,
29 } from "./internal.ts";
30
31 export type PatientId = {
32 /** Patient identifier value (PID-2/3/4). */
33 value?: string;
34 /** Identifier type, for example `MRN`. */
35 type?: string;
36 };
37
38 export type DatasetsHl7V2StoresMessageProps = {
39 /**
40 * Parent HL7v2 store resource name
41 * `projects/{project}/locations/{location}/datasets/{dataset}/hl7V2Stores/{store}`.
42 * Immutable — changing it replaces the message.
43 */
44 parent: string;
45 /**
46 * Raw HL7v2 message text. Segment terminator is CR. Alchemy
47 * base64-encodes this for the Healthcare API. Immutable — changing it
48 * replaces the message.
49 */
50 data: string;
51 /**
52 * Server-assigned message id. Set on create. Immutable — changing it
53 * replaces the message.
54 */
55 messageId?: string;
56 /**
57 * User labels. Alchemy ownership labels are merged in automatically.
58 */
59 labels?: Record<string, string>;
60 };
61
62 export type DatasetsHl7V2StoresMessage = Resource<
63 "GCP.Healthcare.DatasetsHl7V2StoresMessage",
64 DatasetsHl7V2StoresMessageProps,
65 {
66 /**
67 * Full resource name
68 * `projects/{project}/locations/{location}/datasets/{dataset}/hl7V2Stores/{store}/messages/{message}`.
69 */
70 name: string;
71 /** Server-assigned message id. */
72 messageId: string;
73 /** Parent HL7v2 store resource name. */
74 parent: string;
75 /** Project id. */
76 project: string;
77 /** Location id. */
78 location: string;
79 /** Raw HL7v2 message text (decoded from the API bytes). */
80 data: string;
81 /** User labels (Alchemy ownership labels stripped). */
82 labels: Record<string, string>;
83 /** Message type from MSH-9.1. */
84 messageType: string | undefined;
85 /** Sending facility from MSH-4. */
86 sendFacility: string | undefined;
87 /** Datetime the sending application sent this message (MSH-7). */
88 sendTime: string | undefined;
89 /** Patient ids parsed from PID-2, PID-3, and PID-4. */
90 patientIds: PatientId[];
91 /** RFC3339 creation timestamp. */
92 createTime: string | undefined;
93 },
94 never,
95 Providers
96 >;
97
98 /**
99 * An HL7v2 message stored in a Cloud Healthcare HL7v2 store.
100 *
101 * Message ids are server-assigned. Parent store and raw `data` are
102 * identity — changing either replaces the message. Labels update in
103 * place (`updateMask=labels`).
104 *
105 * ### Creating a Message
106 * **Example:** ADT^A01 into an existing store
107 * ```typescript
108 * const message = yield* GCP.Healthcare.DatasetsHl7V2StoresMessage("Adt", {
109 * parent: store.name,
110 * data: [
111 * "MSH|^~\\&|APP|FACILITY|DEST|DESTFAC|20240101120000||ADT^A01|MSG00001|P|2.5",
112 * "PID|1||PAT001^^^MR||DOE^JOHN",
113 * ].join("\r"),
114 * labels: { env: "test" },
115 * });
116 * ```
117 *
118 * ### Updating a Message
119 * Change props on the same logical id; the engine keeps the physical id.
120 *
121 * **Example:** Relabel an existing message
122 * ```typescript
123 * const message = yield* GCP.Healthcare.DatasetsHl7V2StoresMessage("Adt", {
124 * parent: store.name,
125 * data: [
126 * "MSH|^~\\&|APP|FACILITY|DEST|DESTFAC|20240101120000||ADT^A01|MSG00001|P|2.5",
127 * "PID|1||PAT001^^^MR||DOE^JOHN",
128 * ].join("\r"),
129 * labels: { env: "prod" },
130 * });
131 * ```
132 *
133 * @resource
134 * @category Healthcare
135 */
136 export const DatasetsHl7V2StoresMessage = Resource<DatasetsHl7V2StoresMessage>(
137 "GCP.Healthcare.DatasetsHl7V2StoresMessage",
138 );
139
140 export class DatasetsHl7V2StoresMessageNotResolved extends Data.TaggedError(
141 "GCP.Healthcare.DatasetsHl7V2StoresMessageNotResolved",
142 )<{
143 parent: string;
144 messageId: string;
145 }> {}
146
147 const userLabels = (
148 labels: Record<string, string | undefined> | null | undefined,
149 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
150
151 const resourceNameOf = (parent: string, messageId: string) => `${parent}/messages/${messageId}`;
152
153 const locationOf = (name: string, fallback: string) => {
154 const parts = name.split("/");
155 const index = parts.indexOf("locations");
156 return index >= 0 ? (parts[index + 1] ?? fallback) : fallback;
157 };
158
159 const projectOf = (name: string, fallback: string) => {
160 const parts = name.split("/");
161 const index = parts.indexOf("projects");
162 return index >= 0 ? (parts[index + 1] ?? fallback) : fallback;
163 };
164
165 const toAttrs = (message: healthcare.Message, project: string, data: string, region: string) => {
166 const name = message.name ?? "";
167 return {
168 name,
169 messageId: lastSegment(name),
170 parent: parentOf(name),
171 project: projectOf(name, project),
172 location: locationOf(name, region),
173 data,
174 labels: userLabels(message.labels),
175 messageType: message.messageType,
176 sendFacility: message.sendFacility,
177 sendTime: message.sendTime,
178 patientIds: (message.patientIds ?? []).map((id) => ({
179 value: id.value,
180 type: id.type,
181 })),
182 createTime: message.createTime,
183 };
184 };
185
186 const getByName = (name: string) =>
187 name.length === 0
188 ? Effect.undefined
189 : healthcare
190 .getProjectsLocationsDatasetsHl7V2StoresMessages({
191 name,
192 view: "FULL",
193 })
194 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
195
196 const findOwned = (parent: string, id: string) =>
197 Effect.gen(function* () {
198 const items = yield* listMessages(parent);
199 for (const item of items) {
200 if (yield* hasAlchemyLabels(id, tagRecord(item.labels))) {
201 return item;
202 }
203 }
204 return undefined;
205 });
206
207 const listOwnedMessages = (project: string, region: string) =>
208 Effect.gen(function* () {
209 const datasets = yield* listRegionDatasets(project, region);
210 const named = datasets.filter((dataset) => (dataset.name ?? "").length > 0);
211 const stores = yield* Effect.forEach(named, (dataset) => listHl7V2Stores(dataset.name!), {
212 concurrency: 4,
213 });
214 const storeNames = stores
215 .flat()
216 .map((store) => store.name)
217 .filter((name): name is string => (name ?? "").length > 0);
218 const pages = yield* Effect.forEach(storeNames, listMessages, {
219 concurrency: 4,
220 });
221 return pages.flat().filter((message) => hasAlchemyLabelMap(message.labels));
222 });
223
224 export const DatasetsHl7V2StoresMessageProvider = () =>
225 Provider.succeed(DatasetsHl7V2StoresMessage, {
226 stables: ["name", "messageId", "parent", "project", "location", "createTime"],
227
228 diff: Effect.fn(function* ({ news, olds, output }) {
229 if (!isResolved(news)) return undefined;
230 const previousParent = olds?.parent ?? output?.parent;
231 if (previousParent !== undefined && news.parent !== previousParent) {
232 return { action: "replace" as const, deleteFirst: false };
233 }
234 const previousId = olds?.messageId ?? output?.messageId;
235 if (
236 previousId !== undefined &&
237 news.messageId !== undefined &&
238 news.messageId !== previousId
239 ) {
240 return { action: "replace" as const, deleteFirst: false };
241 }
242 const previousData = olds?.data ?? output?.data;
243 if (previousData !== undefined && news.data !== previousData) {
244 return { action: "replace" as const, deleteFirst: false };
245 }
246 return undefined;
247 }),
248
249 read: Effect.fn(function* ({ id, olds, output }) {
250 const env = yield* GcpEnvironment.current;
251 const parent = olds?.parent ?? output?.parent ?? "";
252 const messageId = olds?.messageId ?? output?.messageId;
253 const name =
254 output?.name ??
255 (messageId !== undefined && parent.length > 0 ? resourceNameOf(parent, messageId) : "");
256 let existing = yield* getByName(name);
257 if (existing === undefined) {
258 existing = yield* findOwned(parent, id);
259 }
260 if (existing === undefined) return undefined;
261 const data = yield* decodeHl7(existing.data);
262 const attrs = toAttrs(existing, env.project, data, env.region);
263 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
264 }),
265
266 list: () =>
267 Effect.gen(function* () {
268 const env = yield* GcpEnvironment.current;
269 const messages = yield* listOwnedMessages(env.project, env.region);
270 return yield* Effect.forEach(messages, (message) =>
271 Effect.gen(function* () {
272 const data = yield* decodeHl7(message.data);
273 return toAttrs(message, env.project, data, env.region);
274 }),
275 );
276 }),
277
278 reconcile: Effect.fn(function* ({ id, news, output }) {
279 const env = yield* GcpEnvironment.current;
280 const parent = news.parent;
281 const desiredLabels = {
282 ...toLabels(news.labels),
283 ...(yield* createInternalLabels(id)),
284 };
285 const encoded = yield* encodeHl7(news.data);
286 const name =
287 output?.name ??
288 (news.messageId !== undefined ? resourceNameOf(parent, news.messageId) : "");
289
290 let current = yield* getByName(name);
291 if (current === undefined) {
292 current = yield* findOwned(parent, id);
293 }
294
295 if (current === undefined) {
296 const created = yield* retryTransient(
297 healthcare.createProjectsLocationsDatasetsHl7V2StoresMessages({
298 parent,
299 body: {
300 message: {
301 data: encoded,
302 labels: desiredLabels,
303 },
304 },
305 }),
306 ).pipe(Effect.catchTag("Conflict", () => findOwned(parent, id)));
307 current = created ?? undefined;
308 }
309
310 if (current === undefined) {
311 return yield* new DatasetsHl7V2StoresMessageNotResolved({
312 parent,
313 messageId: news.messageId ?? output?.messageId ?? "",
314 });
315 }
316
317 const currentName = current.name ?? name;
318 const observedLabels = tagRecord(current.labels);
319 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
320 const labelsChanged = upsert.length > 0 || removed.length > 0;
321
322 if (labelsChanged) {
323 current = yield* retryTransient(
324 healthcare.patchProjectsLocationsDatasetsHl7V2StoresMessages({
325 name: currentName,
326 updateMask: "labels",
327 body: {
328 labels: desiredLabels,
329 },
330 }),
331 );
332 }
333
334 const data = sameText(current.data, encoded) ? news.data : yield* decodeHl7(current.data);
335 return toAttrs(current, env.project, data, env.region);
336 }),
337
338 delete: Effect.fn(function* ({ output }) {
339 if (output.name.length === 0) return;
340 yield* retryTransient(
341 healthcare.deleteProjectsLocationsDatasetsHl7V2StoresMessages({
342 name: output.name,
343 }),
344 ).pipe(Effect.catchTag("NotFound", () => Effect.void));
345 }),
346 });