@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 331 lines 10.6 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 sameJson,
21 sameText,
22 updateMaskOf,
23 userLabels,
24 waitUntilGone,
25 withOwnershipMetadata,
26 } from "./internal.ts";
27
28 export type ConsentPolicy = {
29 /** Resource attributes this policy matches. */
30 resourceAttributes?: healthcare.Attribute[];
31 /** CEL authorization rule. */
32 authorizationRule?: healthcare.Expr;
33 };
34
35 export type DatasetsConsentStoresConsentProps = {
36 /**
37 * Parent consent store. Full name
38 * `.../consentStores/{consentStore}` or the store id (combined with
39 * `dataset` and `location`). Immutable — changing it replaces the
40 * consent.
41 */
42 consentStore: string;
43 /**
44 * Parent dataset used when `consentStore` is a bare id.
45 */
46 dataset?: string;
47 /**
48 * Region used when `consentStore` is a bare id.
49 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
50 */
51 location?: string;
52 /**
53 * User UUID supplied by the client.
54 */
55 userId: string;
56 /**
57 * Consent artifact resource name proving the end-user consent.
58 */
59 consentArtifact: string;
60 /**
61 * Consent state. Created as `DRAFT` unless set. State transitions
62 * after create use activate/revoke RPCs (`ACTIVE`, `REVOKED`).
63 * @default "DRAFT"
64 */
65 state?: healthcare.ConsentStateEnum | (string & {});
66 /**
67 * Consent metadata. Alchemy ownership keys are merged in
68 * automatically.
69 */
70 metadata?: Record<string, string>;
71 /**
72 * Authorization policies.
73 */
74 policies?: ConsentPolicy[];
75 /**
76 * Input-only TTL from create time (e.g. `"86400s"`).
77 */
78 ttl?: string;
79 };
80
81 export type DatasetsConsentStoresConsent = Resource<
82 "GCP.Healthcare.DatasetsConsentStoresConsent",
83 DatasetsConsentStoresConsentProps,
84 {
85 /** Full resource name `.../consents/{consent}`. */
86 name: string;
87 /** Server-assigned consent id. */
88 consentId: string;
89 /** Parent consent store resource name. */
90 consentStore: string;
91 /** Project id. */
92 project: string;
93 /** Location id. */
94 location: string;
95 /** User id. */
96 userId: string | undefined;
97 /** Consent artifact resource name. */
98 consentArtifact: string | undefined;
99 /** Consent state. */
100 state: string | undefined;
101 /** User metadata (Alchemy ownership keys stripped). */
102 metadata: Record<string, string>;
103 /** Revision id. */
104 revisionId: string | undefined;
105 /** RFC3339 revision create time. */
106 revisionCreateTime: string | undefined;
107 /** RFC3339 expiry. */
108 expireTime: string | undefined;
109 },
110 never,
111 Providers
112 >;
113
114 /**
115 * A user's consent in a consent store.
116 *
117 * Consent ids are server-assigned. `userId`, policies, consent artifact,
118 * and metadata update by committing a new revision. Ownership is stamped
119 * into `metadata`.
120 *
121 * ### Creating a Consent
122 * **Example:** Draft consent
123 * ```typescript
124 * const consent = yield* GCP.Healthcare.DatasetsConsentStoresConsent(
125 * "Grant",
126 * {
127 * consentStore: store.name,
128 * userId: "user-123",
129 * consentArtifact: artifact.name,
130 * state: "DRAFT",
131 * metadata: { source: "app" },
132 * },
133 * );
134 * ```
135 *
136 * @resource
137 * @category Healthcare
138 */
139 export const DatasetsConsentStoresConsent = Resource<DatasetsConsentStoresConsent>(
140 "GCP.Healthcare.DatasetsConsentStoresConsent",
141 );
142
143 export class DatasetsConsentStoresConsentNotResolved extends Data.TaggedError(
144 "GCP.Healthcare.DatasetsConsentStoresConsentNotResolved",
145 )<{
146 resourceName: string;
147 }> {}
148
149 const DEFAULT_STATE = "DRAFT";
150
151 const storeOf = (
152 consentStore: string,
153 project: string,
154 location: string,
155 dataset: string | undefined,
156 ) => {
157 if (consentStore.includes("/")) return consentStore.replace(/\/+$/, "");
158 if (dataset === undefined) {
159 return expandParent(consentStore, project, location, "consentStores");
160 }
161 const datasetName = expandParent(dataset, project, location, "datasets");
162 return `${datasetName}/consentStores/${consentStore}`;
163 };
164
165 const toAttrs = (consent: healthcare.Consent, project: string, region: string) => {
166 const name = consent.name ?? "";
167 const parsed = parseResourceName(name, "consents", region);
168 return {
169 name,
170 consentId: parsed.id.split("@")[0] ?? parsed.id,
171 consentStore: parsed.parent,
172 project: parsed.project || project,
173 location: parsed.location,
174 userId: consent.userId,
175 consentArtifact: consent.consentArtifact,
176 state: consent.state,
177 metadata: userLabels(consent.metadata),
178 revisionId: consent.revisionId,
179 revisionCreateTime: consent.revisionCreateTime,
180 expireTime: consent.expireTime,
181 };
182 };
183
184 const getByName = (name: string) =>
185 name.length === 0
186 ? Effect.undefined
187 : healthcare
188 .getProjectsLocationsDatasetsConsentStoresConsents({ name })
189 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
190
191 export const DatasetsConsentStoresConsentProvider = () =>
192 Provider.succeed(DatasetsConsentStoresConsent, {
193 stables: ["name", "consentId", "consentStore", "project", "location"],
194
195 diff: Effect.fn(function* ({ news, olds, output }) {
196 if (!isResolved(news)) return undefined;
197 const env = yield* GcpEnvironment.current;
198 const previousParent = olds?.consentStore ?? output?.consentStore;
199 const nextParent = storeOf(
200 news.consentStore,
201 env.project,
202 normalizeLocation(news.location ?? output?.location, env.region),
203 news.dataset,
204 );
205 if (previousParent !== undefined && previousParent !== nextParent) {
206 return { action: "replace" as const, deleteFirst: false };
207 }
208 return undefined;
209 }),
210
211 read: Effect.fn(function* ({ id, output }) {
212 const env = yield* GcpEnvironment.current;
213 const existing = yield* getByName(output?.name ?? "");
214 if (existing === undefined) return undefined;
215 const attrs = toAttrs(existing, env.project, env.region);
216 return (yield* hasAlchemyLabels(id, tagRecord(existing.metadata))) ? attrs : Unowned(attrs);
217 }),
218
219 list: () =>
220 Effect.gen(function* () {
221 const env = yield* GcpEnvironment.current;
222 const stores = yield* listAlchemyConsentStores(env.project, env.region);
223 const consents = yield* Effect.forEach(
224 stores,
225 (store) =>
226 collectPages(
227 healthcare.listProjectsLocationsDatasetsConsentStoresConsents.pages({
228 parent: store.name ?? "",
229 pageSize: 1000,
230 }),
231 (page) => page.consents,
232 ),
233 { concurrency: 4 },
234 );
235 return consents
236 .flat()
237 .filter((consent) => hasAlchemyLabelMap(consent.metadata))
238 .map((consent) => toAttrs(consent, env.project, env.region));
239 }),
240
241 reconcile: Effect.fn(function* ({ id, news, output }) {
242 const env = yield* GcpEnvironment.current;
243 const location = normalizeLocation(news.location ?? output?.location, env.region);
244 const consentStore = storeOf(news.consentStore, env.project, location, news.dataset);
245 const ownership = yield* createInternalLabels(id);
246 const metadata = withOwnershipMetadata(news.metadata, ownership);
247 const state = news.state ?? DEFAULT_STATE;
248
249 let current = yield* getByName(output?.name ?? "");
250
251 if (current === undefined) {
252 current = yield* retryTransient(
253 healthcare.createProjectsLocationsDatasetsConsentStoresConsents({
254 parent: consentStore,
255 body: {
256 userId: news.userId,
257 consentArtifact: news.consentArtifact,
258 state,
259 metadata,
260 policies: news.policies,
261 ttl: news.ttl,
262 },
263 }),
264 );
265 }
266
267 if (current === undefined) {
268 return yield* new DatasetsConsentStoresConsentNotResolved({
269 resourceName: consentStore,
270 });
271 }
272
273 const currentName = current.name ?? output?.name ?? "";
274 const userChanged = !sameText(current.userId, news.userId);
275 const artifactChanged = !sameText(current.consentArtifact, news.consentArtifact);
276 const policiesChanged = !sameJson(current.policies, news.policies);
277 const metadataChanged =
278 !sameJson(userLabels(current.metadata), userLabels(news.metadata)) ||
279 !hasAlchemyLabelMap(current.metadata);
280
281 if (userChanged || artifactChanged || policiesChanged || metadataChanged) {
282 current = yield* retryTransient(
283 healthcare.patchProjectsLocationsDatasetsConsentStoresConsents({
284 name: currentName,
285 updateMask: updateMaskOf(
286 userChanged ? "userId" : undefined,
287 artifactChanged ? "consentArtifact" : undefined,
288 policiesChanged ? "policies" : undefined,
289 metadataChanged ? "metadata" : undefined,
290 ),
291 body: {
292 userId: news.userId,
293 consentArtifact: news.consentArtifact,
294 policies: news.policies,
295 metadata,
296 },
297 }),
298 );
299 }
300
301 const currentState = current.state ?? DEFAULT_STATE;
302 if (state === "ACTIVE" && currentState === "DRAFT") {
303 current = yield* retryTransient(
304 healthcare.activateProjectsLocationsDatasetsConsentStoresConsents({
305 name: current.name ?? currentName,
306 body: {
307 consentArtifact: news.consentArtifact,
308 },
309 }),
310 );
311 } else if (state === "REVOKED" && currentState === "ACTIVE") {
312 current = yield* retryTransient(
313 healthcare.revokeProjectsLocationsDatasetsConsentStoresConsents({
314 name: current.name ?? currentName,
315 }),
316 );
317 }
318
319 return toAttrs(current, env.project, env.region);
320 }),
321
322 delete: Effect.fn(function* ({ output }) {
323 if (!output.name) return;
324 yield* retryTransient(
325 healthcare.deleteProjectsLocationsDatasetsConsentStoresConsents({
326 name: output.name,
327 }),
328 ).pipe(Effect.catchTag("NotFound", () => Effect.void));
329 yield* waitUntilGone(getByName(output.name), output.name);
330 }),
331 });