File
Blob: test/util/do-retry.ts
| 1 | import { runDurableObjectAlarm, runInDurableObject } from "cloudflare:test"; |
| 2 | |
| 3 | import type { RepoDurableObject } from "@/worker/do"; |
| 4 | |
| 5 | export type RepoDOStub = DurableObjectStub<RepoDurableObject>; |
| 6 | export type RepoDOStubFactory = () => RepoDOStub; |
| 7 | |
| 8 | /** |
| 9 | * Run work against a Durable Object instance and reacquire the stub if workerd |
| 10 | * invalidated the previous instance during local test execution. |
| 11 | */ |
| 12 | export async function runDOWithRetry<T>( |
| 13 | getStub: RepoDOStubFactory, |
| 14 | fn: (instance: RepoDurableObject, state: DurableObjectState) => Promise<T> | T |
| 15 | ): Promise<T> { |
| 16 | const exec = async (stub: RepoDOStub): Promise<T> => { |
| 17 | return await runInDurableObject<RepoDurableObject, T>(stub, (instance, state) => |
| 18 | fn(instance, state) |
| 19 | ); |
| 20 | }; |
| 21 | try { |
| 22 | return await exec(getStub()); |
| 23 | } catch (error) { |
| 24 | const message = String(error || ""); |
| 25 | if (message.includes("invalidating this Durable Object")) { |
| 26 | return await exec(getStub()); |
| 27 | } |
| 28 | throw error; |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | /** |
| 33 | * Call a stub method directly and retry once if the underlying instance was |
| 34 | * invalidated between calls. |
| 35 | */ |
| 36 | export async function callStubWithRetry<T>( |
| 37 | getStub: RepoDOStubFactory, |
| 38 | fn: (stub: RepoDOStub) => Promise<T> |
| 39 | ): Promise<T> { |
| 40 | try { |
| 41 | return await fn(getStub()); |
| 42 | } catch (error) { |
| 43 | const message = String(error || ""); |
| 44 | if (message.includes("invalidating this Durable Object")) { |
| 45 | return await fn(getStub()); |
| 46 | } |
| 47 | throw error; |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | /** |
| 52 | * Fire a Durable Object alarm and reacquire the stub if workerd invalidated the |
| 53 | * previous instance during local test execution. |
| 54 | */ |
| 55 | export async function runAlarmWithRetry(getStub: RepoDOStubFactory): Promise<boolean> { |
| 56 | try { |
| 57 | return await runDurableObjectAlarm(getStub()); |
| 58 | } catch (error) { |
| 59 | const message = String(error || ""); |
| 60 | if (message.includes("invalidating this Durable Object")) { |
| 61 | return await runDurableObjectAlarm(getStub()); |
| 62 | } |
| 63 | throw error; |
| 64 | } |
| 65 | } |