@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 281 lines 9.97 KB
Raw
1 import { flociServices } from "@alchemy.run/aws/Local/FlociServices";
2 import * as Test from "@alchemy.run/test/Alchemy";
3 import * as organizations from "@distilled.cloud/aws/organizations";
4 import * as Effect from "effect/Effect";
5 import * as Redacted from "effect/Redacted";
6 import * as Schedule from "effect/Schedule";
7 import * as Semaphore from "effect/Semaphore";
8 import * as Stream from "effect/Stream";
9
10 /**
11 * Process-wide lease on the account's single AWS Organization.
12 *
13 * Suites that read or mutate the organization take a `shared` lease; a suite
14 * that creates and deletes the organization itself takes the `exclusive`
15 * lease, which waits until every shared holder has released.
16 *
17 * Under `ALCHEMY_TEST_DEV=1` (Floci) the first shared holder ensures an
18 * organization exists and the last one removes what this module provisioned:
19 * its named OU and member account, and the organization only if this module
20 * created it. Against real AWS the lease only schedules; it never creates or
21 * deletes anything, and env-supplied values always win.
22 */
23
24 // Shared holders take 1 permit; the exclusive holder takes all of them.
25 const PERMITS = 1024;
26 const lease = Semaphore.makeUnsafe(PERMITS);
27 // Writer preference: a waiting exclusive holder blocks new shared holders.
28 const turnstile = Semaphore.makeUnsafe(1);
29 // Serializes the holder count with fixture provisioning and teardown.
30 const fixtureLock = Semaphore.makeUnsafe(1);
31
32 export const emulator = process.env.ALCHEMY_TEST_DEV === "1";
33
34 /** Whether the delegated-administrator lifecycle has a member account. */
35 export const canProvideDelegatedAdminAccount =
36 !!process.env.AWS_ORG_DELEGATED_ADMIN_ACCOUNT_ID ||
37 (emulator && !!process.env.AWS_ORG_MANAGEMENT_ACCOUNT);
38
39 const FIXTURE_NAME = "alchemy-test-org-lease";
40 const FIXTURE_MEMBER_EMAIL = `${FIXTURE_NAME}@example.com`;
41
42 let holders = 0;
43 // `ready`: the organization is ensured; `touched`: reclaim on last release.
44 let ready = false;
45 let touched = false;
46 let createdOrganization = false;
47
48 const unredact = (value: string | Redacted.Redacted<string> | undefined) =>
49 value === undefined || typeof value === "string" ? value : Redacted.value(value);
50
51 const describeOrganization = organizations.describeOrganization({}).pipe(
52 Effect.map((response) => response.Organization),
53 Effect.catchTag("AWSOrganizationsNotInUseException", () => Effect.succeed(undefined)),
54 );
55
56 const ensureOrganization = Effect.gen(function* () {
57 if ((yield* describeOrganization) !== undefined) return;
58 yield* organizations.createOrganization({ FeatureSet: "ALL" }).pipe(
59 Effect.tap(() =>
60 Effect.sync(() => {
61 createdOrganization = true;
62 }),
63 ),
64 Effect.catchTag("AlreadyInOrganizationException", () => Effect.void),
65 );
66 });
67
68 const findRootId = organizations.listRoots({}).pipe(
69 Effect.map((response) => response.Roots?.[0]?.Id),
70 Effect.catchTag("AWSOrganizationsNotInUseException", () => Effect.succeed(undefined)),
71 );
72
73 const findFixtureOu = (rootId: string) =>
74 organizations.listOrganizationalUnitsForParent.pages({ ParentId: rootId }).pipe(
75 Stream.runCollect,
76 Effect.map((pages) =>
77 Array.from(pages)
78 .flatMap((page) => page.OrganizationalUnits ?? [])
79 .find((unit) => unit.Name === FIXTURE_NAME),
80 ),
81 );
82
83 const ensureFixtureOu = Effect.gen(function* () {
84 const rootId = yield* findRootId;
85 if (rootId === undefined) {
86 return yield* Effect.fail(new Error("the emulator has no organization"));
87 }
88 const unit =
89 (yield* findFixtureOu(rootId)) ??
90 (yield* organizations.createOrganizationalUnit({ ParentId: rootId, Name: FIXTURE_NAME }).pipe(
91 Effect.map((response) => response.OrganizationalUnit),
92 Effect.catchTag("DuplicateOrganizationalUnitException", () => findFixtureOu(rootId)),
93 ));
94 if (unit?.Arn === undefined) {
95 return yield* Effect.fail(new Error(`could not resolve OU ${FIXTURE_NAME}`));
96 }
97 return unit.Arn;
98 });
99
100 const findFixtureMember = organizations.listAccounts.pages({}).pipe(
101 Stream.runCollect,
102 Effect.map((pages) =>
103 Array.from(pages)
104 .flatMap((page) => page.Accounts ?? [])
105 .find((account) => unredact(account.Email) === FIXTURE_MEMBER_EMAIL),
106 ),
107 Effect.catchTag("AWSOrganizationsNotInUseException", () => Effect.succeed(undefined)),
108 );
109
110 const ensureFixtureMember = Effect.gen(function* () {
111 const existing = yield* findFixtureMember;
112 if (existing?.Id !== undefined) return existing.Id;
113 const created = yield* organizations.createAccount({
114 AccountName: FIXTURE_NAME,
115 Email: FIXTURE_MEMBER_EMAIL,
116 });
117 const requestId = created.CreateAccountStatus?.Id;
118 if (requestId === undefined) {
119 return yield* Effect.fail(new Error("CreateAccount returned no request id"));
120 }
121 const status = yield* organizations
122 .describeCreateAccountStatus({ CreateAccountRequestId: requestId })
123 .pipe(
124 Effect.map((response) => response.CreateAccountStatus),
125 Effect.repeat({
126 schedule: Schedule.spaced("2 seconds"),
127 until: (status): boolean => status?.State !== "IN_PROGRESS",
128 times: 15,
129 }),
130 );
131 if (status?.State !== "SUCCEEDED" || status.AccountId === undefined) {
132 return yield* Effect.fail(
133 new Error(
134 `member account creation ended ${status?.State ?? "without status"} (${status?.FailureReason ?? "no reason"})`,
135 ),
136 );
137 }
138 return status.AccountId;
139 });
140
141 /** Removes the fixture's named OU and member, and the org if it created it. */
142 const reclaimFixture = Effect.gen(function* () {
143 const member = yield* findFixtureMember;
144 if (member?.Id !== undefined) {
145 yield* organizations
146 .removeAccountFromOrganization({ AccountId: member.Id })
147 .pipe(Effect.catchTag("AccountNotFoundException", () => Effect.void));
148 }
149 const rootId = yield* findRootId;
150 const unit = rootId === undefined ? undefined : yield* findFixtureOu(rootId);
151 if (unit?.Id !== undefined) {
152 yield* organizations
153 .deleteOrganizationalUnit({ OrganizationalUnitId: unit.Id })
154 .pipe(Effect.catchTag("OrganizationalUnitNotFoundException", () => Effect.void));
155 }
156 if (createdOrganization) {
157 yield* organizations
158 .deleteOrganization({})
159 .pipe(Effect.catchTag("AWSOrganizationsNotInUseException", () => Effect.void));
160 createdOrganization = false;
161 }
162 });
163
164 // Pins every fixture call to the emulator, independent of the caller's context.
165 const onEmulator = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
166 effect.pipe(Effect.provide(flociServices()));
167
168 const requireShared = Effect.suspend(() =>
169 holders > 0
170 ? Effect.void
171 : Effect.fail(
172 new Error('the organization fixture requires OrganizationLease.make(..., "shared")'),
173 ),
174 );
175
176 /** OU for the Control Tower lifecycles: `AWS_TEST_CONTROLTOWER_OU`, else the emulator fixture OU. */
177 export const controlTowerOuArn = Effect.suspend(() => {
178 const fromEnv = process.env.AWS_TEST_CONTROLTOWER_OU;
179 if (fromEnv) return Effect.succeed(fromEnv);
180 if (!emulator) {
181 return Effect.fail(new Error("AWS_TEST_CONTROLTOWER_OU is required"));
182 }
183 return requireShared.pipe(
184 Effect.andThen(fixtureLock.withPermits(1)(onEmulator(ensureFixtureOu))),
185 );
186 });
187
188 /** Member account: `AWS_ORG_DELEGATED_ADMIN_ACCOUNT_ID`, else the emulator fixture member. */
189 export const delegatedAdminAccountId = Effect.suspend(() => {
190 const fromEnv = process.env.AWS_ORG_DELEGATED_ADMIN_ACCOUNT_ID;
191 if (fromEnv) return Effect.succeed(fromEnv);
192 if (!emulator) {
193 return Effect.fail(new Error("AWS_ORG_DELEGATED_ADMIN_ACCOUNT_ID is required"));
194 }
195 return requireShared.pipe(
196 Effect.andThen(fixtureLock.withPermits(1)(onEmulator(ensureFixtureMember))),
197 );
198 });
199
200 const makeShared = () => {
201 let held = false;
202 let joined = false;
203 const release = Effect.suspend(() => {
204 if (!held) return Effect.void;
205 held = false;
206 return fixtureLock
207 .withPermits(1)(
208 Effect.suspend(() => {
209 if (!joined) return Effect.void;
210 joined = false;
211 holders -= 1;
212 if (holders > 0 || !touched) return Effect.void;
213 ready = false;
214 touched = false;
215 return onEmulator(reclaimFixture);
216 }),
217 )
218 .pipe(Effect.ensuring(lease.release(1)));
219 });
220 const acquire = Effect.uninterruptibleMask((restore) =>
221 Effect.gen(function* () {
222 yield* restore(turnstile.withPermits(1)(lease.take(1)));
223 held = true;
224 yield* Effect.addFinalizer(() =>
225 release.pipe(
226 Effect.catchCause((cause) => Effect.logError("organization lease release failed", cause)),
227 ),
228 );
229 yield* fixtureLock.withPermits(1)(
230 Effect.suspend(() => {
231 holders += 1;
232 joined = true;
233 if (!emulator || ready) return Effect.void;
234 touched = true;
235 return restore(onEmulator(ensureOrganization)).pipe(
236 Effect.tap(() =>
237 Effect.sync(() => {
238 ready = true;
239 }),
240 ),
241 );
242 }),
243 );
244 }),
245 );
246 return { acquire, release };
247 };
248
249 const makeExclusive = () => {
250 let held = false;
251 const release = Effect.suspend(() => {
252 if (!held) return Effect.void;
253 held = false;
254 return lease.release(PERMITS).pipe(Effect.asVoid);
255 });
256 const acquire = Effect.uninterruptibleMask((restore) =>
257 Effect.gen(function* () {
258 yield* restore(turnstile.withPermits(1)(lease.take(PERMITS)));
259 held = true;
260 yield* Effect.addFinalizer(() => release);
261 }),
262 );
263 return { acquire, release };
264 };
265
266 /**
267 * `Test.make` adapter that holds the organization lease for the whole file.
268 * The release hook registers before the file's own `afterAll` hooks, so those
269 * must not own organization resources; a scope finalizer backs it up.
270 */
271 export const make = <ROut = any>(
272 options: Test.MakeOptions<ROut>,
273 mode: "shared" | "exclusive",
274 ): Test.TestApi => {
275 const api = Test.make(options);
276 const handle = mode === "shared" ? makeShared() : makeExclusive();
277 // Waiting is scheduling across the whole run, not a cloud operation.
278 api.beforeAll(handle.acquire, { timeout: 3_600_000 });
279 api.afterAll(handle.release, { timeout: 120_000 });
280 return api;
281 };