@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 246 lines 9.26 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import { CloudflareEnvironment } from "@alchemy.run/cloudflare/CloudflareEnvironment";
3 import { expect } from "@alchemy.run/test";
4 import * as Test from "@alchemy.run/test/Alchemy";
5 import * as accounts from "@distilled.cloud/cloudflare/accounts";
6 import * as Provider from "alchemy/Provider";
7 import * as Effect from "effect/Effect";
8 import { MinimumLogLevel } from "effect/References";
9 import * as Schedule from "effect/Schedule";
10 import * as Stream from "effect/Stream";
11
12 const { test } = Test.make({ providers: Cloudflare.providers() });
13
14 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
15
16 // Deterministic invite addresses we own — invites stay `pending`, which is
17 // fine; deleting the member cancels the invite. Each test owns a distinct
18 // address: the suites run concurrently against one shared account, so a
19 // shared email would let one test's destroy/cleanup cancel another's invite
20 // mid-flight (a `MemberNotFound` race).
21 const crudEmail = "sam+alchemy-test-member-crud@alchemy.run";
22 const replaceEmail = "sam+alchemy-test-member-replace@alchemy.run";
23 const replacedEmail = "sam+alchemy-test-member-replaced@alchemy.run";
24 const healEmail = "sam+alchemy-test-member-heal@alchemy.run";
25
26 // The scoped API token the test harness mints propagates eventually-
27 // consistently across Cloudflare's edge — ride out 403 blips (`Forbidden`,
28 // declared in the distilled error union) on out-of-band verification calls.
29 const forbiddenRetry = {
30 while: (e: { _tag: string }) => e._tag === "Forbidden",
31 schedule: Schedule.exponential("500 millis"),
32 times: 8,
33 } as const;
34
35 const getMember = (accountId: string, memberId: string) =>
36 accounts.getMember({ accountId, memberId }).pipe(Effect.retry(forbiddenRetry));
37
38 const expectGone = (accountId: string, memberId: string) =>
39 getMember(accountId, memberId).pipe(
40 Effect.flatMap(() => Effect.fail({ _tag: "MemberNotDeleted" } as const)),
41 // A missing member surfaces as `MemberNotFound` (Cloudflare error
42 // code 1003) — that's the success condition here.
43 Effect.catchTag("MemberNotFound", () => Effect.void),
44 Effect.retry({
45 while: (e) => e._tag === "MemberNotDeleted",
46 schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(10)]),
47 }),
48 );
49
50 // Remove any membership left behind by a previous crashed run so the test
51 // account stays clean and create paths start from a known baseline.
52 const cleanupEmail = (accountId: string, email: string) =>
53 accounts.listMembers.items({ accountId }).pipe(
54 Stream.runCollect,
55 Effect.retry(forbiddenRetry),
56 Effect.flatMap((chunk) => {
57 const match = Array.from(chunk).find(
58 (member) => member.email?.toLowerCase() === email.toLowerCase(),
59 );
60 return match?.id != null
61 ? accounts
62 .deleteMember({ accountId, memberId: match.id })
63 .pipe(Effect.catchTag("MemberNotFound", () => Effect.void))
64 : Effect.void;
65 }),
66 );
67
68 // Pick two deterministic non-super-admin roles for the account: sorted by
69 // name so every run selects the same pair.
70 const pickTwoRoles = (accountId: string) =>
71 accounts.listRoles.items({ accountId }).pipe(
72 Stream.runCollect,
73 Effect.retry(forbiddenRetry),
74 Effect.map((chunk) => {
75 const roles = Array.from(chunk)
76 .filter((role) => !role.name.startsWith("Super Administrator"))
77 .sort((a, b) => a.name.localeCompare(b.name));
78 expect(roles.length).toBeGreaterThanOrEqual(2);
79 return [roles[0]!, roles[1]!] as const;
80 }),
81 );
82
83 // Read-only: enumerating account members sends no invites. The account
84 // owner is always an accepted member, so `list()` must return a non-empty,
85 // well-typed `Attributes[]` containing at least one accepted membership.
86 test.provider(
87 "list enumerates the account members",
88 (_stack) =>
89 Effect.gen(function* () {
90 const { accountId } = yield* yield* CloudflareEnvironment;
91
92 const provider = yield* Provider.findProvider(Cloudflare.Account.Member);
93 const all = yield* provider.list().pipe(Effect.retry(forbiddenRetry));
94
95 expect(all.length).toBeGreaterThan(0);
96 // Every element is the exact `read` shape, scoped to this account.
97 for (const member of all) {
98 expect(member.memberId).toBeTruthy();
99 expect(member.accountId).toEqual(accountId);
100 expect(typeof member.email).toBe("string");
101 expect(Array.isArray(member.roles)).toBe(true);
102 }
103 // The account owner is an accepted member.
104 expect(all.some((member) => member.status === "accepted")).toBe(true);
105 }).pipe(logLevel),
106 { tags: ["provider:cloudflare", "provider:cloudflare:account", "live"] },
107 );
108
109 test.provider(
110 "create member, update roles in place, delete",
111 (stack) =>
112 Effect.gen(function* () {
113 const { accountId } = yield* yield* CloudflareEnvironment;
114
115 yield* stack.destroy();
116 yield* cleanupEmail(accountId, crudEmail);
117
118 const [roleA, roleB] = yield* pickTwoRoles(accountId);
119
120 const member = yield* stack.deploy(
121 Cloudflare.Account.Member("TestMember", {
122 email: crudEmail,
123 roles: [roleA.id],
124 }),
125 );
126
127 expect(member.memberId).toBeTruthy();
128 expect(member.accountId).toEqual(accountId);
129 expect(member.email.toLowerCase()).toEqual(crudEmail);
130 expect(member.status).toEqual("pending");
131 expect(member.roles.map((r) => r.id)).toEqual([roleA.id]);
132
133 // Out-of-band verify the invite exists with the assigned role.
134 const live = yield* getMember(accountId, member.memberId);
135 expect(live.email?.toLowerCase()).toEqual(crudEmail);
136 expect((live.roles ?? []).map((r) => r.id)).toEqual([roleA.id]);
137
138 // Swap the role — same email, so the membership is updated in place.
139 const updated = yield* stack.deploy(
140 Cloudflare.Account.Member("TestMember", {
141 email: crudEmail,
142 roles: [roleB.id],
143 }),
144 );
145 expect(updated.memberId).toEqual(member.memberId);
146 expect(updated.roles.map((r) => r.id)).toEqual([roleB.id]);
147
148 const liveUpdated = yield* getMember(accountId, member.memberId);
149 expect((liveUpdated.roles ?? []).map((r) => r.id)).toEqual([roleB.id]);
150
151 // Redeploying identical props is a no-op (same membership).
152 const noop = yield* stack.deploy(
153 Cloudflare.Account.Member("TestMember", {
154 email: crudEmail,
155 roles: [roleB.id],
156 }),
157 );
158 expect(noop.memberId).toEqual(member.memberId);
159
160 yield* stack.destroy();
161 yield* expectGone(accountId, member.memberId);
162 }).pipe(logLevel),
163 { tags: ["provider:cloudflare", "provider:cloudflare:account", "live"] },
164 );
165
166 test.provider(
167 "replaces the member when the email changes",
168 (stack) =>
169 Effect.gen(function* () {
170 const { accountId } = yield* yield* CloudflareEnvironment;
171
172 yield* stack.destroy();
173 yield* cleanupEmail(accountId, replaceEmail);
174 yield* cleanupEmail(accountId, replacedEmail);
175
176 const [roleA] = yield* pickTwoRoles(accountId);
177
178 const original = yield* stack.deploy(
179 Cloudflare.Account.Member("ReplaceMember", {
180 email: replaceEmail,
181 roles: [roleA.id],
182 }),
183 );
184
185 // Changing the email re-invites: a fresh membership id, and the old
186 // invite is cancelled by the replacement's delete phase.
187 const replaced = yield* stack.deploy(
188 Cloudflare.Account.Member("ReplaceMember", {
189 email: replacedEmail,
190 roles: [roleA.id],
191 }),
192 );
193
194 expect(replaced.memberId).not.toEqual(original.memberId);
195 expect(replaced.email.toLowerCase()).toEqual(replacedEmail);
196 yield* expectGone(accountId, original.memberId);
197
198 yield* stack.destroy();
199 yield* expectGone(accountId, replaced.memberId);
200 }).pipe(logLevel),
201 { tags: ["provider:cloudflare", "provider:cloudflare:account", "live"] },
202 );
203
204 test.provider(
205 "recreates after out-of-band delete",
206 (stack) =>
207 Effect.gen(function* () {
208 const { accountId } = yield* yield* CloudflareEnvironment;
209
210 yield* stack.destroy();
211 yield* cleanupEmail(accountId, healEmail);
212
213 const [roleA, roleB] = yield* pickTwoRoles(accountId);
214
215 const member = yield* stack.deploy(
216 Cloudflare.Account.Member("HealMember", {
217 email: healEmail,
218 roles: [roleA.id],
219 }),
220 );
221
222 // Cancel the invite out-of-band. A redeploy with identical props is a
223 // planner no-op, so change the role to force reconcile — it must
224 // observe the member as missing and re-invite instead of failing.
225 yield* accounts
226 .deleteMember({ accountId, memberId: member.memberId })
227 .pipe(Effect.retry(forbiddenRetry));
228
229 const healed = yield* stack.deploy(
230 Cloudflare.Account.Member("HealMember", {
231 email: healEmail,
232 roles: [roleB.id],
233 }),
234 );
235
236 expect(healed.memberId).not.toEqual(member.memberId);
237 expect(healed.roles.map((r) => r.id)).toEqual([roleB.id]);
238
239 const live = yield* getMember(accountId, healed.memberId);
240 expect((live.roles ?? []).map((r) => r.id)).toEqual([roleB.id]);
241
242 yield* stack.destroy();
243 yield* expectGone(accountId, healed.memberId);
244 }).pipe(logLevel),
245 { tags: ["provider:cloudflare", "provider:cloudflare:account", "live"] },
246 );