@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 317 lines 10.7 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 sameJson,
22 toPhysicalId,
23 updateMaskOf,
24 userLabels,
25 waitUntilGone,
26 } from "./internal.ts";
27
28 export type Hl7V2NotificationConfig = {
29 /** Pub/Sub topic for matching messages. */
30 pubsubTopic?: string;
31 /** Optional filter restricting which messages notify. */
32 filter?: string;
33 };
34
35 export type Hl7V2ParserConfig = {
36 /** Allow messages with no header. */
37 allowNullHeader?: boolean;
38 /**
39 * Parser version. Immutable after create.
40 */
41 version?: healthcare.ParserConfigVersionEnum | (string & {});
42 };
43
44 export type DatasetsHl7V2StoreProps = {
45 /**
46 * Parent dataset. Full name
47 * `projects/{project}/locations/{location}/datasets/{dataset}` or the
48 * dataset id (combined with `location`). Immutable — changing it
49 * replaces the HL7v2 store.
50 */
51 dataset: string;
52 /**
53 * Region used when `dataset` is a bare id.
54 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
55 */
56 location?: string;
57 /**
58 * HL7v2 store id. Must match letters, numbers, underscores, hyphens,
59 * and periods; 1-256 characters. Immutable — changing it replaces the
60 * store.
61 */
62 hl7V2StoreId?: string;
63 /**
64 * User labels. Alchemy ownership labels are merged in automatically.
65 */
66 labels?: Record<string, string>;
67 /**
68 * Reject ingest/create of duplicate raw messages.
69 * @default false
70 */
71 rejectDuplicateMessage?: boolean;
72 /**
73 * Parser configuration. `version` is immutable after create.
74 */
75 parserConfig?: Hl7V2ParserConfig;
76 /**
77 * Destinations for filtered message notifications.
78 */
79 notificationConfigs?: Hl7V2NotificationConfig[];
80 };
81
82 export type DatasetsHl7V2Store = Resource<
83 "GCP.Healthcare.DatasetsHl7V2Store",
84 DatasetsHl7V2StoreProps,
85 {
86 /** Full resource name `.../datasets/{dataset}/hl7V2Stores/{hl7V2Store}`. */
87 name: string;
88 /** HL7v2 store id. */
89 hl7V2StoreId: string;
90 /** Parent dataset resource name. */
91 dataset: string;
92 /** Project id. */
93 project: string;
94 /** Location id. */
95 location: string;
96 /** User labels (Alchemy ownership labels stripped). */
97 labels: Record<string, string>;
98 /** Whether duplicate messages are rejected. */
99 rejectDuplicateMessage: boolean;
100 /** Parser configuration. */
101 parserConfig: Hl7V2ParserConfig | undefined;
102 /** Notification destinations. */
103 notificationConfigs: Hl7V2NotificationConfig[] | undefined;
104 },
105 never,
106 Providers
107 >;
108
109 /**
110 * A Cloud Healthcare HL7v2 store inside a dataset.
111 *
112 * Dataset, store id, location, and parser version are immutable. Labels,
113 * duplicate rejection, `allowNullHeader`, and notification configs update
114 * in place.
115 *
116 * ### Creating an HL7v2 Store
117 * **Example:** Store with labels
118 * ```typescript
119 * const store = yield* GCP.Healthcare.DatasetsHl7V2Store("Adt", {
120 * dataset: dataset.name,
121 * labels: { env: "test" },
122 * });
123 * ```
124 *
125 * **Example:** Named store that rejects duplicates
126 * ```typescript
127 * const store = yield* GCP.Healthcare.DatasetsHl7V2Store("Adt", {
128 * dataset: dataset.name,
129 * hl7V2StoreId: "clinic-adt",
130 * rejectDuplicateMessage: true,
131 * });
132 * ```
133 *
134 * @resource
135 * @category Healthcare
136 */
137 export const DatasetsHl7V2Store = Resource<DatasetsHl7V2Store>("GCP.Healthcare.DatasetsHl7V2Store");
138
139 export class DatasetsHl7V2StoreNotResolved extends Data.TaggedError(
140 "GCP.Healthcare.DatasetsHl7V2StoreNotResolved",
141 )<{
142 resourceName: string;
143 }> {}
144
145 const datasetOf = (dataset: string, project: string, location: string) =>
146 expandParent(dataset, project, location, "datasets");
147
148 const resourceName = (dataset: string, hl7V2StoreId: string) =>
149 `${dataset}/hl7V2Stores/${hl7V2StoreId}`;
150
151 const parserOf = (config: healthcare.ParserConfig | undefined): Hl7V2ParserConfig | undefined => {
152 if (config === undefined) return undefined;
153 return {
154 allowNullHeader: config.allowNullHeader,
155 version: config.version,
156 };
157 };
158
159 const toAttrs = (store: healthcare.Hl7V2Store, project: string, region: string) => {
160 const name = store.name ?? "";
161 const parsed = parseResourceName(name, "hl7V2Stores", region);
162 return {
163 name,
164 hl7V2StoreId: parsed.id,
165 dataset: parsed.parent,
166 project: parsed.project || project,
167 location: parsed.location,
168 labels: userLabels(store.labels),
169 rejectDuplicateMessage: store.rejectDuplicateMessage === true,
170 parserConfig: parserOf(store.parserConfig),
171 notificationConfigs: store.notificationConfigs,
172 };
173 };
174
175 const getByName = (name: string) =>
176 name.length === 0
177 ? Effect.undefined
178 : healthcare
179 .getProjectsLocationsDatasetsHl7V2Stores({ name })
180 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
181
182 export const DatasetsHl7V2StoreProvider = () =>
183 Provider.succeed(DatasetsHl7V2Store, {
184 stables: ["name", "hl7V2StoreId", "dataset", "project", "location"],
185
186 diff: Effect.fn(function* ({ news, olds, output }) {
187 if (!isResolved(news)) return undefined;
188 const env = yield* GcpEnvironment.current;
189 const previousVersion = olds?.parserConfig?.version ?? output?.parserConfig?.version;
190 const nextVersion = news.parserConfig?.version;
191 const extra =
192 previousVersion !== undefined &&
193 nextVersion !== undefined &&
194 previousVersion !== nextVersion;
195 return replaceOnIdentity({
196 previousId: olds?.hl7V2StoreId ?? output?.hl7V2StoreId,
197 nextId: news.hl7V2StoreId,
198 previousParent: olds?.dataset ?? output?.dataset,
199 nextParent: datasetOf(
200 news.dataset,
201 env.project,
202 normalizeLocation(news.location ?? output?.location, env.region),
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 hl7V2StoreId = yield* toPhysicalId(id, olds?.hl7V2StoreId, output?.hl7V2StoreId);
212 const dataset =
213 olds?.dataset !== undefined
214 ? datasetOf(olds.dataset, env.project, location)
215 : (output?.dataset ?? "");
216 const name = output?.name ?? (dataset.length > 0 ? resourceName(dataset, hl7V2StoreId) : "");
217 const existing = yield* getByName(name);
218 if (existing === undefined) return undefined;
219 const attrs = toAttrs(existing, env.project, env.region);
220 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
221 }),
222
223 list: () =>
224 Effect.gen(function* () {
225 const env = yield* GcpEnvironment.current;
226 const stores = yield* forEachDataset(env.project, env.region, (parent) =>
227 collectPages(
228 healthcare.listProjectsLocationsDatasetsHl7V2Stores.pages({
229 parent,
230 pageSize: 1000,
231 }),
232 (page) => page.hl7V2Stores,
233 ),
234 );
235 return stores
236 .filter((store) => hasAlchemyLabelMap(store.labels))
237 .map((store) => toAttrs(store, env.project, env.region));
238 }),
239
240 reconcile: Effect.fn(function* ({ id, news, output }) {
241 const env = yield* GcpEnvironment.current;
242 const location = normalizeLocation(news.location ?? output?.location, env.region);
243 const dataset = datasetOf(news.dataset, env.project, location);
244 const hl7V2StoreId = yield* toPhysicalId(id, news.hl7V2StoreId, output?.hl7V2StoreId);
245 const name = output?.name ?? resourceName(dataset, hl7V2StoreId);
246 const desiredLabels = {
247 ...toLabels(news.labels),
248 ...(yield* createInternalLabels(id)),
249 };
250
251 let current = yield* getByName(name);
252
253 if (current === undefined) {
254 const created = yield* retryTransient(
255 healthcare.createProjectsLocationsDatasetsHl7V2Stores({
256 parent: dataset,
257 hl7V2StoreId,
258 body: {
259 labels: desiredLabels,
260 rejectDuplicateMessage: news.rejectDuplicateMessage,
261 parserConfig: news.parserConfig,
262 notificationConfigs: news.notificationConfigs,
263 },
264 }),
265 ).pipe(Effect.catchTag("Conflict", () => getByName(name)));
266 current = created ?? undefined;
267 }
268
269 if (current === undefined) {
270 return yield* new DatasetsHl7V2StoreNotResolved({ resourceName: name });
271 }
272
273 const currentName = current.name ?? name;
274 const observedLabels = tagRecord(current.labels);
275 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
276 const labelsChanged = upsert.length > 0 || removed.length > 0;
277 const rejectChanged =
278 (current.rejectDuplicateMessage === true) !== (news.rejectDuplicateMessage === true);
279 const parserChanged =
280 news.parserConfig !== undefined &&
281 (current.parserConfig?.allowNullHeader === true) !==
282 (news.parserConfig.allowNullHeader === true);
283 const notificationsChanged = !sameJson(current.notificationConfigs, news.notificationConfigs);
284
285 if (labelsChanged || rejectChanged || parserChanged || notificationsChanged) {
286 current = yield* retryTransient(
287 healthcare.patchProjectsLocationsDatasetsHl7V2Stores({
288 name: currentName,
289 updateMask: updateMaskOf(
290 labelsChanged ? "labels" : undefined,
291 rejectChanged ? "rejectDuplicateMessage" : undefined,
292 parserChanged ? "parserConfig.allowNullHeader" : undefined,
293 notificationsChanged ? "notificationConfigs" : undefined,
294 ),
295 body: {
296 labels: desiredLabels,
297 rejectDuplicateMessage: news.rejectDuplicateMessage,
298 parserConfig: news.parserConfig,
299 notificationConfigs: news.notificationConfigs,
300 },
301 }),
302 );
303 }
304
305 return toAttrs(current, env.project, env.region);
306 }),
307
308 delete: Effect.fn(function* ({ output }) {
309 if (!output.name) return;
310 yield* retryTransient(
311 healthcare.deleteProjectsLocationsDatasetsHl7V2Stores({
312 name: output.name,
313 }),
314 ).pipe(Effect.catchTag("NotFound", () => Effect.void));
315 yield* waitUntilGone(getByName(output.name), output.name);
316 }),
317 });