The best way to control Claude Code, Codex and more from any computer or phone

main
ts 287 lines 10.8 KB
Raw
1 import crypto from "node:crypto";
2 import * as Cloudflare from "@alchemy.run/cloudflare";
3 import { CloudflareEnvironment } from "@alchemy.run/cloudflare/CloudflareEnvironment";
4 import { expect } from "@alchemy.run/test";
5 import * as Test from "@alchemy.run/test/Alchemy";
6 import * as accounts from "@distilled.cloud/cloudflare/accounts";
7 import * as pipelines from "@distilled.cloud/cloudflare/pipelines";
8 import * as user from "@distilled.cloud/cloudflare/user";
9 import * as Output from "alchemy/Output";
10 import * as Effect from "effect/Effect";
11 import * as Redacted from "effect/Redacted";
12 import { MinimumLogLevel } from "effect/References";
13 import * as Schedule from "effect/Schedule";
14
15 const { test } = Test.make({ providers: Cloudflare.providers() });
16
17 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
18
19 // The scoped API token the test harness mints propagates eventually-
20 // consistently across Cloudflare's edge — ride out 403 blips
21 // (`Forbidden`, declared in the distilled error unions) on the test's
22 // own out-of-band verification calls.
23 const forbiddenBlips = {
24 while: (e: { _tag: string }) => e._tag === "Forbidden",
25 schedule: Schedule.exponential("500 millis"),
26 times: 8,
27 } as const;
28
29 // The same blip can hit engine-side calls mid-deploy. Reconcile is
30 // idempotent (observe→ensure→sync), so retrying the whole deploy is safe.
31 const retryAuthBlip = <A, E, R>(eff: Effect.Effect<A, E, R>) =>
32 eff.pipe(
33 Effect.retry({
34 while: (e) => String(e).includes("Unable to authenticate request"),
35 schedule: Schedule.exponential("1 second"),
36 times: 5,
37 }),
38 );
39
40 // R2 S3-compatible credentials are derived from the active API token:
41 // the access key id is the token id and the secret is the SHA-256 hex
42 // digest of the token value.
43 const r2Credentials = Effect.gen(function* () {
44 const creds = yield* yield* CloudflareEnvironment;
45 if (creds.type !== "apiToken") {
46 return yield* Effect.die(
47 new Error(
48 "Pipelines sink test requires an apiToken profile (R2 S3 credentials are derived from the token)",
49 ),
50 );
51 }
52 const token = Redacted.value(creds.apiToken);
53 // Account-owned tokens verify against the account route.
54 const verified = token.startsWith("cfat_")
55 ? yield* retryAuthBlip(accounts.verifyToken({ accountId: creds.accountId }))
56 : yield* retryAuthBlip(user.verifyToken({}));
57 const secretAccessKey = yield* Effect.sync(() =>
58 crypto.createHash("sha256").update(token).digest("hex"),
59 );
60 return {
61 accessKeyId: Redacted.make(verified.id),
62 secretAccessKey: Redacted.make(secretAccessKey),
63 };
64 });
65
66 const getStream = (accountId: string, streamId: string) =>
67 pipelines.getStream({ accountId, streamId }).pipe(Effect.retry(forbiddenBlips));
68
69 const getSink = (accountId: string, sinkId: string) =>
70 pipelines.getSink({ accountId, sinkId }).pipe(Effect.retry(forbiddenBlips));
71
72 const getPipeline = (accountId: string, pipelineId: string) =>
73 pipelines.getV1Pipeline({ accountId, pipelineId }).pipe(Effect.retry(forbiddenBlips));
74
75 const expectStreamGone = (accountId: string, streamId: string) =>
76 getStream(accountId, streamId).pipe(
77 Effect.flatMap(() => Effect.fail({ _tag: "StreamNotDeleted" } as const)),
78 Effect.catchTag("StreamNotFound", () => Effect.void),
79 Effect.retry({
80 while: (e) => e._tag === "StreamNotDeleted",
81 schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(10)]),
82 }),
83 );
84
85 const expectSinkGone = (accountId: string, sinkId: string) =>
86 getSink(accountId, sinkId).pipe(
87 Effect.flatMap(() => Effect.fail({ _tag: "SinkNotDeleted" } as const)),
88 Effect.catchTag("SinkNotFound", () => Effect.void),
89 Effect.retry({
90 while: (e) => e._tag === "SinkNotDeleted",
91 schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(10)]),
92 }),
93 );
94
95 const expectPipelineGone = (accountId: string, pipelineId: string) =>
96 getPipeline(accountId, pipelineId).pipe(
97 Effect.flatMap(() => Effect.fail({ _tag: "PipelineNotDeleted" } as const)),
98 Effect.catchTag("PipelineNotExists", () => Effect.void),
99 Effect.retry({
100 while: (e) => e._tag === "PipelineNotDeleted",
101 schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(10)]),
102 }),
103 );
104
105 test.provider(
106 "stream: create with defaults, patch http in place, replace on schema change",
107 (stack) =>
108 Effect.gen(function* () {
109 const { accountId } = yield* yield* CloudflareEnvironment;
110
111 yield* stack.destroy();
112
113 // Create — engine-generated name, default http/workerBinding. The
114 // secure default is no public HTTP endpoint.
115 const initial = yield* retryAuthBlip(stack.deploy(Cloudflare.Pipelines.Stream("Stream", {})));
116
117 expect(initial.streamId).toBeTruthy();
118 expect(initial.accountId).toEqual(accountId);
119 expect(initial.httpEnabled).toEqual(false);
120 expect(initial.workerBindingEnabled).toEqual(true);
121
122 const live = yield* getStream(accountId, initial.streamId);
123 expect(live.id).toEqual(initial.streamId);
124 expect(live.name).toEqual(initial.name);
125 expect(live.http.enabled).toEqual(false);
126
127 // Patch http in place — same streamId.
128 const updated = yield* retryAuthBlip(
129 stack.deploy(
130 Cloudflare.Pipelines.Stream("Stream", {
131 http: {
132 enabled: true,
133 authentication: true,
134 cors: { origins: ["https://example.com"] },
135 },
136 }),
137 ),
138 );
139
140 expect(updated.streamId).toEqual(initial.streamId);
141 expect(updated.httpEnabled).toEqual(true);
142 expect(updated.endpoint).toBeTruthy();
143 expect(updated.httpAuthentication).toEqual(true);
144 expect(updated.corsOrigins).toEqual(["https://example.com"]);
145
146 const liveUpdated = yield* getStream(accountId, updated.streamId);
147 expect(liveUpdated.http.authentication).toEqual(true);
148 expect(liveUpdated.http.cors?.origins).toEqual(["https://example.com"]);
149
150 // The schema is immutable — declaring one triggers a replacement.
151 const replaced = yield* retryAuthBlip(
152 stack.deploy(
153 Cloudflare.Pipelines.Stream("Stream", {
154 schema: {
155 fields: [
156 { type: "string", name: "url", required: true },
157 { type: "timestamp", name: "ts", unit: "millisecond" },
158 ],
159 },
160 }),
161 ),
162 );
163
164 expect(replaced.streamId).not.toEqual(initial.streamId);
165 yield* expectStreamGone(accountId, initial.streamId);
166
167 yield* stack.destroy();
168 yield* expectStreamGone(accountId, replaced.streamId);
169
170 // Destroy again — delete must be idempotent.
171 yield* stack.destroy();
172 }).pipe(logLevel),
173 {
174 tags: ["provider:cloudflare", "provider:cloudflare:pipelines", "live"],
175 timeout: 300_000,
176 },
177 );
178
179 interface EtlOpts {
180 path?: string;
181 where?: string;
182 }
183
184 // One program deploying the whole Pipelines topology: an R2 destination
185 // bucket, the sink writing to it, an ingest stream, and the SQL pipeline
186 // connecting them. The pipeline SQL interpolates the stream/sink names so
187 // the engine orders pipeline-after-stream/sink on deploy (and the reverse
188 // on destroy).
189 const etl = (
190 creds: {
191 accessKeyId: Redacted.Redacted<string>;
192 secretAccessKey: Redacted.Redacted<string>;
193 },
194 opts: EtlOpts = {},
195 ) =>
196 Effect.gen(function* () {
197 const bucket = yield* Cloudflare.R2.Bucket("SinkBucket", {
198 forceDestroy: true,
199 });
200 const stream = yield* Cloudflare.Pipelines.Stream("Stream", {});
201 const sink = yield* Cloudflare.Pipelines.Sink("Sink", {
202 type: "r2",
203 config: {
204 bucket: bucket.bucketName,
205 credentials: creds,
206 path: opts.path,
207 rollingPolicy: { intervalSeconds: 10 },
208 },
209 });
210 const pipeline = yield* Cloudflare.Pipelines.Pipeline("Etl", {
211 sql: Output.interpolate`INSERT INTO ${sink.name} SELECT * FROM ${stream.name}${opts.where ? ` WHERE ${opts.where}` : ""}`,
212 });
213 return { bucket, stream, sink, pipeline };
214 });
215
216 test.provider(
217 "end-to-end: stream → sql pipeline → r2 sink, replacement on sink change",
218 (stack) =>
219 Effect.gen(function* () {
220 const { accountId } = yield* yield* CloudflareEnvironment;
221 const creds = yield* r2Credentials;
222
223 yield* stack.destroy();
224
225 const initial = yield* retryAuthBlip(stack.deploy(etl(creds)));
226
227 expect(initial.sink.sinkId).toBeTruthy();
228 expect(initial.sink.type).toEqual("r2");
229 expect(initial.sink.bucket).toEqual(initial.bucket.bucketName);
230 expect(initial.pipeline.pipelineId).toBeTruthy();
231 expect(initial.pipeline.sql).toContain(
232 `INSERT INTO ${initial.sink.name} SELECT * FROM ${initial.stream.name}`,
233 );
234
235 const liveSink = yield* getSink(accountId, initial.sink.sinkId);
236 expect(liveSink.name).toEqual(initial.sink.name);
237 expect(liveSink.config?.bucket).toEqual(initial.bucket.bucketName);
238
239 const livePipeline = yield* getPipeline(accountId, initial.pipeline.pipelineId);
240 expect(livePipeline.name).toEqual(initial.pipeline.name);
241 expect(livePipeline.sql).toEqual(initial.pipeline.sql);
242 expect(livePipeline.status).toBeTruthy();
243
244 // Redeploying identical props is a no-op.
245 const noop = yield* retryAuthBlip(stack.deploy(etl(creds)));
246 expect(noop.sink.sinkId).toEqual(initial.sink.sinkId);
247 expect(noop.pipeline.pipelineId).toEqual(initial.pipeline.pipelineId);
248 expect(noop.stream.streamId).toEqual(initial.stream.streamId);
249
250 // Sinks have no update API — changing the path replaces the sink,
251 // and the pipeline's SQL change replaces the pipeline with it. The
252 // stream is untouched.
253 const replaced = yield* retryAuthBlip(
254 stack.deploy(etl(creds, { path: "ingest", where: "1 = 1" })),
255 );
256
257 expect(replaced.sink.sinkId).not.toEqual(initial.sink.sinkId);
258 expect(replaced.sink.path).toEqual("ingest");
259 expect(replaced.pipeline.pipelineId).not.toEqual(initial.pipeline.pipelineId);
260 expect(replaced.pipeline.sql).toContain("WHERE 1 = 1");
261 expect(replaced.stream.streamId).toEqual(initial.stream.streamId);
262
263 // The old sink and pipeline were deleted as part of the replacement.
264 yield* expectPipelineGone(accountId, initial.pipeline.pipelineId);
265 yield* expectSinkGone(accountId, initial.sink.sinkId);
266
267 // Destroy tears down pipeline → sink/stream → bucket in dependency
268 // order.
269 yield* stack.destroy();
270
271 yield* expectPipelineGone(accountId, replaced.pipeline.pipelineId);
272 yield* expectSinkGone(accountId, replaced.sink.sinkId);
273 yield* expectStreamGone(accountId, replaced.stream.streamId);
274
275 // Destroy again — deletes must be idempotent.
276 yield* stack.destroy();
277 }).pipe(logLevel),
278 {
279 tags: [
280 "provider:cloudflare",
281 "provider:cloudflare:pipelines",
282 "provider:cloudflare:r2",
283 "live",
284 ],
285 timeout: 600_000,
286 },
287 );