@tldraw/sync-core 5.5.0-next.9352f6ad229c → 5.5.0-next.9ceb52b8a830

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/dist-cjs/index.d.ts +7 -2
  2. package/dist-cjs/index.js +1 -1
  3. package/dist-cjs/lib/ClientWebSocketAdapter.js +23 -7
  4. package/dist-cjs/lib/ClientWebSocketAdapter.js.map +2 -2
  5. package/dist-cjs/lib/InMemorySyncStorage.js +18 -18
  6. package/dist-cjs/lib/InMemorySyncStorage.js.map +2 -2
  7. package/dist-cjs/lib/TLSocketRoom.js +5 -1
  8. package/dist-cjs/lib/TLSocketRoom.js.map +2 -2
  9. package/dist-cjs/lib/TLSyncClient.js +3 -1
  10. package/dist-cjs/lib/TLSyncClient.js.map +2 -2
  11. package/dist-cjs/lib/TLSyncRoom.js +22 -3
  12. package/dist-cjs/lib/TLSyncRoom.js.map +2 -2
  13. package/dist-cjs/lib/chunk.js +25 -2
  14. package/dist-cjs/lib/chunk.js.map +2 -2
  15. package/dist-esm/index.d.mts +7 -2
  16. package/dist-esm/index.mjs +1 -1
  17. package/dist-esm/lib/ClientWebSocketAdapter.mjs +24 -8
  18. package/dist-esm/lib/ClientWebSocketAdapter.mjs.map +2 -2
  19. package/dist-esm/lib/InMemorySyncStorage.mjs +18 -18
  20. package/dist-esm/lib/InMemorySyncStorage.mjs.map +2 -2
  21. package/dist-esm/lib/TLSocketRoom.mjs +6 -2
  22. package/dist-esm/lib/TLSocketRoom.mjs.map +2 -2
  23. package/dist-esm/lib/TLSyncClient.mjs +3 -1
  24. package/dist-esm/lib/TLSyncClient.mjs.map +2 -2
  25. package/dist-esm/lib/TLSyncRoom.mjs +22 -3
  26. package/dist-esm/lib/TLSyncRoom.mjs.map +2 -2
  27. package/dist-esm/lib/chunk.mjs +25 -2
  28. package/dist-esm/lib/chunk.mjs.map +2 -2
  29. package/package.json +11 -7
  30. package/src/lib/ClientWebSocketAdapter.test.ts +104 -19
  31. package/src/lib/ClientWebSocketAdapter.ts +33 -10
  32. package/src/lib/InMemorySyncStorage.test.ts +21 -0
  33. package/src/lib/InMemorySyncStorage.ts +20 -22
  34. package/src/lib/TLSocketRoom.ts +8 -2
  35. package/src/lib/TLSyncClient.ts +2 -0
  36. package/src/lib/TLSyncRoom.ts +32 -3
  37. package/src/lib/chunk.test.ts +54 -1
  38. package/src/lib/chunk.ts +46 -2
  39. package/src/test/TLSocketRoom.test.ts +24 -0
  40. package/src/test/TLSyncRoom.test.ts +71 -0
@@ -12,6 +12,7 @@ vi.mock('@tldraw/utils', async (importOriginal) => {
12
12
  // NOTE: setupVitest.js replaces the global WebSocket with the 'ws' package's WebSocket,
13
13
  // matching the WebSocketServer the tests connect to.
14
14
  import { WebSocketServer, WebSocket as WsWebSocket } from 'ws'
15
+ import { MAX_ASSEMBLED_MESSAGE_CHARS } from './chunk'
15
16
  import {
16
17
  ACTIVE_MAX_DELAY,
17
18
  ACTIVE_MIN_DELAY,
@@ -73,24 +74,38 @@ describe('ClientWebSocketAdapter', () => {
73
74
  connectedServerSocket = socket
74
75
  })
75
76
 
77
+ // Bound per test on an OS-assigned port. A fixed port raced against the previous test's
78
+ // server, which closes asynchronously, and intermittently failed with EADDRINUSE.
79
+ let port: number
80
+
76
81
  let consoleWarnSpy: ReturnType<typeof vi.spyOn>
77
- beforeEach(() => {
82
+ beforeEach(async () => {
78
83
  consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
79
- adapter = new ClientWebSocketAdapter(() => 'ws://localhost:2233')
80
- wsServer = new WebSocketServer({ port: 2233 })
84
+ wsServer = new WebSocketServer({ port: 0 })
85
+ // Attach before the adapter exists: the server is already listening by the time the
86
+ // adapter is constructed, so a handler added afterwards can miss the first connection.
81
87
  wsServer.on('connection', connectMock as any)
88
+ await new Promise<void>((resolve, reject) => {
89
+ wsServer.once('listening', resolve)
90
+ wsServer.once('error', reject)
91
+ })
92
+ port = (wsServer.address() as { port: number }).port
93
+ adapter = new ClientWebSocketAdapter(() => `ws://localhost:${port}`)
82
94
  })
83
95
 
84
96
  afterEach(() => {
85
97
  consoleWarnSpy.mockRestore()
86
98
  adapter.close()
99
+ // Not awaited: the next test binds its own OS-assigned port, so a server still closing
100
+ // here can't collide with it. Awaiting would deliver in-flight messages to the socket
101
+ // adapter.close() just orphaned.
87
102
  wsServer.close()
88
103
  connectMock.mockClear()
89
104
  })
90
105
 
91
106
  describe('connection and initial state (CW1, CW2)', () => {
92
107
  it('[CW2] starts with connectionStatus offline while the internal status is initial', () => {
93
- const newAdapter = new ClientWebSocketAdapter(() => 'ws://localhost:2233')
108
+ const newAdapter = new ClientWebSocketAdapter(() => `ws://localhost:${port}`)
94
109
  try {
95
110
  expect(newAdapter._connectionStatus.get()).toBe('initial')
96
111
  expect(newAdapter.connectionStatus).toBe('offline')
@@ -113,7 +128,7 @@ describe('ClientWebSocketAdapter', () => {
113
128
  let uriCallCount = 0
114
129
  const dynamicAdapter = new ClientWebSocketAdapter(() => {
115
130
  uriCallCount++
116
- return `ws://localhost:2233?attempt=${uriCallCount}`
131
+ return `ws://localhost:${port}?attempt=${uriCallCount}`
117
132
  })
118
133
  try {
119
134
  await waitFor(() => dynamicAdapter._ws?.readyState === WebSocket.OPEN)
@@ -143,7 +158,7 @@ describe('ClientWebSocketAdapter', () => {
143
158
  // no socket can be created until the promise resolves
144
159
  expect(asyncAdapter._ws).toBeNull()
145
160
 
146
- resolveUri!('ws://localhost:2233')
161
+ resolveUri!(`ws://localhost:${port}`)
147
162
 
148
163
  await waitFor(() => asyncAdapter._ws?.readyState === WebSocket.OPEN)
149
164
  expect(asyncAdapter.connectionStatus).toBe('online')
@@ -301,7 +316,7 @@ describe('ClientWebSocketAdapter', () => {
301
316
 
302
317
  describe('URI conversion (CW1)', () => {
303
318
  it('[CW1] converts http URIs to ws and connects', async () => {
304
- const httpAdapter = new ClientWebSocketAdapter(() => 'http://localhost:2233')
319
+ const httpAdapter = new ClientWebSocketAdapter(() => `http://localhost:${port}`)
305
320
  try {
306
321
  await waitFor(() => httpAdapter._ws?.readyState === WebSocket.OPEN)
307
322
  expect(httpAdapter._ws!.url).toMatch(/^ws:\/\//)
@@ -312,7 +327,7 @@ describe('ClientWebSocketAdapter', () => {
312
327
  })
313
328
 
314
329
  it('[CW1] converts https URIs to wss', async () => {
315
- const httpsAdapter = new ClientWebSocketAdapter(() => 'https://localhost:2233')
330
+ const httpsAdapter = new ClientWebSocketAdapter(() => `https://localhost:${port}`)
316
331
  try {
317
332
  await waitFor(() => httpsAdapter._ws !== null)
318
333
  expect(httpsAdapter._ws!.url).toMatch(/^wss:\/\//)
@@ -386,6 +401,32 @@ describe('ClientWebSocketAdapter', () => {
386
401
  )
387
402
  })
388
403
 
404
+ it('[CW6] refuses to send a message the server would reject as too large', async () => {
405
+ const onMessage = vi.fn()
406
+ connectMock.mockImplementationOnce((ws: any) => {
407
+ ws.on('message', onMessage)
408
+ })
409
+ await waitFor(() => adapter._ws?.readyState === WebSocket.OPEN)
410
+
411
+ const onStatusChange = vi.fn()
412
+ adapter.onStatusChange(onStatusChange)
413
+
414
+ const message = {
415
+ ...connectMessage(),
416
+ largeData: 'x'.repeat(MAX_ASSEMBLED_MESSAGE_CHARS),
417
+ } as any
418
+ adapter.sendMessage(message)
419
+
420
+ // nothing goes on the wire: sending would only earn a close and a reconnect that
421
+ // re-sends the same message
422
+ expect(onMessage).not.toHaveBeenCalled()
423
+ expect(adapter.connectionStatus).toBe('error')
424
+ expect(onStatusChange).toHaveBeenCalledWith({
425
+ status: 'error',
426
+ reason: TLSyncErrorCloseEventReason.MESSAGE_TOO_LARGE,
427
+ })
428
+ })
429
+
389
430
  it('[CW6] silently drops the message when there is no socket', async () => {
390
431
  await waitFor(() => adapter._ws?.readyState === WebSocket.OPEN)
391
432
 
@@ -529,7 +570,7 @@ describe('ClientWebSocketAdapter', () => {
529
570
  })
530
571
 
531
572
  it('[CW9][RM5] closing immediately does not start another getUri call', async () => {
532
- const getUri = vi.fn(() => 'ws://localhost:2233')
573
+ const getUri = vi.fn(() => `ws://localhost:${port}`)
533
574
  const testAdapter = new ClientWebSocketAdapter(getUri)
534
575
  testAdapter.close()
535
576
  const callsAtClose = getUri.mock.calls.length
@@ -544,7 +585,7 @@ describe('ClientWebSocketAdapter', () => {
544
585
  let uriCallCount = 0
545
586
  const testAdapter = new ClientWebSocketAdapter(() => {
546
587
  uriCallCount++
547
- return 'ws://localhost:2233'
588
+ return `ws://localhost:${port}`
548
589
  })
549
590
  const onStatusChange = vi.fn()
550
591
  testAdapter.onStatusChange(onStatusChange)
@@ -606,17 +647,26 @@ describe('ReconnectManager', () => {
606
647
  connectedServerSocket = socket
607
648
  })
608
649
 
650
+ // See the note on the other suite's port: bound per test on an OS-assigned port.
651
+ let port: number
652
+
609
653
  let consoleWarnSpy: ReturnType<typeof vi.spyOn>
610
- beforeEach(() => {
654
+ beforeEach(async () => {
611
655
  consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
612
- adapter = new ClientWebSocketAdapter(() => 'ws://localhost:2234')
613
- wsServer = new WebSocketServer({ port: 2234 })
656
+ wsServer = new WebSocketServer({ port: 0 })
614
657
  wsServer.on('connection', connectMock as any)
658
+ await new Promise<void>((resolve, reject) => {
659
+ wsServer.once('listening', resolve)
660
+ wsServer.once('error', reject)
661
+ })
662
+ port = (wsServer.address() as { port: number }).port
663
+ adapter = new ClientWebSocketAdapter(() => `ws://localhost:${port}`)
615
664
  })
616
665
 
617
666
  afterEach(() => {
618
667
  consoleWarnSpy.mockRestore()
619
668
  adapter.close()
669
+ // Not awaited - see the note on the other suite's teardown.
620
670
  wsServer.close()
621
671
  connectMock.mockClear()
622
672
  })
@@ -631,7 +681,7 @@ describe('ReconnectManager', () => {
631
681
  })
632
682
 
633
683
  it('[RM1] reconnection delays back off exponentially, bounded by the active delays', () => {
634
- const testAdapter = new ClientWebSocketAdapter(() => 'ws://localhost:2234')
684
+ const testAdapter = new ClientWebSocketAdapter(() => `ws://localhost:${port}`)
635
685
  try {
636
686
  const manager = testAdapter._reconnectManager
637
687
  // make every disconnected() call take the "attempt now" branch
@@ -656,7 +706,7 @@ describe('ReconnectManager', () => {
656
706
 
657
707
  it('[RM1] uses the inactive delay bounds when the tab is hidden', () => {
658
708
  const hiddenMock = vi.spyOn(document, 'hidden', 'get').mockReturnValue(true)
659
- const testAdapter = new ClientWebSocketAdapter(() => 'ws://localhost:2234')
709
+ const testAdapter = new ClientWebSocketAdapter(() => `ws://localhost:${port}`)
660
710
  try {
661
711
  const manager = testAdapter._reconnectManager
662
712
  ;(manager as any).lastAttemptStart = Date.now() - 1_000_000
@@ -828,7 +878,7 @@ describe('ReconnectManager', () => {
828
878
  if (failure === 'throws') throw error
829
879
  return Promise.reject(error)
830
880
  }
831
- return 'ws://localhost:2234'
881
+ return `ws://localhost:${port}`
832
882
  })
833
883
  try {
834
884
  await waitFor(() => testAdapter._ws?.readyState === WebSocket.OPEN)
@@ -843,7 +893,7 @@ describe('ReconnectManager', () => {
843
893
  )
844
894
 
845
895
  it('[RM5] close cancels timers and removes the reconnect event listeners', () => {
846
- const testAdapter = new ClientWebSocketAdapter(() => 'ws://localhost:2234')
896
+ const testAdapter = new ClientWebSocketAdapter(() => `ws://localhost:${port}`)
847
897
  const manager = testAdapter._reconnectManager
848
898
 
849
899
  testAdapter.close()
@@ -859,9 +909,44 @@ describe('ReconnectManager', () => {
859
909
  // closing again is safe
860
910
  expect(() => manager.close()).not.toThrow()
861
911
  })
912
+
913
+ it('[RM4] reconnect hints and the disconnect handler survive an undefined WebSocket global', async () => {
914
+ // Regression test for the undefined-WebSocket crash guarded in ClientWebSocketAdapter.ts (#10106).
915
+ await waitFor(() => adapter._ws?.readyState === WebSocket.OPEN)
916
+ const manager = adapter._reconnectManager
917
+ // jsdom reports a throwing event listener on window instead of from dispatchEvent
918
+ const listenerErrors: unknown[] = []
919
+ const onError = (event: ErrorEvent) => {
920
+ event.preventDefault()
921
+ listenerErrors.push(event.error)
922
+ }
923
+ window.addEventListener('error', onError)
924
+ const originalWebSocket = globalThis.WebSocket
925
+ try {
926
+ ;(globalThis as any).WebSocket = undefined
927
+
928
+ window.dispatchEvent(new Event('online'))
929
+ expect(() => manager.maybeReconnected()).not.toThrow()
930
+ expect(() => manager.connected()).not.toThrow()
931
+ expect(adapter.connectionStatus).toBe('online')
932
+
933
+ window.dispatchEvent(new Event('offline'))
934
+ expect(() => manager.disconnected()).not.toThrow()
935
+ expect(listenerErrors).toEqual([])
936
+ expect(adapter.connectionStatus).toBe('offline')
937
+ expect(adapter._ws).toBeNull()
938
+ } finally {
939
+ globalThis.WebSocket = originalWebSocket
940
+ window.removeEventListener('error', onError)
941
+ }
942
+ })
862
943
  })
863
944
 
864
945
  describe('URI failure boundaries', () => {
946
+ // These tests never open a real socket - the adapter is closed first, or the socket is a
947
+ // mock - so the URI only has to parse. No server, hence no port to bind.
948
+ const UNUSED_URI = 'ws://localhost:1'
949
+
865
950
  it.each(['resolves', 'rejects'])('ignores getUri that %s after close', async (outcome) => {
866
951
  const uri = promiseWithResolve<string>()
867
952
  const getUri = vi.fn(() => uri)
@@ -872,7 +957,7 @@ describe('URI failure boundaries', () => {
872
957
  try {
873
958
  await Promise.resolve()
874
959
  testAdapter.close()
875
- if (outcome === 'resolves') uri.resolve('ws://localhost:2234')
960
+ if (outcome === 'resolves') uri.resolve(UNUSED_URI)
876
961
  else uri.reject(new Error('token endpoint unavailable'))
877
962
  await vi.advanceTimersByTimeAsync(INACTIVE_MAX_DELAY)
878
963
 
@@ -890,7 +975,7 @@ describe('URI failure boundaries', () => {
890
975
  it.each([
891
976
  { uri: 'not a URL', openSocket: false, error: 'Invalid URL' },
892
977
  {
893
- uri: 'ws://localhost:2234',
978
+ uri: UNUSED_URI,
894
979
  openSocket: true,
895
980
  error: 'There should be no connection attempts while already connected',
896
981
  },
@@ -1,7 +1,7 @@
1
1
  import { atom, Atom } from '@tldraw/state'
2
2
  import { TLRecord } from '@tldraw/tlschema'
3
3
  import { assert, warnOnce } from '@tldraw/utils'
4
- import { chunk } from './chunk'
4
+ import { chunk, MAX_ASSEMBLED_MESSAGE_CHARS } from './chunk'
5
5
  import { TLSocketClientSentEvent, TLSocketServerSentEvent } from './protocol'
6
6
  import {
7
7
  TLPersistentClientSocket,
@@ -11,6 +11,16 @@ import {
11
11
  TLSyncErrorCloseEventReason,
12
12
  } from './TLSyncClient'
13
13
 
14
+ // The ready states from the WebSocket spec, kept local instead of read off the global
15
+ // constructor: an extension or page teardown can leave `WebSocket` undefined by the time a
16
+ // window `online` or close handler fires, and `WebSocket.OPEN` then throws (#10106).
17
+ const ReadyState = {
18
+ CONNECTING: 0,
19
+ OPEN: 1,
20
+ CLOSING: 2,
21
+ CLOSED: 3,
22
+ } as const
23
+
14
24
  function listenTo<T extends EventTarget>(target: T, event: string, handler: () => void) {
15
25
  target.addEventListener(event, handler)
16
26
  return () => {
@@ -176,8 +186,8 @@ export class ClientWebSocketAdapter implements TLPersistentClientSocket<
176
186
  assert(!this.isDisposed, 'Tried to set a new websocket on a disposed socket')
177
187
  assert(
178
188
  this._ws === null ||
179
- this._ws.readyState === WebSocket.CLOSED ||
180
- this._ws.readyState === WebSocket.CLOSING,
189
+ this._ws.readyState === ReadyState.CLOSED ||
190
+ this._ws.readyState === ReadyState.CLOSING,
181
191
  `Tried to set a new websocket in when the existing one was ${this._ws?.readyState}`
182
192
  )
183
193
 
@@ -280,7 +290,20 @@ export class ClientWebSocketAdapter implements TLPersistentClientSocket<
280
290
 
281
291
  if (!this._ws) return
282
292
  if (this.connectionStatus === 'online') {
283
- const chunks = chunk(JSON.stringify(msg))
293
+ const stringified = JSON.stringify(msg)
294
+ // The server rejects a session whose assembled message exceeds this, so sending would
295
+ // only earn a close and a reconnect that re-sends the same message. Fail here the way
296
+ // the server would, so onSyncError runs once instead of the client looping forever.
297
+ if (stringified.length > MAX_ASSEMBLED_MESSAGE_CHARS) {
298
+ this._handleDisconnect(
299
+ 'closed',
300
+ TLSyncErrorCloseEventCode,
301
+ true,
302
+ TLSyncErrorCloseEventReason.MESSAGE_TOO_LARGE
303
+ )
304
+ return
305
+ }
306
+ const chunks = chunk(stringified)
284
307
  for (const part of chunks) {
285
308
  this._ws.send(part)
286
309
  }
@@ -536,7 +559,7 @@ export class ReconnectManager {
536
559
  // this can happen if the promise gets resolved too late
537
560
  if (this.state !== 'pendingAttempt' || this.isDisposed) return
538
561
  assert(
539
- this.socketAdapter._ws?.readyState !== WebSocket.OPEN,
562
+ this.socketAdapter._ws?.readyState !== ReadyState.OPEN,
540
563
  'There should be no connection attempts while already connected'
541
564
  )
542
565
 
@@ -590,13 +613,13 @@ export class ReconnectManager {
590
613
  this.clearRecheckConnectingTimeout()
591
614
 
592
615
  // readyState can be CONNECTING, OPEN, CLOSING, CLOSED, or null (if getUri() is still pending)
593
- if (this.socketAdapter._ws?.readyState === WebSocket.OPEN) {
616
+ if (this.socketAdapter._ws?.readyState === ReadyState.OPEN) {
594
617
  debug('ReconnectManager.maybeReconnected: already connected')
595
618
  // nothing to do, we're already OK
596
619
  return
597
620
  }
598
621
 
599
- if (this.socketAdapter._ws?.readyState === WebSocket.CONNECTING) {
622
+ if (this.socketAdapter._ws?.readyState === ReadyState.CONNECTING) {
600
623
  debug('ReconnectManager.maybeReconnected: connecting')
601
624
  // We might be waiting for a TCP connection that sent SYN out and will never get it back,
602
625
  // while a new connection appeared. On the other hand, we might have just started connecting
@@ -660,8 +683,8 @@ export class ReconnectManager {
660
683
 
661
684
  // Guard against delayed notifications and recheck synchronously
662
685
  if (
663
- this.socketAdapter._ws?.readyState !== WebSocket.OPEN &&
664
- this.socketAdapter._ws?.readyState !== WebSocket.CONNECTING
686
+ this.socketAdapter._ws?.readyState !== ReadyState.OPEN &&
687
+ this.socketAdapter._ws?.readyState !== ReadyState.CONNECTING
665
688
  ) {
666
689
  debug('ReconnectManager.disconnected: websocket is not OPEN or CONNECTING')
667
690
  this.clearReconnectTimeout()
@@ -718,7 +741,7 @@ export class ReconnectManager {
718
741
  connected() {
719
742
  debug('ReconnectManager.connected')
720
743
  // this notification could've been delayed, recheck synchronously
721
- if (this.socketAdapter._ws?.readyState === WebSocket.OPEN) {
744
+ if (this.socketAdapter._ws?.readyState === ReadyState.OPEN) {
722
745
  debug('ReconnectManager.connected: websocket is OPEN')
723
746
  this.state = 'connected'
724
747
  this.clearReconnectTimeout()
@@ -51,6 +51,27 @@ describe('InMemorySyncStorage', () => {
51
51
  expect(storage.getClock()).toBe(25)
52
52
  })
53
53
 
54
+ it('[IM1] handles snapshots with far more records and tombstones than fit in a spread call', () => {
55
+ const documents = []
56
+ for (let i = 0; i < 150_000; i++) {
57
+ documents.push({
58
+ state: { ...contractRecords[0], id: `shape:${i}` } as TLRecord,
59
+ lastChangedClock: i,
60
+ })
61
+ }
62
+ const tombstones: Record<string, number> = {}
63
+ for (let i = 0; i < 150_000; i++) tombstones[`shape:gone-${i}`] = 150_000 + i
64
+ const storage = new InMemorySyncStorage<TLRecord>({
65
+ snapshot: makeContractSnapshot(contractRecords, {
66
+ documents,
67
+ tombstones,
68
+ documentClock: 0,
69
+ tombstoneHistoryStartsAtClock: 0,
70
+ }),
71
+ })
72
+ expect(storage.getClock()).toBe(299_999)
73
+ })
74
+
54
75
  it('[IM2] clamps tombstoneHistoryStartsAtClock down to the document clock', () => {
55
76
  const storage = new InMemorySyncStorage<TLRecord>({
56
77
  snapshot: makeContractSnapshot(contractRecords, {
@@ -153,27 +153,27 @@ export class InMemorySyncStorage<R extends UnknownRecord> implements TLSyncStora
153
153
  onChange?(arg: TLSyncStorageOnChangeCallbackProps): unknown
154
154
  } = {}) {
155
155
  this.objectTypes = new Set(objectTypes ?? [])
156
- const maxClockValue = Math.max(
157
- 0,
158
- ...Object.values(snapshot.tombstones ?? {}),
159
- ...Object.values(snapshot.documents.map((d) => d.lastChangedClock))
160
- )
156
+ // a loop rather than `Math.max(0, ...clocks)`: spreading a large room's clocks as call
157
+ // arguments overflows the stack at roughly 100k+ records/tombstones
158
+ let maxClockValue = 0
161
159
  // route snapshot entries into their partitions (a seed snapshot may carry object-lane
162
160
  // records merged in, e.g. loaded from a separate persistence lane)
163
- const toEntry = (
164
- d: RoomSnapshot['documents'][number]
165
- ): [string, { state: R; lastChangedClock: number }] => [
166
- d.state.id,
167
- { state: devFreeze(d.state) as R, lastChangedClock: d.lastChangedClock },
168
- ]
169
- this.documents = new AtomMap(
170
- 'room documents',
171
- snapshot.documents.filter((d) => !this.objectTypes.has(d.state.typeName)).map(toEntry)
172
- )
173
- this.objects = new AtomMap(
174
- 'room objects',
175
- snapshot.documents.filter((d) => this.objectTypes.has(d.state.typeName)).map(toEntry)
176
- )
161
+ const documentEntries: [string, { state: R; lastChangedClock: number }][] = []
162
+ const objectEntries: [string, { state: R; lastChangedClock: number }][] = []
163
+ for (const d of snapshot.documents) {
164
+ if (d.lastChangedClock > maxClockValue) maxClockValue = d.lastChangedClock
165
+ const entries = this.objectTypes.has(d.state.typeName) ? objectEntries : documentEntries
166
+ entries.push([
167
+ d.state.id,
168
+ { state: devFreeze(d.state) as R, lastChangedClock: d.lastChangedClock },
169
+ ])
170
+ }
171
+ const tombstoneEntries = objectMapEntries(snapshot.tombstones ?? {})
172
+ for (const [, clock] of tombstoneEntries) {
173
+ if (clock > maxClockValue) maxClockValue = clock
174
+ }
175
+ this.documents = new AtomMap('room documents', documentEntries)
176
+ this.objects = new AtomMap('room objects', objectEntries)
177
177
  const documentClock = Math.max(maxClockValue, snapshot.documentClock ?? snapshot.clock ?? 0)
178
178
 
179
179
  this.documentClock = atom('document clock', documentClock)
@@ -192,9 +192,7 @@ export class InMemorySyncStorage<R extends UnknownRecord> implements TLSyncStora
192
192
  'room tombstones',
193
193
  // If the tombstone history starts now (or we didn't have the
194
194
  // tombstoneHistoryStartsAtClock) then there are no tombstones
195
- tombstoneHistoryStartsAtClock === documentClock
196
- ? []
197
- : objectMapEntries(snapshot.tombstones ?? {})
195
+ tombstoneHistoryStartsAtClock === documentClock ? [] : tombstoneEntries
198
196
  )
199
197
  if (onChange) {
200
198
  this.onChange(onChange)
@@ -1,7 +1,7 @@
1
1
  import type { SerializedSchema, StoreSchema, UnknownRecord } from '@tldraw/store'
2
2
  import { createTLSchema, TLInstancePresence, TLStoreSnapshot } from '@tldraw/tlschema'
3
3
  import { getOwnProperty, hasOwnProperty, isEqual, structuredClone } from '@tldraw/utils'
4
- import { JsonChunkAssembler } from './chunk'
4
+ import { JsonChunkAssembler, MessageTooLargeError } from './chunk'
5
5
  import { DEFAULT_INITIAL_SNAPSHOT, InMemorySyncStorage } from './InMemorySyncStorage'
6
6
  import { TLObjectStoreAccess, TLSocketServerSentEvent } from './protocol'
7
7
  import { RoomSessionState } from './RoomSession'
@@ -477,6 +477,11 @@ export class TLSocketRoom<R extends UnknownRecord = UnknownRecord, SessionMeta =
477
477
  })
478
478
  this.room.pruneSessions()
479
479
  this.scheduleDebouncedSnapshot(sessionId)
480
+ } else if (res.error instanceof MessageTooLargeError) {
481
+ this.log?.error?.('Error assembling message', res.error)
482
+ // Resetting the connection would have the client reconnect and re-send the same
483
+ // oversized message, so reject the session instead and let the client surface it.
484
+ this.room.rejectSession(sessionId, TLSyncErrorCloseEventReason.MESSAGE_TOO_LARGE)
480
485
  } else {
481
486
  this.log?.error?.('Error assembling message', res.error)
482
487
  // close the socket to reset the connection
@@ -909,7 +914,8 @@ export class TLSocketRoom<R extends UnknownRecord = UnknownRecord, SessionMeta =
909
914
  * The client will attempt to reconnect automatically unless a fatal reason is provided.
910
915
  *
911
916
  * @param sessionId - Session identifier to remove
912
- * @param fatalReason - Optional fatal error reason that prevents reconnection
917
+ * @param fatalReason - Optional fatal error reason that prevents reconnection. WebSocket close
918
+ * reasons are capped at 123 UTF-8 bytes, so a longer reason is truncated and ends with `... (+N bytes)`.
913
919
  *
914
920
  * @example
915
921
  * ```ts
@@ -122,6 +122,8 @@ export const TLSyncErrorCloseEventReason = {
122
122
  RATE_LIMITED: 'RATE_LIMITED',
123
123
  /** Room has reached maximum capacity */
124
124
  ROOM_FULL: 'ROOM_FULL',
125
+ /** A single message exceeded the size the server will assemble */
126
+ MESSAGE_TOO_LARGE: 'MESSAGE_TOO_LARGE',
125
127
  } as const
126
128
 
127
129
  /**
@@ -88,6 +88,29 @@ export const DATA_MESSAGE_DEBOUNCE_INTERVAL = 1000 / 60
88
88
 
89
89
  const timeSince = (time: number) => Date.now() - time
90
90
 
91
+ // WebSocket close frames cap the reason at 123 UTF-8 bytes; a longer one makes `close()` throw
92
+ const MAX_CLOSE_REASON_BYTES = 123
93
+ const closeReasonEncoder = new TextEncoder()
94
+
95
+ const truncatedSuffix = (droppedBytes: number) => `... (+${droppedBytes} bytes)`
96
+
97
+ function truncateCloseReason(reason: string) {
98
+ const totalBytes = closeReasonEncoder.encode(reason).length
99
+ if (totalBytes <= MAX_CLOSE_REASON_BYTES) return reason
100
+ // the dropped count can't have more digits than the total, so reserving room for it always fits
101
+ const budget = MAX_CLOSE_REASON_BYTES - truncatedSuffix(totalBytes).length
102
+ let out = ''
103
+ let outBytes = 0
104
+ // step by code point so a multi-byte character is never cut in half
105
+ for (const char of reason) {
106
+ const charBytes = closeReasonEncoder.encode(char).length
107
+ if (outBytes + charBytes > budget) break
108
+ out += char
109
+ outBytes += charBytes
110
+ }
111
+ return out + truncatedSuffix(totalBytes - outBytes)
112
+ }
113
+
91
114
  /**
92
115
  * Snapshot of a room's complete state that can be persisted and restored.
93
116
  * Contains all documents, tombstones, and metadata needed to reconstruct the room.
@@ -559,7 +582,8 @@ export class TLSyncRoom<R extends UnknownRecord, SessionMeta> {
559
582
 
560
583
  try {
561
584
  if (fatalReason) {
562
- session.socket.close(TLSyncErrorCloseEventCode, fatalReason)
585
+ // the session is already gone, so a throwing close() would leave its socket open
586
+ session.socket.close(TLSyncErrorCloseEventCode, truncateCloseReason(fatalReason))
563
587
  } else {
564
588
  session.socket.close()
565
589
  }
@@ -941,7 +965,8 @@ export class TLSyncRoom<R extends UnknownRecord, SessionMeta> {
941
965
  * Sends appropriate error messages before closing the connection.
942
966
  *
943
967
  * @param sessionId - The session to reject
944
- * @param fatalReason - The reason for rejection (optional)
968
+ * @param fatalReason - The reason for rejection (optional). WebSocket close reasons are capped
969
+ * at 123 UTF-8 bytes, so a longer reason is truncated and ends with `... (+N bytes)`.
945
970
  * @example
946
971
  * ```ts
947
972
  * // Reject due to version mismatch
@@ -998,6 +1023,10 @@ export class TLSyncRoom<R extends UnknownRecord, SessionMeta> {
998
1023
 
999
1024
  private forceAllReconnect() {
1000
1025
  for (const session of this.sessions.values()) {
1026
+ // Only connected clients hold state at a clock we can no longer diff from. A session
1027
+ // mid-handshake gets hydrated from its own lastServerClock in the same transaction, so
1028
+ // removing it would close its socket and then re-add it as Connected (resurrected).
1029
+ if (session.state !== RoomSessionState.Connected) continue
1001
1030
  this.removeSession(session.sessionId)
1002
1031
  }
1003
1032
  }
@@ -1091,7 +1120,7 @@ export class TLSyncRoom<R extends UnknownRecord, SessionMeta> {
1091
1120
 
1092
1121
  const requiresDownMigrations = migrations.value.length > 0
1093
1122
 
1094
- const connect = async (msg: Extract<TLSocketServerSentEvent<R>, { type: 'connect' }>) => {
1123
+ const connect = (msg: Extract<TLSocketServerSentEvent<R>, { type: 'connect' }>) => {
1095
1124
  this.sessions.set(session.sessionId, {
1096
1125
  state: RoomSessionState.Connected,
1097
1126
  sessionId: session.sessionId,
@@ -1,5 +1,11 @@
1
1
  import { assert } from 'tldraw'
2
- import { JsonChunkAssembler, chunk } from './chunk'
2
+ import {
3
+ JsonChunkAssembler,
4
+ MAX_ASSEMBLED_MESSAGE_CHARS,
5
+ MAX_CHUNK_COUNT,
6
+ MessageTooLargeError,
7
+ chunk,
8
+ } from './chunk'
3
9
 
4
10
  describe('chunk (CH1–CH3)', () => {
5
11
  describe('size boundary (CH1)', () => {
@@ -403,4 +409,51 @@ describe('JsonChunkAssembler (CH4–CH8)', () => {
403
409
  })
404
410
  })
405
411
  })
412
+
413
+ describe('assembly bounds (CH10)', () => {
414
+ it('[CH10] rejects a first chunk declaring more than MAX_CHUNK_COUNT chunks', () => {
415
+ const unchunker = new JsonChunkAssembler()
416
+
417
+ const result = unchunker.handleMessage(`${MAX_CHUNK_COUNT}_{"a":`)
418
+ expect(result).toMatchObject({
419
+ error: expect.objectContaining({ message: `Too many chunks: ${MAX_CHUNK_COUNT + 1}` }),
420
+ })
421
+ expect(unchunker.state).toBe('idle')
422
+ })
423
+
424
+ it('[CH10] accepts a declared count at the limit', () => {
425
+ const unchunker = new JsonChunkAssembler()
426
+
427
+ expect(unchunker.handleMessage(`${MAX_CHUNK_COUNT - 1}_{"a":`)).toBeNull()
428
+ expect(unchunker.state).not.toBe('idle')
429
+ })
430
+
431
+ it('[CH10] rejects an assembly once its accumulated bodies pass MAX_ASSEMBLED_MESSAGE_CHARS', () => {
432
+ const unchunker = new JsonChunkAssembler()
433
+ // A chunk stream that never sends its final chunk. Before CH10 this accumulated
434
+ // without limit for as long as the sender kept sending.
435
+ const body = 'x'.repeat(1024 * 1024)
436
+ const chunksNeeded = Math.ceil(MAX_ASSEMBLED_MESSAGE_CHARS / body.length) + 1
437
+
438
+ let result = null
439
+ for (let i = 0; i < chunksNeeded; i++) {
440
+ result = unchunker.handleMessage(`${chunksNeeded - i}_${body}`)
441
+ if (result) break
442
+ }
443
+
444
+ expect(result).toMatchObject({ error: expect.any(MessageTooLargeError) })
445
+ expect(unchunker.state).toBe('idle')
446
+ })
447
+
448
+ it('[CH10] leaves the assembler usable after rejecting an oversized assembly', () => {
449
+ const unchunker = new JsonChunkAssembler()
450
+ const body = 'x'.repeat(1024 * 1024)
451
+ const chunksNeeded = Math.ceil(MAX_ASSEMBLED_MESSAGE_CHARS / body.length) + 1
452
+ for (let i = 0; i < chunksNeeded; i++) {
453
+ if (unchunker.handleMessage(`${chunksNeeded - i}_${body}`)) break
454
+ }
455
+
456
+ expect(unchunker.handleMessage('{"test": true}')).toMatchObject({ data: { test: true } })
457
+ })
458
+ })
406
459
  })