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..c42c7418 100644 --- a/packages/rpc/src/codec/codec.ts +++ b/packages/rpc/src/codec/codec.ts @@ -2,7 +2,14 @@ * 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' && + typeof Uint8Array.fromBase64 === '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) { @@ -12,6 +19,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); @@ -28,11 +36,17 @@ 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; }); +/** 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..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' }); @@ -118,7 +120,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. */ + const text = `{"t":"event","id":${id},"data":${data}}`; if (this._blocked) { if (subscription.coalesce) subscription.queue = [text]; else { diff --git a/packages/rpc/test/codec/codec.spec.ts b/packages/rpc/test/codec/codec.spec.ts index a7feb67a..5fa9943a 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,49 @@ describe('codec', () => { expect(decoded.nested).toEqual(value.nested); }); + 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); + expect(encode({ bytes, buffer: bytes.buffer })).toBe( + 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 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); + } + }); + + 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 }); }); diff --git a/packages/rpc/test/rpc.spec.ts b/packages/rpc/test/rpc.spec.ts index d70965f0..9a437527 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,81 @@ 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('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: handler } }); + const sent: string[] = []; + const session = router.createSession({ user: 'alice' }, (message) => sent.push(message) > 0); + 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: 7, ns: 'frames', topic: 'tick', params: null }), + ); + expect(handler).toHaveBeenCalledOnce(); + }); + + 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() } },