@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, 04:45 UTC

main
ts 280 lines 10.5 KB
Raw
1 import * as datazone from "@distilled.cloud/aws/datazone";
2 import { isResolved } from "alchemy/Diff";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Effect from "effect/Effect";
7 import * as Schedule from "effect/Schedule";
8 import { unredact } from "./internal.ts";
9
10 export interface ProjectProps {
11 /**
12 * The identifier of the {@link Domain} the project lives in. Accepts a
13 * domain's `domainId` output. Changing it triggers a replacement.
14 */
15 domainId: string;
16 /**
17 * Name of the project. If omitted, a deterministic physical name is
18 * generated from the app, stage, and logical ID. The name is mutable — it
19 * converges via `UpdateProject` without replacement.
20 */
21 name?: string;
22 /**
23 * A description of the project.
24 */
25 description?: string;
26 /**
27 * Glossary term identifiers to attach to the project.
28 */
29 glossaryTerms?: string[];
30 }
31
32 export interface Project extends Resource<
33 "AWS.DataZone.Project",
34 ProjectProps,
35 {
36 /** The unique identifier of the project. */
37 projectId: string;
38 /** The identifier of the domain the project lives in. */
39 domainId: string;
40 /** The name of the project. */
41 name: string;
42 /** The status of the project (`ACTIVE` once settled). */
43 projectStatus: string | undefined;
44 /** The identifier of the domain unit the project belongs to. */
45 domainUnitId: string | undefined;
46 /** The DataZone user who created the project. */
47 createdBy: string;
48 }
49 > {}
50
51 /**
52 * An Amazon DataZone project — the collaboration space within a domain where
53 * teams catalog, publish, and subscribe to data assets.
54 *
55 * The creating principal is automatically the project owner. DataZone
56 * projects do not support resource tags, so ownership is tracked purely by
57 * identity.
58 *
59 * ### Creating Projects
60 * **Example:** Minimal Project
61 * ```typescript
62 * import * as DataZone from "@alchemy.run/aws/DataZone";
63 *
64 * const domain = yield* DataZone.Domain("governance", {});
65 *
66 * const project = yield* DataZone.Project("analytics", {
67 * domainId: domain.domainId,
68 * description: "Analytics team project",
69 * });
70 * ```
71 *
72 * **Example:** Project with an Explicit Name
73 * ```typescript
74 * const project = yield* DataZone.Project("analytics", {
75 * domainId: domain.domainId,
76 * name: "analytics-team",
77 * glossaryTerms: [term.id],
78 * });
79 * ```
80 *
81 * @resource
82 */
83 export const Project = Resource<Project>("AWS.DataZone.Project");
84
85 /** Project status values indicating an in-flight transition to wait out. */
86 const PROJECT_TRANSIENT = new Set(["DELETING", "MOVING", "UPDATING"]);
87
88 /**
89 * A freshly created domain propagates the creator's user profile eventually;
90 * `createProject` can transiently reject with `AccessDeniedException` right
91 * after domain creation. Wrapped in an explicitly-typed helper so the
92 * `Effect.retry` conditional return type does not leak into declaration emit
93 * (see PATTERNS §7).
94 */
95 const retryWhileUserProfilePropagates = <A, E extends { _tag: string }, R>(
96 self: Effect.Effect<A, E, R>,
97 ): Effect.Effect<A, E, R> =>
98 Effect.retry(self, {
99 while: (e) => e._tag === "AccessDeniedException",
100 schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(10)]),
101 });
102
103 export const ProjectProvider = () =>
104 Provider.effect(
105 Project,
106 Effect.gen(function* () {
107 const createName = Effect.fn(function* (id: string, props: ProjectProps) {
108 return props.name ?? (yield* createPhysicalName({ id, maxLength: 64 }));
109 });
110
111 // A deleted project — or a project inside a deleted domain — is
112 // reported as AccessDeniedException, NOT ResourceNotFoundException:
113 // DataZone evaluates domain-scoped authorization before existence.
114 // Both mean "absent".
115 const getProjectOrUndefined = Effect.fn(function* (domainId: string, projectId: string) {
116 return yield* datazone
117 .getProject({ domainIdentifier: domainId, identifier: projectId })
118 .pipe(
119 Effect.catchTags({
120 ResourceNotFoundException: () => Effect.undefined,
121 AccessDeniedException: () => Effect.undefined,
122 }),
123 );
124 });
125
126 const findByName = Effect.fn(function* (domainId: string, name: string) {
127 const found = yield* datazone.listProjects({ domainIdentifier: domainId, name }).pipe(
128 Effect.catchTags({
129 ResourceNotFoundException: () => Effect.undefined,
130 AccessDeniedException: () => Effect.undefined,
131 }),
132 );
133 const summary = (found?.items ?? []).find(
134 (s) => unredact(s.name) === name && s.projectStatus !== "DELETING",
135 );
136 return summary?.id;
137 });
138
139 // Poll the project to a settled (non-transient) status — project
140 // operations settle within seconds.
141 const waitForSettled = Effect.fn(function* (domainId: string, projectId: string) {
142 return yield* getProjectOrUndefined(domainId, projectId).pipe(
143 Effect.repeat({
144 schedule: Schedule.fixed("3 seconds"),
145 until: (project) =>
146 project === undefined ||
147 project.projectStatus === undefined ||
148 !PROJECT_TRANSIENT.has(project.projectStatus),
149 times: 20,
150 }),
151 );
152 });
153
154 // Poll the project until it no longer exists — deletion is async but
155 // settles within seconds for empty projects.
156 const waitForGone = Effect.fn(function* (domainId: string, projectId: string) {
157 yield* getProjectOrUndefined(domainId, projectId).pipe(
158 Effect.repeat({
159 schedule: Schedule.fixed("3 seconds"),
160 until: (project) => project === undefined,
161 times: 20,
162 }),
163 );
164 });
165
166 const toAttributes = (project: datazone.GetProjectOutput | datazone.CreateProjectOutput) => ({
167 projectId: project.id,
168 domainId: project.domainId,
169 name: unredact(project.name),
170 projectStatus: project.projectStatus,
171 domainUnitId: project.domainUnitId,
172 createdBy: project.createdBy,
173 });
174
175 return Project.Provider.of({
176 stables: ["projectId", "domainId", "createdBy"],
177
178 // Projects are keyed by their parent domain — there is no
179 // account-level enumeration without a domain identifier.
180 list: () => Effect.succeed([]),
181
182 read: Effect.fn(function* ({ id, olds, output }) {
183 const domainId = output?.domainId ?? olds?.domainId;
184 if (domainId === undefined) return undefined;
185 const projectId =
186 output?.projectId ??
187 (yield* findByName(domainId, yield* createName(id, olds ?? { domainId })));
188 if (projectId === undefined) return undefined;
189 const project = yield* getProjectOrUndefined(domainId, projectId);
190 if (project === undefined || project.projectStatus === "DELETING") {
191 return undefined;
192 }
193 // Projects have no tags — ownership is tracked purely by identity.
194 return toAttributes(project);
195 }),
196
197 diff: Effect.fn(function* ({ news, olds }) {
198 if (!isResolved(news)) return undefined;
199 if (olds !== undefined && olds.domainId !== news.domainId) {
200 return { action: "replace" } as const;
201 }
202 // name, description, and glossaryTerms converge via updateProject.
203 }),
204
205 reconcile: Effect.fn(function* ({ id, news, output, session }) {
206 const domainId = news.domainId;
207 const name = yield* createName(id, news);
208
209 // 1. OBSERVE — cloud state is authoritative; output is only an id
210 // cache. Fall back to a name lookup after state loss.
211 let project = output?.projectId
212 ? yield* getProjectOrUndefined(domainId, output.projectId)
213 : undefined;
214 if (project === undefined) {
215 const foundId = yield* findByName(domainId, name);
216 if (foundId !== undefined) {
217 project = yield* getProjectOrUndefined(domainId, foundId);
218 }
219 }
220
221 if (project === undefined) {
222 // 2. ENSURE — create (retrying the user-profile propagation
223 // window right after domain creation).
224 project = yield* retryWhileUserProfilePropagates(
225 datazone.createProject({
226 domainIdentifier: domainId,
227 name,
228 description: news.description,
229 glossaryTerms: news.glossaryTerms,
230 }),
231 );
232 project = (yield* waitForSettled(domainId, project.id)) ?? project;
233 } else {
234 // 3. SYNC — wait out any in-flight transition, then converge the
235 // mutable aspects by diffing OBSERVED state against desired.
236 project = (yield* waitForSettled(domainId, project.id)) ?? project;
237 const observedTerms = project.glossaryTerms ?? [];
238 const desiredTerms = news.glossaryTerms ?? [];
239 const drifted =
240 unredact(project.name) !== name ||
241 (project.description === undefined ? undefined : unredact(project.description)) !==
242 (news.description ?? undefined) ||
243 observedTerms.length !== desiredTerms.length ||
244 desiredTerms.some((t) => !observedTerms.includes(t));
245 if (drifted) {
246 yield* datazone.updateProject({
247 domainIdentifier: domainId,
248 identifier: project.id,
249 name,
250 description: news.description,
251 glossaryTerms: news.glossaryTerms,
252 });
253 project = (yield* getProjectOrUndefined(domainId, project.id)) ?? project;
254 }
255 }
256
257 yield* session.note(project.id);
258 return toAttributes(project);
259 }),
260
261 delete: Effect.fn(function* ({ output }) {
262 yield* datazone
263 .deleteProject({
264 domainIdentifier: output.domainId,
265 identifier: output.projectId,
266 skipDeletionCheck: true,
267 })
268 .pipe(
269 Effect.catchTags({
270 ResourceNotFoundException: () => Effect.void,
271 // deleting a project whose domain is already gone surfaces as
272 // AccessDenied — auth is checked before existence.
273 AccessDeniedException: () => Effect.void,
274 }),
275 );
276 yield* waitForGone(output.domainId, output.projectId);
277 }),
278 });
279 }),
280 );