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

main
ts 279 lines 9.3 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 DicomNotificationConfig = {
29 /** Pub/Sub topic for DICOM change notifications. */
30 pubsubTopic?: string;
31 };
32
33 export type DicomLegacyNotificationConfig = {
34 /** Pub/Sub topic for new DICOM instances. */
35 pubsubTopic?: string;
36 /** Send notifications on bulk import. */
37 sendForBulkImport?: boolean;
38 };
39
40 export type DatasetsDicomStoreProps = {
41 /**
42 * Parent dataset. Full name
43 * `projects/{project}/locations/{location}/datasets/{dataset}` or the
44 * dataset id (combined with `location`). Immutable — changing it
45 * replaces the DICOM store.
46 */
47 dataset: string;
48 /**
49 * Region used when `dataset` is a bare id.
50 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
51 */
52 location?: string;
53 /**
54 * DICOM store id. Any string up to 256 characters. Immutable —
55 * changing it replaces the store.
56 */
57 dicomStoreId?: string;
58 /**
59 * User labels. Alchemy ownership labels are merged in automatically.
60 */
61 labels?: Record<string, string>;
62 /**
63 * Destinations for change notifications.
64 */
65 notificationConfigs?: DicomNotificationConfig[];
66 /**
67 * Legacy single notification destination.
68 */
69 notificationConfig?: DicomLegacyNotificationConfig;
70 };
71
72 export type DatasetsDicomStore = Resource<
73 "GCP.Healthcare.DatasetsDicomStore",
74 DatasetsDicomStoreProps,
75 {
76 /** Full resource name `.../datasets/{dataset}/dicomStores/{dicomStore}`. */
77 name: string;
78 /** DICOM store id. */
79 dicomStoreId: string;
80 /** Parent dataset resource name. */
81 dataset: string;
82 /** Project id. */
83 project: string;
84 /** Location id. */
85 location: string;
86 /** User labels (Alchemy ownership labels stripped). */
87 labels: Record<string, string>;
88 /** Change-notification destinations. */
89 notificationConfigs: DicomNotificationConfig[] | undefined;
90 /** Legacy notification destination. */
91 notificationConfig: DicomLegacyNotificationConfig | undefined;
92 },
93 never,
94 Providers
95 >;
96
97 /**
98 * A Cloud Healthcare DICOM store inside a dataset.
99 *
100 * Dataset, store id, and location are immutable. Labels and notification
101 * configs update in place.
102 *
103 * ### Creating a DICOM Store
104 * **Example:** Store with labels
105 * ```typescript
106 * const store = yield* GCP.Healthcare.DatasetsDicomStore("Images", {
107 * dataset: dataset.name,
108 * labels: { env: "test" },
109 * });
110 * ```
111 *
112 * **Example:** Named store
113 * ```typescript
114 * const store = yield* GCP.Healthcare.DatasetsDicomStore("Images", {
115 * dataset: dataset.name,
116 * dicomStoreId: "clinic-images",
117 * });
118 * ```
119 *
120 * @resource
121 * @category Healthcare
122 */
123 export const DatasetsDicomStore = Resource<DatasetsDicomStore>("GCP.Healthcare.DatasetsDicomStore");
124
125 export class DatasetsDicomStoreNotResolved extends Data.TaggedError(
126 "GCP.Healthcare.DatasetsDicomStoreNotResolved",
127 )<{
128 resourceName: string;
129 }> {}
130
131 const datasetOf = (dataset: string, project: string, location: string) =>
132 expandParent(dataset, project, location, "datasets");
133
134 const resourceName = (dataset: string, dicomStoreId: string) =>
135 `${dataset}/dicomStores/${dicomStoreId}`;
136
137 const toAttrs = (store: healthcare.DicomStore, project: string, region: string) => {
138 const name = store.name ?? "";
139 const parsed = parseResourceName(name, "dicomStores", region);
140 return {
141 name,
142 dicomStoreId: parsed.id,
143 dataset: parsed.parent,
144 project: parsed.project || project,
145 location: parsed.location,
146 labels: userLabels(store.labels),
147 notificationConfigs: store.notificationConfigs,
148 notificationConfig: store.notificationConfig,
149 };
150 };
151
152 const getByName = (name: string) =>
153 name.length === 0
154 ? Effect.undefined
155 : healthcare
156 .getProjectsLocationsDatasetsDicomStores({ name })
157 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
158
159 export const DatasetsDicomStoreProvider = () =>
160 Provider.succeed(DatasetsDicomStore, {
161 stables: ["name", "dicomStoreId", "dataset", "project", "location"],
162
163 diff: Effect.fn(function* ({ news, olds, output }) {
164 if (!isResolved(news)) return undefined;
165 const env = yield* GcpEnvironment.current;
166 return replaceOnIdentity({
167 previousId: olds?.dicomStoreId ?? output?.dicomStoreId,
168 nextId: news.dicomStoreId,
169 previousParent: olds?.dataset ?? output?.dataset,
170 nextParent: datasetOf(
171 news.dataset,
172 env.project,
173 normalizeLocation(news.location ?? output?.location, env.region),
174 ),
175 });
176 }),
177
178 read: Effect.fn(function* ({ id, olds, output }) {
179 const env = yield* GcpEnvironment.current;
180 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
181 const dicomStoreId = yield* toPhysicalId(id, olds?.dicomStoreId, output?.dicomStoreId);
182 const dataset =
183 olds?.dataset !== undefined
184 ? datasetOf(olds.dataset, env.project, location)
185 : (output?.dataset ?? "");
186 const name = output?.name ?? (dataset.length > 0 ? resourceName(dataset, dicomStoreId) : "");
187 const existing = yield* getByName(name);
188 if (existing === undefined) return undefined;
189 const attrs = toAttrs(existing, env.project, env.region);
190 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
191 }),
192
193 list: () =>
194 Effect.gen(function* () {
195 const env = yield* GcpEnvironment.current;
196 const stores = yield* forEachDataset(env.project, env.region, (parent) =>
197 collectPages(
198 healthcare.listProjectsLocationsDatasetsDicomStores.pages({
199 parent,
200 pageSize: 1000,
201 }),
202 (page) => page.dicomStores,
203 ),
204 );
205 return stores
206 .filter((store) => hasAlchemyLabelMap(store.labels))
207 .map((store) => toAttrs(store, env.project, env.region));
208 }),
209
210 reconcile: Effect.fn(function* ({ id, news, output }) {
211 const env = yield* GcpEnvironment.current;
212 const location = normalizeLocation(news.location ?? output?.location, env.region);
213 const dataset = datasetOf(news.dataset, env.project, location);
214 const dicomStoreId = yield* toPhysicalId(id, news.dicomStoreId, output?.dicomStoreId);
215 const name = output?.name ?? resourceName(dataset, dicomStoreId);
216 const desiredLabels = {
217 ...toLabels(news.labels),
218 ...(yield* createInternalLabels(id)),
219 };
220
221 let current = yield* getByName(name);
222
223 if (current === undefined) {
224 const created = yield* retryTransient(
225 healthcare.createProjectsLocationsDatasetsDicomStores({
226 parent: dataset,
227 dicomStoreId,
228 body: {
229 labels: desiredLabels,
230 notificationConfigs: news.notificationConfigs,
231 notificationConfig: news.notificationConfig,
232 },
233 }),
234 ).pipe(Effect.catchTag("Conflict", () => getByName(name)));
235 current = created ?? undefined;
236 }
237
238 if (current === undefined) {
239 return yield* new DatasetsDicomStoreNotResolved({ resourceName: name });
240 }
241
242 const currentName = current.name ?? name;
243 const observedLabels = tagRecord(current.labels);
244 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
245 const labelsChanged = upsert.length > 0 || removed.length > 0;
246 const notificationsChanged = !sameJson(current.notificationConfigs, news.notificationConfigs);
247 const legacyChanged = !sameJson(current.notificationConfig, news.notificationConfig);
248
249 if (labelsChanged || notificationsChanged || legacyChanged) {
250 current = yield* retryTransient(
251 healthcare.patchProjectsLocationsDatasetsDicomStores({
252 name: currentName,
253 updateMask: updateMaskOf(
254 labelsChanged ? "labels" : undefined,
255 notificationsChanged ? "notificationConfigs" : undefined,
256 legacyChanged ? "notificationConfig" : undefined,
257 ),
258 body: {
259 labels: desiredLabels,
260 notificationConfigs: news.notificationConfigs,
261 notificationConfig: news.notificationConfig,
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.deleteProjectsLocationsDatasetsDicomStores({
274 name: output.name,
275 }),
276 ).pipe(Effect.catchTag("NotFound", () => Effect.void));
277 yield* waitUntilGone(getByName(output.name), output.name);
278 }),
279 });