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, 04:45 UTC
| 1 | // Alchemy modifications are licensed under Apache-2.0. |
| 2 | // This file includes third-party code; see /THIRD_PARTY_LICENSES.md. |
| 3 | // Alchemy modifications: uses Array<T> syntax for non-tuple array types to match the repository convention; |
| 4 | // attaches disposers through `withDisposer` and annotates `this` so the tests type-check under strict settings. |
| 5 | import { createExecutionContext, runInDurableObject } from "cloudflare:test"; |
| 6 | import { env } from "cloudflare:workers"; |
| 7 | import { afterEach, it, vi } from "vitest"; |
| 8 | import workerdUnsafe from "workerd:unsafe"; |
| 9 | import { WorkflowBinding } from "../binding.ts"; |
| 10 | import { InstanceEvent } from "../instance.ts"; |
| 11 | import { WorkflowInstanceIntrospectorHandle } from "../introspection.ts"; |
| 12 | import { normalizeForStorage } from "../lib/serialization.ts"; |
| 13 | import { WorkflowInstanceModifier } from "../modifier.ts"; |
| 14 | import type { WorkflowBinding as IntrospectionBinding } from "../types.ts"; |
| 15 | import { setTestWorkflowCallback } from "./test-entry.ts"; |
| 16 | import { runWorkflowAndAwait } from "./utils.ts"; |
| 17 | |
| 18 | afterEach(async () => { |
| 19 | await workerdUnsafe.abortAllDurableObjects(); |
| 20 | vi.restoreAllMocks(); |
| 21 | Reflect.deleteProperty(WorkflowInstanceModifier.prototype, Symbol.dispose); |
| 22 | }); |
| 23 | |
| 24 | /** Attaches an RPC disposer without changing the value's serializable type. */ |
| 25 | const withDisposer = <T extends object>(value: T, dispose: () => void): T => |
| 26 | Object.assign(value, { [Symbol.dispose]: dispose }); |
| 27 | |
| 28 | function createBinding(): WorkflowBinding { |
| 29 | return new WorkflowBinding(createExecutionContext(), { |
| 30 | ENGINE: env.ENGINE, |
| 31 | BINDING_NAME: "TEST_WORKFLOW", |
| 32 | WORKFLOW_NAME: "test-workflow", |
| 33 | }); |
| 34 | } |
| 35 | |
| 36 | it("releases the step callback's RPC result and preserves the live data shape", async ({ |
| 37 | expect, |
| 38 | }) => { |
| 39 | const dispose = vi.fn(); |
| 40 | let result: unknown; |
| 41 | await runWorkflowAndAwait(crypto.randomUUID(), async (_event, step) => { |
| 42 | result = await step.do("RPC result", async () => |
| 43 | withDisposer({ value: 42, bytes: new Uint8Array(new ArrayBuffer(8), 2, 2) }, dispose), |
| 44 | ); |
| 45 | }); |
| 46 | |
| 47 | expect(result).toEqual({ value: 42, bytes: new Uint8Array(2) }); |
| 48 | expect(result).toHaveProperty("bytes.byteOffset", 2); |
| 49 | expect(result).toHaveProperty("bytes.buffer.byteLength", 8); |
| 50 | // The remote disposer runs asynchronously after the local stub is released. |
| 51 | await vi.waitFor(() => expect(dispose).toHaveBeenCalledOnce()); |
| 52 | }); |
| 53 | |
| 54 | it.for([false, true])( |
| 55 | "disposes an introspector's modifier (modified: %s)", |
| 56 | async (modified, { expect }) => { |
| 57 | const binding = createBinding(); |
| 58 | await using instance = new WorkflowInstanceIntrospectorHandle( |
| 59 | binding as unknown as IntrospectionBinding, |
| 60 | crypto.randomUUID(), |
| 61 | ); |
| 62 | if (modified) { |
| 63 | await instance.modify((modifier) => modifier.disableSleeps()); |
| 64 | } |
| 65 | |
| 66 | await instance.dispose(); |
| 67 | await expect(instance.modify((modifier) => modifier.disableSleeps())).rejects.toThrow( |
| 68 | "RPC stub used after being disposed", |
| 69 | ); |
| 70 | // The await-using scope calls dispose() again, exercising idempotence. |
| 71 | }, |
| 72 | ); |
| 73 | |
| 74 | it.for([false, true])( |
| 75 | "releases the temporary modifier used by create (modified: %s)", |
| 76 | async (modified, { expect }) => { |
| 77 | const id = crypto.randomUUID(); |
| 78 | const binding = createBinding(); |
| 79 | const dispose = vi.fn(); |
| 80 | // RPC target disposers are looked up on the prototype. |
| 81 | Object.defineProperty(WorkflowInstanceModifier.prototype, Symbol.dispose, { |
| 82 | value: dispose, |
| 83 | configurable: true, |
| 84 | }); |
| 85 | |
| 86 | const sessionId = await binding.unsafeStartIntrospection(); |
| 87 | try { |
| 88 | if (modified) { |
| 89 | await binding.unsafeSetIntrospectionOperations(sessionId, [{ type: "disableSleeps" }]); |
| 90 | } |
| 91 | setTestWorkflowCallback(async () => undefined); |
| 92 | await binding.create({ id }); |
| 93 | const instance = await binding.get(id); |
| 94 | await vi.waitUntil(async () => (await instance.status()).status === "complete"); |
| 95 | await vi.waitFor(() => expect(dispose).toHaveBeenCalledOnce()); |
| 96 | } finally { |
| 97 | await binding.unsafeStopIntrospection(sessionId); |
| 98 | await binding.unsafeAbort(id); |
| 99 | } |
| 100 | }, |
| 101 | ); |
| 102 | |
| 103 | it.for([false, true])( |
| 104 | "aborts after modifier acquisition fails (modify attempted: %s)", |
| 105 | async (attemptModify, { expect }) => { |
| 106 | const binding = createBinding(); |
| 107 | const error = new Error("modifier acquisition failed"); |
| 108 | vi.spyOn(binding, "unsafeGetInstanceModifier").mockRejectedValue(error); |
| 109 | const abort = vi.spyOn(binding, "unsafeAbort"); |
| 110 | const id = crypto.randomUUID(); |
| 111 | { |
| 112 | await using instance = new WorkflowInstanceIntrospectorHandle( |
| 113 | binding as unknown as IntrospectionBinding, |
| 114 | id, |
| 115 | ); |
| 116 | if (attemptModify) { |
| 117 | await expect(instance.modify((modifier) => modifier.disableSleeps())).rejects.toBe(error); |
| 118 | } |
| 119 | await expect(instance.dispose()).resolves.toBeUndefined(); |
| 120 | } |
| 121 | expect(abort).toHaveBeenCalledExactlyOnceWith(id, "Instance dispose"); |
| 122 | }, |
| 123 | ); |
| 124 | |
| 125 | it("still reports a modifier disposer failure after aborting", async ({ expect }) => { |
| 126 | const binding = createBinding(); |
| 127 | const error = new Error("modifier disposal failed"); |
| 128 | vi.spyOn(binding, "unsafeGetInstanceModifier").mockResolvedValue({ |
| 129 | [Symbol.dispose]() { |
| 130 | throw error; |
| 131 | }, |
| 132 | }); |
| 133 | const abort = vi.spyOn(binding, "unsafeAbort"); |
| 134 | const id = crypto.randomUUID(); |
| 135 | const instance = new WorkflowInstanceIntrospectorHandle( |
| 136 | binding as unknown as IntrospectionBinding, |
| 137 | id, |
| 138 | ); |
| 139 | await expect(instance.dispose()).rejects.toBe(error); |
| 140 | expect(abort).toHaveBeenCalledExactlyOnceWith(id, "Instance dispose"); |
| 141 | }); |
| 142 | |
| 143 | it.for([ |
| 144 | { name: "function-valued property", create: () => ({ helper: () => 42 }) }, |
| 145 | { |
| 146 | name: "function-valued array property", |
| 147 | create: () => Object.assign([42], { helper: () => 42 }), |
| 148 | }, |
| 149 | ])("rejects a non-cloneable step result: $name", async ({ create }, { expect }) => { |
| 150 | // The storage normaliser used to discard extra array properties. They must |
| 151 | // not let non-serialisable output bypass the step result contract. |
| 152 | const id = crypto.randomUUID(); |
| 153 | await runWorkflowAndAwait(id, async (_event, step) => { |
| 154 | await step.do("non-cloneable result", async () => create()); |
| 155 | }); |
| 156 | const engine = env.ENGINE.get(env.ENGINE.idFromName(id)); |
| 157 | const { logs } = await engine.readLogs(); |
| 158 | expect(logs).toContainEqual( |
| 159 | expect.objectContaining({ |
| 160 | event: InstanceEvent.WORKFLOW_FAILURE, |
| 161 | metadata: expect.objectContaining({ |
| 162 | error: expect.objectContaining({ |
| 163 | message: expect.stringContaining("not serialisable"), |
| 164 | }), |
| 165 | }), |
| 166 | }), |
| 167 | ); |
| 168 | }); |
| 169 | |
| 170 | it("preserves data from class instances with prototype methods", async ({ expect }) => { |
| 171 | class Result { |
| 172 | value = 42; |
| 173 | method(): number { |
| 174 | return this.value; |
| 175 | } |
| 176 | } |
| 177 | const stub = env.ENGINE.get(env.ENGINE.idFromName(crypto.randomUUID())); |
| 178 | await runInDurableObject(stub, async (_engine, state) => { |
| 179 | const value = new Result(); |
| 180 | // Both the old storage path and structuredClone ignore prototype methods. |
| 181 | await state.storage.put("result", { value: normalizeForStorage(value) }); |
| 182 | expect(await state.storage.get("result")).toEqual({ value: { value: 42 } }); |
| 183 | expect(structuredClone(value)).toEqual({ value: 42 }); |
| 184 | }); |
| 185 | }); |
| 186 | |
| 187 | it.for(["object", "stream", "reject", "cancel-reject"] as const)( |
| 188 | "cleans up a late callback after a timeout: %s", |
| 189 | async (kind, { expect }) => { |
| 190 | const lateCleanup = vi.fn(); |
| 191 | const originalCancel = ReadableStream.prototype.cancel; |
| 192 | const cancel = vi.spyOn(ReadableStream.prototype, "cancel"); |
| 193 | if (kind === "cancel-reject") { |
| 194 | cancel.mockImplementation(async function (this: ReadableStream, reason) { |
| 195 | await originalCancel.call(this, reason); |
| 196 | throw new Error("late stream cancellation failed"); |
| 197 | }); |
| 198 | } |
| 199 | const winningDispose = vi.fn(); |
| 200 | const winningCancel = vi.fn(); |
| 201 | const attempts: Array<number> = []; |
| 202 | const lateResult = Promise.withResolvers<void>(); |
| 203 | let lateSettled = false; |
| 204 | let cleanupSeenByRetry = false; |
| 205 | let result: unknown; |
| 206 | await runWorkflowAndAwait(crypto.randomUUID(), async (_event, step) => { |
| 207 | const value = await step.do<{ attempt: number } | ReadableStream<Uint8Array>>( |
| 208 | "late callback result", |
| 209 | { |
| 210 | timeout: "1 second", |
| 211 | retries: { limit: 1, delay: 1, backoff: "constant" }, |
| 212 | }, |
| 213 | async (ctx) => { |
| 214 | attempts.push(ctx.attempt); |
| 215 | if (ctx.attempt === 1) { |
| 216 | // Only the retry can release this callback: cleanup must not |
| 217 | // delay the retry until the abandoned callback finishes. |
| 218 | await lateResult.promise; |
| 219 | lateSettled = true; |
| 220 | if (kind === "reject") { |
| 221 | throw new Error("late callback failed"); |
| 222 | } |
| 223 | if (kind === "object") { |
| 224 | return { attempt: 1, [Symbol.dispose]: lateCleanup }; |
| 225 | } |
| 226 | // Observe cancellation on the receiving stream. Workerd does |
| 227 | // not reliably notify the source's cancel hook over RPC. |
| 228 | return new ReadableStream<Uint8Array>(); |
| 229 | } |
| 230 | lateResult.resolve(); |
| 231 | cleanupSeenByRetry = await vi |
| 232 | .waitUntil( |
| 233 | () => |
| 234 | kind === "reject" |
| 235 | ? lateSettled |
| 236 | : kind === "object" |
| 237 | ? lateCleanup.mock.calls.length === 1 |
| 238 | : cancel.mock.settledResults.length === 1, |
| 239 | { timeout: 500 }, |
| 240 | ) |
| 241 | .then( |
| 242 | () => true, |
| 243 | () => false, |
| 244 | ); |
| 245 | if (kind === "stream" || kind === "cancel-reject") { |
| 246 | return new ReadableStream<Uint8Array>({ |
| 247 | start(controller) { |
| 248 | controller.enqueue(new TextEncoder().encode("retry succeeded")); |
| 249 | controller.close(); |
| 250 | }, |
| 251 | cancel: winningCancel, |
| 252 | }); |
| 253 | } |
| 254 | return { attempt: 2, [Symbol.dispose]: winningDispose }; |
| 255 | }, |
| 256 | ); |
| 257 | result = value instanceof ReadableStream ? await new Response(value).text() : value; |
| 258 | }); |
| 259 | |
| 260 | expect(attempts).toEqual([1, 2]); |
| 261 | expect(lateSettled).toBe(true); |
| 262 | expect(cleanupSeenByRetry).toBe(true); |
| 263 | if (kind === "stream" || kind === "cancel-reject") { |
| 264 | expect(result).toBe("retry succeeded"); |
| 265 | expect(winningCancel).not.toHaveBeenCalled(); |
| 266 | } else { |
| 267 | expect(result).toEqual({ attempt: 2 }); |
| 268 | await vi.waitFor(() => expect(winningDispose).toHaveBeenCalledOnce()); |
| 269 | } |
| 270 | if (kind === "object") { |
| 271 | expect(lateCleanup).toHaveBeenCalledOnce(); |
| 272 | } |
| 273 | if (kind === "stream" || kind === "cancel-reject") { |
| 274 | expect(cancel).toHaveBeenCalledExactlyOnceWith( |
| 275 | expect.objectContaining({ |
| 276 | name: "WorkflowTimeoutError", |
| 277 | }), |
| 278 | ); |
| 279 | expect(cancel.mock.settledResults[0]?.type).toBe( |
| 280 | kind === "stream" ? "fulfilled" : "rejected", |
| 281 | ); |
| 282 | } else { |
| 283 | expect(cancel).not.toHaveBeenCalled(); |
| 284 | } |
| 285 | }, |
| 286 | ); |
| 287 | |
| 288 | it("cleans up a late callback that lands after its step has finished", async ({ expect }) => { |
| 289 | const lateCleanup = vi.fn(); |
| 290 | const attempts: Array<number> = []; |
| 291 | const lateResult = Promise.withResolvers<void>(); |
| 292 | let cleanupSeenByLaterStep = false; |
| 293 | |
| 294 | await runWorkflowAndAwait(crypto.randomUUID(), async (_event, step) => { |
| 295 | await step.do( |
| 296 | "late callback result", |
| 297 | { |
| 298 | timeout: "1 second", |
| 299 | retries: { limit: 1, delay: 1, backoff: "constant" }, |
| 300 | }, |
| 301 | async (ctx) => { |
| 302 | attempts.push(ctx.attempt); |
| 303 | if (ctx.attempt === 1) { |
| 304 | // Held open past the retry, so the abandoned callback's cleanup is |
| 305 | // left running from the engine with no step awaiting it. |
| 306 | await lateResult.promise; |
| 307 | return withDisposer({ attempt: 1 }, lateCleanup); |
| 308 | } |
| 309 | return { attempt: 2 }; |
| 310 | }, |
| 311 | ); |
| 312 | |
| 313 | // The engine keeps the abandoned cleanup alive across the step boundary: |
| 314 | // releasing the first callback here still disposes its result. |
| 315 | await step.do("later step", async () => { |
| 316 | lateResult.resolve(); |
| 317 | cleanupSeenByLaterStep = await vi |
| 318 | .waitUntil(() => lateCleanup.mock.calls.length === 1, { timeout: 500 }) |
| 319 | .then( |
| 320 | () => true, |
| 321 | () => false, |
| 322 | ); |
| 323 | }); |
| 324 | }); |
| 325 | |
| 326 | expect(attempts).toEqual([1, 2]); |
| 327 | expect(cleanupSeenByLaterStep).toBe(true); |
| 328 | expect(lateCleanup).toHaveBeenCalledOnce(); |
| 329 | }); |