-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathindex.ts
More file actions
1758 lines (1603 loc) · 51.9 KB
/
index.ts
File metadata and controls
1758 lines (1603 loc) · 51.9 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
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
CrdtType,
ProtocolMessage,
tryDecode,
MessageType,
JoinResponseOk,
encode,
JoinRequest,
DocUpdate,
JoinError,
DocUpdateFragmentHeader,
DocUpdateFragment,
Ack,
RoomError,
RoomErrorCode,
UpdateStatusCode,
Leave,
JoinErrorCode,
MAX_MESSAGE_SIZE,
bytesToHex,
HexString,
} from "loro-protocol";
import type { CrdtDocAdaptor } from "loro-adaptors";
export * from "loro-adaptors";
export type AuthProvider = () => Uint8Array | Promise<Uint8Array>;
type AuthOption = Uint8Array | AuthProvider;
interface FragmentBatch {
header: DocUpdateFragmentHeader;
fragments: Map<number, Uint8Array>;
timeoutId: ReturnType<typeof setTimeout>;
}
interface PendingRoom {
room: Promise<LoroWebsocketClientRoom>;
resolve: (res: JoinResponseOk) => void;
reject: (error: Error) => void;
adaptor: CrdtDocAdaptor;
roomId: string;
auth?: AuthOption;
isRejoin?: boolean;
}
interface InternalRoomHandler {
handleDocUpdate(updates: Uint8Array[], refId?: HexString): void;
handleAck(ack: Ack): void;
handleRoomError(error: RoomError): void;
}
interface ActiveRoom {
room: LoroWebsocketClientRoom;
handler: InternalRoomHandler;
}
interface SocketListeners {
open: () => void;
error: (event: Event) => void;
close: (event: CloseEvent) => void;
message: (event: MessageEvent<string | ArrayBuffer>) => void;
}
type NodeProcessLike = {
on?: (event: string, listener: () => void) => unknown;
off?: (event: string, listener: () => void) => unknown;
removeListener?: (event: string, listener: () => void) => unknown;
};
function randomBatchId(): HexString {
const bytes = new Uint8Array(8);
crypto.getRandomValues(bytes);
return bytesToHex(bytes);
}
/**
* The websocket client's high-level connection status.
* - `Connecting`: initial connect or a manual `connect()` in progress.
* - `Connected`: the websocket is open and usable.
* - `Disconnected`: the client is not connected. Call `connect()` to retry.
*/
export const ClientStatus = {
Connecting: "connecting",
Connected: "connected",
Disconnected: "disconnected",
} as const;
export type ClientStatusValue =
(typeof ClientStatus)[keyof typeof ClientStatus];
/**
* Options for `LoroWebsocketClient`.
*
* Behavior summary:
* - The client auto-connects on construction and retries on unexpected closures with an exponential backoff.
* - Call `close()` to stop auto-reconnect and move to `Disconnected`. Call `connect()` to resume.
* - Pings are sent periodically to keep the connection alive; `latency` estimates are updated on pong.
*/
export interface LoroWebsocketClientOptions {
/** WebSocket URL (ws:// or wss://). */
url: string;
/** Optional custom ping interval. Defaults to 20s. Set with `disablePing` to stop timers. */
pingIntervalMs?: number;
/** Ping timeout; after two consecutive misses the client will force-close and reconnect. Defaults to 10s. */
pingTimeoutMs?: number;
/** Disable periodic ping/pong entirely. */
disablePing?: boolean;
/** Optional callback for low-level ws close (before status transitions). */
onWsClose?: () => void;
/** Optional callback for any client-level errors (socket error, decode/apply failures, send on closed, etc.). */
onError?: (error: Error) => void;
/**
* Reconnect policy (kept minimal).
* - enabled: toggle auto-retry (default true)
* - initialDelayMs: starting backoff delay (default 500)
* - maxDelayMs: max backoff delay (default 15000)
* - jitter: 0-1 multiplier applied randomly around the delay (default 0.25)
* - maxAttempts: number | "infinite" (default "infinite")
* - fatalCloseCodes: close codes that should not retry (default 4400-4499, 1008, 1011)
* - fatalCloseReasons: close reasons that should not retry (default permission_changed, room_closed, auth_failed)
*/
reconnect?: {
enabled?: boolean;
initialDelayMs?: number;
maxDelayMs?: number;
jitter?: number;
maxAttempts?: number | "infinite";
fatalCloseCodes?: number[];
fatalCloseReasons?: string[];
};
}
export const RoomJoinStatus = {
Connecting: "connecting",
Joined: "joined",
Reconnecting: "reconnecting",
Disconnected: "disconnected",
Error: "error",
} as const;
export type RoomJoinStatusValue =
(typeof RoomJoinStatus)[keyof typeof RoomJoinStatus];
/**
* Loro websocket client with auto-reconnect, connection status events, and latency tracking.
*
* Status model:
* - `Connected`: ws open.
* - `Disconnected`: socket closed. Auto-reconnect retries run unless `close()`/`destroy()` stop them.
* - `Connecting`: initial or manual connect in progress.
*
* Events:
* - `onStatusChange(cb)`: called whenever status changes.
* - `onLatency(cb)`: called when a new RTT estimate is measured from ping/pong.
*/
export class LoroWebsocketClient {
private ws!: WebSocket;
// Invariant: `connectedPromise` always represents the next transition to `Connected`.
// - It resolves exactly once, when the currently active socket fires `open`.
// - It is replaced (via `ensureConnectedPromise`) whenever we start a new connect
// attempt or a reconnect is scheduled, so callers blocking on `waitConnected()`
// will wait for the next successful connection.
// - It rejects only when we deliberately stop reconnecting (`close()` or fatal close).
private connectedPromise!: Promise<void>;
private resolveConnected?: () => void;
private rejectConnected?: (e: Error) => void;
private status: ClientStatusValue = ClientStatus.Connecting;
private statusListeners = new Set<(s: ClientStatusValue) => void>();
private latencyListeners = new Set<(ms: number) => void>();
private lastLatencyMs?: number;
private awaitingPongSince?: number;
private pendingRooms: Map<string, PendingRoom> = new Map();
private activeRooms: Map<string, ActiveRoom> = new Map();
// Buffer for %ELO only: backfills can arrive immediately after JoinResponseOk
private preJoinUpdates: Map<string, Array<{ updates: Uint8Array[]; refId?: HexString }>> = new Map();
// Track outbound update batches so we can surface errors with payload context
private sentUpdateBatches: Map<HexString, { roomKey: string; updates: Uint8Array[] }> = new Map();
private fragmentBatches: Map<string, FragmentBatch> = new Map();
private roomAdaptors: Map<string, CrdtDocAdaptor> = new Map();
// Track roomId for each active id so we can rejoin on reconnect
private roomIds: Map<string, string> = new Map();
private roomAuth: Map<string, AuthOption | undefined> = new Map();
private roomStatusListeners: Map<
string,
Set<(s: RoomJoinStatusValue) => void>
> = new Map();
private socketListeners = new WeakMap<WebSocket, SocketListeners>();
private pingTimer?: ReturnType<typeof setInterval>;
private pingWaiters: Array<{
resolve: () => void;
reject: (err: Error) => void;
timeoutId: ReturnType<typeof setTimeout>;
}> = [];
private missedPongs = 0;
// Reconnect controls
private shouldReconnect = true;
private reconnectAttempts = 0;
private reconnectTimer?: ReturnType<typeof setTimeout>;
private removeNetworkListeners?: () => void;
private offline = false;
// Join requests issued while socket is still connecting
private queuedJoins: Uint8Array[] = [];
constructor(private ops: LoroWebsocketClientOptions) {
this.attachNetworkListeners();
// Start initial connection
this.ensureConnectedPromise();
void this.connect();
}
private async resolveAuth(auth?: AuthOption): Promise<Uint8Array> {
if (typeof auth === "function") {
const value = await auth();
if (!(value instanceof Uint8Array)) {
throw new Error("Auth provider must return Uint8Array");
}
return value;
}
return auth ?? new Uint8Array();
}
get socket(): WebSocket {
return this.ws;
}
private ensureConnectedPromise(): void {
if (this.resolveConnected) return;
this.connectedPromise = new Promise<void>((resolve, reject) => {
this.resolveConnected = () => {
this.resolveConnected = undefined;
this.rejectConnected = undefined;
resolve();
};
this.rejectConnected = (err: Error) => {
this.resolveConnected = undefined;
this.rejectConnected = undefined;
reject(err);
};
});
// prevent unhandled rejection if nobody awaits
void this.connectedPromise.catch(() => { });
}
private attachNetworkListeners(): void {
this.removeNetworkListeners?.();
this.removeNetworkListeners = undefined;
if (
typeof window !== "undefined" &&
typeof window.addEventListener === "function"
) {
window.addEventListener("online", this.handleOnline);
window.addEventListener("offline", this.handleOffline);
this.removeNetworkListeners = () => {
window.removeEventListener("online", this.handleOnline);
window.removeEventListener("offline", this.handleOffline);
};
return;
}
const globalScope = globalThis as typeof globalThis & {
addEventListener?: (
type: string,
listener: EventListenerOrEventListenerObject
) => void;
removeEventListener?: (
type: string,
listener: EventListenerOrEventListenerObject
) => void;
process?: NodeProcessLike;
};
if (typeof globalScope.addEventListener === "function") {
const online = this.handleOnline as EventListener;
const offline = this.handleOffline as EventListener;
globalScope.addEventListener("online", online);
globalScope.addEventListener("offline", offline);
this.removeNetworkListeners = () => {
globalScope.removeEventListener?.("online", online);
globalScope.removeEventListener?.("offline", offline);
};
return;
}
const maybeProcess = globalScope.process;
if (maybeProcess && typeof maybeProcess.on === "function") {
// Node environments may surface online/offline via the global process emitter.
const online = () => {
this.handleOnline();
};
const offline = () => {
this.handleOffline();
};
maybeProcess.on("online", online);
maybeProcess.on("offline", offline);
this.removeNetworkListeners = () => {
if (typeof maybeProcess.off === "function") {
maybeProcess.off("online", online);
maybeProcess.off("offline", offline);
} else if (typeof maybeProcess.removeListener === "function") {
maybeProcess.removeListener("online", online);
maybeProcess.removeListener("offline", offline);
}
};
}
}
/** Current client status. */
getStatus(): ClientStatusValue {
return this.status;
}
/** Latest measured RTT in ms (if any). */
getLatency(): number | undefined {
return this.lastLatencyMs;
}
/** Subscribe to status changes. Returns an unsubscribe function. */
onStatusChange(cb: (s: ClientStatusValue) => void): () => void {
this.statusListeners.add(cb);
// Emit current immediately to inform subscribers
try {
cb(this.status);
} catch (err) {
this.logCbError("onStatusChange", err);
}
return () => this.statusListeners.delete(cb);
}
/** Subscribe to latency updates (RTT via ping/pong). Returns an unsubscribe function. */
onLatency(cb: (ms: number) => void): () => void {
this.latencyListeners.add(cb);
if (this.lastLatencyMs != null) {
try {
cb(this.lastLatencyMs);
} catch (err) {
this.logCbError("onLatency", err);
}
}
return () => this.latencyListeners.delete(cb);
}
private setStatus(s: ClientStatusValue) {
if (this.status === s) return;
this.status = s;
const listeners = Array.from(this.statusListeners);
for (const cb of listeners) {
try {
cb(s);
} catch (err) {
this.logCbError("onStatusChange", err);
}
}
}
/** Initiate or resume connection. Resolves when `Connected`. */
async connect(opts?: { resetBackoff?: boolean }): Promise<void> {
if (opts?.resetBackoff) {
this.reconnectAttempts = 0;
}
// Ensure future unexpected closes will auto-reconnect again
this.shouldReconnect = true;
const current = this.ws;
if (current) {
const state = current.readyState;
if (state === WebSocket.OPEN || state === WebSocket.CONNECTING) {
return this.connectedPromise;
}
}
this.clearReconnectTimer();
// Ensure there's a pending promise for this attempt
this.ensureConnectedPromise();
this.setStatus(ClientStatus.Connecting);
let ws: WebSocket;
try {
ws = new WebSocket(this.ops.url);
} catch (err) {
const error = err instanceof Error ? err : new Error(String(err));
this.rejectConnected?.(error);
this.setStatus(ClientStatus.Disconnected);
throw error;
}
this.ws = ws;
if (current && current !== ws) {
this.detachSocketListeners(current);
}
this.attachSocketListeners(ws);
ws.binaryType = "arraybuffer";
return this.connectedPromise;
}
private attachSocketListeners(ws: WebSocket): void {
const open = () => {
this.onSocketOpen(ws);
};
const error = (event: Event) => {
this.onSocketError(ws, event);
};
const close = (event: CloseEvent) => {
this.onSocketClose(ws, event);
};
const message = (event: MessageEvent<string | ArrayBuffer>) => {
void this.onSocketMessage(ws, event).catch(err => {
this.emitError(err instanceof Error ? err : new Error(String(err)));
});
};
ws.addEventListener("open", open);
ws.addEventListener("error", error);
ws.addEventListener("close", close);
ws.addEventListener("message", message);
this.socketListeners.set(ws, {
open,
error,
close,
message,
});
}
private onSocketOpen(ws: WebSocket): void {
if (ws !== this.ws) {
// TODO: REVIEW stale sockets bail early so they can't tear down the new connection
this.detachSocketListeners(ws);
try {
ws.close(1000, "Superseded");
} catch { }
return;
}
this.clearReconnectTimer();
this.reconnectAttempts = 0;
this.setStatus(ClientStatus.Connected);
this.startPingTimer();
this.resolveConnected?.();
// Rejoin rooms after reconnect
this.rejoinActiveRooms();
// Flush any queued joins that were requested while connecting
this.flushQueuedJoins();
}
private onSocketError(ws: WebSocket, _event: Event): void {
if (ws !== this.ws) {
this.detachSocketListeners(ws);
}
this.emitError(new Error("WebSocket error"));
// Leave further handling to the close event for the active socket
}
private onSocketClose(ws: WebSocket, event?: CloseEvent): void {
const isCurrent = ws === this.ws;
this.detachSocketListeners(ws);
if (!isCurrent) {
return;
}
const closeCode = event?.code;
const closeReason = event?.reason;
if (this.isFatalClose(closeCode, closeReason)) {
this.shouldReconnect = false;
}
this.clearPingTimer();
this.missedPongs = 0;
// Clear any pending fragment reassembly timers to avoid late callbacks
if (this.fragmentBatches.size) {
for (const [, batch] of this.fragmentBatches) {
clearTimeout(batch.timeoutId);
}
this.fragmentBatches.clear();
}
// Drop any unacked outbound batches to avoid leaking memory across reconnects
if (this.sentUpdateBatches.size) {
this.sentUpdateBatches.clear();
}
// Reset any in-flight RTT probe to allow future pings after reconnect
this.awaitingPongSince = undefined;
this.ops.onWsClose?.();
this.rejectAllPingWaiters(new Error("WebSocket closed"));
const maxAttempts = this.getReconnectPolicy().maxAttempts;
if (
typeof maxAttempts === "number" &&
maxAttempts > 0 &&
this.reconnectAttempts >= maxAttempts
) {
this.shouldReconnect = false;
}
// Update room-level status based on whether we will retry
for (const [id] of this.activeRooms) {
if (this.shouldReconnect) {
this.emitRoomStatus(id, RoomJoinStatus.Reconnecting);
} else {
this.emitRoomStatus(id, RoomJoinStatus.Disconnected);
}
}
if (!this.shouldReconnect) {
this.setStatus(ClientStatus.Disconnected);
this.rejectConnected?.(new Error("Disconnected"));
// Fail all pending joins and mark rooms disconnected/error
const err = new Error(
closeReason ? `Disconnected: ${closeReason}` : "Disconnected"
);
this.failAllPendingRooms(err, this.shouldReconnect ? RoomJoinStatus.Reconnecting : RoomJoinStatus.Disconnected);
return;
}
// Renew the promise so callers waiting on waitConnected() block until the next successful reconnect.
this.ensureConnectedPromise();
// Start (or continue) exponential backoff retries
this.setStatus(ClientStatus.Disconnected);
this.scheduleReconnect();
}
private async onSocketMessage(
ws: WebSocket,
event: MessageEvent<string | ArrayBuffer>
): Promise<void> {
if (ws !== this.ws) {
return;
}
try {
if (typeof event.data === "string") {
if (event.data === "ping") {
this.safeSend(ws, "pong", "pong");
return;
}
if (event.data === "pong") {
this.handlePong();
return;
}
return; // ignore other texts
}
const dataU8 = new Uint8Array(event.data);
const msg = tryDecode(dataU8);
if (msg != null) await this.handleMessage(msg);
} catch (err) {
this.emitError(err instanceof Error ? err : new Error(String(err)));
}
}
private scheduleReconnect(immediate = false) {
if (this.reconnectTimer) return;
if (this.offline) return;
const policy = this.getReconnectPolicy();
if (!policy.enabled) return;
const attempt = ++this.reconnectAttempts;
const delay = immediate ? 0 : this.computeBackoffDelay(attempt);
this.reconnectTimer = setTimeout(() => {
this.reconnectTimer = undefined;
void this.connect();
}, delay);
}
private clearReconnectTimer() {
if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
this.reconnectTimer = undefined;
}
private handleOnline = () => {
this.offline = false;
if (!this.shouldReconnect) return;
if (this.status === ClientStatus.Connected) return;
this.clearReconnectTimer();
this.scheduleReconnect(true);
};
private handleOffline = () => {
this.offline = true;
// Pause scheduled retries until online
this.clearReconnectTimer();
if (this.shouldReconnect) {
this.setStatus(ClientStatus.Disconnected);
try {
this.ws?.close(1001, "Offline");
} catch { }
}
};
// Re-send JoinRequest for all active rooms after reconnect
private rejoinActiveRooms() {
for (const [id, adaptor] of this.roomAdaptors) {
const roomId = this.roomIds.get(id);
if (!roomId) continue;
const active = this.activeRooms.get(id);
if (!active) continue;
void this.sendRejoinRequest(id, roomId, adaptor, active.room, this.roomAuth.get(id));
}
}
private async sendRejoinRequest(
id: string,
roomId: string,
adaptor: CrdtDocAdaptor,
room: LoroWebsocketClientRoom,
auth?: AuthOption
) {
let authValue: Uint8Array;
try {
authValue = await this.resolveAuth(auth);
} catch (e) {
console.error("Failed to resolve auth for rejoin:", e);
this.cleanupRoom(roomId, adaptor.crdtType);
this.emitRoomStatus(id, RoomJoinStatus.Error);
return;
}
// Prepare a lightweight pending entry so JoinError handling can retry version formats
const pending: PendingRoom = {
room: Promise.resolve(room),
resolve: (res: JoinResponseOk) => {
adaptor
.handleJoinOk(res)
.catch(e => {
console.error(e);
})
.finally(() => {
this.pendingRooms.delete(id);
this.emitRoomStatus(id, RoomJoinStatus.Joined);
});
},
reject: (error: Error) => {
console.error("Rejoin failed:", error);
this.pendingRooms.delete(id);
this.cleanupRoom(roomId, adaptor.crdtType);
this.emitRoomStatus(id, RoomJoinStatus.Error);
},
adaptor,
roomId,
auth,
isRejoin: true,
};
this.pendingRooms.set(id, pending);
const payload = encode({
type: MessageType.JoinRequest,
crdt: adaptor.crdtType,
roomId,
auth: authValue,
version: adaptor.getVersion(),
} as JoinRequest);
try {
this.sendJoinPayload(payload);
this.emitRoomStatus(id, RoomJoinStatus.Reconnecting);
} catch (e) {
console.error("Failed to send rejoin request:", e);
this.cleanupRoom(roomId, adaptor.crdtType);
this.emitRoomStatus(id, RoomJoinStatus.Error);
}
}
private async handleMessage(msg: ProtocolMessage) {
const roomIdStr = msg.roomId;
const roomId = msg.crdt + roomIdStr;
switch (msg.type) {
case MessageType.JoinRequest: {
throw new Error("JoinRequest should not be received by client");
}
case MessageType.JoinResponseOk: {
const pending = this.pendingRooms.get(roomId);
if (pending) {
pending.resolve(msg);
}
break;
}
case MessageType.JoinError: {
const pending = this.pendingRooms.get(roomId);
if (pending) {
await this.handleJoinError(msg, pending, roomId);
}
break;
}
case MessageType.DocUpdate: {
const active = this.activeRooms.get(roomId);
if (active) {
active.handler.handleDocUpdate(msg.updates, msg.batchId);
} else {
const pending = this.pendingRooms.get(roomId);
if (pending) {
const buf = this.preJoinUpdates.get(roomId) ?? [];
buf.push({ updates: msg.updates, refId: msg.batchId });
this.preJoinUpdates.set(roomId, buf);
}
}
break;
}
case MessageType.DocUpdateFragmentHeader: {
this.handleFragmentHeader(msg);
break;
}
case MessageType.DocUpdateFragment: {
this.handleFragment(msg);
break;
}
case MessageType.RoomError: {
const active = this.activeRooms.get(roomId);
const adaptor = this.roomAdaptors.get(roomId);
const auth = this.roomAuth.get(roomId);
const shouldRejoin = msg.code === RoomErrorCode.RejoinSuggested;
if (active) {
active.handler.handleRoomError(msg);
}
// Drop any in-flight join since the server explicitly removed us
this.pendingRooms.delete(roomId);
if (shouldRejoin && active && adaptor) {
void this.sendRejoinRequest(roomId, msg.roomId, adaptor, active.room, auth);
} else {
// Remove local room state so client does not auto-retry unless requested
this.cleanupRoom(msg.roomId, msg.crdt);
this.emitRoomStatus(roomId, RoomJoinStatus.Error);
}
break;
}
case MessageType.Ack: {
const active = this.activeRooms.get(roomId);
if (active) {
active.handler.handleAck(msg);
}
break;
}
}
}
private handleFragmentHeader(msg: DocUpdateFragmentHeader) {
const roomIdStr = msg.roomId;
const batchKey = `${msg.crdt}-${roomIdStr}-${msg.batchId}`;
// Clear any existing batch with same ID
const existing = this.fragmentBatches.get(batchKey);
if (existing) {
clearTimeout(existing.timeoutId);
}
// Set up timeout (10 seconds default)
const timeoutId = setTimeout(() => {
this.fragmentBatches.delete(batchKey);
// Notify server to prompt resend
try {
const payload = encode({
type: MessageType.Ack,
crdt: msg.crdt,
roomId: msg.roomId,
refId: msg.batchId,
status: UpdateStatusCode.FragmentTimeout,
} as Ack);
this.safeSend(this.ws, payload, "fragment-timeout-ack");
} catch { }
}, 10000);
this.fragmentBatches.set(batchKey, {
header: msg,
fragments: new Map(),
timeoutId,
});
}
private handleFragment(msg: DocUpdateFragment) {
const roomIdStr = msg.roomId;
const batchKey = `${msg.crdt}-${roomIdStr}-${msg.batchId}`;
const batch = this.fragmentBatches.get(batchKey);
if (!batch) {
console.error(`Received fragment for unknown batch ${msg.batchId}`);
return;
}
batch.fragments.set(msg.index, msg.fragment);
// Check if all fragments received
if (batch.fragments.size === batch.header.fragmentCount) {
clearTimeout(batch.timeoutId);
this.fragmentBatches.delete(batchKey);
// Reassemble fragments
const reassembledData = new Uint8Array(batch.header.totalSizeBytes);
let offset = 0;
// Reassemble in order
for (let i = 0; i < batch.header.fragmentCount; i++) {
const fragment = batch.fragments.get(i);
if (!fragment) {
console.error(`Missing fragment ${i} in batch ${msg.batchId}`);
return;
}
reassembledData.set(fragment, offset);
offset += fragment.length;
}
// Deliver to room
const id = msg.crdt + roomIdStr;
const active = this.activeRooms.get(id);
if (active) {
// Treat reassembled data as a single update
active.handler.handleDocUpdate([reassembledData], batch.header.batchId);
} else {
const pending = this.pendingRooms.get(id);
if (pending) {
const buf = this.preJoinUpdates.get(id) ?? [];
buf.push({ updates: [reassembledData], refId: batch.header.batchId });
this.preJoinUpdates.set(id, buf);
}
}
}
}
private registerActiveRoom(
roomId: string,
crdtType: CrdtType,
room: LoroWebsocketClientRoom,
handler: InternalRoomHandler,
adaptor: CrdtDocAdaptor
) {
const id = crdtType + roomId;
this.activeRooms.set(id, { room, handler });
this.roomAdaptors.set(id, adaptor);
this.roomIds.set(id, roomId);
// Flush buffered updates if any
const buf = this.preJoinUpdates.get(id);
if (buf && buf.length) {
try {
for (const entry of buf) {
handler.handleDocUpdate(entry.updates, entry.refId);
}
} finally {
this.preJoinUpdates.delete(id);
}
}
this.pendingRooms.delete(id);
this.emitRoomStatus(id, RoomJoinStatus.Joined);
}
private async handleJoinError(
msg: JoinError,
pending: PendingRoom,
roomId: string
) {
if (msg.code === JoinErrorCode.VersionUnknown) {
let authValue: Uint8Array;
try {
authValue = await this.resolveAuth(pending.auth);
} catch (e) {
pending.reject(e as Error);
this.pendingRooms.delete(roomId);
this.emitRoomStatus(
pending.adaptor.crdtType + pending.roomId,
RoomJoinStatus.Error
);
return;
}
// Try alternative version format
const currentVersion = pending.adaptor.getVersion();
const alternativeVersion =
pending.adaptor.getAlternativeVersion?.(currentVersion);
if (alternativeVersion) {
// Retry with alternative version format
const payload = encode({
type: MessageType.JoinRequest,
crdt: pending.adaptor.crdtType,
roomId: pending.roomId,
auth: authValue,
version: alternativeVersion,
} as JoinRequest);
this.sendJoinPayload(payload);
return;
} else {
console.warn("Version unknown. Now join with an empty version");
const payload = encode({
type: MessageType.JoinRequest,
crdt: pending.adaptor.crdtType,
roomId: pending.roomId,
auth: authValue,
version: new Uint8Array(),
} as JoinRequest);
this.sendJoinPayload(payload);
return;
}
}
// No retry possible, reject the promise
const err = new Error(`Join failed: ${msg.code} - ${msg.message}`);
this.emitRoomStatus(
pending.adaptor.crdtType + pending.roomId,
RoomJoinStatus.Error
);
// Remove active room references so caller can rejoin manually if this was a rejoin
if (pending.isRejoin) {
this.cleanupRoom(pending.roomId, pending.adaptor.crdtType);
}
pending.reject(err);
this.pendingRooms.delete(roomId);
}
cleanupRoom(roomId: string, crdtType: CrdtType) {
const id = crdtType + roomId;
this.purgeSentBatchesForRoom(id);
this.activeRooms.delete(id);
this.pendingRooms.delete(id);
this.roomAdaptors.delete(id);
this.roomIds.delete(id);
this.roomAuth.delete(id);
this.roomStatusListeners.delete(id);
}
waitConnected() {
return this.connectedPromise;
}
// Send an application-level ping and resolve on matching pong
async ping(timeoutMs: number = 5000): Promise<void> {
// Ensure connection
await this.connectedPromise;
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
throw new Error("WebSocket is not open");
}
return new Promise<void>((resolve, reject) => {
const timeoutId = setTimeout(
() => {
reject(new Error("Ping timeout"));
},
Math.max(1, timeoutMs)
);
const waiter = {
resolve: () => {
clearTimeout(timeoutId);
resolve();
},
reject: (err: Error) => {
clearTimeout(timeoutId);
reject(err);
},
timeoutId,
};
// If there's already a pending ping, just wait for the pong
if (this.awaitingPongSince != null) {
this.pingWaiters.push(waiter);
return;
}
// Try to send ping; if it fails, reject immediately instead of waiting for timeout
const sent = this.safeSend(this.ws, "ping", "ping");
if (!sent) {
clearTimeout(timeoutId);
reject(new Error("Failed to send ping: WebSocket not open"));
return;
}
this.awaitingPongSince = Date.now();
this.pingWaiters.push(waiter);
});
}
/**
* Join a room.
* - `auth` may be a `Uint8Array` or a provider function.
* - The provider is invoked on the initial join and again on protocol-driven retries
* (e.g. `VersionUnknown`) and reconnect rejoins, so it can refresh short-lived tokens.
* If callers need a stable token, memoize in the provider.
*/
join({
roomId,
crdtAdaptor,
auth,
onStatusChange,
}: {
roomId: string;
crdtAdaptor: CrdtDocAdaptor;
auth?: AuthOption;
onStatusChange?: (s: RoomJoinStatusValue) => void;
}): Promise<LoroWebsocketClientRoom> {
const id = crdtAdaptor.crdtType + roomId;
// Check if already joining or joined
const pending = this.pendingRooms.get(id);
if (pending) {
return pending.room;
}
const active = this.activeRooms.get(id);
if (active) {
return Promise.resolve(active.room);
}
let resolve!: (res: JoinResponseOk) => void;