| 1 | import { adopt, OwnedBySomeoneElse } from "@/AdoptPolicy"; |
| 2 | import * as Cloudflare from "@/Cloudflare"; |
| 3 | import { CloudflareEnvironment } from "@/Cloudflare/CloudflareEnvironment"; |
| 4 | import { findZoneByName } from "@/Cloudflare/Zone/lookup"; |
| 5 | import * as Provider from "@/Provider"; |
| 6 | import * as Test from "@/Test/Alchemy"; |
| 7 | import * as pageRules from "@distilled.cloud/cloudflare/page-rules"; |
| 8 | import { expect } from "alchemy-test"; |
| 9 | import * as Cause from "effect/Cause"; |
| 10 | import * as Effect from "effect/Effect"; |
| 11 | import { MinimumLogLevel } from "effect/References"; |
| 12 | import * as Schedule from "effect/Schedule"; |
| 13 | |
| 14 | const { test } = Test.make({ providers: Cloudflare.providers() }); |
| 15 | |
| 16 | const logLevel = Effect.provideService( |
| 17 | MinimumLogLevel, |
| 18 | process.env.DEBUG ? "Debug" : "Info", |
| 19 | ); |
| 20 | |
| 21 | const zoneName = |
| 22 | process.env.CLOUDFLARE_TEST_DNS_ZONE_NAME ?? "alchemy-test-2.us"; |
| 23 | |
| 24 | // Deterministic per-test URL targets. Each test owns a disjoint path so |
| 25 | // reruns never collide, and the same target is reused on every run (never |
| 26 | // derive identity from Date.now()/random). Free zones allow only 3 Page |
| 27 | // Rules — every test starts and ends clean to stay within quota. |
| 28 | const TARGET_DEFAULT = `${zoneName}/alchemy-pagerule-default/*`; |
| 29 | const TARGET_UPDATE = `${zoneName}/alchemy-pagerule-update/*`; |
| 30 | const TARGET_UPDATE_MOVED = `${zoneName}/alchemy-pagerule-update-moved/*`; |
| 31 | const TARGET_ADOPT = `${zoneName}/alchemy-pagerule-adopt/*`; |
| 32 | const TARGET_LIST = `${zoneName}/alchemy-pagerule-list/*`; |
| 33 | |
| 34 | const resolveZoneId = Effect.gen(function* () { |
| 35 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 36 | const zone = yield* findZoneByName({ accountId, name: zoneName }); |
| 37 | if (!zone) { |
| 38 | return yield* Effect.die( |
| 39 | new Error(`zone "${zoneName}" not found in account`), |
| 40 | ); |
| 41 | } |
| 42 | return zone.id; |
| 43 | }); |
| 44 | |
| 45 | // The scoped API token the test harness mints propagates eventually- |
| 46 | // consistently across Cloudflare's edge — a fresh token intermittently 403s |
| 47 | // with "Unable to authenticate request". Ride out the blips on the test's |
| 48 | // own out-of-band verification calls by retrying the typed `Forbidden` |
| 49 | // error (part of each page-rules operation's error union via distilled |
| 50 | // patches). |
| 51 | const forbiddenRetrySchedule = Schedule.exponential("500 millis"); |
| 52 | |
| 53 | const retryForbidden = <A, E extends { _tag: string }, R>( |
| 54 | effect: Effect.Effect<A, E, R>, |
| 55 | ) => |
| 56 | effect.pipe( |
| 57 | Effect.retry({ |
| 58 | while: (e) => e._tag === "Forbidden", |
| 59 | schedule: forbiddenRetrySchedule, |
| 60 | times: 8, |
| 61 | }), |
| 62 | ); |
| 63 | |
| 64 | const targetOf = (rule: { |
| 65 | targets: ReadonlyArray<{ constraint?: { value: string } | null }>; |
| 66 | }) => rule.targets[0]?.constraint?.value; |
| 67 | |
| 68 | const listRules = (zoneId: string) => |
| 69 | retryForbidden(pageRules.listPageRules({ zoneId })); |
| 70 | |
| 71 | const findRule = (zoneId: string, target: string) => |
| 72 | listRules(zoneId).pipe( |
| 73 | Effect.map((rules) => rules.find((r) => targetOf(r) === target)), |
| 74 | ); |
| 75 | |
| 76 | const getRule = (zoneId: string, pageruleId: string) => |
| 77 | retryForbidden(pageRules.getPageRule({ zoneId, pageruleId })); |
| 78 | |
| 79 | // Delete every rule matching one of our deterministic targets — used to |
| 80 | // purge leftovers from interrupted runs so tests start from a clean slate |
| 81 | // (and stay within the free-plan quota of 3 rules). |
| 82 | const purgeRules = (zoneId: string, targets: ReadonlyArray<string>) => |
| 83 | listRules(zoneId).pipe( |
| 84 | Effect.flatMap( |
| 85 | Effect.forEach((rule) => |
| 86 | targets.includes(targetOf(rule) ?? "") |
| 87 | ? pageRules |
| 88 | .deletePageRule({ zoneId, pageruleId: rule.id }) |
| 89 | .pipe(Effect.catchTag("PageRuleNotFound", () => Effect.void)) |
| 90 | : Effect.void, |
| 91 | ), |
| 92 | ), |
| 93 | ); |
| 94 | |
| 95 | test.provider( |
| 96 | "create, verify out-of-band, and destroy a page rule", |
| 97 | (stack) => |
| 98 | Effect.gen(function* () { |
| 99 | const zoneId = yield* resolveZoneId; |
| 100 | |
| 101 | yield* stack.destroy(); |
| 102 | yield* purgeRules(zoneId, [TARGET_DEFAULT]); |
| 103 | |
| 104 | const rule = yield* stack.deploy( |
| 105 | Effect.gen(function* () { |
| 106 | return yield* Cloudflare.PageRule.PageRule("DefaultRule", { |
| 107 | zoneId, |
| 108 | target: TARGET_DEFAULT, |
| 109 | actions: [ |
| 110 | { id: "cache_level", value: "cache_everything" }, |
| 111 | { id: "edge_cache_ttl", value: 7200 }, |
| 112 | ], |
| 113 | }).pipe(adopt(true)); |
| 114 | }), |
| 115 | ); |
| 116 | |
| 117 | expect(rule.pageRuleId).toBeDefined(); |
| 118 | expect(rule.zoneId).toEqual(zoneId); |
| 119 | expect(rule.target).toEqual(TARGET_DEFAULT); |
| 120 | // Alchemy defaults differ from the raw API: status active, priority 1. |
| 121 | expect(rule.status).toEqual("active"); |
| 122 | expect(rule.priority).toEqual(1); |
| 123 | |
| 124 | const live = yield* getRule(zoneId, rule.pageRuleId); |
| 125 | expect(live.id).toEqual(rule.pageRuleId); |
| 126 | expect(targetOf(live)).toEqual(TARGET_DEFAULT); |
| 127 | expect(live.status).toEqual("active"); |
| 128 | const actionIds = live.actions.map((a) => a.id).sort(); |
| 129 | expect(actionIds).toEqual(["cache_level", "edge_cache_ttl"]); |
| 130 | |
| 131 | yield* stack.destroy(); |
| 132 | |
| 133 | const gone = yield* findRule(zoneId, TARGET_DEFAULT); |
| 134 | expect(gone).toBeUndefined(); |
| 135 | }).pipe(logLevel), |
| 136 | { |
| 137 | tags: [ |
| 138 | "provider:cloudflare", |
| 139 | "provider:cloudflare:pagerule", |
| 140 | "provider:cloudflare:zone", |
| 141 | "live", |
| 142 | ], |
| 143 | }, |
| 144 | ); |
| 145 | |
| 146 | test.provider( |
| 147 | "updating actions, status, priority and target syncs in place", |
| 148 | (stack) => |
| 149 | Effect.gen(function* () { |
| 150 | const zoneId = yield* resolveZoneId; |
| 151 | |
| 152 | yield* stack.destroy(); |
| 153 | yield* purgeRules(zoneId, [TARGET_UPDATE, TARGET_UPDATE_MOVED]); |
| 154 | |
| 155 | const initial = yield* stack.deploy( |
| 156 | Effect.gen(function* () { |
| 157 | return yield* Cloudflare.PageRule.PageRule("UpdateRule", { |
| 158 | zoneId, |
| 159 | target: TARGET_UPDATE, |
| 160 | actions: [{ id: "cache_level", value: "bypass" }], |
| 161 | status: "disabled", |
| 162 | }).pipe(adopt(true)); |
| 163 | }), |
| 164 | ); |
| 165 | |
| 166 | expect(initial.status).toEqual("disabled"); |
| 167 | expect(initial.target).toEqual(TARGET_UPDATE); |
| 168 | |
| 169 | const updated = yield* stack.deploy( |
| 170 | Effect.gen(function* () { |
| 171 | return yield* Cloudflare.PageRule.PageRule("UpdateRule", { |
| 172 | zoneId, |
| 173 | // Targets are mutable via PUT — same rule, new URL pattern. |
| 174 | target: TARGET_UPDATE_MOVED, |
| 175 | actions: [ |
| 176 | { id: "cache_level", value: "cache_everything" }, |
| 177 | { id: "browser_cache_ttl", value: 3600 }, |
| 178 | ], |
| 179 | status: "active", |
| 180 | }).pipe(adopt(true)); |
| 181 | }), |
| 182 | ); |
| 183 | |
| 184 | // Same rule updated in place — not a replacement. |
| 185 | expect(updated.pageRuleId).toEqual(initial.pageRuleId); |
| 186 | expect(updated.target).toEqual(TARGET_UPDATE_MOVED); |
| 187 | expect(updated.status).toEqual("active"); |
| 188 | // Cloudflare clamps priority to the number of rules on the zone |
| 189 | // (priority is positional) — a lone rule is always priority 1. |
| 190 | expect(updated.priority).toEqual(1); |
| 191 | |
| 192 | const live = yield* getRule(zoneId, updated.pageRuleId); |
| 193 | expect(targetOf(live)).toEqual(TARGET_UPDATE_MOVED); |
| 194 | expect(live.status).toEqual("active"); |
| 195 | const actionIds = live.actions.map((a) => a.id).sort(); |
| 196 | expect(actionIds).toEqual(["browser_cache_ttl", "cache_level"]); |
| 197 | |
| 198 | // Re-deploying the identical desired state is a no-op (sync skips |
| 199 | // the PUT entirely) and keeps the same physical rule. |
| 200 | const noop = yield* stack.deploy( |
| 201 | Effect.gen(function* () { |
| 202 | return yield* Cloudflare.PageRule.PageRule("UpdateRule", { |
| 203 | zoneId, |
| 204 | target: TARGET_UPDATE_MOVED, |
| 205 | actions: [ |
| 206 | { id: "cache_level", value: "cache_everything" }, |
| 207 | { id: "browser_cache_ttl", value: 3600 }, |
| 208 | ], |
| 209 | status: "active", |
| 210 | }).pipe(adopt(true)); |
| 211 | }), |
| 212 | ); |
| 213 | expect(noop.pageRuleId).toEqual(initial.pageRuleId); |
| 214 | |
| 215 | yield* stack.destroy(); |
| 216 | |
| 217 | const gone = yield* findRule(zoneId, TARGET_UPDATE_MOVED); |
| 218 | expect(gone).toBeUndefined(); |
| 219 | }).pipe(logLevel), |
| 220 | { |
| 221 | tags: [ |
| 222 | "provider:cloudflare", |
| 223 | "provider:cloudflare:pagerule", |
| 224 | "provider:cloudflare:zone", |
| 225 | "live", |
| 226 | ], |
| 227 | }, |
| 228 | ); |
| 229 | |
| 230 | test.provider( |
| 231 | "adoption — existing rule errors without adopt, takes over with adopt(true)", |
| 232 | (stack) => |
| 233 | Effect.gen(function* () { |
| 234 | const zoneId = yield* resolveZoneId; |
| 235 | |
| 236 | yield* stack.destroy(); |
| 237 | yield* purgeRules(zoneId, [TARGET_ADOPT]); |
| 238 | |
| 239 | // Create the rule out-of-band so the stack has no state of its own |
| 240 | // for it — exactly the "the rule already exists" scenario. |
| 241 | const pre = yield* retryForbidden( |
| 242 | pageRules.createPageRule({ |
| 243 | zoneId, |
| 244 | targets: [ |
| 245 | { |
| 246 | target: "url", |
| 247 | constraint: { operator: "matches", value: TARGET_ADOPT }, |
| 248 | }, |
| 249 | ], |
| 250 | actions: [{ id: "cache_level", value: "bypass" }], |
| 251 | status: "active", |
| 252 | }), |
| 253 | ); |
| 254 | expect(pre.id).toBeDefined(); |
| 255 | |
| 256 | // Without `adopt`: Page Rules carry no ownership markers, so the |
| 257 | // engine cannot prove we created it and refuses to take it over. |
| 258 | const error = yield* stack |
| 259 | .deploy( |
| 260 | Effect.gen(function* () { |
| 261 | return yield* Cloudflare.PageRule.PageRule("AdoptedRule", { |
| 262 | zoneId, |
| 263 | target: TARGET_ADOPT, |
| 264 | actions: [{ id: "cache_level", value: "cache_everything" }], |
| 265 | }); |
| 266 | }), |
| 267 | ) |
| 268 | .pipe( |
| 269 | Effect.as(undefined), |
| 270 | Effect.catchCause((cause) => Effect.succeed(findOwnedError(cause))), |
| 271 | ); |
| 272 | expect(error).toBeInstanceOf(OwnedBySomeoneElse); |
| 273 | |
| 274 | // With `adopt(true)`: the engine takes over the pre-existing rule |
| 275 | // (same physical id) and converges it to the desired actions. |
| 276 | const adopted = yield* stack.deploy( |
| 277 | Effect.gen(function* () { |
| 278 | return yield* Cloudflare.PageRule.PageRule("AdoptedRule", { |
| 279 | zoneId, |
| 280 | target: TARGET_ADOPT, |
| 281 | actions: [{ id: "cache_level", value: "cache_everything" }], |
| 282 | }).pipe(adopt(true)); |
| 283 | }), |
| 284 | ); |
| 285 | |
| 286 | expect(adopted.pageRuleId).toEqual(pre.id); |
| 287 | |
| 288 | const live = yield* getRule(zoneId, adopted.pageRuleId); |
| 289 | const cacheLevel = live.actions.find((a) => a.id === "cache_level"); |
| 290 | expect( |
| 291 | cacheLevel?.id === "cache_level" ? cacheLevel.value : undefined, |
| 292 | ).toEqual("cache_everything"); |
| 293 | |
| 294 | yield* stack.destroy(); |
| 295 | |
| 296 | const gone = yield* findRule(zoneId, TARGET_ADOPT); |
| 297 | expect(gone).toBeUndefined(); |
| 298 | }).pipe(logLevel), |
| 299 | { |
| 300 | tags: [ |
| 301 | "provider:cloudflare", |
| 302 | "provider:cloudflare:pagerule", |
| 303 | "provider:cloudflare:zone", |
| 304 | "live", |
| 305 | ], |
| 306 | }, |
| 307 | ); |
| 308 | |
| 309 | // Canonical `list()` test (zone-scoped collection): `list()` enumerates |
| 310 | // every zone via `listAllZones` and lists each zone's Page Rules, hydrating |
| 311 | // each into the same `Attributes` shape `read` returns. Deploy a rule with a |
| 312 | // deterministic target, then assert it appears in the exhaustive result. |
| 313 | test.provider( |
| 314 | "list enumerates the deployed page rule", |
| 315 | (stack) => |
| 316 | Effect.gen(function* () { |
| 317 | const zoneId = yield* resolveZoneId; |
| 318 | |
| 319 | yield* stack.destroy(); |
| 320 | yield* purgeRules(zoneId, [TARGET_LIST]); |
| 321 | |
| 322 | const rule = yield* stack.deploy( |
| 323 | Effect.gen(function* () { |
| 324 | return yield* Cloudflare.PageRule.PageRule("ListRule", { |
| 325 | zoneId, |
| 326 | target: TARGET_LIST, |
| 327 | actions: [{ id: "cache_level", value: "cache_everything" }], |
| 328 | }).pipe(adopt(true)); |
| 329 | }), |
| 330 | ); |
| 331 | |
| 332 | const provider = yield* Provider.findProvider( |
| 333 | Cloudflare.PageRule.PageRule, |
| 334 | ); |
| 335 | const all = yield* provider.list(); |
| 336 | |
| 337 | expect(all.some((r) => r.pageRuleId === rule.pageRuleId)).toBe(true); |
| 338 | const found = all.find((r) => r.pageRuleId === rule.pageRuleId); |
| 339 | expect(found?.zoneId).toEqual(zoneId); |
| 340 | expect(found?.target).toEqual(TARGET_LIST); |
| 341 | |
| 342 | yield* stack.destroy(); |
| 343 | |
| 344 | const gone = yield* findRule(zoneId, TARGET_LIST); |
| 345 | expect(gone).toBeUndefined(); |
| 346 | }).pipe(logLevel), |
| 347 | { |
| 348 | tags: [ |
| 349 | "provider:cloudflare", |
| 350 | "provider:cloudflare:pagerule", |
| 351 | "provider:cloudflare:zone", |
| 352 | "live", |
| 353 | ], |
| 354 | }, |
| 355 | ); |
| 356 | |
| 357 | /** |
| 358 | * Pull the {@link OwnedBySomeoneElse} value out of a Cause regardless of |
| 359 | * whether the engine raised it as a typed failure or a defect. |
| 360 | */ |
| 361 | const findOwnedError = ( |
| 362 | cause: Cause.Cause<unknown>, |
| 363 | ): OwnedBySomeoneElse | undefined => |
| 364 | cause.reasons |
| 365 | .map((reason) => |
| 366 | Cause.isFailReason(reason) |
| 367 | ? reason.error |
| 368 | : Cause.isDieReason(reason) |
| 369 | ? reason.defect |
| 370 | : undefined, |
| 371 | ) |
| 372 | .find( |
| 373 | (value): value is OwnedBySomeoneElse => |
| 374 | value instanceof OwnedBySomeoneElse, |
| 375 | ); |