Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions packages/rpc/src/client/rpc-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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);
Expand Down
14 changes: 14 additions & 0 deletions packages/rpc/src/codec/codec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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);
Expand All @@ -28,11 +36,17 @@ export const encode = (value: unknown): string =>
JSON.stringify(value, function (this: Record<string, unknown>, 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 = <T = unknown>(text: string): T =>
JSON.parse(text, (_key, value: unknown) => {
if (isPlainTagged(value, '$bin')) return fromBase64(value.$bin!);
Expand Down
8 changes: 7 additions & 1 deletion packages/rpc/src/router/rpc-session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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' });
Expand Down Expand Up @@ -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 {
Expand Down
45 changes: 44 additions & 1 deletion packages/rpc/test/codec/codec.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { describe, expect, it } from 'vitest';
import { describe, expect, it, vi } from 'vitest';

import { decode, encode } from '../../src/codec/codec';

Expand All @@ -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<Uint8Array>).toBase64;
delete (Uint8Array as Partial<typeof Uint8Array>).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 });
});
Expand Down
77 changes: 76 additions & 1 deletion packages/rpc/test/rpc.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', {
Expand Down Expand Up @@ -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() } },
Expand Down
Loading