File size: 29,714 Bytes
eb3f11e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 | // Runtime proxy tests cover SSE parsing, terminal error handling, and request
// payload scrubbing before proxying model streams.
import { once } from "node:events";
import http from "node:http";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { Context, Model, Usage } from "../../llm/types.js";
import { streamProxy } from "./proxy.js";
const usage: Usage = {
input: 1,
output: 2,
cacheRead: 0,
cacheWrite: 0,
totalTokens: 3,
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
};
const model: Model = {
id: "test-model",
name: "Test Model",
provider: "test",
api: "openai-responses",
baseUrl: "https://example.test",
reasoning: false,
input: ["text"],
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
contextWindow: 1024,
maxTokens: 1024,
};
const context: Context = {
messages: [{ role: "user", content: "hello", timestamp: 1 }],
};
function responseFromText(text: string): Response {
return new Response(
new ReadableStream({
start(controller) {
controller.enqueue(new TextEncoder().encode(text));
controller.close();
},
}),
{ status: 200 },
);
}
function responseFromSseFrames(frames: unknown[]): Response {
const encoder = new TextEncoder();
const chunks = frames.map((frame) => encoder.encode(`data: ${JSON.stringify(frame)}\n\n`));
const reader = {
read: vi.fn(async () => {
await new Promise<void>((resolve) => {
setImmediate(resolve);
});
const value = chunks.shift();
return value ? { done: false, value } : { done: true, value: undefined };
}),
cancel: vi.fn(async () => undefined),
releaseLock: vi.fn(),
} as unknown as ReadableStreamDefaultReader<Uint8Array>;
return {
ok: true,
status: 200,
body: { getReader: () => reader },
} as Response;
}
function responseFromReaderText(
text: string,
releaseLock: () => void,
cancel: () => Promise<void> = async () => undefined,
): Response {
const chunks: Array<ReadableStreamReadResult<Uint8Array>> = [
{ done: false, value: new TextEncoder().encode(text) },
{ done: true, value: undefined },
];
const reader = {
read: async () => chunks.shift() ?? { done: true, value: undefined },
cancel,
releaseLock,
} as ReadableStreamDefaultReader<Uint8Array>;
return {
ok: true,
status: 200,
body: { getReader: () => reader },
} as Response;
}
const unresolved = Symbol("unresolved stream result");
function pendingReaderResponse(params: {
chunks: Uint8Array[];
status?: number;
statusText?: string;
onCancel?: (reason?: unknown) => void;
}): Response {
const chunks = [...params.chunks];
const reader = {
read: vi.fn(async () => {
const chunk = chunks.shift();
if (chunk) {
return { done: false, value: chunk };
}
return await new Promise<ReadableStreamReadResult<Uint8Array>>(() => {});
}),
cancel: vi.fn(async (reason?: unknown) => {
params.onCancel?.(reason);
}),
releaseLock: vi.fn(),
} as unknown as ReadableStreamDefaultReader<Uint8Array>;
return {
ok: (params.status ?? 200) >= 200 && (params.status ?? 200) < 300,
status: params.status ?? 200,
statusText: params.statusText ?? "OK",
body: { getReader: () => reader },
} as Response;
}
async function resultWithinMs(
stream: { result(): Promise<unknown> },
timeoutMs = 25,
): Promise<unknown> {
let timer: ReturnType<typeof setTimeout> | undefined;
try {
return await Promise.race([
stream.result(),
new Promise<symbol>((resolve) => {
timer = setTimeout(() => resolve(unresolved), timeoutMs);
}),
]);
} finally {
clearTimeout(timer);
}
}
async function settledResult(stream: { result(): Promise<unknown> }): Promise<unknown> {
return await Promise.race([stream.result(), Promise.resolve(unresolved)]);
}
describe("streamProxy", () => {
afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
vi.unstubAllGlobals();
});
it("reconstructs a text signature from text_start before streamed deltas", async () => {
const contentSignature = JSON.stringify({
v: 1,
id: "item-commentary",
phase: "commentary",
});
const proxyEvents = [
{ type: "text_start", contentIndex: 0, contentSignature },
{ type: "text_delta", contentIndex: 0, delta: "Working..." },
{ type: "text_end", contentIndex: 0 },
{ type: "done", reason: "stop", usage },
];
vi.stubGlobal(
"fetch",
vi.fn(async () =>
responseFromText(proxyEvents.map((event) => `data: ${JSON.stringify(event)}\n\n`).join("")),
),
);
const stream = streamProxy(model, context, {
authToken: "token",
proxyUrl: "https://proxy.example",
});
const events = [];
for await (const event of stream) {
events.push(event);
}
expect(events.map((event) => event.type)).toEqual([
"text_start",
"text_delta",
"text_end",
"done",
]);
await expect(stream.result()).resolves.toMatchObject({
content: [{ type: "text", text: "Working...", textSignature: contentSignature }],
});
});
it("accepts data lines without a space after the colon", async () => {
// The SSE spec makes the space optional; proxies emitting `data:{...}`
// must not have their events silently dropped.
const proxyEvents = [
{ type: "text_start", contentIndex: 0, contentSignature: "sig" },
{ type: "text_delta", contentIndex: 0, delta: "Working..." },
{ type: "text_end", contentIndex: 0 },
{ type: "done", reason: "stop", usage },
];
const body = [
`data:${JSON.stringify(proxyEvents[0])}`,
"",
`data: ${JSON.stringify(proxyEvents[1])}`,
"",
`data:${JSON.stringify(proxyEvents[2])}`,
"",
`data:${JSON.stringify(proxyEvents[3])}`,
"",
].join("\n");
vi.stubGlobal(
"fetch",
vi.fn(async () => responseFromText(body)),
);
const stream = streamProxy(model, context, {
authToken: "token",
proxyUrl: "https://proxy.example",
});
const events = [];
for await (const event of stream) {
events.push(event);
}
expect(events.map((event) => event.type)).toEqual([
"text_start",
"text_delta",
"text_end",
"done",
]);
await expect(stream.result()).resolves.toMatchObject({
content: [{ type: "text", text: "Working..." }],
});
});
it("delays tool argument previews while preserving exact terminal arguments", async () => {
const initialContent = "a".repeat(128);
const checkpointContent = "b".repeat(400);
const deltas = [`{"content":"${initialContent}`, checkpointContent, `","terminal":"exact"}`];
vi.stubGlobal(
"fetch",
vi.fn(async () =>
responseFromSseFrames([
{ type: "toolcall_start", contentIndex: 0, id: "call-1", toolName: "write" },
...deltas.map((delta) => ({ type: "toolcall_delta", contentIndex: 0, delta })),
{ type: "toolcall_end", contentIndex: 0 },
{ type: "done", reason: "toolUse", usage },
]),
),
);
const stream = streamProxy(model, context, {
authToken: "token",
proxyUrl: "https://proxy.example",
});
const argumentSnapshots: Array<Record<string, unknown>> = [];
let terminalArguments: Record<string, unknown> | undefined;
for await (const event of stream) {
if (event.type === "toolcall_delta") {
const content = event.partial.content[event.contentIndex];
if (content?.type === "toolCall") {
argumentSnapshots.push(structuredClone(content.arguments));
}
} else if (event.type === "toolcall_end") {
terminalArguments = structuredClone(event.toolCall.arguments);
}
}
const checkpointPreview = { content: initialContent + checkpointContent };
expect(argumentSnapshots).toEqual([{}, checkpointPreview, checkpointPreview]);
const exactArguments = {
content: initialContent + checkpointContent,
terminal: "exact",
};
expect(terminalArguments).toEqual(exactArguments);
await expect(stream.result()).resolves.toMatchObject({
content: [{ type: "toolCall", arguments: exactArguments }],
});
});
it("preserves empty arguments for terminal-only tool calls", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async () =>
responseFromSseFrames([
{ type: "toolcall_start", contentIndex: 0, id: "call-1", toolName: "list" },
{ type: "toolcall_end", contentIndex: 0 },
{ type: "done", reason: "toolUse", usage },
]),
),
);
const stream = streamProxy(model, context, {
authToken: "token",
proxyUrl: "https://proxy.example",
});
await expect(stream.result()).resolves.toMatchObject({
stopReason: "toolUse",
content: [{ type: "toolCall", id: "call-1", name: "list", arguments: {} }],
});
});
it("flushes a final SSE frame without a trailing newline", async () => {
// Provider proxies can close immediately after the last SSE frame; the
// parser still has to emit the terminal done event.
const fetchMock = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) =>
responseFromText(
`data: ${JSON.stringify({
type: "done",
reason: "stop",
usage,
})}`,
),
);
vi.stubGlobal("fetch", fetchMock);
const options = {
authToken: "token",
headers: { Authorization: "Bearer upstream", "x-api-key": "secret" },
proxyUrl: "https://proxy.example",
};
const stream = streamProxy(model, context, options);
const events = [];
for await (const event of stream) {
events.push(event);
}
expect(events.at(-1)?.type).toBe("done");
await expect(stream.result()).resolves.toMatchObject({
role: "assistant",
stopReason: "stop",
usage,
});
const rawBody = fetchMock.mock.calls[0]?.[1]?.body;
expect(typeof rawBody).toBe("string");
const body = JSON.parse(rawBody as string) as {
model?: { headers?: unknown };
options?: { headers?: unknown; promptCacheKey?: string };
};
expect(body.options).not.toHaveProperty("headers");
expect(body.options?.promptCacheKey).toBeUndefined();
expect(body.model).not.toHaveProperty("headers");
});
it("forwards prompt cache affinity separately from session identity", async () => {
const fetchMock = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) =>
responseFromText(
`data: ${JSON.stringify({
type: "done",
reason: "stop",
usage,
})}`,
),
);
vi.stubGlobal("fetch", fetchMock);
await streamProxy(model, context, {
authToken: "token",
proxyUrl: "https://proxy.example",
sessionId: "run-session",
promptCacheKey: "stable-cache-key",
}).result();
const rawBody = fetchMock.mock.calls[0]?.[1]?.body;
expect(typeof rawBody).toBe("string");
const body = JSON.parse(rawBody as string) as {
options?: { promptCacheKey?: string; sessionId?: string };
};
expect(body.options).toMatchObject({
sessionId: "run-session",
promptCacheKey: "stable-cache-key",
});
});
it("applies timeoutMs before proxy response headers arrive", async () => {
vi.useFakeTimers();
vi.stubGlobal(
"fetch",
vi.fn((_input: RequestInfo | URL, init?: RequestInit) => {
const signal = init?.signal;
return new Promise<Response>((_resolve, reject) => {
signal?.addEventListener("abort", () => {
reject(
signal.reason instanceof Error ? signal.reason : new Error("Request was aborted"),
);
});
});
}),
);
const stream = streamProxy(model, context, {
authToken: "token",
proxyUrl: "https://proxy.example",
timeoutMs: 5,
});
await vi.advanceTimersByTimeAsync(5);
expect(await settledResult(stream)).toMatchObject({
stopReason: "error",
errorMessage: "Proxy request timed out after 5ms",
});
});
it("bounds non-2xx proxy JSON error reads", async () => {
const firstChunk = new TextEncoder().encode(`{"error":"${"x".repeat(17 * 1024 * 1024)}`);
let cancelled = false;
vi.stubGlobal(
"fetch",
vi.fn(async () =>
pendingReaderResponse({
chunks: [firstChunk],
status: 502,
statusText: "Bad Gateway",
onCancel: () => {
cancelled = true;
},
}),
),
);
const stream = streamProxy(model, context, {
authToken: "token",
proxyUrl: "https://proxy.example",
});
expect(await resultWithinMs(stream)).toMatchObject({
stopReason: "error",
errorMessage: "Proxy error body exceeded 16777216 bytes",
});
expect(cancelled).toBe(true);
});
it("caps unterminated pending SSE bytes before a frame delimiter arrives", async () => {
const overLimitFrame = new TextEncoder().encode(`data: ${"x".repeat(17 * 1024 * 1024)}`);
let cancelReason: unknown;
vi.stubGlobal(
"fetch",
vi.fn(async () =>
pendingReaderResponse({
chunks: [overLimitFrame],
onCancel: (reason) => {
cancelReason = reason;
},
}),
),
);
const stream = streamProxy(model, context, {
authToken: "token",
proxyUrl: "https://proxy.example",
});
expect(await resultWithinMs(stream)).toMatchObject({
stopReason: "error",
errorMessage: "Proxy SSE stream exceeded 16777216 bytes",
});
expect(cancelReason).toBeInstanceOf(Error);
});
it("caps delimiter-terminated SSE success body bytes", async () => {
const overLimitFrame = new TextEncoder().encode(`data: ${"x".repeat(17 * 1024 * 1024)}\n`);
let cancelReason: unknown;
vi.stubGlobal(
"fetch",
vi.fn(async () =>
pendingReaderResponse({
chunks: [overLimitFrame],
onCancel: (reason) => {
cancelReason = reason;
},
}),
),
);
const stream = streamProxy(model, context, {
authToken: "token",
proxyUrl: "https://proxy.example",
});
expect(await resultWithinMs(stream)).toMatchObject({
stopReason: "error",
errorMessage: "Proxy SSE stream exceeded 16777216 bytes",
});
expect(cancelReason).toBeInstanceOf(Error);
});
it("re-arms the SSE idle timeout after each received chunk", async () => {
vi.useFakeTimers();
const encoder = new TextEncoder();
let secondReadResolve: ((result: ReadableStreamReadResult<Uint8Array>) => void) | undefined;
let thirdReadResolve: ((result: ReadableStreamReadResult<Uint8Array>) => void) | undefined;
const cancel = vi.fn(async () => undefined);
const reader = {
read: vi
.fn()
.mockResolvedValueOnce({ done: false, value: encoder.encode("data: ") })
.mockImplementationOnce(
() =>
new Promise<ReadableStreamReadResult<Uint8Array>>((resolve) => {
secondReadResolve = resolve;
}),
)
.mockImplementationOnce(
() =>
new Promise<ReadableStreamReadResult<Uint8Array>>((resolve) => {
thirdReadResolve = resolve;
}),
),
cancel,
releaseLock: vi.fn(),
} as unknown as ReadableStreamDefaultReader<Uint8Array>;
vi.stubGlobal(
"fetch",
vi.fn(
async () =>
({
ok: true,
status: 200,
body: { getReader: () => reader },
}) as Response,
),
);
const stream = streamProxy(model, context, {
authToken: "token",
proxyUrl: "https://proxy.example",
});
await vi.advanceTimersByTimeAsync(119_000);
expect(cancel).not.toHaveBeenCalled();
secondReadResolve?.({
done: false,
value: encoder.encode(`${JSON.stringify({ type: "start" })}\n\n`),
});
await vi.advanceTimersByTimeAsync(119_000);
expect(cancel).not.toHaveBeenCalled();
thirdReadResolve?.({
done: false,
value: encoder.encode(`data: ${JSON.stringify({ type: "done", reason: "stop", usage })}\n\n`),
});
await expect(stream.result()).resolves.toMatchObject({
stopReason: "stop",
usage,
});
});
it("does not apply the pre-header timeout as an absolute stream deadline", async () => {
vi.useFakeTimers();
const encoder = new TextEncoder();
let secondReadResolve: ((result: ReadableStreamReadResult<Uint8Array>) => void) | undefined;
let thirdReadResolve: ((result: ReadableStreamReadResult<Uint8Array>) => void) | undefined;
const cancel = vi.fn(async () => undefined);
const reader = {
read: vi
.fn()
.mockResolvedValueOnce({ done: false, value: encoder.encode("data: ") })
.mockImplementationOnce(
() =>
new Promise<ReadableStreamReadResult<Uint8Array>>((resolve) => {
secondReadResolve = resolve;
}),
)
.mockImplementationOnce(
() =>
new Promise<ReadableStreamReadResult<Uint8Array>>((resolve) => {
thirdReadResolve = resolve;
}),
),
cancel,
releaseLock: vi.fn(),
} as unknown as ReadableStreamDefaultReader<Uint8Array>;
vi.stubGlobal(
"fetch",
vi.fn(
async () =>
({
ok: true,
status: 200,
body: { getReader: () => reader },
}) as Response,
),
);
const stream = streamProxy(model, context, {
authToken: "token",
proxyUrl: "https://proxy.example",
timeoutMs: 5,
});
await vi.advanceTimersByTimeAsync(4);
expect(cancel).not.toHaveBeenCalled();
secondReadResolve?.({
done: false,
value: encoder.encode(`${JSON.stringify({ type: "start" })}\n\n`),
});
await vi.advanceTimersByTimeAsync(4);
expect(cancel).not.toHaveBeenCalled();
thirdReadResolve?.({
done: false,
value: encoder.encode(`data: ${JSON.stringify({ type: "done", reason: "stop", usage })}\n\n`),
});
await expect(stream.result()).resolves.toMatchObject({
stopReason: "stop",
usage,
});
});
it("returns an error result when the SSE read idles", async () => {
vi.useFakeTimers();
const cancel = vi.fn(async () => undefined);
vi.stubGlobal(
"fetch",
vi.fn(
async () =>
({
ok: true,
status: 200,
body: {
getReader: () =>
({
read: vi.fn(
async () => await new Promise<ReadableStreamReadResult<Uint8Array>>(() => {}),
),
cancel,
releaseLock: vi.fn(),
}) as unknown as ReadableStreamDefaultReader<Uint8Array>,
},
}) as Response,
),
);
const stream = streamProxy(model, context, {
authToken: "token",
proxyUrl: "https://proxy.example",
});
await vi.advanceTimersByTimeAsync(120_000);
expect(await settledResult(stream)).toMatchObject({
stopReason: "error",
errorMessage: "Proxy SSE stream stalled: no data received for 120000ms",
});
expect(cancel).toHaveBeenCalledWith(expect.any(Error));
});
it("honors a longer configured SSE read idle timeout", async () => {
vi.useFakeTimers();
const cancel = vi.fn(async () => undefined);
vi.stubGlobal(
"fetch",
vi.fn(
async () =>
({
ok: true,
status: 200,
body: {
getReader: () =>
({
read: vi.fn(
async () => await new Promise<ReadableStreamReadResult<Uint8Array>>(() => {}),
),
cancel,
releaseLock: vi.fn(),
}) as unknown as ReadableStreamDefaultReader<Uint8Array>,
},
}) as Response,
),
);
const stream = streamProxy(model, context, {
authToken: "token",
proxyUrl: "https://proxy.example",
timeoutMs: 180_000,
});
await vi.advanceTimersByTimeAsync(120_000);
expect(await settledResult(stream)).toBe(unresolved);
expect(cancel).not.toHaveBeenCalled();
await vi.advanceTimersByTimeAsync(60_000);
expect(await settledResult(stream)).toMatchObject({
stopReason: "error",
errorMessage: "Proxy SSE stream stalled: no data received for 180000ms",
});
expect(cancel).toHaveBeenCalledWith(expect.any(Error));
});
it("releases the response reader when terminal stream cancellation never settles", async () => {
const releaseLock = vi.fn();
vi.stubGlobal(
"fetch",
vi.fn(async () =>
responseFromReaderText(
`data: ${JSON.stringify({
type: "done",
reason: "stop",
usage,
})}\n\n`,
releaseLock,
() => new Promise<void>(() => {}),
),
),
);
await streamProxy(model, context, {
authToken: "token",
proxyUrl: "https://proxy.example",
}).result();
expect(releaseLock).toHaveBeenCalledTimes(1);
});
it("does not cancel a naturally drained response ending with a terminal frame", async () => {
const cancel = vi.fn(async () => undefined);
vi.stubGlobal(
"fetch",
vi.fn(async () =>
responseFromReaderText(
`data: ${JSON.stringify({ type: "done", reason: "stop", usage })}`,
() => undefined,
cancel,
),
),
);
await expect(
streamProxy(model, context, {
authToken: "token",
proxyUrl: "https://proxy.example",
}).result(),
).resolves.toMatchObject({ stopReason: "stop" });
expect(cancel).not.toHaveBeenCalled();
});
it("returns an error result when EOF arrives without a terminal event", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async () => responseFromText(`data: ${JSON.stringify({ type: "start" })}`)),
);
const stream = streamProxy(model, context, {
authToken: "token",
proxyUrl: "https://proxy.example",
});
const events = [];
for await (const event of stream) {
events.push(event);
}
expect(events.at(-1)?.type).toBe("error");
await expect(stream.result()).resolves.toMatchObject({
stopReason: "error",
errorMessage: "Proxy stream ended before terminal event",
});
});
});
describe("streamProxy loopback /api/stream", () => {
let server: http.Server | undefined;
const dripIntervals = new Set<ReturnType<typeof setInterval>>();
afterEach(async () => {
for (const interval of dripIntervals) {
clearInterval(interval);
}
dripIntervals.clear();
if (!server) {
return;
}
const closed = once(server, "close");
server.close();
server.closeAllConnections();
await closed;
server = undefined;
});
async function listenDripProxy(): Promise<number> {
server = http.createServer((req, res) => {
res.on("error", () => {});
if (req.method !== "POST" || req.url !== "/api/stream") {
res.writeHead(404);
res.end();
return;
}
res.writeHead(200, {
"Content-Type": "text/event-stream",
"Transfer-Encoding": "chunked",
});
// Keepalive-style drip resets chunk-idle; outer abort must win.
const drip = () => {
if (res.writableEnded || res.destroyed) {
return;
}
res.write(`data: ${JSON.stringify({ type: "start" })}\n\n`);
};
const interval = setInterval(drip, 20);
dripIntervals.add(interval);
res.once("close", () => {
clearInterval(interval);
dripIntervals.delete(interval);
});
drip();
});
server.on("clientError", (_err, socket) => socket.destroy());
server.listen(0, "127.0.0.1");
await once(server, "listening");
const address = server.address();
if (!address || typeof address === "string") {
throw new Error("expected loopback server address");
}
return address.port;
}
async function listenProxyErrorBody(bytes: Buffer, splitAt: number) {
const request: {
method?: string;
path?: string;
authorization?: string;
} = {};
server = http.createServer((req, res) => {
request.method = req.method;
request.path = req.url;
request.authorization = req.headers.authorization;
if (req.method !== "POST" || req.url !== "/api/stream") {
res.writeHead(404);
res.end();
return;
}
res.writeHead(502, "Bad Gateway", { "Content-Type": "application/json" });
res.write(bytes.subarray(0, splitAt));
res.end(bytes.subarray(splitAt));
});
server.on("clientError", (_err, socket) => socket.destroy());
server.listen(0, "127.0.0.1");
await once(server, "listening");
const address = server.address();
if (!address || typeof address === "string") {
throw new Error("expected loopback server address");
}
return { port: address.port, request };
}
it.each([
{
name: "terminal success",
terminal: { type: "done", reason: "stop", usage },
expected: { stopReason: "stop" },
},
{
name: "terminal error",
terminal: { type: "error", reason: "error", errorMessage: "upstream failed", usage },
expected: { stopReason: "error", errorMessage: "upstream failed" },
},
{
name: "malformed event",
terminal: "{invalid json",
expected: { stopReason: "error" },
},
])(
"closes a hanging native SSE body after $name without applying later frames",
async (entry) => {
let notifyClosed: (() => void) | undefined;
const closed = new Promise<void>((resolve) => {
notifyClosed = resolve;
});
server = http.createServer((_req, res) => {
res.writeHead(200, { "Content-Type": "text/event-stream" });
res.once("close", () => notifyClosed?.());
const frames = [
{ type: "text_start", contentIndex: 0 },
{ type: "text_delta", contentIndex: 0, delta: "visible" },
entry.terminal,
{ type: "text_delta", contentIndex: 0, delta: " late mutation" },
];
res.write(
frames
.map(
(frame) => `data: ${typeof frame === "string" ? frame : JSON.stringify(frame)}\n\n`,
)
.join(""),
);
});
server.listen(0, "127.0.0.1");
await once(server, "listening");
const address = server.address();
if (!address || typeof address === "string") {
throw new Error("expected loopback server address");
}
const result = await streamProxy(model, context, {
authToken: "token",
proxyUrl: `http://127.0.0.1:${address.port}`,
timeoutMs: 3_000,
}).result();
// Native cancellation closes the remote socket asynchronously; the test owns the deadline.
await closed;
expect(result).toMatchObject({
...entry.expected,
content: [{ type: "text", text: "visible" }],
});
},
);
it("falls back to the HTTP status for malformed UTF-8 proxy errors", async () => {
const prefix = Buffer.from('{"error":"corrupted ');
const bytes = Buffer.concat([prefix, Buffer.from([0xff]), Buffer.from(' upstream"}')]);
const { port, request } = await listenProxyErrorBody(bytes, prefix.length);
const result = await streamProxy(model, context, {
authToken: "token",
proxyUrl: `http://127.0.0.1:${port}`,
timeoutMs: 3_000,
}).result();
expect(request).toEqual({
method: "POST",
path: "/api/stream",
authorization: "Bearer token",
});
expect(result).toMatchObject({
stopReason: "error",
errorMessage: "Proxy error: 502 Bad Gateway",
});
});
it("preserves a valid replacement character in proxy error responses", async () => {
const error = "upstream legitimately contains \uFFFD";
const bytes = Buffer.from(JSON.stringify({ error }));
const { port, request } = await listenProxyErrorBody(bytes, bytes.indexOf(0xef) + 1);
const result = await streamProxy(model, context, {
authToken: "token",
proxyUrl: `http://127.0.0.1:${port}`,
timeoutMs: 3_000,
}).result();
expect(request).toEqual({
method: "POST",
path: "/api/stream",
authorization: "Bearer token",
});
expect(result).toMatchObject({
stopReason: "error",
errorMessage: `Proxy error: ${error}`,
});
});
it("cancels a dripping native SSE body when the outer abort signal fires", async () => {
const port = await listenDripProxy();
const controller = new AbortController();
const stream = streamProxy(model, context, {
authToken: "token",
proxyUrl: `http://127.0.0.1:${port}`,
// Idle well above drip cadence so only the outer abort can terminate.
timeoutMs: 10_000,
signal: controller.signal,
});
const firstEvent = await stream[Symbol.asyncIterator]().next();
expect(firstEvent).toMatchObject({ done: false, value: { type: "start" } });
controller.abort();
expect(await resultWithinMs(stream, 1_500)).toMatchObject({
stopReason: "aborted",
errorMessage: "Request aborted by user",
});
});
});
|