-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathpayload-serialization.test.ts
More file actions
348 lines (305 loc) Β· 12.2 KB
/
Copy pathpayload-serialization.test.ts
File metadata and controls
348 lines (305 loc) Β· 12.2 KB
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
import { expect, it } from 'vitest';
import { setupServer } from './setup-server';
import { receive, track } from './test-events';
const ctx = setupServer();
class CustomPayload {
constructor(readonly value: string) {}
method(): string {
return this.value;
}
}
it('client-to-server payloads use JSON results and snapshot at emit', async () => {
const { client, serverSocket } = await ctx.connectClient();
const shared = { count: 1 };
const source = {
date: new Date('2026-08-12T00:00:00.000Z'),
missing: undefined,
nonfinite: Number.POSITIVE_INFINITY,
custom: new CustomPayload('kept'),
first: shared,
second: shared,
array: [undefined, Number.NaN, () => undefined, Symbol('value')],
};
const received = new Promise<Record<string, unknown>>((resolve) =>
serverSocket.once('payload', resolve),
);
client.emit('payload', source);
shared.count = 2;
const value = await received;
expect(value).toEqual({
date: '2026-08-12T00:00:00.000Z',
nonfinite: null,
custom: { value: 'kept' },
first: { count: 1 },
second: { count: 1 },
array: [null, null, null, null],
});
expect(value).not.toHaveProperty('missing');
expect(value.first).not.toBe(value.second);
expect(Object.getPrototypeOf(value.custom)).toBe(Object.prototype);
});
it('server-to-client payloads snapshot at emit and decode fresh values', async () => {
const { client, serverSocket } = await ctx.connectClient();
const shared = { count: 1 };
const source = { date: new Date('2026-08-12T01:00:00.000Z'), first: shared, second: shared };
const received = receive(client, 'payload');
serverSocket.emit('payload', source);
shared.count = 2;
await expect(received).resolves.toEqual({
date: '2026-08-12T01:00:00.000Z',
first: { count: 1 },
second: { count: 1 },
});
const value = (await received) as typeof source;
expect(value).not.toBe(source);
expect(value.first).not.toBe(value.second);
});
it('client-to-server ack requests and responses cross independent snapshots', async () => {
const { client, serverSocket } = await ctx.connectClient();
let requestSeen: unknown;
serverSocket.on('question', (request: unknown, ack: (response: unknown) => void) => {
requestSeen = request;
const shared = { count: 1 };
const response = { date: new Date('2026-08-12T02:00:00.000Z'), a: shared, b: shared };
ack(response);
shared.count = 2;
});
const request = { date: new Date('2026-08-12T01:00:00.000Z'), nested: { count: 1 } };
const response = (await client.emitWithAck('question', request)) as Record<string, unknown>;
request.nested.count = 2;
expect(requestSeen).toEqual({ date: '2026-08-12T01:00:00.000Z', nested: { count: 1 } });
expect(response).toEqual({
date: '2026-08-12T02:00:00.000Z',
a: { count: 1 },
b: { count: 1 },
});
expect(response.a).not.toBe(response.b);
});
it('server-to-client ack requests and responses cross independent snapshots', async () => {
const { client, serverSocket } = await ctx.connectClient();
let requestSeen: unknown;
client.on('question', (request: unknown, ack: (response: unknown) => void) => {
requestSeen = request;
const response = { date: new Date('2026-08-12T04:00:00.000Z'), nested: { count: 1 } };
ack(response);
response.nested.count = 2;
});
const request = { date: new Date('2026-08-12T03:00:00.000Z'), nested: { count: 1 } };
const response = await serverSocket.emitWithAck('question', request);
request.nested.count = 2;
expect(requestSeen).toEqual({ date: '2026-08-12T03:00:00.000Z', nested: { count: 1 } });
expect(response).toEqual({ date: '2026-08-12T04:00:00.000Z', nested: { count: 1 } });
});
it('a buffered client payload stays live until outgoing observation and flush', async () => {
const received = new Promise<unknown>((resolve) => {
ctx.io.on('connection', (socket) => socket.once('buffered', resolve));
});
const client = ctx.openClient();
const source = { count: 1 };
let outgoingCalls = 0;
client.onAnyOutgoing((_event, payload) => {
outgoingCalls += 1;
(payload as { count: number }).count += 1;
});
client.emit('buffered', source);
expect(outgoingCalls).toBe(0);
source.count = 2;
await expect(received).resolves.toEqual({ count: 3 });
expect(outgoingCalls).toBe(1);
});
it('direct outgoing listeners mutate the live source before the snapshot', async () => {
const { client, serverSocket } = await ctx.connectClient();
const source = { count: 1 };
serverSocket.onAnyOutgoing((_event, payload) => {
(payload as { count: number }).count = 2;
});
const received = receive(client, 'payload');
serverSocket.emit('payload', source);
source.count = 3;
await expect(received).resolves.toEqual({ count: 2 });
});
it('broadcast snapshots once before outgoing listeners and decodes per recipient', async () => {
const first = await ctx.connectClient();
const second = await ctx.connectClient();
const source = { nested: { count: 1 } };
const outgoing: number[] = [];
first.serverSocket.onAnyOutgoing((_event, payload) => {
const value = payload as typeof source;
outgoing.push(value.nested.count);
value.nested.count = 2;
});
second.serverSocket.onAnyOutgoing((_event, payload) => {
const value = payload as typeof source;
outgoing.push(value.nested.count);
value.nested.count = 3;
});
const receivedFirst = receive(first.client, 'payload');
const receivedSecond = receive(second.client, 'payload');
ctx.io.emit('payload', source);
const [a, b] = (await Promise.all([receivedFirst, receivedSecond])) as [
typeof source,
typeof source,
];
expect(outgoing).toEqual([1, 2]);
expect(source.nested.count).toBe(3);
expect(a).toEqual({ nested: { count: 1 } });
expect(b).toEqual({ nested: { count: 1 } });
expect(a).not.toBe(b);
expect(a.nested).not.toBe(b.nested);
});
it('room ack broadcasts snapshot requests and responses per recipient', async () => {
const first = await ctx.connectClient();
const second = await ctx.connectClient();
await first.serverSocket.join('room');
await second.serverSocket.join('room');
const source = { nested: { count: 1 } };
const outgoing: number[] = [];
const received: Array<typeof source> = [];
first.serverSocket.onAnyOutgoing((_event, payload) => {
const value = payload as typeof source;
outgoing.push(value.nested.count);
value.nested.count = 2;
});
second.serverSocket.onAnyOutgoing((_event, payload) => {
const value = payload as typeof source;
outgoing.push(value.nested.count);
value.nested.count = 3;
});
for (const [index, { client }] of [first, second].entries()) {
client.on('question', (payload: typeof source, ack: (response: unknown) => void) => {
received.push(payload);
const response = { id: index, nested: { count: 1 } };
ack(response);
response.nested.count = 2;
});
}
let sourceCountAfterEmit: number | undefined;
const result = await new Promise<{ err: unknown; responses: unknown[] }>((resolve) => {
ctx.io
.to('room')
.timeout(200)
.emit('question', source, (err: unknown, responses: unknown[]) =>
resolve({ err, responses }),
);
sourceCountAfterEmit = source.nested.count;
source.nested.count = 4;
});
expect(result.err).toBeNull();
expect(outgoing).toEqual([1, 2]);
expect(sourceCountAfterEmit).toBe(3);
expect(received).toHaveLength(2);
expect(received[0]).toEqual({ nested: { count: 1 } });
expect(received[1]).toEqual({ nested: { count: 1 } });
expect(received[0]).not.toBe(received[1]);
expect(received[0]?.nested).not.toBe(received[1]?.nested);
expect(
(result.responses as Array<{ id: number; nested: { count: number } }>).sort(
(a, b) => a.id - b.id,
),
).toEqual([
{ id: 0, nested: { count: 1 } },
{ id: 1, nested: { count: 1 } },
]);
});
it('toJSON and enumerable own properties determine decoded object results', async () => {
const { client, serverSocket } = await ctx.connectClient();
const error = Object.assign(new Error('hidden message'), { code: 'E_PAYLOAD' });
const received = receive(client, 'payload');
serverSocket.emit('payload', {
custom: { toJSON: () => ({ converted: true }) },
map: new Map([['key', 'value']]),
set: new Set(['value']),
regexp: /value/u,
error,
});
await expect(received).resolves.toEqual({
custom: { converted: true },
map: {},
set: {},
regexp: {},
error: { code: 'E_PAYLOAD' },
});
});
it('a plain toJSON result keeps an original binary property out of the packet', async () => {
const { client, serverSocket } = await ctx.connectClient();
const received = receive(client, 'payload');
const source = {
binary: new Uint8Array([1]),
toJSON: () => ({ converted: true }),
};
serverSocket.emit('payload', source);
await expect(received).resolves.toEqual({ converted: true });
await expect(received).resolves.not.toBe(source);
});
it('a broadcast encodes even when its room has no recipients', async () => {
const circular: { self?: unknown } = {};
circular.self = circular;
expect(() => ctx.io.to('empty').emit('payload', circular)).toThrow();
});
it('circular and BigInt payloads fail before delivery in both directions', async () => {
const { client, serverSocket } = await ctx.connectClient();
const serverBad = track(client, 'server-bad');
const clientBad = { received: false };
serverSocket.on('client-bad', () => {
clientBad.received = true;
});
const circular: { self?: unknown } = {};
circular.self = circular;
expect(() => serverSocket.emit('server-bad', circular)).toThrow();
expect(() => client.emit('client-bad', 1n)).toThrow();
const clientMarker = receive(client, 'client-marker');
const serverMarker = new Promise<void>((resolve) => serverSocket.once('server-marker', resolve));
serverSocket.emit('client-marker', 'done');
client.emit('server-marker', 'done');
await Promise.all([clientMarker, serverMarker]);
expect(serverBad.received).toBe(false);
expect(clientBad.received).toBe(false);
});
it('only a client timeout survives a payload encoding failure', async () => {
const { client, serverSocket } = await ctx.connectClient();
serverSocket.on('client-echo', (ack: (value: string) => void) => ack('answer'));
client.on('server-echo', (ack: (value: string) => void) => ack('answer'));
client.timeout(1000);
expect(() => client.emit('client-bad', 1n)).toThrow();
const clientFirst = await new Promise<unknown[]>((resolve) => {
client.emit('client-echo', (...args: unknown[]) => resolve(args));
});
const clientSecond = await new Promise<unknown[]>((resolve) => {
client.emit('client-echo', (...args: unknown[]) => resolve(args));
});
serverSocket.timeout(1000);
expect(() => serverSocket.emit('server-bad', 1n)).toThrow();
const serverNext = await new Promise<unknown[]>((resolve) => {
serverSocket.emit('server-echo', (...args: unknown[]) => resolve(args));
});
expect(clientFirst).toEqual([null, 'answer']);
expect(clientSecond).toEqual(['answer']);
expect(serverNext).toEqual(['answer']);
});
it('timeout and connected volatile wrappers use the same payload boundary', async () => {
const { client, serverSocket } = await ctx.connectClient();
let requestSeen: unknown;
client.on('question', (payload: unknown, ack: (response: unknown) => void) => {
requestSeen = payload;
ack({ date: new Date('2026-08-12T06:00:00.000Z') });
});
const volatilePayload = receive(client, 'volatile-payload');
const clientVolatilePayload = new Promise<unknown>((resolve) =>
serverSocket.once('client-volatile-payload', resolve),
);
const answer = await serverSocket
.timeout(200)
.emitWithAck('question', { date: new Date('2026-08-12T05:00:00.000Z') });
serverSocket.volatile.emit('volatile-payload', {
date: new Date('2026-08-12T07:00:00.000Z'),
});
client.volatile.emit('client-volatile-payload', {
date: new Date('2026-08-12T08:00:00.000Z'),
});
expect(requestSeen).toEqual({ date: '2026-08-12T05:00:00.000Z' });
expect(answer).toEqual({ date: '2026-08-12T06:00:00.000Z' });
await expect(volatilePayload).resolves.toEqual({ date: '2026-08-12T07:00:00.000Z' });
await expect(clientVolatilePayload).resolves.toEqual({
date: '2026-08-12T08:00:00.000Z',
});
});