-
Notifications
You must be signed in to change notification settings - Fork 268
Expand file tree
/
Copy pathSignalClient.test.ts
More file actions
859 lines (708 loc) · 29.8 KB
/
SignalClient.test.ts
File metadata and controls
859 lines (708 loc) · 29.8 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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
import {
ClientInfo_Capability,
DisconnectReason,
JoinRequest,
JoinResponse,
LeaveRequest,
ReconnectResponse,
SignalRequest,
SignalResponse,
WrappedJoinRequest,
WrappedJoinRequest_Compression,
} from '@livekit/protocol';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { ConnectionError, ConnectionErrorReason } from '../room/errors';
import { SignalClient, SignalConnectionState } from './SignalClient';
import type { WebSocketCloseInfo, WebSocketConnection } from './WebSocketStream';
import { WebSocketStream } from './WebSocketStream';
// Mock the WebSocketStream
vi.mock('./WebSocketStream');
// Mock fetch for validation endpoint
global.fetch = vi.fn();
// Test Helpers
function createJoinResponse() {
return new JoinResponse({
room: { name: 'test-room', sid: 'room-sid' },
participant: { sid: 'participant-sid', identity: 'test-user' },
pingTimeout: 30,
pingInterval: 10,
});
}
function createSignalResponse(
messageCase: 'join' | 'reconnect' | 'leave' | 'update',
value: any,
): SignalResponse {
return new SignalResponse({
message: { case: messageCase, value },
});
}
function createMockReadableStream(responses: SignalResponse[]): ReadableStream<ArrayBuffer> {
return new ReadableStream<ArrayBuffer>({
async start(controller) {
for (const response of responses) {
controller.enqueue(response.toBinary().buffer as ArrayBuffer);
}
},
});
}
function createMockConnection(readable: ReadableStream<ArrayBuffer>): WebSocketConnection {
return {
readable,
writable: new WritableStream(),
protocol: '',
extensions: '',
};
}
interface MockWebSocketStreamOptions {
connection?: WebSocketConnection;
opened?: Promise<WebSocketConnection>;
closed?: Promise<WebSocketCloseInfo>;
onUrl?: (url: string) => void;
readyState?: number;
}
function mockWebSocketStream(options: MockWebSocketStreamOptions = {}) {
const {
connection,
opened = connection ? Promise.resolve(connection) : new Promise(() => {}),
closed = new Promise(() => {}),
readyState = 1,
onUrl,
} = options;
return vi.mocked(WebSocketStream).mockImplementationOnce((url) => {
onUrl?.(url);
return {
url: 'wss://test.livekit.io',
opened,
closed,
close: vi.fn(),
readyState,
} as any;
});
}
describe('SignalClient.connect', () => {
let signalClient: SignalClient;
const defaultOptions = {
autoSubscribe: true,
maxRetries: 0,
e2eeEnabled: false,
websocketTimeout: 1000,
singlePeerConnection: false,
};
beforeEach(() => {
vi.clearAllMocks();
signalClient = new SignalClient(false);
});
async function decodeJoinRequestFromUrl(url: string): Promise<JoinRequest> {
const joinRequestParam = new URL(url).searchParams.get('join_request');
expect(joinRequestParam).toBeTruthy();
const paddedBase64Url = joinRequestParam!.padEnd(
joinRequestParam!.length + ((4 - (joinRequestParam!.length % 4)) % 4),
'=',
);
const binaryString = atob(paddedBase64Url.replace(/-/g, '+').replace(/_/g, '/'));
const wrappedBytes = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i += 1) {
wrappedBytes[i] = binaryString.charCodeAt(i);
}
const wrappedJoinRequest = WrappedJoinRequest.fromBinary(wrappedBytes);
if (wrappedJoinRequest.compression === WrappedJoinRequest_Compression.NONE) {
return JoinRequest.fromBinary(wrappedJoinRequest.joinRequest);
}
const stream = new DecompressionStream('gzip');
const writer = stream.writable.getWriter();
writer.write(wrappedJoinRequest.joinRequest);
writer.close();
const chunks: Uint8Array[] = [];
const reader = stream.readable.getReader();
while (true) {
const { done, value } = await reader.read();
if (done) break;
chunks.push(value);
}
const totalLength = chunks.reduce((acc, chunk) => acc + chunk.length, 0);
const bytes = new Uint8Array(totalLength);
let offset = 0;
for (const chunk of chunks) {
bytes.set(chunk, offset);
offset += chunk.length;
}
return JoinRequest.fromBinary(bytes);
}
describe('Happy Path - Initial Join', () => {
it('should successfully connect and receive join response', async () => {
const joinResponse = createJoinResponse();
const signalResponse = createSignalResponse('join', joinResponse);
const mockReadable = createMockReadableStream([signalResponse]);
const mockConnection = createMockConnection(mockReadable);
mockWebSocketStream({ connection: mockConnection });
const result = await signalClient.join('wss://test.livekit.io', 'test-token', defaultOptions);
expect(result).toEqual(joinResponse);
expect(signalClient.currentState).toBe(SignalConnectionState.CONNECTED);
});
it('does not advertise packet trailer capability by default', async () => {
const joinResponse = createJoinResponse();
const signalResponse = createSignalResponse('join', joinResponse);
const mockReadable = createMockReadableStream([signalResponse]);
const mockConnection = createMockConnection(mockReadable);
let capturedUrl = '';
mockWebSocketStream({
connection: mockConnection,
onUrl: (url) => {
capturedUrl = url;
},
});
await signalClient.join('wss://test.livekit.io', 'test-token', defaultOptions);
const joinRequest = await decodeJoinRequestFromUrl(capturedUrl);
expect(joinRequest.clientInfo?.capabilities).toEqual([]);
});
it('advertises packet trailer capability when provided', async () => {
const joinResponse = createJoinResponse();
const signalResponse = createSignalResponse('join', joinResponse);
const mockReadable = createMockReadableStream([signalResponse]);
const mockConnection = createMockConnection(mockReadable);
let capturedUrl = '';
mockWebSocketStream({
connection: mockConnection,
onUrl: (url) => {
capturedUrl = url;
},
});
await signalClient.join('wss://test.livekit.io', 'test-token', {
...defaultOptions,
clientInfoCapabilities: [ClientInfo_Capability.CAP_PACKET_TRAILER],
});
const joinRequest = await decodeJoinRequestFromUrl(capturedUrl);
expect(joinRequest.clientInfo?.capabilities).toEqual([
ClientInfo_Capability.CAP_PACKET_TRAILER,
]);
});
});
describe('Happy Path - Reconnect', () => {
it('should successfully reconnect and receive reconnect response', async () => {
// First, set up initial connection
const joinResponse = createJoinResponse();
const joinSignalResponse = createSignalResponse('join', joinResponse);
const initialMockReadable = createMockReadableStream([joinSignalResponse]);
const initialMockConnection = createMockConnection(initialMockReadable);
mockWebSocketStream({ connection: initialMockConnection });
await signalClient.join('wss://test.livekit.io', 'test-token', defaultOptions);
// Now test reconnect
const reconnectResponse = new ReconnectResponse({
iceServers: [],
});
const reconnectSignalResponse = createSignalResponse('reconnect', reconnectResponse);
const reconnectMockReadable = createMockReadableStream([reconnectSignalResponse]);
const reconnectMockConnection = createMockConnection(reconnectMockReadable);
mockWebSocketStream({ connection: reconnectMockConnection });
const result = await signalClient.reconnect('wss://test.livekit.io', 'test-token', 'sid-123');
expect(result).toEqual(reconnectResponse);
expect(signalClient.currentState).toBe(SignalConnectionState.CONNECTED);
});
it('should handle reconnect with non-reconnect message (edge case)', async () => {
// First, initial connection
const joinResponse = createJoinResponse();
const joinSignalResponse = createSignalResponse('join', joinResponse);
const initialMockReadable = createMockReadableStream([joinSignalResponse]);
const initialMockConnection = createMockConnection(initialMockReadable);
mockWebSocketStream({ connection: initialMockConnection });
await signalClient.join('wss://test.livekit.io', 'test-token', defaultOptions);
// Setup reconnect with non-reconnect message (e.g., participant update)
const updateSignalResponse = createSignalResponse('update', { participants: [] });
const reconnectMockReadable = createMockReadableStream([updateSignalResponse]);
const reconnectMockConnection = createMockConnection(reconnectMockReadable);
mockWebSocketStream({ connection: reconnectMockConnection });
const result = await signalClient.reconnect('wss://test.livekit.io', 'test-token', 'sid-123');
// This is an edge case: reconnect resolves with undefined when non-reconnect message is received
expect(result).toBeUndefined();
expect(signalClient.currentState).toBe(SignalConnectionState.CONNECTED);
}, 1000);
});
describe('Failure Case - Timeout', () => {
it('should reject with timeout error when websocket connection takes too long', async () => {
mockWebSocketStream({ readyState: 0 }); // Never resolves
const shortTimeoutOptions = {
...defaultOptions,
websocketTimeout: 100,
};
const error = await signalClient
.join('wss://test.livekit.io', 'test-token', shortTimeoutOptions)
.catch((e) => e);
expect(error).toBeInstanceOf(ConnectionError);
expect(error.reason).toBe(ConnectionErrorReason.Cancelled);
});
});
describe('Failure Case - AbortSignal', () => {
it('should reject when AbortSignal is triggered', async () => {
const abortController = new AbortController();
vi.mocked(WebSocketStream).mockImplementation(() => {
// Simulate abort
setTimeout(() => abortController.abort(new Error('User aborted connection')), 50);
return {
url: 'wss://test.livekit.io',
opened: new Promise(() => {}), // Never resolves
closed: new Promise(() => {}),
close: vi.fn(),
readyState: 0,
} as any;
});
await expect(
signalClient.join(
'wss://test.livekit.io',
'test-token',
defaultOptions,
abortController.signal,
),
).rejects.toThrow('User aborted connection');
});
it('should send leave request before closing when AbortSignal is triggered during connection', async () => {
const abortController = new AbortController();
const writtenMessages: Array<ArrayBuffer | string> = [];
let streamWriterReady: (() => void) | undefined;
const streamWriterReadyPromise = new Promise<void>((resolve) => {
streamWriterReady = resolve;
});
// Create a mock writable stream that captures writes
const mockWritable = new WritableStream({
write(chunk) {
writtenMessages.push(chunk);
return Promise.resolve();
},
});
// Override getWriter to signal when streamWriter is assigned
const originalGetWriter = mockWritable.getWriter.bind(mockWritable);
mockWritable.getWriter = () => {
const writer = originalGetWriter();
streamWriterReady?.();
return writer;
};
const mockReadable = new ReadableStream<ArrayBuffer>({
async start() {
// Keep connection open but don't send join response yet
// This simulates aborting during connection (after WS opens, before join response)
},
});
const mockConnection = {
readable: mockReadable,
writable: mockWritable,
protocol: '',
extensions: '',
};
vi.mocked(WebSocketStream).mockImplementation(() => {
return {
url: 'wss://test.livekit.io',
opened: Promise.resolve(mockConnection),
closed: new Promise(() => {}),
close: vi.fn(),
readyState: 1,
} as any;
});
// Start the connection
const joinPromise = signalClient.join(
'wss://test.livekit.io',
'test-token',
defaultOptions,
abortController.signal,
);
// Wait for streamWriter to be assigned
await streamWriterReadyPromise;
// Now abort the connection (after WS opens, before join response)
abortController.abort(new Error('User aborted connection'));
// joinPromise should reject
await expect(joinPromise).rejects.toThrow('User aborted connection');
// Verify that a leave request was sent before closing
const leaveRequestSent = writtenMessages.some((data) => {
if (typeof data === 'string') {
return false;
}
try {
const request = SignalRequest.fromBinary(
data instanceof ArrayBuffer ? new Uint8Array(data) : data,
);
return request.message?.case === 'leave';
} catch {
return false;
}
});
expect(leaveRequestSent).toBe(true);
});
});
describe('Failure Case - WebSocket Connection Errors', () => {
it('should reject with NotAllowed error for 4xx HTTP status', async () => {
const openedPromise = Promise.reject(new Error('Connection failed'));
openedPromise.catch(() => {}); // prevent unhandled rejection before join attaches its handler
mockWebSocketStream({
opened: openedPromise,
readyState: 3,
});
// Mock fetch to return 403
(global.fetch as any).mockResolvedValueOnce({
status: 403,
text: async () => 'Forbidden',
});
await expect(
signalClient.join('wss://test.livekit.io', 'test-token', defaultOptions),
).rejects.toMatchObject({
message: 'Forbidden',
reason: ConnectionErrorReason.NotAllowed,
status: 403,
});
});
it('should reject with ServerUnreachable when fetch fails', async () => {
const openedPromise = Promise.reject(new Error('Connection failed'));
openedPromise.catch(() => {}); // prevent unhandled rejection before join attaches its handler
mockWebSocketStream({
opened: openedPromise,
readyState: 3,
});
// Mock fetch to throw (network error)
(global.fetch as any).mockRejectedValueOnce(new Error('Network error'));
await expect(
signalClient.join('wss://test.livekit.io', 'test-token', defaultOptions),
).rejects.toMatchObject({
reason: ConnectionErrorReason.ServerUnreachable,
});
});
it('should handle ConnectionError from WebSocket rejection', async () => {
const customError = ConnectionError.internal('Custom error', { status: 500 });
const openedPromise = Promise.reject(customError);
openedPromise.catch(() => {}); // prevent unhandled rejection before join attaches its handler
mockWebSocketStream({
opened: openedPromise,
readyState: 3,
});
// Mock fetch to return 500
(global.fetch as any).mockResolvedValueOnce({
status: 500,
text: async () => 'Internal Server Error',
});
await expect(
signalClient.join('wss://test.livekit.io', 'test-token', defaultOptions),
).rejects.toMatchObject({
reason: ConnectionErrorReason.InternalError,
});
});
});
describe('Failure Case - No First Message', () => {
it('should reject when no first message is received', async () => {
// Close the stream immediately without sending a message
const mockReadable = new ReadableStream<ArrayBuffer>({
async start(controller) {
controller.close();
},
});
const mockConnection = createMockConnection(mockReadable);
mockWebSocketStream({ connection: mockConnection });
await expect(
signalClient.join('wss://test.livekit.io', 'test-token', defaultOptions),
).rejects.toMatchObject({
message: 'no message received as first message',
reason: ConnectionErrorReason.InternalError,
});
});
});
describe('Failure Case - Leave Request During Connection', () => {
it('should reject when receiving leave request during initial join', async () => {
const leaveRequest = new LeaveRequest({
reason: 1, // Some disconnect reason
});
const signalResponse = createSignalResponse('leave', leaveRequest);
const mockReadable = createMockReadableStream([signalResponse]);
const mockConnection = createMockConnection(mockReadable);
mockWebSocketStream({ connection: mockConnection });
await expect(
signalClient.join('wss://test.livekit.io', 'test-token', defaultOptions),
).rejects.toMatchObject(
ConnectionError.leaveRequest(
'Received leave request while trying to (re)connect',
DisconnectReason.CLIENT_INITIATED,
),
);
});
});
describe('Failure Case - Wrong Message Type for Non-Reconnect', () => {
it('should reject when receiving non-join message on initial connection', async () => {
// Send a reconnect response instead of join (wrong for initial connection)
const reconnectResponse = new ReconnectResponse({
iceServers: [],
});
const signalResponse = createSignalResponse('reconnect', reconnectResponse);
const mockReadable = createMockReadableStream([signalResponse]);
const mockConnection = createMockConnection(mockReadable);
mockWebSocketStream({ connection: mockConnection });
await expect(
signalClient.join('wss://test.livekit.io', 'test-token', defaultOptions),
).rejects.toMatchObject({
message: 'did not receive join response, got reconnect instead',
reason: ConnectionErrorReason.InternalError,
});
});
});
describe('Failure Case - WebSocket Closed During Connection', () => {
it('should reject when WebSocket closes during connection attempt', async () => {
let closedResolve: (value: WebSocketCloseInfo) => void;
const closedPromise = new Promise<WebSocketCloseInfo>((resolve) => {
closedResolve = resolve;
});
vi.mocked(WebSocketStream).mockImplementation(() => {
// Simulate close during connection
queueMicrotask(() => {
closedResolve({ closeCode: 1006, reason: 'Connection lost' });
});
return {
url: 'wss://test.livekit.io',
opened: new Promise(() => {}), // Never resolves
closed: closedPromise,
close: vi.fn(),
readyState: 2, // CLOSING
} as any;
});
await expect(
signalClient.join('wss://test.livekit.io', 'test-token', defaultOptions),
).rejects.toMatchObject({
message: 'Websocket got closed during a (re)connection attempt: Connection lost',
reason: ConnectionErrorReason.InternalError,
});
});
});
describe('Edge Cases and State Management', () => {
it('should set state to CONNECTING when joining', async () => {
expect(signalClient.currentState).toBe(SignalConnectionState.DISCONNECTED);
const joinResponse = createJoinResponse();
const signalResponse = createSignalResponse('join', joinResponse);
const mockReadable = createMockReadableStream([signalResponse]);
const mockConnection = createMockConnection(mockReadable);
mockWebSocketStream({ connection: mockConnection });
const joinPromise = signalClient.join('wss://test.livekit.io', 'test-token', defaultOptions);
// State should be CONNECTING before connection completes
expect(signalClient.currentState).toBe(SignalConnectionState.CONNECTING);
await joinPromise;
expect(signalClient.currentState).toBe(SignalConnectionState.CONNECTED);
});
});
});
describe('SignalClient utility functions', () => {
describe('toProtoSessionDescription', () => {
it('should convert RTCSessionDescriptionInit to proto SessionDescription', async () => {
const { toProtoSessionDescription } = await import('./SignalClient');
const rtcDesc: RTCSessionDescriptionInit = {
type: 'offer',
sdp: 'v=0\r\no=- 123 456 IN IP4 127.0.0.1\r\n',
};
const protoDesc = toProtoSessionDescription(rtcDesc, 42);
expect(protoDesc.type).toBe('offer');
expect(protoDesc.sdp).toBe('v=0\r\no=- 123 456 IN IP4 127.0.0.1\r\n');
expect(protoDesc.id).toBe(42);
});
it('should handle answer type', async () => {
const { toProtoSessionDescription } = await import('./SignalClient');
const rtcDesc: RTCSessionDescriptionInit = {
type: 'answer',
sdp: 'v=0\r\n',
};
const protoDesc = toProtoSessionDescription(rtcDesc);
expect(protoDesc.type).toBe('answer');
expect(protoDesc.sdp).toBe('v=0\r\n');
});
});
});
describe('SignalClient.handleSignalConnected', () => {
let signalClient: SignalClient;
const defaultOptions = {
autoSubscribe: true,
maxRetries: 0,
e2eeEnabled: false,
websocketTimeout: 1000,
singlePeerConnection: false,
};
beforeEach(() => {
vi.clearAllMocks();
signalClient = new SignalClient(false);
});
it('should set state to CONNECTED', () => {
const mockReadable = new ReadableStream<ArrayBuffer>();
const mockConnection = createMockConnection(mockReadable);
// Access the method through a type assertion for testing
const handleMethod = (signalClient as any).handleSignalConnected;
if (handleMethod) {
handleMethod.call(signalClient, mockConnection);
expect(signalClient.currentState).toBe(SignalConnectionState.CONNECTED);
}
});
it('should start reading loop without first message', async () => {
const joinResponse = createJoinResponse();
const signalResponse = createSignalResponse('join', joinResponse);
const mockReadable = createMockReadableStream([signalResponse]);
const mockConnection = createMockConnection(mockReadable);
mockWebSocketStream({ connection: mockConnection });
await signalClient.join('wss://test.livekit.io', 'test-token', defaultOptions);
// Verify connection was established successfully
expect(signalClient.currentState).toBe(SignalConnectionState.CONNECTED);
});
it('should start reading loop with first message', async () => {
const joinResponse = createJoinResponse();
const signalResponse = createSignalResponse('join', joinResponse);
const mockReadable = createMockReadableStream([signalResponse]);
const mockConnection = createMockConnection(mockReadable);
mockWebSocketStream({ connection: mockConnection });
await signalClient.join('wss://test.livekit.io', 'test-token', defaultOptions);
expect(signalClient.currentState).toBe(SignalConnectionState.CONNECTED);
});
});
describe('SignalClient.validateFirstMessage', () => {
let signalClient: SignalClient;
const defaultOptions = {
autoSubscribe: true,
maxRetries: 0,
e2eeEnabled: false,
websocketTimeout: 1000,
singlePeerConnection: false,
};
beforeEach(() => {
vi.clearAllMocks();
signalClient = new SignalClient(false);
});
it('should accept join response for initial connection', () => {
const joinResponse = createJoinResponse();
const signalResponse = createSignalResponse('join', joinResponse);
const validateMethod = (signalClient as any).validateFirstMessage;
if (validateMethod) {
const result = validateMethod.call(signalClient, signalResponse, false);
expect(result.isValid).toBe(true);
expect(result.response).toEqual(joinResponse);
}
});
it('should accept reconnect response for reconnection', async () => {
// First establish a connection to set options
const joinResponse = createJoinResponse();
const joinSignalResponse = createSignalResponse('join', joinResponse);
const initialMockReadable = createMockReadableStream([joinSignalResponse]);
const initialMockConnection = createMockConnection(initialMockReadable);
mockWebSocketStream({ connection: initialMockConnection });
await signalClient.join('wss://test.livekit.io', 'test-token', defaultOptions);
// Set state to RECONNECTING to match the validation logic
(signalClient as any).state = SignalConnectionState.RECONNECTING;
const reconnectResponse = new ReconnectResponse({ iceServers: [] });
const signalResponse = createSignalResponse('reconnect', reconnectResponse);
const validateMethod = (signalClient as any).validateFirstMessage;
if (validateMethod) {
const result = validateMethod.call(signalClient, signalResponse, true);
expect(result.isValid).toBe(true);
expect(result.response).toEqual(reconnectResponse);
}
});
it('should accept non-reconnect message during reconnecting state', async () => {
// First establish a connection
const joinResponse = createJoinResponse();
const joinSignalResponse = createSignalResponse('join', joinResponse);
const initialMockReadable = createMockReadableStream([joinSignalResponse]);
const initialMockConnection = createMockConnection(initialMockReadable);
mockWebSocketStream({ connection: initialMockConnection });
await signalClient.join('wss://test.livekit.io', 'test-token', defaultOptions);
// Set state to reconnecting
(signalClient as any).state = SignalConnectionState.RECONNECTING;
const updateSignalResponse = createSignalResponse('update', { participants: [] });
const validateMethod = (signalClient as any).validateFirstMessage;
if (validateMethod) {
const result = validateMethod.call(signalClient, updateSignalResponse, true);
expect(result.isValid).toBe(true);
expect(result.response).toBeUndefined();
expect(result.shouldProcessFirstMessage).toBe(true);
}
});
it('should reject leave request during connection attempt', () => {
// Set state to CONNECTING to be in establishing connection state
(signalClient as any).state = SignalConnectionState.CONNECTING;
const leaveRequest = new LeaveRequest({ reason: 1 });
const signalResponse = createSignalResponse('leave', leaveRequest);
const validateMethod = (signalClient as any).validateFirstMessage;
if (validateMethod) {
const result = validateMethod.call(signalClient, signalResponse, false);
expect(result.isValid).toBe(false);
expect(result.error).toBeInstanceOf(ConnectionError);
expect(result.error?.reason).toBe(ConnectionErrorReason.LeaveRequest);
}
});
it('should reject non-join message for initial connection', () => {
const reconnectResponse = new ReconnectResponse({ iceServers: [] });
const signalResponse = createSignalResponse('reconnect', reconnectResponse);
const validateMethod = (signalClient as any).validateFirstMessage;
if (validateMethod) {
const result = validateMethod.call(signalClient, signalResponse, false);
expect(result.isValid).toBe(false);
expect(result.error).toBeInstanceOf(ConnectionError);
expect(result.error?.reason).toBe(ConnectionErrorReason.InternalError);
}
});
});
describe('SignalClient.handleConnectionError', () => {
let signalClient: SignalClient;
beforeEach(() => {
vi.clearAllMocks();
signalClient = new SignalClient(false);
});
it('should return NotAllowed error for 4xx HTTP status', async () => {
(global.fetch as any).mockResolvedValueOnce({
status: 403,
text: async () => 'Forbidden',
});
const handleMethod = (signalClient as any).handleConnectionError;
if (handleMethod) {
const error = new Error('Connection failed');
const result = await handleMethod.call(signalClient, error, 'wss://test.livekit.io/validate');
expect(result).toBeInstanceOf(ConnectionError);
expect(result.reason).toBe(ConnectionErrorReason.NotAllowed);
expect(result.status).toBe(403);
expect(result.message).toBe('Forbidden');
}
});
it('should return ConnectionError as-is if it is already a ConnectionError', async () => {
const connectionError = ConnectionError.internal('Custom error');
(global.fetch as any).mockResolvedValueOnce({
status: 500,
text: async () => 'Internal Server Error',
});
const handleMethod = (signalClient as any).handleConnectionError;
if (handleMethod) {
const result = await handleMethod.call(
signalClient,
connectionError,
'wss://test.livekit.io/validate',
);
expect(result).toBe(connectionError);
expect(result.reason).toBe(ConnectionErrorReason.InternalError);
}
});
it('should return InternalError for non-4xx HTTP status', async () => {
(global.fetch as any).mockResolvedValueOnce({
status: 500,
text: async () => 'Internal Server Error',
});
const handleMethod = (signalClient as any).handleConnectionError;
if (handleMethod) {
const error = new Error('Connection failed');
const result = await handleMethod.call(signalClient, error, 'wss://test.livekit.io/validate');
expect(result).toBeInstanceOf(ConnectionError);
expect(result.reason).toBe(ConnectionErrorReason.InternalError);
}
});
it('should return ServerUnreachable when fetch fails', async () => {
(global.fetch as any).mockRejectedValueOnce(new Error('Network error'));
const handleMethod = (signalClient as any).handleConnectionError;
if (handleMethod) {
const error = new Error('Connection failed');
const result = await handleMethod.call(signalClient, error, 'wss://test.livekit.io/validate');
expect(result).toBeInstanceOf(ConnectionError);
expect(result.reason).toBe(ConnectionErrorReason.ServerUnreachable);
}
});
it('should handle fetch throwing ConnectionError', async () => {
const fetchError = ConnectionError.serverUnreachable('Fetch failed');
(global.fetch as any).mockRejectedValueOnce(fetchError);
const handleMethod = (signalClient as any).handleConnectionError;
if (handleMethod) {
const error = new Error('Connection failed');
const result = await handleMethod.call(signalClient, error, 'wss://test.livekit.io/validate');
expect(result).toBe(fetchError);
}
});
});