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

main
ts 275 lines 8.87 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, hasAlchemyLabels } from "../Labels.ts";
11 import type { Providers } from "../Providers.ts";
12 import {
13 collectPages,
14 expandParent,
15 hasAlchemyLabelMap,
16 listAlchemyConsentStores,
17 normalizeLocation,
18 parseResourceName,
19 retryTransient,
20 userLabels,
21 waitUntilGone,
22 withOwnershipMetadata,
23 } from "./internal.ts";
24
25 export type ConsentSignature = {
26 /** Signing user id. */
27 userId?: string;
28 /** RFC3339 signature time. */
29 signatureTime?: string;
30 /** Signature metadata. */
31 metadata?: Record<string, string>;
32 };
33
34 export type DatasetsConsentStoresConsentArtifactProps = {
35 /**
36 * Parent consent store. Full name
37 * `.../consentStores/{consentStore}` or the store id (combined with
38 * `dataset` and `location`). Immutable — changing it replaces the
39 * artifact.
40 */
41 consentStore: string;
42 /**
43 * Parent dataset used when `consentStore` is a bare id.
44 */
45 dataset?: string;
46 /**
47 * Region used when `consentStore` is a bare id.
48 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
49 */
50 location?: string;
51 /**
52 * User UUID supplied by the client.
53 */
54 userId: string;
55 /**
56 * Version string of the consent information shown to the user.
57 */
58 consentContentVersion?: string;
59 /**
60 * Artifact metadata. Alchemy ownership keys are merged in
61 * automatically (`alchemy-stack`, `alchemy-stage`, `alchemy-id`).
62 */
63 metadata?: Record<string, string>;
64 /**
65 * User signature.
66 */
67 userSignature?: ConsentSignature;
68 /**
69 * Guardian signature.
70 */
71 guardianSignature?: ConsentSignature;
72 /**
73 * Witness signature.
74 */
75 witnessSignature?: ConsentSignature;
76 };
77
78 export type DatasetsConsentStoresConsentArtifact = Resource<
79 "GCP.Healthcare.DatasetsConsentStoresConsentArtifact",
80 DatasetsConsentStoresConsentArtifactProps,
81 {
82 /** Full resource name `.../consentArtifacts/{consentArtifact}`. */
83 name: string;
84 /** Server-assigned artifact id. */
85 consentArtifactId: string;
86 /** Parent consent store resource name. */
87 consentStore: string;
88 /** Project id. */
89 project: string;
90 /** Location id. */
91 location: string;
92 /** User id. */
93 userId: string | undefined;
94 /** Consent content version. */
95 consentContentVersion: string | undefined;
96 /** User metadata (Alchemy ownership keys stripped). */
97 metadata: Record<string, string>;
98 },
99 never,
100 Providers
101 >;
102
103 /**
104 * Documentation of a user's consent (artifact) in a consent store.
105 *
106 * Artifact ids are server-assigned. There is no patch API — changing
107 * `userId`, version, metadata, or parent replaces the artifact.
108 * Ownership is stamped into `metadata`.
109 *
110 * ### Creating a Consent Artifact
111 * **Example:** Artifact for a user
112 * ```typescript
113 * const artifact = yield* GCP.Healthcare.DatasetsConsentStoresConsentArtifact(
114 * "Proof",
115 * {
116 * consentStore: store.name,
117 * userId: "user-123",
118 * consentContentVersion: "v1",
119 * metadata: { locale: "en" },
120 * },
121 * );
122 * ```
123 *
124 * @resource
125 * @category Healthcare
126 */
127 export const DatasetsConsentStoresConsentArtifact = Resource<DatasetsConsentStoresConsentArtifact>(
128 "GCP.Healthcare.DatasetsConsentStoresConsentArtifact",
129 );
130
131 export class DatasetsConsentStoresConsentArtifactNotResolved extends Data.TaggedError(
132 "GCP.Healthcare.DatasetsConsentStoresConsentArtifactNotResolved",
133 )<{
134 resourceName: string;
135 }> {}
136
137 const storeOf = (
138 consentStore: string,
139 project: string,
140 location: string,
141 dataset: string | undefined,
142 ) => {
143 if (consentStore.includes("/")) return consentStore.replace(/\/+$/, "");
144 if (dataset === undefined) {
145 return expandParent(consentStore, project, location, "consentStores");
146 }
147 const datasetName = expandParent(dataset, project, location, "datasets");
148 return `${datasetName}/consentStores/${consentStore}`;
149 };
150
151 const toAttrs = (artifact: healthcare.ConsentArtifact, project: string, region: string) => {
152 const name = artifact.name ?? "";
153 const parsed = parseResourceName(name, "consentArtifacts", region);
154 return {
155 name,
156 consentArtifactId: parsed.id,
157 consentStore: parsed.parent,
158 project: parsed.project || project,
159 location: parsed.location,
160 userId: artifact.userId,
161 consentContentVersion: artifact.consentContentVersion,
162 metadata: userLabels(artifact.metadata),
163 };
164 };
165
166 const getByName = (name: string) =>
167 name.length === 0
168 ? Effect.undefined
169 : healthcare
170 .getProjectsLocationsDatasetsConsentStoresConsentArtifacts({ name })
171 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
172
173 export const DatasetsConsentStoresConsentArtifactProvider = () =>
174 Provider.succeed(DatasetsConsentStoresConsentArtifact, {
175 stables: ["name", "consentArtifactId", "consentStore", "project", "location"],
176
177 diff: Effect.fn(function* ({ news, olds, output }) {
178 if (!isResolved(news)) return undefined;
179 const env = yield* GcpEnvironment.current;
180 const previousParent = olds?.consentStore ?? output?.consentStore;
181 const nextParent = storeOf(
182 news.consentStore,
183 env.project,
184 normalizeLocation(news.location ?? output?.location, env.region),
185 news.dataset,
186 );
187 const parentChanged = previousParent !== undefined && previousParent !== nextParent;
188 const userChanged = olds?.userId !== undefined && olds.userId !== news.userId;
189 const versionChanged =
190 (olds?.consentContentVersion ?? output?.consentContentVersion) !== undefined &&
191 (olds?.consentContentVersion ?? output?.consentContentVersion) !==
192 news.consentContentVersion;
193 if (parentChanged || userChanged || versionChanged) {
194 return {
195 action: "replace" as const,
196 deleteFirst: !parentChanged,
197 };
198 }
199 return undefined;
200 }),
201
202 read: Effect.fn(function* ({ id, output }) {
203 const env = yield* GcpEnvironment.current;
204 const existing = yield* getByName(output?.name ?? "");
205 if (existing === undefined) return undefined;
206 const attrs = toAttrs(existing, env.project, env.region);
207 return (yield* hasAlchemyLabels(id, tagRecord(existing.metadata))) ? attrs : Unowned(attrs);
208 }),
209
210 list: () =>
211 Effect.gen(function* () {
212 const env = yield* GcpEnvironment.current;
213 const stores = yield* listAlchemyConsentStores(env.project, env.region);
214 const artifacts = yield* Effect.forEach(
215 stores,
216 (store) =>
217 collectPages(
218 healthcare.listProjectsLocationsDatasetsConsentStoresConsentArtifacts.pages({
219 parent: store.name ?? "",
220 pageSize: 1000,
221 }),
222 (page) => page.consentArtifacts,
223 ),
224 { concurrency: 4 },
225 );
226 return artifacts
227 .flat()
228 .filter((artifact) => hasAlchemyLabelMap(artifact.metadata))
229 .map((artifact) => toAttrs(artifact, env.project, env.region));
230 }),
231
232 reconcile: Effect.fn(function* ({ id, news, output }) {
233 const env = yield* GcpEnvironment.current;
234 const location = normalizeLocation(news.location ?? output?.location, env.region);
235 const consentStore = storeOf(news.consentStore, env.project, location, news.dataset);
236 const ownership = yield* createInternalLabels(id);
237 const metadata = withOwnershipMetadata(news.metadata, ownership);
238
239 let current = yield* getByName(output?.name ?? "");
240
241 if (current === undefined) {
242 current = yield* retryTransient(
243 healthcare.createProjectsLocationsDatasetsConsentStoresConsentArtifacts({
244 parent: consentStore,
245 body: {
246 userId: news.userId,
247 consentContentVersion: news.consentContentVersion,
248 metadata,
249 userSignature: news.userSignature,
250 guardianSignature: news.guardianSignature,
251 witnessSignature: news.witnessSignature,
252 },
253 }),
254 );
255 }
256
257 if (current === undefined) {
258 return yield* new DatasetsConsentStoresConsentArtifactNotResolved({
259 resourceName: consentStore,
260 });
261 }
262
263 return toAttrs(current, env.project, env.region);
264 }),
265
266 delete: Effect.fn(function* ({ output }) {
267 if (!output.name) return;
268 yield* retryTransient(
269 healthcare.deleteProjectsLocationsDatasetsConsentStoresConsentArtifacts({
270 name: output.name,
271 }),
272 ).pipe(Effect.catchTag("NotFound", () => Effect.void));
273 yield* waitUntilGone(getByName(output.name), output.name);
274 }),
275 });