@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 1,509 lines 55.1 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 r2 from "@distilled.cloud/cloudflare/r2";
6 import * as Drift from "alchemy/Drift";
7 import * as Nuke from "alchemy/Nuke";
8 import { findProviderByType } from "alchemy/Provider";
9 import * as RemovalPolicy from "alchemy/RemovalPolicy";
10 import { type ResourceState, State } from "alchemy/State";
11 import * as Data from "effect/Data";
12 import * as Effect from "effect/Effect";
13 import * as HttpClient from "effect/http/HttpClient";
14 import type * as HttpClientError from "effect/http/HttpClientError";
15 import * as Layer from "effect/Layer";
16 import { MinimumLogLevel } from "effect/References";
17 import * as Result from "effect/Result";
18 import * as Schedule from "effect/Schedule";
19 import * as Stream from "effect/Stream";
20 import { stageSuffix, testName } from "../../names.ts";
21 import MultipartWorker, { MultipartBucket } from "./fixtures/multipart-worker.ts";
22
23 const { test } = Test.make({ providers: Cloudflare.providers() });
24
25 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
26
27 test.provider(
28 "create and delete bucket with default props",
29 (stack) =>
30 Effect.gen(function* () {
31 const { accountId } = yield* yield* CloudflareEnvironment;
32
33 yield* stack.destroy();
34
35 const bucket = yield* stack.deploy(
36 Effect.gen(function* () {
37 return yield* Cloudflare.R2.Bucket("DefaultBucket", { forceDestroy: true });
38 }),
39 );
40
41 expect(bucket.bucketName).toBeDefined();
42 expect(bucket.storageClass).toEqual("Standard");
43 expect(bucket.jurisdiction).toEqual("default");
44 expect(bucket.publicDomain).toBeUndefined();
45
46 const actualBucket = yield* getBucketWhenReady(bucket.bucketName, accountId);
47 expect(actualBucket.name).toEqual(bucket.bucketName);
48
49 yield* stack.destroy();
50
51 yield* waitForBucketToBeDeleted(bucket.bucketName, accountId);
52 }).pipe(logLevel),
53 { tags: ["provider:cloudflare", "provider:cloudflare:r2", "live"] },
54 );
55
56 test.provider(
57 "create, update, delete bucket",
58 (stack) =>
59 Effect.gen(function* () {
60 const { accountId } = yield* yield* CloudflareEnvironment;
61
62 yield* stack.destroy();
63
64 const bucket = yield* stack.deploy(
65 Effect.gen(function* () {
66 return yield* Cloudflare.R2.Bucket("TestBucket", {
67 forceDestroy: true,
68 storageClass: "Standard",
69 });
70 }),
71 );
72
73 const actualBucket = yield* getBucketWhenReady(bucket.bucketName, accountId);
74 expect(actualBucket.name).toEqual(bucket.bucketName);
75 expect(actualBucket.storageClass).toEqual("Standard");
76
77 const updatedBucket = yield* stack.deploy(
78 Effect.gen(function* () {
79 return yield* Cloudflare.R2.Bucket("TestBucket", {
80 forceDestroy: true,
81 storageClass: "InfrequentAccess",
82 });
83 }),
84 );
85
86 // The storage-class change is an IN-PLACE update (PATCH with the
87 // `cf-r2-storage-class` header), never a replacement: same physical
88 // bucket name and unchanged creation date.
89 expect(updatedBucket.bucketName).toEqual(bucket.bucketName);
90
91 const actualUpdatedBucket = yield* getBucketWhenReady(updatedBucket.bucketName, accountId);
92 expect(actualUpdatedBucket.name).toEqual(updatedBucket.bucketName);
93 expect(actualUpdatedBucket.storageClass).toEqual("InfrequentAccess");
94 expect(actualUpdatedBucket.creationDate).toEqual(actualBucket.creationDate);
95
96 yield* stack.destroy();
97
98 yield* waitForBucketToBeDeleted(updatedBucket.bucketName, accountId);
99 }).pipe(logLevel),
100 { tags: ["provider:cloudflare", "provider:cloudflare:r2", "live"] },
101 );
102
103 // Engine-level adoption: R2 buckets have no ownership signal (Cloudflare
104 // doesn't expose tags on R2 buckets), so a name match in `read` is treated
105 // as silent adoption.
106 test.provider(
107 "existing bucket (matching name) is silently adopted without --adopt",
108 (stack) =>
109 Effect.gen(function* () {
110 const { accountId } = yield* yield* CloudflareEnvironment;
111
112 yield* stack.destroy();
113
114 // Phase 1: deploy normally so a real R2 bucket exists. No explicit
115 // `name` — the engine generates a random-suffixed physical name
116 // (collision-free across concurrent runs); the deploy output hands
117 // back the real name, which pins the bucket's identity for the
118 // adoption phase below.
119 const initial = yield* stack.deploy(
120 Effect.gen(function* () {
121 return yield* Cloudflare.R2.Bucket("AdoptableBucket", { forceDestroy: true });
122 }),
123 );
124 const bucketName = initial.bucketName;
125
126 // Phase 2: wipe local state — the bucket stays on Cloudflare.
127 yield* Effect.gen(function* () {
128 const state = yield* yield* State;
129 yield* state.delete({ stack: stack.name, stage: stack.stage, fqn: "AdoptableBucket" });
130 }).pipe(Effect.provide(stack.state));
131
132 // Phase 3: redeploy without `adopt(true)`. The engine calls
133 // `provider.read`, which fetches the bucket by name and returns
134 // plain attrs — silent adoption.
135 const adopted = yield* stack.deploy(
136 Effect.gen(function* () {
137 return yield* Cloudflare.R2.Bucket("AdoptableBucket", {
138 forceDestroy: true,
139 name: bucketName,
140 });
141 }),
142 );
143
144 expect(adopted.bucketName).toEqual(bucketName);
145
146 const persisted = yield* Effect.gen(function* () {
147 const state = yield* yield* State;
148 return yield* state.get({ stack: stack.name, stage: stack.stage, fqn: "AdoptableBucket" });
149 }).pipe(Effect.provide(stack.state));
150
151 expect((persisted as any)?.attr).toMatchObject({ bucketName });
152
153 yield* stack.destroy();
154 yield* waitForBucketToBeDeleted(bucketName, accountId);
155 }).pipe(logLevel),
156 { tags: ["provider:cloudflare", "provider:cloudflare:r2", "live"] },
157 );
158
159 test.provider(
160 "destroying a bucket with forceDestroy empties its objects first",
161 (stack) =>
162 Effect.gen(function* () {
163 const { accountId } = yield* yield* CloudflareEnvironment;
164
165 yield* stack.destroy();
166
167 const bucket = yield* stack.deploy(
168 Effect.gen(function* () {
169 return yield* Cloudflare.R2.Bucket("BucketWithObjects", { forceDestroy: true });
170 }),
171 );
172
173 yield* putObject(accountId, bucket.bucketName, "hello.txt", "hello");
174 yield* putObject(accountId, bucket.bucketName, "nested/world.txt", "world");
175
176 const before = yield* listKeysWhenReady(accountId, bucket.bucketName, 2);
177 expect(before.sort()).toEqual(["hello.txt", "nested/world.txt"]);
178
179 yield* stack.destroy();
180
181 yield* waitForBucketToBeDeleted(bucket.bucketName, accountId);
182 }).pipe(logLevel),
183 { tags: ["provider:cloudflare", "provider:cloudflare:r2", "live"] },
184 );
185
186 // An incomplete multipart upload holds a bucket but is invisible to the
187 // object listing; only R2's S3 API can abort it, with S3 credentials derived
188 // from the API token alchemy is authenticated with.
189 // See https://github.com/alchemy-run/alchemy/issues/2478.
190 test.provider(
191 "forceDestroy aborts incomplete multipart uploads with the API token",
192 (stack) =>
193 Effect.gen(function* () {
194 const { accountId } = yield* yield* CloudflareEnvironment;
195
196 yield* stack.destroy();
197
198 const { bucket, worker } = yield* stack.deploy(
199 Effect.gen(function* () {
200 const bucket = yield* MultipartBucket;
201 const worker = yield* MultipartWorker;
202 return { bucket, worker };
203 }),
204 );
205
206 const key = "big/entry.bin";
207 const client = yield* HttpClient.HttpClient;
208 const post = (url: string) =>
209 client.post(url).pipe(
210 Effect.flatMap((res) =>
211 res.status === 200
212 ? res.json
213 : Effect.fail<WorkerNotReady | HttpClientError.HttpClientError>(
214 new WorkerNotReady({ status: res.status }),
215 ),
216 ),
217 Effect.retry({ schedule: Schedule.exponential("500 millis"), times: 10 }),
218 );
219 yield* post(`${worker.url}/start-upload?key=${encodeURIComponent(key)}`);
220
221 // The upload lists no objects, yet R2 refuses to delete the bucket.
222 expect(yield* listKeysWhenReady(accountId, bucket.bucketName, 0)).toEqual([]);
223 const refused = yield* r2
224 .deleteBucket({ accountId, bucketName: bucket.bucketName })
225 .pipe(Effect.flip);
226 expect(refused._tag).toEqual("BucketNotEmpty");
227
228 // The testing profile authenticates with an API token, so destroy
229 // aborts the upload through R2's S3 API and deletes the bucket.
230 yield* stack.destroy();
231
232 yield* waitForBucketToBeDeleted(bucket.bucketName, accountId);
233 }).pipe(logLevel),
234 {
235 tags: ["provider:cloudflare", "provider:cloudflare:r2", "provider:cloudflare:worker", "live"],
236 timeout: 180_000,
237 },
238 );
239
240 class WorkerNotReady extends Data.TaggedError("WorkerNotReady")<{ status: number }> {}
241
242 // Without `forceDestroy`, R2's own refusal to delete a non-empty bucket is
243 // the last line of defense for the data in it — alchemy must not empty the
244 // bucket to get past it. See https://github.com/alchemy-run/alchemy/issues/1248.
245 test.provider(
246 "destroying a non-empty bucket without forceDestroy keeps the objects",
247 (stack) =>
248 Effect.gen(function* () {
249 const { accountId } = yield* yield* CloudflareEnvironment;
250
251 yield* stack.destroy();
252
253 const declaration = Effect.gen(function* () {
254 return yield* Cloudflare.R2.Bucket("ProtectedBucket");
255 });
256
257 const bucket = yield* stack.deploy(declaration);
258
259 yield* putObject(accountId, bucket.bucketName, "keep.txt", "precious");
260 yield* listKeysWhenReady(accountId, bucket.bucketName, 1);
261
262 // R2's own refusal (`BucketNotEmpty`) is what fails the teardown.
263 const destroyed = yield* Effect.result(stack.destroy());
264 expect(Result.isFailure(destroyed)).toBe(true);
265 expect(String(destroyed)).toContain("BucketNotEmpty");
266
267 // Both the bucket and its object survived the teardown.
268 const survived = yield* r2.getBucket({ accountId, bucketName: bucket.bucketName });
269 expect(survived.name).toEqual(bucket.bucketName);
270 const keys = yield* listKeysWhenReady(accountId, bucket.bucketName, 1);
271 expect(keys).toEqual(["keep.txt"]);
272
273 // Opting in lets the same stack tear down for real.
274 yield* stack.deploy(
275 Effect.gen(function* () {
276 return yield* Cloudflare.R2.Bucket("ProtectedBucket", { forceDestroy: true });
277 }),
278 );
279 yield* stack.destroy();
280 yield* waitForBucketToBeDeleted(bucket.bucketName, accountId);
281 }).pipe(logLevel),
282 { tags: ["provider:cloudflare", "provider:cloudflare:r2", "live"] },
283 );
284
285 // `alchemy unsafe nuke` lists buckets from the cloud, so its deletes carry
286 // Attributes and never `forceDestroy`: the operator's confirmation (`force`)
287 // is what opts into emptying the bucket.
288 test.provider(
289 "nuke empties a non-empty bucket without forceDestroy",
290 (stack) =>
291 Effect.gen(function* () {
292 const { accountId } = yield* yield* CloudflareEnvironment;
293
294 yield* stack.destroy();
295
296 const bucket = yield* stack.deploy(
297 Effect.gen(function* () {
298 return yield* Cloudflare.R2.Bucket("NukedBucket");
299 }),
300 );
301
302 yield* putObject(accountId, bucket.bucketName, "precious.txt", "precious");
303 yield* listKeysWhenReady(accountId, bucket.bucketName, 1);
304
305 // The nuke engine, over the one target `alchemy unsafe nuke` would list.
306 const result = yield* Nuke.destroy({
307 targets: [
308 {
309 key: bucket.bucketName,
310 providerId: Cloudflare.R2.Bucket.Type,
311 displayName: bucket.bucketName,
312 attributes: { ...bucket },
313 provider: yield* findProviderByType(Cloudflare.R2.Bucket.Type),
314 },
315 ],
316 context: yield* Effect.context<never>(),
317 strategy: { type: "independent", retries: 0 },
318 });
319 expect(result.failed).toEqual([]);
320 expect(result.deleted).toHaveLength(1);
321 yield* waitForBucketToBeDeleted(bucket.bucketName, accountId);
322
323 // The stack's row now names a deleted bucket; destroy is idempotent.
324 yield* stack.destroy();
325 }).pipe(logLevel),
326 { tags: ["provider:cloudflare", "provider:cloudflare:r2", "live"] },
327 );
328
329 // The incident behind https://github.com/alchemy-run/alchemy/issues/1248,
330 // end to end against a real bucket: `retain` is added to an
331 // already-deployed bucket (a props-identical, noop deploy), the bucket's
332 // declaration then moves away, and the old stack's orphan sweep must leave
333 // both the bucket and its objects untouched.
334 //
335 // A bucket cannot be renamed in place — R2 has no rename API, and the
336 // provider's `diff` orders a REPLACE on a name change — so "moving" a
337 // bucket is always: drop the state row here, adopt the same physical bucket
338 // there. Retain is what makes that safe.
339 test.provider(
340 "a retained bucket outlives its declaration with its objects intact",
341 (stack) =>
342 Effect.gen(function* () {
343 const { accountId } = yield* yield* CloudflareEnvironment;
344 const bucketName = testName("alchemy-test-retained-move");
345
346 // A retained bucket is alchemy's to forget, not to delete, so an
347 // interrupted earlier run can leave a NON-EMPTY bucket behind — which
348 // the leading `stack.destroy()` could never reclaim on its own (that
349 // is the whole point of the protection under test). Reclaim it out of
350 // band first, then let destroy drain any state row pointing at it.
351 yield* forceDeleteBucket(accountId, bucketName);
352 yield* stack.destroy();
353
354 // ── 1. deploy with the DEFAULT policy, then put an object in it ──
355 const origin = yield* stack.deploy(
356 Effect.gen(function* () {
357 return yield* Cloudflare.R2.Bucket("Origin", { name: bucketName });
358 }),
359 );
360 expect(origin.bucketName).toEqual(bucketName);
361 yield* putObject(accountId, bucketName, "precious.txt", "irreplaceable");
362 yield* listKeysWhenReady(accountId, bucketName, 1);
363 expect(yield* removalPolicyOf(stack, "Origin")).toEqual("destroy");
364
365 // ── 2. add `retain`, props otherwise identical ──
366 // The policy is a declaration decoration, not a prop, so the plan is a
367 // noop — and the noop path is the only pass that can persist it.
368 const retained = Effect.gen(function* () {
369 return yield* Cloudflare.R2.Bucket("Origin", { name: bucketName }).pipe(
370 RemovalPolicy.retain(),
371 );
372 });
373 const plan = yield* stack.plan(retained);
374 expect((Object.values(plan.resources) as { action: string }[])[0]?.action).toEqual("noop");
375 yield* stack.deploy(retained);
376 expect(yield* removalPolicyOf(stack, "Origin")).toEqual("retain");
377
378 // ── 3. the declaration moves away — the old stack sweeps ──
379 yield* stack.destroy();
380
381 // The state row is dropped either way; only the physical bucket
382 // survives. That is why the bug was silent.
383 expect(yield* stateOf(stack, "Origin")).toBeUndefined();
384 const survivor = yield* r2.getBucket({ accountId, bucketName });
385 expect(survivor.name).toEqual(bucketName);
386 expect(yield* listKeysWhenReady(accountId, bucketName, 1)).toEqual(["precious.txt"]);
387
388 // ── 4. it lands in its new home by adopting the same bucket ──
389 // (Same stack, new logical id — the engine cannot tell that apart from
390 // the same declaration in a different stack: both `read` the bucket by
391 // name and adopt it.) `forceDestroy` is set here purely so the final
392 // teardown reclaims the test bucket.
393 const moved = yield* stack.deploy(
394 Effect.gen(function* () {
395 return yield* Cloudflare.R2.Bucket("Destination", {
396 name: bucketName,
397 forceDestroy: true,
398 });
399 }),
400 );
401 expect(moved.bucketName).toEqual(bucketName);
402 expect(yield* listKeysWhenReady(accountId, bucketName, 1)).toEqual(["precious.txt"]);
403
404 yield* stack.destroy();
405 yield* waitForBucketToBeDeleted(bucketName, accountId);
406 }).pipe(logLevel),
407 { tags: ["provider:cloudflare", "provider:cloudflare:r2", "live"], timeout: 180_000 },
408 );
409
410 // The other half of a move: a retained bucket whose REPLACEMENT is ordered
411 // (an explicit name change, the only way to "rename" an R2 bucket). The old
412 // generation must be left standing, objects and all.
413 test.provider(
414 "replacing a retained bucket leaves the old generation and its objects",
415 (stack) =>
416 Effect.gen(function* () {
417 const { accountId } = yield* yield* CloudflareEnvironment;
418
419 const oldName = testName("alchemy-test-retained-replace-old");
420 const newName = testName("alchemy-test-retained-replace-new");
421
422 // Same reason as above: retained leftovers from an interrupted run are
423 // never reclaimed by the engine.
424 yield* forceDeleteBucket(accountId, oldName);
425 yield* forceDeleteBucket(accountId, newName);
426 yield* stack.destroy();
427
428 const declare = (name: string) =>
429 Effect.gen(function* () {
430 return yield* Cloudflare.R2.Bucket("Renamed", { name }).pipe(RemovalPolicy.retain());
431 });
432
433 yield* stack.deploy(declare(oldName));
434 yield* putObject(accountId, oldName, "precious.txt", "irreplaceable");
435 yield* listKeysWhenReady(accountId, oldName, 1);
436
437 // A name change is a replacement: new bucket created, state re-pointed.
438 const replaced = yield* stack.deploy(declare(newName));
439 expect(replaced.bucketName).toEqual(newName);
440 yield* getBucketWhenReady(newName, accountId);
441
442 // Retain covers the replacement's old generation too — the bucket is
443 // dropped from state, never deleted, and its objects are still there.
444 const old = yield* r2.getBucket({ accountId, bucketName: oldName });
445 expect(old.name).toEqual(oldName);
446 expect(yield* listKeysWhenReady(accountId, oldName, 1)).toEqual(["precious.txt"]);
447
448 yield* stack.destroy();
449
450 // Retained buckets are alchemy's to forget, not to delete, so this
451 // suite reclaims both out of band.
452 yield* forceDeleteBucket(accountId, oldName);
453 yield* forceDeleteBucket(accountId, newName);
454 }).pipe(logLevel),
455 { tags: ["provider:cloudflare", "provider:cloudflare:r2", "live"], timeout: 180_000 },
456 );
457
458 test.provider(
459 "lifecycle rules are added, updated, and removed",
460 (stack) =>
461 Effect.gen(function* () {
462 const { accountId } = yield* yield* CloudflareEnvironment;
463
464 yield* stack.destroy();
465
466 // Create with one rule.
467 const initial = yield* stack.deploy(
468 Effect.gen(function* () {
469 return yield* Cloudflare.R2.Bucket("LifecycleBucket", {
470 forceDestroy: true,
471 lifecycleRules: [
472 {
473 id: "expire-after-30d",
474 deleteObjectsTransition: { condition: { type: "Age", maxAge: 60 * 60 * 24 * 30 } },
475 },
476 ],
477 });
478 }),
479 );
480
481 const initialRules = yield* r2.getBucketLifecycle({
482 accountId,
483 bucketName: initial.bucketName,
484 });
485 expect(initialRules.rules).toHaveLength(1);
486 expect(initialRules.rules?.[0]?.id).toEqual("expire-after-30d");
487 expect(initialRules.rules?.[0]?.enabled).toEqual(true);
488 expect(initialRules.rules?.[0]?.deleteObjectsTransition?.condition).toEqual({
489 type: "Age",
490 maxAge: 60 * 60 * 24 * 30,
491 });
492
493 // Update: change the prefix and add a storage class transition.
494 yield* stack.deploy(
495 Effect.gen(function* () {
496 return yield* Cloudflare.R2.Bucket("LifecycleBucket", {
497 forceDestroy: true,
498 lifecycleRules: [
499 {
500 id: "expire-after-30d",
501 prefix: "logs/",
502 storageClassTransitions: [
503 {
504 condition: { type: "Age", maxAge: 60 * 60 * 24 * 7 },
505 storageClass: "InfrequentAccess",
506 },
507 ],
508 deleteObjectsTransition: { condition: { type: "Age", maxAge: 60 * 60 * 24 * 30 } },
509 },
510 ],
511 });
512 }),
513 );
514
515 const updatedRules = yield* r2.getBucketLifecycle({
516 accountId,
517 bucketName: initial.bucketName,
518 });
519 expect(updatedRules.rules).toHaveLength(1);
520 expect(updatedRules.rules?.[0]?.conditions.prefix).toEqual("logs/");
521 expect(updatedRules.rules?.[0]?.storageClassTransitions).toEqual([
522 { condition: { type: "Age", maxAge: 60 * 60 * 24 * 7 }, storageClass: "InfrequentAccess" },
523 ]);
524
525 // Clear all rules.
526 yield* stack.deploy(
527 Effect.gen(function* () {
528 return yield* Cloudflare.R2.Bucket("LifecycleBucket", {
529 forceDestroy: true,
530 lifecycleRules: [],
531 });
532 }),
533 );
534
535 const clearedRules = yield* r2.getBucketLifecycle({
536 accountId,
537 bucketName: initial.bucketName,
538 });
539 expect(clearedRules.rules ?? []).toEqual([]);
540
541 yield* stack.destroy();
542 yield* waitForBucketToBeDeleted(initial.bucketName, accountId);
543 }).pipe(logLevel),
544 { tags: ["provider:cloudflare", "provider:cloudflare:r2", "live"] },
545 );
546
547 test.provider(
548 "cors rules are added, updated, and removed",
549 (stack) =>
550 Effect.gen(function* () {
551 const { accountId } = yield* yield* CloudflareEnvironment;
552
553 yield* stack.destroy();
554
555 // Create with one rule.
556 const initial = yield* stack.deploy(
557 Effect.gen(function* () {
558 return yield* Cloudflare.R2.Bucket("CorsBucket", {
559 forceDestroy: true,
560 cors: [
561 {
562 id: "range-reads",
563 allowedMethods: ["GET", "HEAD"],
564 allowedOrigins: ["https://map.example.com"],
565 allowedHeaders: ["range"],
566 exposeHeaders: ["etag", "content-range"],
567 maxAgeSeconds: 3600,
568 },
569 ],
570 });
571 }),
572 );
573
574 expect(initial.cors).toHaveLength(1);
575
576 const initialCors = yield* r2.getBucketCors({ accountId, bucketName: initial.bucketName });
577 expect(initialCors.rules).toHaveLength(1);
578 expect(initialCors.rules?.[0]?.id).toEqual("range-reads");
579 expect(initialCors.rules?.[0]?.allowed.methods).toEqual(["GET", "HEAD"]);
580 expect(initialCors.rules?.[0]?.allowed.origins).toEqual(["https://map.example.com"]);
581 expect(initialCors.rules?.[0]?.exposeHeaders).toEqual(["etag", "content-range"]);
582 expect(initialCors.rules?.[0]?.maxAgeSeconds).toEqual(3600);
583
584 // Update: widen origins and add a second rule.
585 yield* stack.deploy(
586 Effect.gen(function* () {
587 return yield* Cloudflare.R2.Bucket("CorsBucket", {
588 forceDestroy: true,
589 cors: [
590 {
591 id: "range-reads",
592 allowedMethods: ["GET", "HEAD"],
593 allowedOrigins: ["*"],
594 allowedHeaders: ["range"],
595 exposeHeaders: ["etag", "content-range"],
596 maxAgeSeconds: 3600,
597 },
598 {
599 id: "uploads",
600 allowedMethods: ["PUT", "POST"],
601 allowedOrigins: ["https://app.example.com"],
602 allowedHeaders: ["content-type"],
603 },
604 ],
605 });
606 }),
607 );
608
609 const updatedCors = yield* r2.getBucketCors({ accountId, bucketName: initial.bucketName });
610 expect(updatedCors.rules).toHaveLength(2);
611 expect(updatedCors.rules?.[0]?.allowed.origins).toEqual(["*"]);
612 expect(updatedCors.rules?.[1]?.id).toEqual("uploads");
613 expect(updatedCors.rules?.[1]?.allowed.methods).toEqual(["PUT", "POST"]);
614
615 // Clear all rules — the CORS configuration is deleted entirely, so the
616 // GET endpoint reports the typed NoCorsConfiguration error.
617 yield* stack.deploy(
618 Effect.gen(function* () {
619 return yield* Cloudflare.R2.Bucket("CorsBucket", { forceDestroy: true, cors: [] });
620 }),
621 );
622
623 const cleared = yield* r2.getBucketCors({ accountId, bucketName: initial.bucketName }).pipe(
624 Effect.map((response) => response.rules ?? []),
625 Effect.catchTag("NoCorsConfiguration", () => Effect.succeed([])),
626 );
627 expect(cleared).toEqual([]);
628
629 yield* stack.destroy();
630 yield* waitForBucketToBeDeleted(initial.bucketName, accountId);
631 }).pipe(logLevel),
632 { tags: ["provider:cloudflare", "provider:cloudflare:r2", "live"] },
633 );
634
635 test.provider(
636 "lock rules are added, updated, and removed",
637 (stack) =>
638 Effect.gen(function* () {
639 const { accountId } = yield* yield* CloudflareEnvironment;
640
641 yield* stack.destroy();
642
643 // Age conditions only: an Indefinite lock would outlive the test bucket.
644 const initial = yield* stack.deploy(
645 Effect.gen(function* () {
646 return yield* Cloudflare.R2.Bucket("LockBucket", {
647 forceDestroy: true,
648 locks: [
649 {
650 id: "raw-retention",
651 enabled: true,
652 prefix: "raw/",
653 condition: { type: "Age", maxAgeSeconds: 60 },
654 },
655 ],
656 });
657 }),
658 );
659
660 expect(initial.locks).toHaveLength(1);
661 const initialLocks = yield* r2.getBucketLock({ accountId, bucketName: initial.bucketName });
662 expect(initialLocks.rules).toHaveLength(1);
663 expect(initialLocks.rules?.[0]?.id).toEqual("raw-retention");
664 expect(initialLocks.rules?.[0]?.enabled).toEqual(true);
665 expect(initialLocks.rules?.[0]?.prefix).toEqual("raw/");
666 expect(initialLocks.rules?.[0]?.condition).toEqual({ type: "Age", maxAgeSeconds: 60 });
667
668 // Update: change the rule and add a bucket-wide one.
669 yield* stack.deploy(
670 Effect.gen(function* () {
671 return yield* Cloudflare.R2.Bucket("LockBucket", {
672 forceDestroy: true,
673 locks: [
674 {
675 id: "raw-retention",
676 enabled: false,
677 prefix: "raw/",
678 condition: { type: "Age", maxAgeSeconds: 120 },
679 },
680 { id: "all-objects", enabled: true, condition: { type: "Age", maxAgeSeconds: 30 } },
681 ],
682 });
683 }),
684 );
685
686 // R2 lists rules sorted by id, not in declaration order.
687 const updatedLocks = yield* r2.getBucketLock({ accountId, bucketName: initial.bucketName });
688 expect(updatedLocks.rules).toHaveLength(2);
689 const ruleById = (ruleId: string) => updatedLocks.rules?.find((r) => r.id === ruleId);
690 expect(ruleById("raw-retention")?.enabled).toEqual(false);
691 expect(ruleById("raw-retention")?.condition).toEqual({ type: "Age", maxAgeSeconds: 120 });
692 expect(ruleById("all-objects")?.enabled).toEqual(true);
693 expect(ruleById("all-objects")?.prefix ?? "").toEqual("");
694
695 // Remove `locks` from the props: the managed rules are cleared.
696 const cleared = yield* stack.deploy(
697 Effect.gen(function* () {
698 return yield* Cloudflare.R2.Bucket("LockBucket", { forceDestroy: true });
699 }),
700 );
701
702 expect(cleared.locks).toEqual([]);
703 const clearedLocks = yield* r2.getBucketLock({ accountId, bucketName: initial.bucketName });
704 expect(clearedLocks.rules ?? []).toEqual([]);
705
706 yield* stack.destroy();
707 yield* waitForBucketToBeDeleted(initial.bucketName, accountId);
708 }).pipe(logLevel),
709 { tags: ["provider:cloudflare", "provider:cloudflare:r2", "live"] },
710 );
711
712 // A lock is protection: reconcile must never clear rules a stack did not
713 // declare, since another tool may have set them.
714 test.provider(
715 "lock rules set out of band stay unmanaged until declared",
716 (stack) =>
717 Effect.gen(function* () {
718 const { accountId } = yield* yield* CloudflareEnvironment;
719
720 yield* stack.destroy();
721
722 const declaration = (locks?: Cloudflare.R2.BucketLockRule[]) =>
723 Effect.gen(function* () {
724 return yield* Cloudflare.R2.Bucket("UnmanagedLockBucket", { forceDestroy: true, locks });
725 });
726
727 const bucket = yield* stack.deploy(declaration());
728 expect(bucket.locks).toBeUndefined();
729
730 // Another tool locks the bucket.
731 yield* r2.putBucketLock({
732 accountId,
733 bucketName: bucket.bucketName,
734 rules: [
735 {
736 id: "raw-retention",
737 enabled: true,
738 prefix: "raw/",
739 condition: { type: "Age", maxAgeSeconds: 60 },
740 },
741 ],
742 });
743
744 // A forced redeploy runs reconcile, which leaves the foreign rule alone.
745 const redeployed = yield* stack.deploy(declaration(), { force: true });
746 expect(redeployed.locks).toBeUndefined();
747 const untouched = yield* r2.getBucketLock({ accountId, bucketName: bucket.bucketName });
748 expect(untouched.rules?.map((rule) => rule.id)).toEqual(["raw-retention"]);
749
750 // Declaring `locks` takes the rule set over and replaces it.
751 const declared = yield* stack.deploy(
752 declaration([
753 { id: "all-objects", enabled: true, condition: { type: "Age", maxAgeSeconds: 30 } },
754 ]),
755 );
756 expect(declared.locks?.map((rule) => rule.id)).toEqual(["all-objects"]);
757 const managed = yield* r2.getBucketLock({ accountId, bucketName: bucket.bucketName });
758 expect(managed.rules?.map((rule) => rule.id)).toEqual(["all-objects"]);
759
760 yield* stack.destroy();
761 yield* waitForBucketToBeDeleted(bucket.bucketName, accountId);
762 }).pipe(logLevel),
763 { tags: ["provider:cloudflare", "provider:cloudflare:r2", "live"] },
764 );
765
766 // R2 lists rules sorted by id with an omitted prefix as "". Declared rules
767 // that differ from that listing only in order or prefix spelling must
768 // converge, not churn on every deploy.
769 test.provider(
770 "lock rules declared out of order converge to R2's listing",
771 (stack) =>
772 Effect.gen(function* () {
773 const { accountId } = yield* yield* CloudflareEnvironment;
774
775 yield* stack.destroy();
776
777 const declaration = Effect.gen(function* () {
778 return yield* Cloudflare.R2.Bucket("OrderedLockBucket", {
779 forceDestroy: true,
780 // Declared out of id order; `all-objects` omits its prefix.
781 locks: [
782 {
783 id: "raw-retention",
784 enabled: true,
785 prefix: "raw/",
786 condition: { type: "Age", maxAgeSeconds: 60 },
787 },
788 { id: "all-objects", enabled: true, condition: { type: "Age", maxAgeSeconds: 30 } },
789 ],
790 });
791 });
792 const expected = [
793 {
794 id: "all-objects",
795 enabled: true,
796 prefix: "",
797 condition: { type: "Age", maxAgeSeconds: 30 },
798 },
799 {
800 id: "raw-retention",
801 enabled: true,
802 prefix: "raw/",
803 condition: { type: "Age", maxAgeSeconds: 60 },
804 },
805 ];
806
807 const bucket = yield* stack.deploy(declaration);
808 expect(bucket.locks).toEqual(expected);
809 const observed = yield* r2.getBucketLock({ accountId, bucketName: bucket.bucketName });
810 expect(observed.rules?.map((rule) => rule.id)).toEqual(["all-objects", "raw-retention"]);
811
812 // Redeploying the same declaration plans nothing.
813 const plan = yield* stack.plan(declaration);
814 expect(plan.resources.OrderedLockBucket?.action).toBe("noop");
815
816 // A forced reconcile converges to the same rules.
817 const redeployed = yield* stack.deploy(declaration, { force: true });
818 expect(redeployed.locks).toEqual(expected);
819 const reobserved = yield* r2.getBucketLock({ accountId, bucketName: bucket.bucketName });
820 expect(reobserved.rules?.map((rule) => rule.id)).toEqual(["all-objects", "raw-retention"]);
821
822 yield* stack.destroy();
823 yield* waitForBucketToBeDeleted(bucket.bucketName, accountId);
824 }).pipe(logLevel),
825 { tags: ["provider:cloudflare", "provider:cloudflare:r2", "live"] },
826 );
827
828 test.provider(
829 "cors reconciliation converges drift and adoption",
830 (stack) =>
831 Effect.gen(function* () {
832 const { accountId } = yield* yield* CloudflareEnvironment;
833
834 yield* stack.destroy();
835
836 const bucketName = testName("alchemy-test-r2-cors-drift");
837 const rangeReads = {
838 id: "range-reads",
839 allowedMethods: ["GET", "HEAD"] as ("GET" | "HEAD")[],
840 allowedOrigins: ["https://map.example.com"],
841 allowedHeaders: ["range"],
842 exposeHeaders: ["etag"],
843 maxAgeSeconds: 3600,
844 };
845 const foreignRule = {
846 id: "foreign",
847 allowed: { methods: ["DELETE" as const], origins: ["https://other.example.com"] },
848 };
849
850 const initial = yield* stack.deploy(
851 Effect.gen(function* () {
852 return yield* Cloudflare.R2.Bucket("DriftCorsBucket", {
853 forceDestroy: true,
854 name: bucketName,
855 cors: [rangeReads],
856 });
857 }),
858 );
859
860 // Drift: overwrite the CORS configuration out-of-band.
861 yield* r2.putBucketCors({ accountId, bucketName, rules: [foreignRule] });
862
863 // Re-deploy with a changed rule. Reconcile diffs desired against
864 // *observed* cloud state (not olds), so the foreign rule is replaced
865 // even though olds still describes the original rule.
866 yield* stack.deploy(
867 Effect.gen(function* () {
868 return yield* Cloudflare.R2.Bucket("DriftCorsBucket", {
869 forceDestroy: true,
870 name: bucketName,
871 cors: [{ ...rangeReads, maxAgeSeconds: 7200 }],
872 });
873 }),
874 );
875
876 const repaired = yield* r2.getBucketCors({ accountId, bucketName });
877 expect(repaired.rules).toHaveLength(1);
878 expect(repaired.rules?.[0]?.id).toEqual("range-reads");
879 expect(repaired.rules?.[0]?.maxAgeSeconds).toEqual(7200);
880
881 // Adoption: re-drift the CORS config, then wipe local state so the next
882 // deploy adopts via `read` (output defined, olds undefined).
883 yield* r2.putBucketCors({ accountId, bucketName, rules: [foreignRule] });
884 yield* Effect.gen(function* () {
885 const state = yield* yield* State;
886 yield* state.delete({ stack: stack.name, stage: stack.stage, fqn: "DriftCorsBucket" });
887 }).pipe(Effect.provide(stack.state));
888
889 const adopted = yield* stack.deploy(
890 Effect.gen(function* () {
891 return yield* Cloudflare.R2.Bucket("DriftCorsBucket", {
892 forceDestroy: true,
893 name: bucketName,
894 cors: [rangeReads],
895 });
896 }),
897 );
898 expect(adopted.bucketName).toEqual(bucketName);
899 expect(adopted.cors).toHaveLength(1);
900 expect(adopted.cors[0]?.id).toEqual("range-reads");
901
902 const converged = yield* r2.getBucketCors({ accountId, bucketName });
903 expect(converged.rules).toHaveLength(1);
904 expect(converged.rules?.[0]?.id).toEqual("range-reads");
905 expect(converged.rules?.[0]?.allowed.origins).toEqual(["https://map.example.com"]);
906
907 yield* stack.destroy();
908 yield* waitForBucketToBeDeleted(bucketName, accountId);
909 }).pipe(logLevel),
910 { tags: ["provider:cloudflare", "provider:cloudflare:r2", "live"] },
911 );
912
913 test.provider(
914 "drift detects and repairs a live storage-class change",
915 (stack) =>
916 Effect.gen(function* () {
917 const { accountId } = yield* yield* CloudflareEnvironment;
918 const bucketName = testName("alchemy-test-r2-drift-repair");
919
920 yield* forceDeleteBucket(accountId, bucketName);
921 yield* stack.destroy();
922
923 yield* stack.deploy(
924 Effect.gen(function* () {
925 return yield* Cloudflare.R2.Bucket("DriftRepairBucket", {
926 forceDestroy: true,
927 name: bucketName,
928 storageClass: "Standard",
929 });
930 }),
931 );
932
933 yield* r2.patchBucket({ accountId, bucketName, storageClass: "InfrequentAccess" });
934
935 const detected = yield* Drift.detect({ name: stack.name, stage: stack.stage }).pipe(
936 Effect.provide(stack.state),
937 );
938 expect(detected.resources.DriftRepairBucket).toMatchObject({
939 action: "drifted",
940 resourceType: "Cloudflare.R2.Bucket",
941 });
942
943 const repaired = yield* Drift.repair({ name: stack.name, stage: stack.stage }).pipe(
944 Effect.provide(stack.state),
945 );
946 expect(repaired.resources.DriftRepairBucket).toMatchObject({ action: "repaired" });
947
948 const bucket = yield* getBucketWhenReady(bucketName, accountId);
949 expect(bucket.storageClass).toEqual("Standard");
950
951 yield* stack.destroy();
952 yield* waitForBucketToBeDeleted(bucketName, accountId);
953 }).pipe(logLevel),
954 { tags: ["provider:cloudflare", "provider:cloudflare:r2", "live"] },
955 );
956
957 test.provider(
958 "drift detects and recreates a bucket deleted out of band",
959 (stack) =>
960 Effect.gen(function* () {
961 const { accountId } = yield* yield* CloudflareEnvironment;
962 const bucketName = testName("alchemy-test-r2-drift-recreate");
963
964 yield* forceDeleteBucket(accountId, bucketName);
965 yield* stack.destroy();
966
967 yield* stack.deploy(
968 Effect.gen(function* () {
969 return yield* Cloudflare.R2.Bucket("DriftRecreateBucket", {
970 forceDestroy: true,
971 name: bucketName,
972 });
973 }),
974 );
975 const before = yield* stateOf(stack, "DriftRecreateBucket");
976
977 yield* forceDeleteBucket(accountId, bucketName);
978 yield* waitForBucketToBeDeleted(bucketName, accountId);
979
980 const detected = yield* Drift.detect({ name: stack.name, stage: stack.stage }).pipe(
981 Effect.provide(stack.state),
982 );
983 expect(detected.resources.DriftRecreateBucket).toMatchObject({
984 action: "missing",
985 resourceType: "Cloudflare.R2.Bucket",
986 });
987
988 const repaired = yield* Drift.repair({ name: stack.name, stage: stack.stage }).pipe(
989 Effect.provide(stack.state),
990 );
991 expect(repaired.resources.DriftRecreateBucket).toMatchObject({ action: "recreated" });
992
993 const after = yield* stateOf(stack, "DriftRecreateBucket");
994 expect(after?.instanceId).toEqual(before?.instanceId);
995 expect((yield* getBucketWhenReady(bucketName, accountId)).name).toEqual(bucketName);
996
997 yield* stack.destroy();
998 yield* waitForBucketToBeDeleted(bucketName, accountId);
999 }).pipe(logLevel),
1000 { tags: ["provider:cloudflare", "provider:cloudflare:r2", "live"], timeout: 180_000 },
1001 );
1002
1003 test.provider(
1004 "cors is applied to the new bucket on replacement",
1005 (stack) =>
1006 Effect.gen(function* () {
1007 const { accountId } = yield* yield* CloudflareEnvironment;
1008
1009 yield* stack.destroy();
1010
1011 const oldName = testName("alchemy-test-r2-cors-replace-a");
1012 const newName = testName("alchemy-test-r2-cors-replace-b");
1013 const cors = [
1014 {
1015 id: "range-reads",
1016 allowedMethods: ["GET", "HEAD"] as ("GET" | "HEAD")[],
1017 allowedOrigins: ["https://map.example.com"],
1018 allowedHeaders: ["range"],
1019 exposeHeaders: ["etag"],
1020 maxAgeSeconds: 3600,
1021 },
1022 ];
1023
1024 const initial = yield* stack.deploy(
1025 Effect.gen(function* () {
1026 return yield* Cloudflare.R2.Bucket("ReplaceCorsBucket", {
1027 forceDestroy: true,
1028 name: oldName,
1029 cors,
1030 });
1031 }),
1032 );
1033 expect(initial.bucketName).toEqual(oldName);
1034
1035 const initialCors = yield* r2.getBucketCors({ accountId, bucketName: oldName });
1036 expect(initialCors.rules).toHaveLength(1);
1037
1038 // Changing the name replaces the bucket: the new bucket is created
1039 // (greenfield reconcile must apply the CORS config from scratch) and
1040 // the old bucket is deleted afterwards.
1041 const replaced = yield* stack.deploy(
1042 Effect.gen(function* () {
1043 return yield* Cloudflare.R2.Bucket("ReplaceCorsBucket", {
1044 forceDestroy: true,
1045 name: newName,
1046 cors,
1047 });
1048 }),
1049 );
1050 expect(replaced.bucketName).toEqual(newName);
1051 expect(replaced.cors).toHaveLength(1);
1052 expect(replaced.cors[0]?.id).toEqual("range-reads");
1053
1054 const replacedCors = yield* r2.getBucketCors({ accountId, bucketName: newName });
1055 expect(replacedCors.rules).toHaveLength(1);
1056 expect(replacedCors.rules?.[0]?.id).toEqual("range-reads");
1057 expect(replacedCors.rules?.[0]?.allowed.origins).toEqual(["https://map.example.com"]);
1058
1059 // The replaced bucket is cleaned up.
1060 yield* waitForBucketToBeDeleted(oldName, accountId);
1061
1062 yield* stack.destroy();
1063 yield* waitForBucketToBeDeleted(newName, accountId);
1064 }).pipe(logLevel),
1065 { tags: ["provider:cloudflare", "provider:cloudflare:r2", "live"] },
1066 );
1067
1068 test.provider(
1069 "local uploads are enabled and disabled in place",
1070 (stack) =>
1071 Effect.gen(function* () {
1072 const { accountId } = yield* yield* CloudflareEnvironment;
1073
1074 yield* stack.destroy();
1075
1076 const initial = yield* stack.deploy(
1077 Effect.gen(function* () {
1078 return yield* Cloudflare.R2.Bucket("LocalUploadsBucket", { forceDestroy: true });
1079 }),
1080 );
1081 expect(initial.localUploads).toBeUndefined();
1082
1083 const enabled = yield* stack.deploy(
1084 Effect.gen(function* () {
1085 return yield* Cloudflare.R2.Bucket("LocalUploadsBucket", {
1086 forceDestroy: true,
1087 localUploads: true,
1088 });
1089 }),
1090 );
1091 expect(enabled.bucketName).toEqual(initial.bucketName);
1092 expect(enabled.localUploads).toEqual(true);
1093 const observedEnabled = yield* r2.getBucketLocalUploads({
1094 accountId,
1095 bucketName: initial.bucketName,
1096 });
1097 expect(observedEnabled.enabled).toEqual(true);
1098
1099 const disabled = yield* stack.deploy(
1100 Effect.gen(function* () {
1101 return yield* Cloudflare.R2.Bucket("LocalUploadsBucket", {
1102 forceDestroy: true,
1103 localUploads: false,
1104 });
1105 }),
1106 );
1107 expect(disabled.bucketName).toEqual(initial.bucketName);
1108 expect(disabled.localUploads).toEqual(false);
1109 const observedDisabled = yield* r2.getBucketLocalUploads({
1110 accountId,
1111 bucketName: initial.bucketName,
1112 });
1113 expect(observedDisabled.enabled).toEqual(false);
1114
1115 // Re-enable, then drop the prop: a declared-then-removed setting is disabled.
1116 yield* stack.deploy(
1117 Effect.gen(function* () {
1118 return yield* Cloudflare.R2.Bucket("LocalUploadsBucket", {
1119 forceDestroy: true,
1120 localUploads: true,
1121 });
1122 }),
1123 );
1124 const removed = yield* stack.deploy(
1125 Effect.gen(function* () {
1126 return yield* Cloudflare.R2.Bucket("LocalUploadsBucket", { forceDestroy: true });
1127 }),
1128 );
1129 expect(removed.bucketName).toEqual(initial.bucketName);
1130 const observedRemoved = yield* r2.getBucketLocalUploads({
1131 accountId,
1132 bucketName: initial.bucketName,
1133 });
1134 expect(observedRemoved.enabled).toEqual(false);
1135
1136 yield* stack.destroy();
1137 yield* waitForBucketToBeDeleted(initial.bucketName, accountId);
1138 }).pipe(logLevel),
1139 { tags: ["provider:cloudflare", "provider:cloudflare:r2", "live"] },
1140 );
1141
1142 test.provider(
1143 "local uploads are refused on a jurisdiction-restricted bucket",
1144 (stack) =>
1145 Effect.gen(function* () {
1146 const { accountId } = yield* yield* CloudflareEnvironment;
1147
1148 yield* stack.destroy();
1149
1150 const name = `alchemy-eu-local-uploads-${stack.stage}`
1151 .toLowerCase()
1152 .replace(/[^a-z0-9-]/g, "-");
1153 const refused = yield* stack
1154 .deploy(
1155 Effect.gen(function* () {
1156 return yield* Cloudflare.R2.Bucket("EuLocalUploadsBucket", {
1157 name,
1158 jurisdiction: "eu",
1159 localUploads: true,
1160 });
1161 }),
1162 )
1163 .pipe(Effect.flip);
1164 expect(refused._tag).toEqual("LocalUploadsUnsupported");
1165
1166 // Refused before create: no EU bucket was left behind.
1167 const missing = yield* r2
1168 .getBucket({ accountId, bucketName: name, jurisdiction: "eu" })
1169 .pipe(Effect.flip);
1170 expect(missing._tag).toEqual("NoSuchBucket");
1171
1172 yield* stack.destroy();
1173 }).pipe(logLevel),
1174 { tags: ["provider:cloudflare", "provider:cloudflare:r2", "live"] },
1175 );
1176
1177 test.provider(
1178 "create and delete bucket in the us jurisdiction",
1179 (stack) =>
1180 Effect.gen(function* () {
1181 const { accountId } = yield* yield* CloudflareEnvironment;
1182
1183 yield* stack.destroy();
1184
1185 const bucket = yield* stack.deploy(
1186 Effect.gen(function* () {
1187 return yield* Cloudflare.R2.Bucket("UsBucket", {
1188 forceDestroy: true,
1189 jurisdiction: "us",
1190 });
1191 }),
1192 );
1193 expect(bucket.jurisdiction).toEqual("us");
1194
1195 const actual = yield* getBucketWhenReady(bucket.bucketName, accountId, "us");
1196 expect(actual.jurisdiction).toEqual("us");
1197
1198 // The bucket lives only in the `us` partition, not the default one.
1199 const outsideUs = yield* r2
1200 .getBucket({ accountId, bucketName: bucket.bucketName })
1201 .pipe(Effect.flip);
1202 expect(outsideUs._tag).toEqual("NoSuchBucket");
1203
1204 // An unchanged redeploy reads the bucket back from the `us` partition.
1205 const plan = yield* stack.plan(
1206 Effect.gen(function* () {
1207 return yield* Cloudflare.R2.Bucket("UsBucket", {
1208 forceDestroy: true,
1209 jurisdiction: "us",
1210 });
1211 }),
1212 );
1213 expect(plan.resources.UsBucket?.action).toEqual("noop");
1214
1215 yield* stack.destroy();
1216
1217 yield* waitForBucketToBeDeleted(bucket.bucketName, accountId, "us");
1218 }).pipe(logLevel),
1219 { tags: ["provider:cloudflare", "provider:cloudflare:r2", "live"] },
1220 );
1221
1222 test.provider(
1223 "managed r2.dev domain is enabled and disabled",
1224 (stack) =>
1225 Effect.gen(function* () {
1226 const { accountId } = yield* yield* CloudflareEnvironment;
1227
1228 yield* stack.destroy();
1229
1230 const initial = yield* stack.deploy(
1231 Effect.gen(function* () {
1232 return yield* Cloudflare.R2.Bucket("PublicBucket", {
1233 forceDestroy: true,
1234 publicAccess: true,
1235 });
1236 }),
1237 );
1238
1239 expect(initial.publicDomain).toBeDefined();
1240 expect(initial.publicDomain).toMatch(/\.r2\.dev$/);
1241
1242 const enabled = yield* r2.listBucketDomainManageds({
1243 accountId,
1244 bucketName: initial.bucketName,
1245 });
1246 expect(enabled.enabled).toEqual(true);
1247 expect(enabled.domain).toEqual(initial.publicDomain);
1248
1249 const disabled = yield* stack.deploy(
1250 Effect.gen(function* () {
1251 return yield* Cloudflare.R2.Bucket("PublicBucket", {
1252 forceDestroy: true,
1253 publicAccess: false,
1254 });
1255 }),
1256 );
1257
1258 expect(disabled.bucketName).toEqual(initial.bucketName);
1259 expect(disabled.publicDomain).toBeUndefined();
1260
1261 const observed = yield* r2.listBucketDomainManageds({
1262 accountId,
1263 bucketName: initial.bucketName,
1264 });
1265 expect(observed.enabled).toEqual(false);
1266 expect(observed.domain).toEqual(enabled.domain);
1267
1268 yield* stack.destroy();
1269 yield* waitForBucketToBeDeleted(initial.bucketName, accountId);
1270 }).pipe(logLevel),
1271 { tags: ["provider:cloudflare", "provider:cloudflare:r2", "live"] },
1272 );
1273
1274 test.provider(
1275 "managed r2.dev domain converges drift and adoption",
1276 (stack) =>
1277 Effect.gen(function* () {
1278 const { accountId } = yield* yield* CloudflareEnvironment;
1279
1280 yield* stack.destroy();
1281
1282 // Pin the physical name on every deploy so adding `name` cannot be
1283 // what schedules the update — same shape as the CORS drift case
1284 // above. A PR/user suffix keeps concurrent runs from colliding.
1285 const suffix = stageSuffix()
1286 .toLowerCase()
1287 .replace(/[^a-z0-9]/g, "")
1288 .slice(0, 24);
1289 const bucketName = `alchemy-test-r2-pub-drift-${suffix}`;
1290
1291 const initial = yield* stack.deploy(
1292 Effect.gen(function* () {
1293 return yield* Cloudflare.R2.Bucket("DriftPublicBucket", {
1294 forceDestroy: true,
1295 name: bucketName,
1296 publicAccess: false,
1297 });
1298 }),
1299 );
1300 expect(initial.publicDomain).toBeUndefined();
1301
1302 // Drift: enable the managed domain out of band.
1303 yield* r2.putBucketDomainManaged({ accountId, bucketName, enabled: true });
1304
1305 // Re-deploy with publicAccess still false. The storage-class change
1306 // is what makes Plan run reconcile (unchanged props skip it); the
1307 // managed-domain sync must still disable the leaked enable because
1308 // it diffs desired against *observed* cloud state, not olds.
1309 const repaired = yield* stack.deploy(
1310 Effect.gen(function* () {
1311 return yield* Cloudflare.R2.Bucket("DriftPublicBucket", {
1312 forceDestroy: true,
1313 name: bucketName,
1314 publicAccess: false,
1315 storageClass: "InfrequentAccess",
1316 });
1317 }),
1318 );
1319 expect(repaired.bucketName).toEqual(bucketName);
1320 expect(repaired.storageClass).toEqual("InfrequentAccess");
1321 expect(repaired.publicDomain).toBeUndefined();
1322
1323 const afterRepair = yield* r2.listBucketDomainManageds({ accountId, bucketName });
1324 expect(afterRepair.enabled).toEqual(false);
1325
1326 // Adoption: re-enable out of band, wipe local state, then adopt
1327 // with publicAccess: true (output defined, olds undefined).
1328 yield* r2.putBucketDomainManaged({ accountId, bucketName, enabled: true });
1329 yield* Effect.gen(function* () {
1330 const state = yield* yield* State;
1331 yield* state.delete({ stack: stack.name, stage: stack.stage, fqn: "DriftPublicBucket" });
1332 }).pipe(Effect.provide(stack.state));
1333
1334 const adopted = yield* stack.deploy(
1335 Effect.gen(function* () {
1336 return yield* Cloudflare.R2.Bucket("DriftPublicBucket", {
1337 forceDestroy: true,
1338 name: bucketName,
1339 publicAccess: true,
1340 });
1341 }),
1342 );
1343 expect(adopted.bucketName).toEqual(bucketName);
1344 expect(adopted.publicDomain).toMatch(/\.r2\.dev$/);
1345
1346 const converged = yield* r2.listBucketDomainManageds({ accountId, bucketName });
1347 expect(converged.enabled).toEqual(true);
1348 expect(converged.domain).toEqual(adopted.publicDomain);
1349
1350 yield* stack.destroy();
1351 yield* waitForBucketToBeDeleted(bucketName, accountId);
1352 }).pipe(logLevel),
1353 { tags: ["provider:cloudflare", "provider:cloudflare:r2", "live"] },
1354 );
1355
1356 test.provider(
1357 "managed r2.dev domain is applied on replacement",
1358 (stack) =>
1359 Effect.gen(function* () {
1360 const { accountId } = yield* yield* CloudflareEnvironment;
1361
1362 yield* stack.destroy();
1363
1364 const initial = yield* stack.deploy(
1365 Effect.gen(function* () {
1366 return yield* Cloudflare.R2.Bucket("ReplacePublicBucket", {
1367 forceDestroy: true,
1368 publicAccess: true,
1369 });
1370 }),
1371 );
1372 const oldName = initial.bucketName;
1373 // Flip the first character so the replacement name is unique and
1374 // stays within R2's 63-char limit regardless of the original length.
1375 const newName = `x${oldName.slice(1)}`;
1376
1377 const replaced = yield* stack.deploy(
1378 Effect.gen(function* () {
1379 return yield* Cloudflare.R2.Bucket("ReplacePublicBucket", {
1380 forceDestroy: true,
1381 name: newName,
1382 publicAccess: true,
1383 });
1384 }),
1385 );
1386 expect(replaced.bucketName).toEqual(newName);
1387 expect(replaced.publicDomain).toMatch(/\.r2\.dev$/);
1388
1389 const replacedDomain = yield* r2.listBucketDomainManageds({ accountId, bucketName: newName });
1390 expect(replacedDomain.enabled).toEqual(true);
1391 expect(replacedDomain.domain).toEqual(replaced.publicDomain);
1392
1393 yield* waitForBucketToBeDeleted(oldName, accountId);
1394
1395 yield* stack.destroy();
1396 yield* waitForBucketToBeDeleted(newName, accountId);
1397 }).pipe(logLevel),
1398 { tags: ["provider:cloudflare", "provider:cloudflare:r2", "live"] },
1399 );
1400
1401 // R2 bucket creates are eventually consistent — a read immediately after
1402 // deploy can briefly return NoSuchBucket until the bucket propagates.
1403 const getBucketWhenReady = Effect.fn(function* (
1404 bucketName: string,
1405 accountId: string,
1406 jurisdiction?: Cloudflare.R2.Bucket.Jurisdiction,
1407 ) {
1408 return yield* r2.getBucket({ accountId, bucketName, jurisdiction }).pipe(
1409 Effect.retry({
1410 while: (e) => e._tag === "NoSuchBucket",
1411 // Cap the backoff at 2s so we keep sampling instead of sleeping
1412 // through the budget on the geometric tail.
1413 schedule: Schedule.max([
1414 Schedule.min([Schedule.exponential("200 millis"), Schedule.spaced("2 seconds")]),
1415 Schedule.recurs(20),
1416 ]),
1417 }),
1418 );
1419 });
1420
1421 const waitForBucketToBeDeleted = Effect.fn(function* (
1422 bucketName: string,
1423 accountId: string,
1424 jurisdiction?: Cloudflare.R2.Bucket.Jurisdiction,
1425 ) {
1426 yield* r2.getBucket({ accountId, bucketName, jurisdiction }).pipe(
1427 Effect.flatMap(() => Effect.fail(new BucketStillExists())),
1428 Effect.retry({
1429 while: (e) => e._tag === "BucketStillExists",
1430 schedule: Schedule.max([
1431 Schedule.min([Schedule.exponential("100 millis"), Schedule.spaced("2 seconds")]),
1432 Schedule.recurs(20),
1433 ]),
1434 }),
1435 Effect.catchTag("NoSuchBucket", () => Effect.void),
1436 );
1437 });
1438
1439 class BucketStillExists extends Data.TaggedError("BucketStillExists") {}
1440
1441 const putObject = (accountId: string, bucketName: string, key: string, body: string) =>
1442 r2.putObject({
1443 accountId,
1444 bucketName,
1445 objectName: key,
1446 contentType: "text/plain",
1447 body: new Blob([body], { type: "text/plain" }),
1448 });
1449
1450 // R2's object listing lags a write by a beat — poll until the expected
1451 // number of keys shows up, then return them.
1452 const listKeysWhenReady = Effect.fn(function* (
1453 accountId: string,
1454 bucketName: string,
1455 count: number,
1456 ) {
1457 return yield* r2.listObjects({ accountId, bucketName, perPage: 1000 }).pipe(
1458 Effect.flatMap((page) => {
1459 const keys = (page.result ?? [])
1460 .map((o) => o.key)
1461 .filter((k): k is string => typeof k === "string");
1462 return keys.length === count ? Effect.succeed(keys) : Effect.fail(new ListLagError());
1463 }),
1464 Effect.retry({
1465 while: (e): e is ListLagError => e instanceof ListLagError,
1466 schedule: Schedule.max([Schedule.exponential(200), Schedule.recurs(8)]),
1467 }),
1468 );
1469 });
1470
1471 class ListLagError extends Data.TaggedError("ListLagError") {}
1472
1473 const stateOf = Effect.fn(function* (
1474 stack: { name: string; stage: string; state: Layer.Layer<State> },
1475 fqn: string,
1476 ) {
1477 return yield* Effect.gen(function* () {
1478 const state = yield* yield* State;
1479 return (yield* state.get({ stack: stack.name, stage: stack.stage, fqn })) as
1480 | ResourceState
1481 | undefined;
1482 }).pipe(Effect.provide(stack.state));
1483 });
1484
1485 const removalPolicyOf = Effect.fn(function* (
1486 stack: { name: string; stage: string; state: Layer.Layer<State> },
1487 fqn: string,
1488 ) {
1489 return (yield* stateOf(stack, fqn))?.removalPolicy;
1490 });
1491
1492 /**
1493 * Empty and delete a bucket out of band. Needed only for buckets a test
1494 * deliberately RETAINED: alchemy has forgotten them by design, so nothing
1495 * else will ever reclaim them.
1496 */
1497 const forceDeleteBucket = Effect.fn(function* (accountId: string, bucketName: string) {
1498 yield* r2.listObjects.items({ accountId, bucketName, perPage: 1000 }).pipe(
1499 Stream.filter((o): o is typeof o & { key: string } => typeof o.key === "string"),
1500 Stream.map((o) => o.key),
1501 Stream.runForEachArray((chunk) =>
1502 r2.deleteObjects({ accountId, bucketName, body: [...chunk] }),
1503 ),
1504 Effect.catchTag("NoSuchBucket", () => Effect.void),
1505 );
1506 yield* r2
1507 .deleteBucket({ accountId, bucketName })
1508 .pipe(Effect.catchTag("NoSuchBucket", () => Effect.void));
1509 });