Files
web/test/echo.test.ts

274 lines
8.4 KiB
TypeScript

// Copyright (C) 2025, Lux Industries Inc. All rights reserved.
// See the file LICENSE for licensing terms.
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import {
buildResponse,
parseRequest,
Status,
type Call,
type Response,
} from "@zap-proto/zap";
import {
connect,
lengthPrefixed,
splitMessages,
WebRpcError,
type Conn,
} from "../src/index.js";
import {
EchoArgs,
EchoResult,
newEchoArgs,
newEchoResult,
} from "./gen/echo_zap.js";
// EchoCap interface, one method: echo(text) -> (text); ordinal 0.
const ECHO = 0;
const SUBSCRIBE = 9;
function echoHandler(call: Call): Response {
if (call.method !== ECHO) {
return {
status: Status.NotFound,
promiseID: call.promiseID,
body: new Uint8Array(0),
};
}
const args = EchoArgs.wrap(call.payload);
return {
status: Status.OK,
promiseID: call.promiseID,
body: newEchoResult({ msg: args.msg }),
};
}
// The runtime has no WebTransport, so the carrier is a stand-in with the real
// one's shape: a bidirectional byte stream. The server end speaks the same
// framing the Go listener does (u32 LE length, one envelope) and, like it,
// takes the bearer from the first envelope's cap. The real HTTP/3 handshake is
// covered by the Go tests in zap-proto/go (transport/quic) and zap-proto/zip.
class FakeWebTransport {
static bearers: string[] = [];
static sessions = 0;
static lastOptions: unknown;
readonly ready = Promise.resolve();
readonly closed = new Promise<void>(() => {});
private fromServer!: TransformStream<Uint8Array, Uint8Array>;
constructor(
readonly url: string,
options?: unknown,
) {
FakeWebTransport.sessions++;
FakeWebTransport.lastOptions = options;
}
async createBidirectionalStream() {
const toServer = new TransformStream<Uint8Array, Uint8Array>();
this.fromServer = new TransformStream<Uint8Array, Uint8Array>();
void this.serve(toServer.readable, this.fromServer.writable);
return { readable: this.fromServer.readable, writable: toServer.writable };
}
close() {
void this.fromServer.writable.close().catch(() => {});
}
private async serve(
input: ReadableStream<Uint8Array>,
output: WritableStream<Uint8Array>,
) {
const reader = input.getReader();
const writer = output.getWriter();
let rest: Uint8Array = new Uint8Array(0);
let first = true;
for (;;) {
const { value, done } = await reader.read();
if (done) return;
const joined = new Uint8Array(rest.byteLength + value.byteLength);
joined.set(rest);
joined.set(value, rest.byteLength);
const split = splitMessages(joined);
rest = split.rest;
for (const message of split.messages) {
const call = parseRequest(message);
if (first) {
FakeWebTransport.bearers.push(new TextDecoder().decode(call.cap));
first = false;
} else if (call.cap.byteLength !== 0) {
FakeWebTransport.bearers.push("REPEATED");
}
if (call.method === SUBSCRIBE) {
for (const body of ["ack", "e1", "e2"]) {
await writer.write(
lengthPrefixed(
buildResponse(
Status.OK,
call.promiseID,
new TextEncoder().encode(body),
),
),
);
if (body === "ack") {
await writer.write(
lengthPrefixed(
buildResponse(Status.OK, 999, new Uint8Array(0)),
),
);
}
}
continue;
}
const resp = echoHandler(call);
// Answered in two writes to prove the client reassembles a split message.
const framed = lengthPrefixed(
buildResponse(resp.status, resp.promiseID, resp.body),
);
await writer.write(framed.subarray(0, 5));
await writer.write(framed.subarray(5));
}
}
}
}
const g = globalThis as Record<string, unknown>;
describe("@zap-proto/web over WebTransport", () => {
beforeEach(() => {
FakeWebTransport.bearers = [];
FakeWebTransport.sessions = 0;
g.WebTransport = FakeWebTransport;
});
afterEach(() => {
delete g.WebTransport;
});
it("roundtrips a ZAP message on one bidirectional stream", async () => {
const { bootstrap, close } = await connect<Conn>(
"https://zap.test/v1/zap",
{
bearer: "test-token",
},
);
const resp = await bootstrap.call(ECHO, {
payload: newEchoArgs({ msg: "hello" }),
});
expect(resp.status).toBe(Status.OK);
expect(EchoResult.wrap(resp.body).msg).toBe("hello");
expect(FakeWebTransport.sessions).toBe(1);
close();
});
it("presents the bearer once, on the first envelope", async () => {
const { bootstrap, close } = await connect<Conn>(
"https://zap.test/v1/zap",
{
bearer: "test-token",
},
);
const first = await bootstrap.call(ECHO, {
payload: newEchoArgs({ msg: "one" }),
});
const second = await bootstrap.call(ECHO, {
payload: newEchoArgs({ msg: "two" }),
});
expect(EchoResult.wrap(first.body).msg).toBe("one");
expect(EchoResult.wrap(second.body).msg).toBe("two");
expect(FakeWebTransport.bearers).toEqual(["test-token"]);
close();
});
it("answers concurrent calls by promise", async () => {
const { bootstrap, close } = await connect<Conn>("https://zap.test/v1/zap");
const [a, b] = await Promise.all(
["a", "b"].map((msg) =>
bootstrap.call(ECHO, { payload: newEchoArgs({ msg }) }),
),
);
expect(EchoResult.wrap(a!.body).msg).toBe("a");
expect(EchoResult.wrap(b!.body).msg).toBe("b");
close();
});
it("passes WebTransport options through", async () => {
const hashes = [{ algorithm: "sha-256", value: new Uint8Array(32) }];
const { close } = await connect("https://zap.test/v1/zap", {
serverCertificateHashes: hashes,
});
expect(FakeWebTransport.lastOptions).toEqual({
serverCertificateHashes: hashes,
});
close();
});
it("fails calls after close", async () => {
const { bootstrap, close } = await connect<Conn>("https://zap.test/v1/zap");
close();
await expect(bootstrap.call(ECHO)).rejects.toBeInstanceOf(WebRpcError);
});
it("fails loudly where WebTransport does not exist", async () => {
delete g.WebTransport;
await expect(connect("https://zap.test/v1/zap")).rejects.toThrow(
/WebTransport/,
);
});
it("routes server pushes by subscription id, beside calls", async () => {
const { bootstrap, close } = await connect<Conn>("https://zap.test/v1/zap");
const seen: string[] = [];
const done = new Promise<void>((resolve) => {
bootstrap.subscribe(SUBSCRIBE, {}, (r) => {
seen.push(new TextDecoder().decode(r.body));
if (seen.length === 3) resolve();
});
});
await done;
expect(seen).toEqual(["ack", "e1", "e2"]);
// A call still resolves once on the same session; the stray push under 999 was dropped.
const resp = await bootstrap.call(ECHO, {
payload: newEchoArgs({ msg: "x" }),
});
expect(EchoResult.wrap(resp.body).msg).toBe("x");
close();
});
it("stops delivering after unsubscribe and ends subscriptions on close", async () => {
const { bootstrap, close } = await connect<Conn>("https://zap.test/v1/zap");
const seen: string[] = [];
const sub = bootstrap.subscribe(SUBSCRIBE, {}, (r) =>
seen.push(new TextDecoder().decode(r.body)),
);
sub.close();
await bootstrap.call(ECHO, { payload: newEchoArgs({ msg: "x" }) }); // pumps past the pushes
expect(seen.length).toBeLessThanOrEqual(1);
let ended: Error | null = null;
bootstrap.subscribe(
SUBSCRIBE,
{},
() => {},
(e) => (ended = e),
);
close();
expect(ended).toBeInstanceOf(WebRpcError);
});
});
describe("framing", () => {
it("splits whole messages and keeps the remainder", () => {
const a = lengthPrefixed(new Uint8Array([1, 2, 3]));
const b = lengthPrefixed(new Uint8Array([4]));
const joined = new Uint8Array([...a, ...b.subarray(0, 3)]);
const { messages, rest } = splitMessages(joined);
expect(messages.map((m) => [...m])).toEqual([[1, 2, 3]]);
expect(rest.byteLength).toBe(3);
});
it("refuses a length prefix beyond the bound", () => {
expect(() =>
splitMessages(new Uint8Array([0xff, 0xff, 0xff, 0xff])),
).toThrow(RangeError);
});
});