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

main
ts 828 lines 29.8 KB
Raw
1 import {
2 RpcDecodeError,
3 RpcCallError,
4 RpcRemoteStreamError,
5 encodeRpcError,
6 decodeRpcResult,
7 decodeRpcValue,
8 ErrorTag,
9 StreamTag,
10 StreamErrorTag,
11 isRpcErrorEnvelope,
12 isRpcStreamEnvelope,
13 fromRpcReadableStream,
14 fromRpcStreamEnvelope,
15 toRpcStream,
16 makeRpcStub,
17 type RpcErrorEnvelope,
18 type RpcStreamEnvelope,
19 } from "@alchemy.run/cloudflare/Workers/Rpc";
20 import { describe, expect, it } from "@alchemy.run/test";
21 import * as Cause from "effect/Cause";
22 import * as Data from "effect/Data";
23 import * as Deferred from "effect/Deferred";
24 import * as Effect from "effect/Effect";
25 import * as Exit from "effect/Exit";
26 import * as Fiber from "effect/Fiber";
27 import * as Scope from "effect/Scope";
28 import * as Stream from "effect/Stream";
29
30 class MyError extends Data.TaggedError("MyError")<{ readonly message: string }> {}
31
32 // ---------------------------------------------------------------------------
33 // RpcDecodeError
34 // ---------------------------------------------------------------------------
35
36 describe(
37 "RpcDecodeError",
38 { tags: ["unit", "provider:cloudflare", "provider:cloudflare:worker", "local"] },
39 () => {
40 it.effect("message delegates to Error.message when cause is an Error", () =>
41 Effect.gen(function* () {
42 const err = new RpcDecodeError({ cause: new Error("inner") });
43 expect(err._tag).toBe("RpcDecodeError");
44 expect(err.message).toBe("inner");
45 }),
46 );
47
48 it.effect("message stringifies non-Error cause", () =>
49 Effect.gen(function* () {
50 const err = new RpcDecodeError({ cause: 42 });
51 expect(err.message).toBe("42");
52 }),
53 );
54 },
55 );
56
57 // ---------------------------------------------------------------------------
58 // RpcCallError
59 // ---------------------------------------------------------------------------
60
61 describe(
62 "RpcCallError",
63 { tags: ["unit", "provider:cloudflare", "provider:cloudflare:worker", "local"] },
64 () => {
65 it.effect("message includes method name and Error.message", () =>
66 Effect.gen(function* () {
67 const err = new RpcCallError({ method: "doStuff", cause: new Error("boom") });
68 expect(err._tag).toBe("RpcCallError");
69 expect(err.message).toBe('RPC call to "doStuff" failed: boom');
70 }),
71 );
72
73 it.effect("message stringifies non-Error cause", () =>
74 Effect.gen(function* () {
75 const err = new RpcCallError({ method: "doStuff", cause: "oops" });
76 expect(err.message).toBe('RPC call to "doStuff" failed: oops');
77 }),
78 );
79 },
80 );
81
82 // ---------------------------------------------------------------------------
83 // isRpcErrorEnvelope
84 // ---------------------------------------------------------------------------
85
86 describe(
87 "isRpcErrorEnvelope",
88 { tags: ["unit", "provider:cloudflare", "provider:cloudflare:worker", "local"] },
89 () => {
90 it.effect("detects valid envelope", () =>
91 Effect.gen(function* () {
92 const envelope: RpcErrorEnvelope = { _tag: ErrorTag, error: { message: "boom" } };
93 expect(isRpcErrorEnvelope(envelope)).toBe(true);
94 }),
95 );
96
97 it.effect("rejects non-envelope values", () =>
98 Effect.gen(function* () {
99 expect(isRpcErrorEnvelope(null)).toBe(false);
100 expect(isRpcErrorEnvelope(undefined)).toBe(false);
101 expect(isRpcErrorEnvelope(42)).toBe(false);
102 expect(isRpcErrorEnvelope("hello")).toBe(false);
103 expect(isRpcErrorEnvelope({ _tag: "Other" })).toBe(false);
104 expect(isRpcErrorEnvelope({ _tag: ErrorTag })).toBe(false);
105 }),
106 );
107 },
108 );
109
110 // ---------------------------------------------------------------------------
111 // isRpcStreamEnvelope
112 // ---------------------------------------------------------------------------
113
114 describe(
115 "isRpcStreamEnvelope",
116 { tags: ["unit", "provider:cloudflare", "provider:cloudflare:worker", "local"] },
117 () => {
118 it.effect("detects valid bytes envelope", () =>
119 Effect.gen(function* () {
120 const envelope: RpcStreamEnvelope = {
121 _tag: StreamTag,
122 encoding: "bytes",
123 body: new ReadableStream(),
124 };
125 expect(isRpcStreamEnvelope(envelope)).toBe(true);
126 }),
127 );
128
129 it.effect("detects valid jsonl envelope", () =>
130 Effect.gen(function* () {
131 const envelope: RpcStreamEnvelope = {
132 _tag: StreamTag,
133 encoding: "jsonl",
134 body: new ReadableStream(),
135 };
136 expect(isRpcStreamEnvelope(envelope)).toBe(true);
137 }),
138 );
139
140 it.effect("rejects missing or wrong fields", () =>
141 Effect.gen(function* () {
142 expect(isRpcStreamEnvelope(null)).toBe(false);
143 expect(isRpcStreamEnvelope(42)).toBe(false);
144 expect(isRpcStreamEnvelope({ _tag: StreamTag })).toBe(false);
145 expect(
146 isRpcStreamEnvelope({ _tag: StreamTag, encoding: "xml", body: new ReadableStream() }),
147 ).toBe(false);
148 expect(
149 isRpcStreamEnvelope({ _tag: StreamTag, encoding: "jsonl", body: "not a stream" }),
150 ).toBe(false);
151 }),
152 );
153 },
154 );
155
156 // ---------------------------------------------------------------------------
157 // encodeRpcError
158 // ---------------------------------------------------------------------------
159
160 describe(
161 "encodeRpcError",
162 { tags: ["unit", "provider:cloudflare", "provider:cloudflare:worker", "local"] },
163 () => {
164 it.effect("preserves tagged error fields", () =>
165 Effect.gen(function* () {
166 const error = new MyError({ message: "BOOF" });
167 const encoded = encodeRpcError(error) as Record<string, unknown>;
168 expect(encoded._tag).toBe("MyError");
169 expect(encoded.message).toBe("BOOF");
170 }),
171 );
172
173 it.effect("normalizes plain Error to name/message/stack", () =>
174 Effect.gen(function* () {
175 const error = new Error("plain failure");
176 const encoded = encodeRpcError(error) as Record<string, unknown>;
177 expect(encoded.name).toBe("Error");
178 expect(encoded.message).toBe("plain failure");
179 expect(encoded.stack).toBeDefined();
180 }),
181 );
182
183 it.effect("passes through primitives", () =>
184 Effect.gen(function* () {
185 expect(encodeRpcError("string error")).toBe("string error");
186 expect(encodeRpcError(42)).toBe(42);
187 expect(encodeRpcError(null)).toBe(null);
188 expect(encodeRpcError(undefined)).toBe(undefined);
189 }),
190 );
191
192 it.effect("passes through plain objects", () =>
193 Effect.gen(function* () {
194 const obj = { code: 404, detail: "not found" };
195 expect(encodeRpcError(obj)).toBe(obj);
196 }),
197 );
198 },
199 );
200
201 // ---------------------------------------------------------------------------
202 // Helper: create a ReadableStream from a string
203 // ---------------------------------------------------------------------------
204
205 const textToReadableStream = (text: string): ReadableStream<Uint8Array> => {
206 const encoder = new TextEncoder();
207 return new ReadableStream({
208 start(controller) {
209 controller.enqueue(encoder.encode(text));
210 controller.close();
211 },
212 });
213 };
214
215 const bytesToReadableStream = (chunks: Uint8Array[]): ReadableStream<Uint8Array> =>
216 new ReadableStream({
217 start(controller) {
218 for (const chunk of chunks) {
219 controller.enqueue(chunk);
220 }
221 controller.close();
222 },
223 });
224
225 // ---------------------------------------------------------------------------
226 // fromRpcReadableStream
227 // ---------------------------------------------------------------------------
228
229 describe(
230 "fromRpcReadableStream",
231 { tags: ["unit", "provider:cloudflare", "provider:cloudflare:worker", "local"] },
232 () => {
233 it.effect("bytes encoding passes raw Uint8Array chunks through", () =>
234 Effect.gen(function* () {
235 const data = new TextEncoder().encode("hello");
236 const body = bytesToReadableStream([data]);
237 const stream = fromRpcReadableStream(body, "bytes");
238 const chunks = yield* Stream.runCollect(stream);
239 expect(chunks).toEqual([data]);
240 }),
241 );
242
243 it.effect("jsonl encoding parses JSON lines", () =>
244 Effect.gen(function* () {
245 const body = textToReadableStream('{"a":1}\n{"b":2}\n');
246 const stream = fromRpcReadableStream(body, "jsonl");
247 const chunks = yield* Stream.runCollect(stream);
248 expect(chunks).toEqual([{ a: 1 }, { b: 2 }]);
249 }),
250 );
251
252 it.effect("jsonl encoding produces RpcDecodeError on malformed JSON", () =>
253 Effect.gen(function* () {
254 const body = textToReadableStream("not json\n");
255 const stream = fromRpcReadableStream(body, "jsonl");
256 const exit = yield* Effect.exit(Stream.runCollect(stream));
257 expect(Exit.isFailure(exit)).toBe(true);
258 }),
259 );
260
261 it.effect("jsonl encoding skips empty lines", () =>
262 Effect.gen(function* () {
263 const body = textToReadableStream('{"x":1}\n\n\n{"y":2}\n');
264 const stream = fromRpcReadableStream(body, "jsonl");
265 const chunks = yield* Stream.runCollect(stream);
266 expect(chunks).toEqual([{ x: 1 }, { y: 2 }]);
267 }),
268 );
269 },
270 );
271
272 // ---------------------------------------------------------------------------
273 // fromRpcStreamEnvelope
274 // ---------------------------------------------------------------------------
275
276 describe(
277 "fromRpcStreamEnvelope",
278 { tags: ["unit", "provider:cloudflare", "provider:cloudflare:worker", "local"] },
279 () => {
280 it.effect("delegates to fromRpcReadableStream", () =>
281 Effect.gen(function* () {
282 const body = textToReadableStream('{"v":99}\n');
283 const envelope: RpcStreamEnvelope = { _tag: StreamTag, encoding: "jsonl", body };
284 const chunks = yield* Stream.runCollect(fromRpcStreamEnvelope(envelope));
285 expect(chunks).toEqual([{ v: 99 }]);
286 }),
287 );
288 },
289 );
290
291 // ---------------------------------------------------------------------------
292 // decodeRpcValue
293 // ---------------------------------------------------------------------------
294
295 describe(
296 "decodeRpcValue",
297 { tags: ["unit", "provider:cloudflare", "provider:cloudflare:worker", "local"] },
298 () => {
299 it.effect("passes through plain values", () =>
300 Effect.gen(function* () {
301 expect(decodeRpcValue("hello")).toBe("hello");
302 expect(decodeRpcValue(42)).toBe(42);
303 expect(decodeRpcValue(null)).toBe(null);
304 }),
305 );
306
307 it.effect("converts stream envelope to Effect Stream", () =>
308 Effect.gen(function* () {
309 const body = textToReadableStream('{"k":1}\n');
310 const envelope: RpcStreamEnvelope = { _tag: StreamTag, encoding: "jsonl", body };
311 const result = decodeRpcValue(envelope);
312 expect(Stream.isStream(result)).toBe(true);
313 const chunks = yield* Stream.runCollect(result as Stream.Stream<any>);
314 expect(chunks).toEqual([{ k: 1 }]);
315 }),
316 );
317
318 it.effect("converts bare ReadableStream to bytes Effect Stream", () =>
319 Effect.gen(function* () {
320 const data = new TextEncoder().encode("raw");
321 const body = bytesToReadableStream([data]);
322 const result = decodeRpcValue(body);
323 expect(Stream.isStream(result)).toBe(true);
324 const chunks = yield* Stream.runCollect(result as Stream.Stream<any>);
325 expect(chunks).toEqual([data]);
326 }),
327 );
328 },
329 );
330
331 // ---------------------------------------------------------------------------
332 // decodeRpcResult
333 // ---------------------------------------------------------------------------
334
335 describe(
336 "decodeRpcResult",
337 { tags: ["unit", "provider:cloudflare", "provider:cloudflare:worker", "local"] },
338 () => {
339 it.effect("succeeds for plain values", () =>
340 Effect.gen(function* () {
341 const result = yield* decodeRpcResult("hello");
342 expect(result).toBe("hello");
343 }),
344 );
345
346 it.effect("succeeds for numeric values", () =>
347 Effect.gen(function* () {
348 const result = yield* decodeRpcResult(42);
349 expect(result).toBe(42);
350 }),
351 );
352
353 it.effect("fails for error envelopes with tagged error", () =>
354 Effect.gen(function* () {
355 const envelope: RpcErrorEnvelope = {
356 _tag: ErrorTag,
357 error: { _tag: "MyError", message: "BOOF" },
358 };
359 const exit = yield* Effect.exit(decodeRpcResult(envelope));
360 expect(Exit.isFailure(exit)).toBe(true);
361 if (Exit.isFailure(exit)) {
362 const failReason = exit.cause.reasons.find((r) => r._tag === "Fail");
363 expect(failReason).toBeDefined();
364 const error = (failReason as any).error as Record<string, unknown>;
365 expect(error._tag).toBe("MyError");
366 expect(error.message).toBe("BOOF");
367 }
368 }),
369 );
370
371 it.effect("fails with plain Error shape for error envelopes", () =>
372 Effect.gen(function* () {
373 const envelope: RpcErrorEnvelope = {
374 _tag: ErrorTag,
375 error: { name: "Error", message: "plain failure" },
376 };
377 const exit = yield* Effect.exit(decodeRpcResult(envelope));
378 expect(Exit.isFailure(exit)).toBe(true);
379 if (Exit.isFailure(exit)) {
380 const failReason = exit.cause.reasons.find((r) => r._tag === "Fail");
381 const error = (failReason as any).error as Record<string, unknown>;
382 expect(error.message).toBe("plain failure");
383 }
384 }),
385 );
386
387 it.effect("wraps stream envelopes in succeed (stream passthrough)", () =>
388 Effect.gen(function* () {
389 const body = textToReadableStream('{"s":1}\n');
390 const envelope: RpcStreamEnvelope = { _tag: StreamTag, encoding: "jsonl", body };
391 const result = yield* decodeRpcResult(envelope);
392 expect(Stream.isStream(result)).toBe(true);
393 const chunks = yield* Stream.runCollect(result as Stream.Stream<any>);
394 expect(chunks).toEqual([{ s: 1 }]);
395 }),
396 );
397 },
398 );
399
400 // ---------------------------------------------------------------------------
401 // toRpcStream
402 // ---------------------------------------------------------------------------
403
404 describe(
405 "toRpcStream",
406 { tags: ["unit", "provider:cloudflare", "provider:cloudflare:worker", "local"] },
407 () => {
408 for (const bytes of [false, true]) {
409 for (const cancel of [false, true]) {
410 it.effect(
411 `${bytes ? "bytes" : "jsonl"} ${cancel ? "cancellation" : "completion"} finalizes the source and attached scope once`,
412 () =>
413 Effect.gen(function* () {
414 const releaseTail = yield* Deferred.make<void>();
415 const eventScope = Scope.makeUnsafe();
416 let sourceClosed = 0;
417 let eventClosed = 0;
418 yield* Scope.addFinalizer(
419 eventScope,
420 Effect.sync(() => {
421 eventClosed++;
422 }),
423 );
424 const source = Stream.unwrap(
425 Effect.gen(function* () {
426 yield* Effect.addFinalizer(() =>
427 Effect.sync(() => {
428 sourceClosed++;
429 }),
430 );
431 return Stream.concat(
432 Stream.succeed(bytes ? new Uint8Array([1]) : 1),
433 Stream.fromEffect(
434 Deferred.await(releaseTail).pipe(
435 Effect.map(() => {
436 expect(sourceClosed).toBe(0);
437 expect(eventClosed).toBe(0);
438 return bytes ? new Uint8Array([2]) : 2;
439 }),
440 ),
441 ),
442 );
443 }),
444 ).pipe(Stream.onExit((exit) => Scope.close(eventScope, exit)));
445 const envelope = yield* toRpcStream(source);
446 const reader = envelope.body.getReader();
447 expect((yield* Effect.promise(() => reader.read())).done).toBe(false);
448 expect(sourceClosed).toBe(0);
449 expect(eventClosed).toBe(0);
450 if (cancel) {
451 yield* Effect.promise(() => reader.cancel());
452 } else {
453 yield* Deferred.succeed(releaseTail, undefined);
454 expect((yield* Effect.promise(() => reader.read())).done).toBe(false);
455 expect((yield* Effect.promise(() => reader.read())).done).toBe(true);
456 }
457 expect(sourceClosed).toBe(1);
458 expect(eventClosed).toBe(1);
459 yield* Effect.promise(() => reader.cancel());
460 expect(sourceClosed).toBe(1);
461 expect(eventClosed).toBe(1);
462 }),
463 );
464 }
465 }
466
467 for (const mode of ["empty", "head-failure", "head-defect", "tail-failure"] as const) {
468 it.effect(`${mode} finalizes the source and attached scope once`, () =>
469 Effect.gen(function* () {
470 const eventScope = Scope.makeUnsafe();
471 let sourceClosed = 0;
472 let eventClosed = 0;
473 yield* Scope.addFinalizer(
474 eventScope,
475 Effect.sync(() => {
476 eventClosed++;
477 }),
478 );
479 const source = Stream.unwrap(
480 Effect.gen(function* () {
481 yield* Effect.addFinalizer(() =>
482 Effect.sync(() => {
483 sourceClosed++;
484 }),
485 );
486 if (mode === "empty") return Stream.empty;
487 if (mode === "head-defect") return Stream.die(new Error("first-pull defect"));
488 const failure = Stream.fail(new MyError({ message: mode }));
489 return mode === "head-failure" ? failure : Stream.concat(Stream.succeed(1), failure);
490 }),
491 ).pipe(Stream.onExit((exit) => Scope.close(eventScope, exit)));
492 const exit = yield* toRpcStream(source).pipe(
493 Effect.flatMap((envelope) => Stream.runCollect(fromRpcStreamEnvelope(envelope))),
494 Effect.exit,
495 );
496 expect(Exit.isSuccess(exit)).toBe(mode === "empty");
497 expect(sourceClosed).toBe(1);
498 expect(eventClosed).toBe(1);
499 yield* Scope.close(eventScope, Exit.void);
500 expect(sourceClosed).toBe(1);
501 expect(eventClosed).toBe(1);
502 }),
503 );
504 }
505
506 it.effect("interrupting encoding before the head releases the source and attached scope", () =>
507 Effect.gen(function* () {
508 const started = yield* Deferred.make<void>();
509 const eventScope = Scope.makeUnsafe();
510 let sourceClosed = 0;
511 let eventClosed = 0;
512 let returnedEnvelope = false;
513 yield* Scope.addFinalizer(
514 eventScope,
515 Effect.sync(() => {
516 eventClosed++;
517 }),
518 );
519 const source = Stream.fromEffect(
520 Effect.gen(function* () {
521 yield* Effect.addFinalizer(() =>
522 Effect.sync(() => {
523 sourceClosed++;
524 }),
525 );
526 yield* Deferred.succeed(started, undefined);
527 return yield* Effect.never;
528 }),
529 ).pipe(Stream.onExit((exit) => Scope.close(eventScope, exit)));
530 const fiber = yield* toRpcStream(source).pipe(
531 Effect.tap(() =>
532 Effect.sync(() => {
533 returnedEnvelope = true;
534 }),
535 ),
536 Effect.forkChild,
537 );
538 yield* Deferred.await(started);
539 expect(sourceClosed).toBe(0);
540 expect(eventClosed).toBe(0);
541 yield* Fiber.interrupt(fiber);
542 expect(Exit.isFailure(yield* Fiber.await(fiber))).toBe(true);
543 expect(returnedEnvelope).toBe(false);
544 expect(sourceClosed).toBe(1);
545 expect(eventClosed).toBe(1);
546 }),
547 );
548
549 it.effect("selects jsonl encoding for non-byte data", () =>
550 Effect.gen(function* () {
551 const stream = Stream.fromIterable([{ a: 1 }]);
552 const envelope = yield* toRpcStream(stream);
553 expect(envelope._tag).toBe(StreamTag);
554 expect(envelope.encoding).toBe("jsonl");
555 expect(envelope.body).toBeInstanceOf(ReadableStream);
556 }),
557 );
558
559 it.effect("roundtrips a single-element jsonl stream", () =>
560 Effect.gen(function* () {
561 const stream = Stream.fromIterable([{ a: 1 }]);
562 const envelope = yield* toRpcStream(stream);
563 const decoded = fromRpcReadableStream(envelope.body, "jsonl");
564 const chunks = yield* Stream.runCollect(decoded);
565 expect(chunks).toEqual([{ a: 1 }]);
566 }),
567 );
568
569 // A first chunk holding several elements must reach the body whole, not
570 // just the element peeked to pick the encoding.
571 it.effect("roundtrips every element of a multi-element jsonl stream", () =>
572 Effect.gen(function* () {
573 const stream = Stream.fromIterable([{ a: 1 }, { a: 2 }, { a: 3 }]);
574 const envelope = yield* toRpcStream(stream);
575 const decoded = fromRpcReadableStream(envelope.body, "jsonl");
576 const chunks = yield* Stream.runCollect(decoded);
577 expect(chunks).toEqual([{ a: 1 }, { a: 2 }, { a: 3 }]);
578 }),
579 );
580
581 it.effect("roundtrips every element of a multi-element bytes stream", () =>
582 Effect.gen(function* () {
583 const data = [new Uint8Array([1]), new Uint8Array([2]), new Uint8Array([3])];
584 const stream = Stream.fromIterable(data);
585 const envelope = yield* toRpcStream(stream);
586 const decoded = fromRpcReadableStream(envelope.body, "bytes");
587 const chunks = yield* Stream.runCollect(decoded);
588 expect(chunks).toEqual(data);
589 }),
590 );
591
592 it.effect("selects bytes encoding for Uint8Array data", () =>
593 Effect.gen(function* () {
594 const data = new Uint8Array([1, 2, 3]);
595 const stream = Stream.fromIterable([data]);
596 const envelope = yield* toRpcStream(stream);
597 expect(envelope._tag).toBe(StreamTag);
598 expect(envelope.encoding).toBe("bytes");
599 expect(envelope.body).toBeInstanceOf(ReadableStream);
600 }),
601 );
602
603 it.effect("roundtrips a single-element bytes stream", () =>
604 Effect.gen(function* () {
605 const data = new Uint8Array([1, 2, 3]);
606 const stream = Stream.fromIterable([data]);
607 const envelope = yield* toRpcStream(stream);
608 const decoded = fromRpcReadableStream(envelope.body, "bytes");
609 const chunks = yield* Stream.runCollect(decoded);
610 expect(chunks).toEqual([data]);
611 }),
612 );
613
614 it.effect("handles empty stream as jsonl", () =>
615 Effect.gen(function* () {
616 const stream = Stream.empty;
617 const envelope = yield* toRpcStream(stream);
618 expect(envelope._tag).toBe(StreamTag);
619 expect(envelope.encoding).toBe("jsonl");
620
621 const decoded = fromRpcReadableStream(envelope.body, envelope.encoding);
622 const chunks = yield* Stream.runCollect(decoded);
623 expect(chunks).toEqual([]);
624 }),
625 );
626 },
627 );
628
629 // ---------------------------------------------------------------------------
630 // makeRpcStub
631 // ---------------------------------------------------------------------------
632
633 describe(
634 "makeRpcStub",
635 { tags: ["unit", "provider:cloudflare", "provider:cloudflare:worker", "local"] },
636 () => {
637 it.effect("proxies successful calls", () =>
638 Effect.gen(function* () {
639 const mockStub = { greet: async (name: string) => `hello ${name}` };
640 const stub = makeRpcStub<{ greet: (name: string) => Effect.Effect<string> }>(mockStub);
641
642 const result = yield* stub.greet("world");
643 expect(result).toBe("hello world");
644 }),
645 );
646
647 it.effect("wraps rejected promises as RpcCallError", () =>
648 Effect.gen(function* () {
649 const mockStub = {
650 boom: async () => {
651 throw new Error("kaboom");
652 },
653 };
654 const stub = makeRpcStub<{ boom: () => Effect.Effect<never, RpcCallError> }>(mockStub);
655
656 const exit = yield* Effect.exit(stub.boom());
657 expect(Exit.isFailure(exit)).toBe(true);
658 if (Exit.isFailure(exit)) {
659 const failReason = exit.cause.reasons.find((r) => r._tag === "Fail");
660 expect(failReason).toBeDefined();
661 const error = (failReason as any).error;
662 expect(error._tag).toBe("RpcCallError");
663 expect(error.method).toBe("boom");
664 }
665 }),
666 );
667
668 it.effect("decodes error envelopes into Effect.fail", () =>
669 Effect.gen(function* () {
670 const mockStub = {
671 failMe: async () => ({
672 _tag: ErrorTag,
673 error: { _tag: "MyError", message: "remote fail" },
674 }),
675 };
676 const stub = makeRpcStub<{
677 failMe: () => Effect.Effect<never, { _tag: string; message: string }>;
678 }>(mockStub);
679
680 const exit = yield* Effect.exit(stub.failMe());
681 expect(Exit.isFailure(exit)).toBe(true);
682 if (Exit.isFailure(exit)) {
683 const failReason = exit.cause.reasons.find((r) => r._tag === "Fail");
684 const error = (failReason as any).error as Record<string, unknown>;
685 expect(error._tag).toBe("MyError");
686 expect(error.message).toBe("remote fail");
687 }
688 }),
689 );
690
691 it.effect("decodes stream envelopes from successful calls", () =>
692 Effect.gen(function* () {
693 const body = textToReadableStream('{"n":42}\n');
694 const mockStub = {
695 streamMe: async () => ({ _tag: StreamTag, encoding: "jsonl" as const, body }),
696 };
697 const stub = makeRpcStub<{ streamMe: () => Effect.Effect<Stream.Stream<{ n: number }>> }>(
698 mockStub,
699 );
700
701 const stream = yield* stub.streamMe();
702 expect(Stream.isStream(stream)).toBe(true);
703 const chunks = yield* Stream.runCollect(stream);
704 expect(chunks).toEqual([{ n: 42 }]);
705 }),
706 );
707 },
708 );
709
710 // ---------------------------------------------------------------------------
711 // Stream error transport
712 // ---------------------------------------------------------------------------
713
714 describe(
715 "stream errors",
716 { tags: ["unit", "provider:cloudflare", "provider:cloudflare:worker", "local"] },
717 () => {
718 it.effect("toRpcStream encodes a stream that fails immediately", () =>
719 Effect.gen(function* () {
720 const stream = Stream.fail(new MyError({ message: "immediate" }));
721 const envelope = yield* toRpcStream(stream);
722 expect(envelope._tag).toBe(StreamTag);
723 expect(envelope.encoding).toBe("jsonl");
724
725 const decoded = fromRpcReadableStream(envelope.body, "jsonl");
726 const exit = yield* Effect.exit(Stream.runCollect(decoded));
727 expect(Exit.isFailure(exit)).toBe(true);
728 if (Exit.isFailure(exit)) {
729 const reason = exit.cause.reasons.find(Cause.isFailReason);
730 expect(reason).toBeDefined();
731 const err = reason!.error;
732 expect(err).toBeInstanceOf(RpcRemoteStreamError);
733 expect((err as RpcRemoteStreamError).error).toEqual({
734 _tag: "MyError",
735 message: "immediate",
736 });
737 }
738 }),
739 );
740
741 it.effect("toRpcStream encodes a stream that fails after elements", () =>
742 Effect.gen(function* () {
743 const stream = Stream.make(1, 2).pipe(
744 Stream.concat(Stream.fail(new MyError({ message: "mid" }))),
745 );
746 const envelope = yield* toRpcStream(stream);
747 expect(envelope._tag).toBe(StreamTag);
748 expect(envelope.encoding).toBe("jsonl");
749
750 const decoded = fromRpcReadableStream(envelope.body, "jsonl");
751 const exit = yield* Effect.exit(Stream.runCollect(decoded));
752 expect(Exit.isFailure(exit)).toBe(true);
753 if (Exit.isFailure(exit)) {
754 const reason = exit.cause.reasons.find(Cause.isFailReason);
755 expect(reason).toBeDefined();
756 const err = reason!.error;
757 expect(err).toBeInstanceOf(RpcRemoteStreamError);
758 expect((err as RpcRemoteStreamError).error).toEqual({ _tag: "MyError", message: "mid" });
759 }
760 }),
761 );
762
763 it.effect("fromRpcReadableStream decodes error marker in JSONL", () =>
764 Effect.gen(function* () {
765 const errorLine = JSON.stringify({
766 _tag: StreamErrorTag,
767 error: { _tag: "MyError", message: "wire" },
768 });
769 const body = textToReadableStream(`${errorLine}\n`);
770 const stream = fromRpcReadableStream(body, "jsonl");
771 const exit = yield* Effect.exit(Stream.runCollect(stream));
772 expect(Exit.isFailure(exit)).toBe(true);
773 if (Exit.isFailure(exit)) {
774 const reason = exit.cause.reasons.find(Cause.isFailReason);
775 const err = reason!.error;
776 expect(err).toBeInstanceOf(RpcRemoteStreamError);
777 expect((err as RpcRemoteStreamError).error).toEqual({ _tag: "MyError", message: "wire" });
778 }
779 }),
780 );
781
782 it.effect("fromRpcReadableStream yields elements before error marker", () =>
783 Effect.gen(function* () {
784 const errorLine = JSON.stringify({
785 _tag: StreamErrorTag,
786 error: { message: "after elements" },
787 });
788 const body = textToReadableStream(`{"v":1}\n{"v":2}\n${errorLine}\n`);
789 const stream = fromRpcReadableStream(body, "jsonl");
790 const collected: unknown[] = [];
791 const exit = yield* Effect.exit(
792 Stream.runForEach(stream, (item) =>
793 Effect.sync(() => {
794 collected.push(item);
795 }),
796 ),
797 );
798 expect(collected).toEqual([{ v: 1 }, { v: 2 }]);
799 expect(Exit.isFailure(exit)).toBe(true);
800 }),
801 );
802
803 it.effect("makeRpcStub preserves stream errors (not collapsed to RpcCallError)", () =>
804 Effect.gen(function* () {
805 const errorLine = JSON.stringify({
806 _tag: StreamErrorTag,
807 error: { _tag: "MyError", message: "remote stream err" },
808 });
809 const body = textToReadableStream(`{"n":1}\n${errorLine}\n`);
810 const mockStub = {
811 streamFail: async () => ({ _tag: StreamTag, encoding: "jsonl" as const, body }),
812 };
813 const stub = makeRpcStub<{
814 streamFail: () => Effect.Effect<Stream.Stream<unknown, RpcRemoteStreamError>>;
815 }>(mockStub);
816
817 const stream = yield* stub.streamFail();
818 const exit = yield* Effect.exit(Stream.runCollect(stream));
819 expect(Exit.isFailure(exit)).toBe(true);
820 if (Exit.isFailure(exit)) {
821 const reason = exit.cause.reasons.find(Cause.isFailReason);
822 expect(reason).toBeDefined();
823 expect(reason!.error).toBeInstanceOf(RpcRemoteStreamError);
824 }
825 }),
826 );
827 },
828 );