@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 183 lines 6.34 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import * as Neon from "@alchemy.run/neon";
3 import { expect } from "@alchemy.run/test";
4 import * as Test from "@alchemy.run/test/Alchemy";
5 import * as Data from "effect/Data";
6 import * as Effect from "effect/Effect";
7 import * as HttpClient from "effect/http/HttpClient";
8 import * as Layer from "effect/Layer";
9 import { MinimumLogLevel } from "effect/References";
10 import * as Schedule from "effect/Schedule";
11 import type { Widget } from "./fixtures/drizzle-workflow/schema.ts";
12 import Stack from "./fixtures/drizzle-workflow/stack.ts";
13
14 const { test, beforeAll, afterAll, deploy, destroy } = Test.make({
15 providers: Layer.mergeAll(Cloudflare.providers(), Neon.providers()),
16 });
17
18 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
19
20 const stack = beforeAll(deploy(Stack));
21 afterAll.skipIf(!!process.env.NO_DESTROY)(destroy(Stack));
22
23 interface WorkflowStatus {
24 status: string;
25 output?: {
26 inserted: Widget;
27 rowCount: number;
28 widget: Widget | null;
29 };
30 error?: { message?: string } | null;
31 }
32
33 class WorkerNotReady extends Data.TaggedError("WorkerNotReady")<{
34 status: number;
35 }> {}
36
37 // Start a fresh workflow instance and poll until it reaches a terminal state.
38 const runToCompletion = (baseUrl: string) =>
39 Effect.gen(function* () {
40 const client = yield* HttpClient.HttpClient;
41
42 // Fresh workers.dev edge takes a few seconds to start serving 200s.
43 const startRes = yield* client.post(`${baseUrl}/workflow/start/1`).pipe(
44 Effect.flatMap((res) =>
45 res.status === 200
46 ? Effect.succeed(res)
47 : Effect.fail(new WorkerNotReady({ status: res.status })),
48 ),
49 Effect.retry({
50 while: (e): e is WorkerNotReady =>
51 e instanceof WorkerNotReady && e.status >= 400 && e.status < 600,
52 schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(15)]),
53 }),
54 );
55 const { instanceId } = (yield* startRes.json) as { instanceId: string };
56 expect(instanceId).toBeTypeOf("string");
57
58 const last = yield* client.get(`${baseUrl}/workflow/status/${instanceId}`).pipe(
59 Effect.flatMap((res) =>
60 res.status === 200
61 ? Effect.succeed(res)
62 : Effect.fail(new WorkerNotReady({ status: res.status })),
63 ),
64 Effect.flatMap((res) => res.json),
65 Effect.map((json) => json as unknown as WorkflowStatus),
66 Effect.repeat({
67 schedule: Schedule.spaced("2 seconds"),
68 until: (s) => s.status === "complete" || s.status === "errored",
69 times: 30,
70 }),
71 );
72 if (last.status !== "complete") {
73 return yield* Effect.fail(
74 new Error(`workflow ${last.status}: ${JSON.stringify(last.error)}`),
75 );
76 }
77 return last;
78 });
79
80 /**
81 * End-to-end regression guard for the ExecutionContext-in-Workflow fix
82 * (PR #515): deploy a Neon project + branch, point a Cloudflare Hyperdrive
83 * at it, host a Workflow that runs `Drizzle.Postgres` queries inside `task`
84 * steps, fire an instance over HTTP, and assert the run completes with the
85 * row it wrote.
86 *
87 * Before the fix the query inside the step dies on a missing
88 * `ExecutionContext` service and the run reports `errored` with no output.
89 */
90 test(
91 "Drizzle.Postgres query runs inside a Workflow task (per-run scope provided by the bridge)",
92 Effect.gen(function* () {
93 const { url } = yield* stack;
94 expect(url).toBeTypeOf("string");
95 const baseUrl = url.replace(/\/+$/, "");
96
97 const last = yield* runToCompletion(baseUrl).pipe(
98 Effect.retry({ schedule: Schedule.spaced("3 seconds"), times: 2 }),
99 );
100
101 expect(last.status).toBe("complete");
102 expect(last.error).toBeFalsy();
103 expect(last.output?.rowCount).toBe(1);
104 expect(last.output?.widget).toMatchObject({ id: 1, name: "widget-1" });
105 expect(last.output?.inserted).toMatchObject({ id: 1, name: "widget-1" });
106 }).pipe(logLevel),
107 {
108 tags: [
109 "provider:cloudflare",
110 "provider:cloudflare:hyperdrive",
111 "provider:cloudflare:worker",
112 "provider:cloudflare:workflow",
113 "provider:neon",
114 "provider:neon:branch",
115 "provider:neon:project",
116 "live",
117 ],
118 timeout: 600_000,
119 },
120 );
121
122 /**
123 * Cross-request regression guard for the build-once bridge: the isolate
124 * builds its layers on the first event and reuses them; each fetch event
125 * builds its own pg pool against its per-event scope and closes it after the
126 * response. Sequential requests must not touch a prior event's pool
127 * ("Cannot use a pool after calling end on the pool") and concurrent
128 * requests must not share I/O objects across request contexts ("Cannot
129 * perform I/O on behalf of a different request").
130 */
131 test(
132 "Drizzle.Postgres queries survive sequential and concurrent fetch events",
133 Effect.gen(function* () {
134 const { url } = yield* stack;
135 const baseUrl = url.replace(/\/+$/, "");
136 const client = yield* HttpClient.HttpClient;
137
138 const query = (id: number) =>
139 Effect.gen(function* () {
140 const res = yield* client.get(`${baseUrl}/query/${id}`).pipe(
141 Effect.flatMap((res) =>
142 res.status === 200
143 ? Effect.succeed(res)
144 : Effect.fail(new WorkerNotReady({ status: res.status })),
145 ),
146 Effect.retry({
147 while: (e): e is WorkerNotReady => e instanceof WorkerNotReady,
148 schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(10)]),
149 }),
150 );
151 return (yield* res.json) as { rowCount: number };
152 }).pipe(Effect.orDie);
153
154 // Sequential: the second event must not observe the first event's
155 // (already closed) pool.
156 const first = yield* query(1);
157 const second = yield* query(1);
158 expect(first.rowCount).toBeTypeOf("number");
159 expect(second.rowCount).toBeTypeOf("number");
160
161 // Concurrent: every event acquires its own pool on its own scope.
162 const results = yield* Effect.all(
163 [1, 2, 3, 4, 5, 6].map((id) => query(id)),
164 { concurrency: "unbounded" },
165 );
166 for (const body of results) {
167 expect(body.rowCount).toBeTypeOf("number");
168 }
169 }).pipe(logLevel),
170 {
171 tags: [
172 "provider:cloudflare",
173 "provider:cloudflare:hyperdrive",
174 "provider:cloudflare:worker",
175 "provider:cloudflare:workflow",
176 "provider:neon",
177 "provider:neon:branch",
178 "provider:neon:project",
179 "live",
180 ],
181 timeout: 600_000,
182 },
183 );