From d09bd59667871c580336ad7918def49574ce5201 Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 02:10:25 +0100 Subject: [PATCH 1/6] perf(rpc): serialize and parse each stream event once The session splices the encoded event into its message instead of parsing it back and stringifying it again. The client revives tags only when the message text holds one, so untagged events (game frames) are parsed once. The wire text is unchanged. Refs #260 --- packages/rpc/src/client/rpc-client.ts | 5 +- packages/rpc/src/codec/codec.ts | 4 ++ packages/rpc/src/router/rpc-session.ts | 6 ++- packages/rpc/test/rpc.spec.ts | 73 +++++++++++++++++++++++++- 4 files changed, 84 insertions(+), 4 deletions(-) diff --git a/packages/rpc/src/client/rpc-client.ts b/packages/rpc/src/client/rpc-client.ts index 81c1328d..d378a9fc 100644 --- a/packages/rpc/src/client/rpc-client.ts +++ b/packages/rpc/src/client/rpc-client.ts @@ -10,7 +10,7 @@ import { toDisposable, } from '@nanoforge-dev/editor-kernel'; -import { decode, encode } from '../codec/codec'; +import { decode, encode, hasTags } from '../codec/codec'; import type { ClientMessage, Contract, ServerMessage } from '../contract/contract.type'; import { RPC_HTTP_PREFIX, RPC_WS_PATH } from '../contract/rpc.const'; import { @@ -202,7 +202,8 @@ export class RpcClient implements Disposable { if (!subscription) return; switch (message.t) { case 'event': - subscription.onEvent(decode(JSON.stringify(message.data))); + /** Revive only when the server's text holds a tag: most events (game frames) have none. */ + subscription.onEvent(hasTags(raw) ? decode(JSON.stringify(message.data)) : message.data); return; case 'error': this._subscriptions.delete(message.id); diff --git a/packages/rpc/src/codec/codec.ts b/packages/rpc/src/codec/codec.ts index 6cf79365..77596ce1 100644 --- a/packages/rpc/src/codec/codec.ts +++ b/packages/rpc/src/codec/codec.ts @@ -33,6 +33,10 @@ export const encode = (value: unknown): string => return current; }); +/** Whether a text from `encode` may hold a `$bin` or `$date` tag (`JSON.stringify` never escapes `$`). */ +export const hasTags = (text: string): boolean => + text.includes('"$bin":') || text.includes('"$date":'); + export const decode = (text: string): T => JSON.parse(text, (_key, value: unknown) => { if (isPlainTagged(value, '$bin')) return fromBase64(value.$bin!); diff --git a/packages/rpc/src/router/rpc-session.ts b/packages/rpc/src/router/rpc-session.ts index 12a965b9..405ff708 100644 --- a/packages/rpc/src/router/rpc-session.ts +++ b/packages/rpc/src/router/rpc-session.ts @@ -118,7 +118,11 @@ export class RpcSession implements Disposable { } private _emit(id: number, subscription: Subscription, event: unknown): void { - const text = JSON.stringify({ t: 'event', id, data: JSON.parse(encode(event)) }); + const data = encode(event); + /** `encode` gives undefined for a value JSON can't hold: throw, as the parse used to. */ + if (data === undefined) throw new TypeError('A stream event must be a JSON value'); + /** Splice the encoded event: same text as `JSON.stringify({ t, id, data })`, without re-parsing it. The id comes unchecked from the client, so it is stringified too. */ + const text = `{"t":"event","id":${JSON.stringify(id)},"data":${data}}`; if (this._blocked) { if (subscription.coalesce) subscription.queue = [text]; else { diff --git a/packages/rpc/test/rpc.spec.ts b/packages/rpc/test/rpc.spec.ts index d70965f0..32da8ac2 100644 --- a/packages/rpc/test/rpc.spec.ts +++ b/packages/rpc/test/rpc.spec.ts @@ -3,7 +3,7 @@ import { z } from 'zod'; import { toDisposable } from '@nanoforge-dev/editor-kernel'; -import { RpcClient, RpcError, RpcRouter, defineContract } from '../src'; +import { RpcClient, RpcError, RpcRouter, defineContract, encode } from '../src'; import { connect, flush } from './fixtures/harness'; const Files = defineContract('fs', { @@ -206,6 +206,77 @@ describe('RPC streams', () => { }); }); +describe('RPC stream events on the wire', () => { + const Frames = defineContract('frames', { + methods: {}, + streams: { tick: { params: z.null(), event: z.unknown() } }, + }); + + it('sends the encoded event as is and revives tags only where they are', async () => { + let emit: (event: unknown) => void = () => undefined; + const router = new RpcRouter<{ user: string }>(); + router.implement(Frames, { + methods: {}, + streams: { tick: (_params, _context, sink) => void (emit = (event) => sink.emit(event)) }, + }); + const { client, sockets } = connect(router); + const received: unknown[] = []; + client.subscribe(Frames, 'tick', null, (event) => received.push(event)); + await flush(); + const socket = sockets[0]!; + const wire: string[] = []; + const onmessage = socket.onmessage!; + socket.onmessage = (event) => (wire.push(String(event.data)), onmessage(event)); + + const events = [ + { bytes: new Uint8Array([0, 1, 255]), when: new Date('2026-11-23T10:00:00Z') }, + { $bin: 'x', other: 1 }, + { text: 'not a tag: "$bin":"AA==" "$date":"x"' }, + { entities: [{ id: 1, position: { x: 1.5, y: -2 } }], name: '\u2028 "quoted"' }, + ]; + for (const event of events) emit(event); + await flush(); + + const id = (JSON.parse(wire[0]!) as { id: number }).id; + expect(wire).toEqual( + events.map((event) => JSON.stringify({ t: 'event', id, data: JSON.parse(encode(event)) })), + ); + expect(received).toEqual(events); + expect((received[0] as { bytes: unknown }).bytes).toBeInstanceOf(Uint8Array); + expect((received[0] as { when: unknown }).when).toBeInstanceOf(Date); + }); + + it('quotes a subscription id the client sent as a string', async () => { + let emit: (event: unknown) => void = () => undefined; + const router = new RpcRouter<{ user: string }>(); + router.implement(Frames, { + methods: {}, + streams: { tick: (_params, _context, sink) => void (emit = (event) => sink.emit(event)) }, + }); + const sent: string[] = []; + const session = router.createSession({ user: 'alice' }, (message) => sent.push(message) > 0); + const id = '1,"t":"end"'; + await session.receive( + JSON.stringify({ t: 'sub', id, ns: 'frames', topic: 'tick', params: null }), + ); + emit({ n: 1 }); + expect(sent).toEqual([JSON.stringify({ t: 'event', id, data: { n: 1 } })]); + }); + + it('refuses an event JSON cannot hold, as before', async () => { + let emit: (event: unknown) => void = () => undefined; + const router = new RpcRouter<{ user: string }>(); + router.implement(Frames, { + methods: {}, + streams: { tick: (_params, _context, sink) => void (emit = (event) => sink.emit(event)) }, + }); + const { client } = connect(router); + client.subscribe(Frames, 'tick', null, () => undefined); + await flush(); + expect(() => emit(undefined)).toThrow(); + }); +}); + describe('RpcRouter.implement', () => { const Greeter = defineContract('greeter', { methods: { hi: { input: z.null(), output: z.string() } }, From 5e70840ce8fa7b6fff930045990884f7d8ab23d7 Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 02:11:24 +0100 Subject: [PATCH 2/6] perf(rpc): encode binary with the native base64 encoder The codec uses Uint8Array.prototype.toBase64 when the runtime has it (Bun, Node, recent browsers) and keeps the btoa loop for the others. An 8 MiB readMany answer no longer blocks the server for about 100 ms. The base64 text is unchanged. Refs #270 --- packages/rpc/src/codec/codec.ts | 4 ++++ packages/rpc/test/codec/codec.spec.ts | 26 +++++++++++++++++++++++++- 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/packages/rpc/src/codec/codec.ts b/packages/rpc/src/codec/codec.ts index 77596ce1..0e7b6d39 100644 --- a/packages/rpc/src/codec/codec.ts +++ b/packages/rpc/src/codec/codec.ts @@ -2,7 +2,11 @@ * JSON with a binary-safe envelope: `Uint8Array`/`ArrayBuffer` become `{ "$bin": base64 }` and * `Date` becomes `{ "$date": iso }`, so file contents can travel through JSON RPC calls. */ +/** Native `toBase64` (Bun, Node, recent browsers) encodes 8 MiB in a few ms; older browsers loop. */ +const nativeBase64 = typeof Uint8Array.prototype.toBase64 === 'function'; + const toBase64 = (bytes: Uint8Array): string => { + if (nativeBase64) return bytes.toBase64(); let binary = ''; const chunk = 0x8000; for (let i = 0; i < bytes.length; i += chunk) { diff --git a/packages/rpc/test/codec/codec.spec.ts b/packages/rpc/test/codec/codec.spec.ts index a7feb67a..67c5c883 100644 --- a/packages/rpc/test/codec/codec.spec.ts +++ b/packages/rpc/test/codec/codec.spec.ts @@ -1,4 +1,4 @@ -import { describe, expect, it } from 'vitest'; +import { describe, expect, it, vi } from 'vitest'; import { decode, encode } from '../../src/codec/codec'; @@ -13,6 +13,30 @@ describe('codec', () => { expect(decoded.nested).toEqual(value.nested); }); + it('writes the same base64 as btoa', () => { + const bytes = new Uint8Array(100_001).map((_, i) => (i * 31) % 256); + let binary = ''; + for (const byte of bytes) binary += String.fromCharCode(byte); + expect(encode({ bytes, buffer: bytes.buffer })).toBe( + JSON.stringify({ bytes: { $bin: btoa(binary) }, buffer: { $bin: btoa(binary) } }), + ); + expect(encode(new Uint8Array(0))).toBe('{"$bin":""}'); + }); + + it('falls back to btoa without a native toBase64', async () => { + const bytes = new Uint8Array(70_000).map((_, i) => (i * 7) % 256); + const expected = encode(bytes); + const native = Object.getOwnPropertyDescriptor(Uint8Array.prototype, 'toBase64')!; + delete (Uint8Array.prototype as Partial).toBase64; + try { + vi.resetModules(); + const codec = await import('../../src/codec/codec'); + expect(codec.encode(bytes)).toBe(expected); + } finally { + Object.defineProperty(Uint8Array.prototype, 'toBase64', native); + } + }); + it('keeps objects that only look like tags if they have other keys', () => { expect(decode(encode({ $bin: 'x', other: 1 }))).toEqual({ $bin: 'x', other: 1 }); }); From a2f270f33f716f486f68850ae99bfd67b050192b Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 02:20:54 +0100 Subject: [PATCH 3/6] fix(rpc): ignore subscription messages whose id is not an integer RpcSession.receive took any sub or unsub id the client sent. It now ignores ids that are not safe integers, as it ignores other broken messages. The client's ids are its integer counter, so nothing changes for it. --- packages/rpc/src/router/rpc-session.ts | 6 ++++-- packages/rpc/test/rpc.spec.ts | 24 ++++++++++++++---------- 2 files changed, 18 insertions(+), 12 deletions(-) diff --git a/packages/rpc/src/router/rpc-session.ts b/packages/rpc/src/router/rpc-session.ts index 405ff708..6b629770 100644 --- a/packages/rpc/src/router/rpc-session.ts +++ b/packages/rpc/src/router/rpc-session.ts @@ -41,6 +41,8 @@ export class RpcSession implements Disposable { return; } if (typeof message !== 'object' || message === null) return; + /** Subscription ids are the client's integer counter: anything else is a broken message. */ + if (message.t !== 'ping' && !Number.isSafeInteger(message.id)) return; switch (message.t) { case 'ping': this._write({ t: 'pong' }); @@ -121,8 +123,8 @@ export class RpcSession implements Disposable { const data = encode(event); /** `encode` gives undefined for a value JSON can't hold: throw, as the parse used to. */ if (data === undefined) throw new TypeError('A stream event must be a JSON value'); - /** Splice the encoded event: same text as `JSON.stringify({ t, id, data })`, without re-parsing it. The id comes unchecked from the client, so it is stringified too. */ - const text = `{"t":"event","id":${JSON.stringify(id)},"data":${data}}`; + /** Splice the encoded event: same text as `JSON.stringify({ t, id, data })`, without re-parsing it. */ + const text = `{"t":"event","id":${id},"data":${data}}`; if (this._blocked) { if (subscription.coalesce) subscription.queue = [text]; else { diff --git a/packages/rpc/test/rpc.spec.ts b/packages/rpc/test/rpc.spec.ts index 32da8ac2..9a437527 100644 --- a/packages/rpc/test/rpc.spec.ts +++ b/packages/rpc/test/rpc.spec.ts @@ -246,21 +246,25 @@ describe('RPC stream events on the wire', () => { expect((received[0] as { when: unknown }).when).toBeInstanceOf(Date); }); - it('quotes a subscription id the client sent as a string', async () => { - let emit: (event: unknown) => void = () => undefined; + it('ignores a subscription whose id is not an integer', async () => { + const handler = vi.fn(); const router = new RpcRouter<{ user: string }>(); - router.implement(Frames, { - methods: {}, - streams: { tick: (_params, _context, sink) => void (emit = (event) => sink.emit(event)) }, - }); + router.implement(Frames, { methods: {}, streams: { tick: handler } }); const sent: string[] = []; const session = router.createSession({ user: 'alice' }, (message) => sent.push(message) > 0); - const id = '1,"t":"end"'; + for (const id of ['1,"t":"end"', { n: 1 }, null, 1.5, Number.NaN, undefined]) { + await session.receive( + JSON.stringify({ t: 'sub', id, ns: 'frames', topic: 'tick', params: null }), + ); + await session.receive(JSON.stringify({ t: 'unsub', id })); + } + expect(handler).not.toHaveBeenCalled(); + expect(session.subscriptionCount).toBe(0); + expect(sent).toEqual([]); await session.receive( - JSON.stringify({ t: 'sub', id, ns: 'frames', topic: 'tick', params: null }), + JSON.stringify({ t: 'sub', id: 7, ns: 'frames', topic: 'tick', params: null }), ); - emit({ n: 1 }); - expect(sent).toEqual([JSON.stringify({ t: 'event', id, data: { n: 1 } })]); + expect(handler).toHaveBeenCalledOnce(); }); it('refuses an event JSON cannot hold, as before', async () => { From 3a9bc032f01d5f5ca1d8c7bc4664e7b2fc1427fe Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 02:23:09 +0100 Subject: [PATCH 4/6] perf(rpc): decode binary with the native base64 decoder The codec uses Uint8Array.fromBase64 when the runtime has it and keeps the atob loop for the others. It accepts and refuses the same texts. --- packages/rpc/src/codec/codec.ts | 7 +++++-- packages/rpc/test/codec/codec.spec.ts | 15 +++++++++++++-- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/packages/rpc/src/codec/codec.ts b/packages/rpc/src/codec/codec.ts index 0e7b6d39..c6f55ae1 100644 --- a/packages/rpc/src/codec/codec.ts +++ b/packages/rpc/src/codec/codec.ts @@ -2,8 +2,10 @@ * JSON with a binary-safe envelope: `Uint8Array`/`ArrayBuffer` become `{ "$bin": base64 }` and * `Date` becomes `{ "$date": iso }`, so file contents can travel through JSON RPC calls. */ -/** Native `toBase64` (Bun, Node, recent browsers) encodes 8 MiB in a few ms; older browsers loop. */ -const nativeBase64 = typeof Uint8Array.prototype.toBase64 === 'function'; +/** Native base64 (Bun, Node, recent browsers) handles 8 MiB in a few ms; older browsers loop. */ +const nativeBase64 = + typeof Uint8Array.prototype.toBase64 === 'function' && + typeof Uint8Array.fromBase64 === 'function'; const toBase64 = (bytes: Uint8Array): string => { if (nativeBase64) return bytes.toBase64(); @@ -16,6 +18,7 @@ const toBase64 = (bytes: Uint8Array): string => { }; const fromBase64 = (base64: string): Uint8Array => { + if (nativeBase64) return Uint8Array.fromBase64(base64); const binary = atob(base64); const bytes = new Uint8Array(binary.length); for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i); diff --git a/packages/rpc/test/codec/codec.spec.ts b/packages/rpc/test/codec/codec.spec.ts index 67c5c883..2c11bdfb 100644 --- a/packages/rpc/test/codec/codec.spec.ts +++ b/packages/rpc/test/codec/codec.spec.ts @@ -13,7 +13,7 @@ describe('codec', () => { expect(decoded.nested).toEqual(value.nested); }); - it('writes the same base64 as btoa', () => { + it('writes and reads the same base64 as btoa and atob', () => { const bytes = new Uint8Array(100_001).map((_, i) => (i * 31) % 256); let binary = ''; for (const byte of bytes) binary += String.fromCharCode(byte); @@ -21,19 +21,30 @@ describe('codec', () => { JSON.stringify({ bytes: { $bin: btoa(binary) }, buffer: { $bin: btoa(binary) } }), ); expect(encode(new Uint8Array(0))).toBe('{"$bin":""}'); + expect(decode<{ bytes: Uint8Array }>(encode({ bytes })).bytes).toEqual(bytes); + expect(decode(`{"$bin":"${btoa(binary)}"}`)).toEqual(bytes); + expect(decode('{"$bin":""}')).toEqual(new Uint8Array(0)); + expect(decode('{"$bin":"AQI"}')).toEqual(new Uint8Array([1, 2])); + expect(() => decode('{"$bin":"@@"}')).toThrow(); }); - it('falls back to btoa without a native toBase64', async () => { + it('falls back to btoa and atob without native base64', async () => { const bytes = new Uint8Array(70_000).map((_, i) => (i * 7) % 256); const expected = encode(bytes); const native = Object.getOwnPropertyDescriptor(Uint8Array.prototype, 'toBase64')!; + const nativeFrom = Object.getOwnPropertyDescriptor(Uint8Array, 'fromBase64')!; delete (Uint8Array.prototype as Partial).toBase64; + delete (Uint8Array as Partial).fromBase64; try { vi.resetModules(); const codec = await import('../../src/codec/codec'); expect(codec.encode(bytes)).toBe(expected); + expect(codec.decode(expected)).toEqual(bytes); + expect(codec.decode('{"$bin":"AQI"}')).toEqual(new Uint8Array([1, 2])); + expect(() => codec.decode('{"$bin":"@@"}')).toThrow(); } finally { Object.defineProperty(Uint8Array.prototype, 'toBase64', native); + Object.defineProperty(Uint8Array, 'fromBase64', nativeFrom); } }); From 9eee610a2489d3930cd07aedf105dde0c4ff4579 Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 02:32:29 +0100 Subject: [PATCH 5/6] fix(rpc): encode a node buffer as bytes The replacer looked at the value after toJSON ran, so a Buffer went out as { type: 'Buffer', data: [...] } instead of a $bin tag. It now checks the raw value first, like the Date branch. --- packages/rpc/src/codec/codec.ts | 2 ++ packages/rpc/test/codec/codec.spec.ts | 8 ++++++++ 2 files changed, 10 insertions(+) diff --git a/packages/rpc/src/codec/codec.ts b/packages/rpc/src/codec/codec.ts index c6f55ae1..0de68e7d 100644 --- a/packages/rpc/src/codec/codec.ts +++ b/packages/rpc/src/codec/codec.ts @@ -35,6 +35,8 @@ export const encode = (value: unknown): string => JSON.stringify(value, function (this: Record, key, current: unknown) { const raw = this[key]; if (raw instanceof Date) return { $date: raw.toISOString() }; + /** `raw`, not `current`: a Node `Buffer`'s `toJSON` has already run on `current`. */ + if (raw instanceof Uint8Array) return { $bin: toBase64(raw) }; if (current instanceof Uint8Array) return { $bin: toBase64(current) }; if (current instanceof ArrayBuffer) return { $bin: toBase64(new Uint8Array(current)) }; return current; diff --git a/packages/rpc/test/codec/codec.spec.ts b/packages/rpc/test/codec/codec.spec.ts index 2c11bdfb..5fa9943a 100644 --- a/packages/rpc/test/codec/codec.spec.ts +++ b/packages/rpc/test/codec/codec.spec.ts @@ -48,6 +48,14 @@ describe('codec', () => { } }); + it('encodes a Node Buffer as bytes, not as its toJSON form', () => { + /** The package has no Node types: Buffer is reached untyped. */ + const { Buffer } = globalThis as unknown as { Buffer: { from: (b: number[]) => Uint8Array } }; + const value = { content: Buffer.from([1, 2]) }; + expect(encode(value)).toBe('{"content":{"$bin":"AQI="}}'); + expect(decode<{ content: Uint8Array }>(encode(value)).content).toEqual(new Uint8Array([1, 2])); + }); + it('keeps objects that only look like tags if they have other keys', () => { expect(decode(encode({ $bin: 'x', other: 1 }))).toEqual({ $bin: 'x', other: 1 }); }); From a8a1383edaeea2f402dba5ef0d24f9ca6cf5267c Mon Sep 17 00:00:00 2001 From: Exelo Date: Mon, 23 Nov 2026 02:32:36 +0100 Subject: [PATCH 6/6] style(rpc): separate the codec header from the next doc comment --- packages/rpc/src/codec/codec.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/rpc/src/codec/codec.ts b/packages/rpc/src/codec/codec.ts index 0de68e7d..c42c7418 100644 --- a/packages/rpc/src/codec/codec.ts +++ b/packages/rpc/src/codec/codec.ts @@ -2,6 +2,7 @@ * JSON with a binary-safe envelope: `Uint8Array`/`ArrayBuffer` become `{ "$bin": base64 }` and * `Date` becomes `{ "$date": iso }`, so file contents can travel through JSON RPC calls. */ + /** Native base64 (Bun, Node, recent browsers) handles 8 MiB in a few ms; older browsers loop. */ const nativeBase64 = typeof Uint8Array.prototype.toBase64 === 'function' &&