@signe/room 3.2.0 → 3.3.0

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.
package/src/server.ts CHANGED
@@ -7,15 +7,26 @@ import {
7
7
  syncClass,
8
8
  DELETE_TOKEN,
9
9
  generateShortUUID,
10
- createStatesSnapshotDeep
10
+ createStatesSnapshotDeep,
11
+ compressMessage,
12
+ createMessageCompressor,
13
+ COMPRESSION_QUERY_PARAM,
14
+ COMPRESSION_QUERY_VALUE,
15
+ COMPRESSION_STREAM_QUERY_PARAM,
16
+ COMPRESSION_STREAM_QUERY_VALUE,
17
+ PathTable,
18
+ PATH_FORMAT_QUERY_PARAM,
19
+ PATH_FORMAT_QUERY_VALUE,
11
20
  } from "@signe/sync";
21
+ import type { MessageCompressor, PathTableCursor } from "@signe/sync";
12
22
  import type * as Party from "./types/party";
13
23
  import {
14
24
  awaitReturn,
15
25
  buildObject,
16
26
  extractParams,
17
27
  isClass,
18
- throttle,
28
+ batch,
29
+ debounce,
19
30
  } from "./utils";
20
31
  import { ServerResponse } from "./request/response";
21
32
  import { createCorsInterceptor } from "./request/cors";
@@ -94,6 +105,150 @@ const SESSION_GC_LAST_RUN_KEY = `${INTERNAL_PREFIX}session-gc:last-run`;
94
105
  const TRANSFER_GC_LAST_RUN_KEY = `${INTERNAL_PREFIX}transfer-gc:last-run`;
95
106
  const DEFAULT_TRANSFER_EXPIRY_MS = 5 * 60 * 1000;
96
107
 
108
+ /**
109
+ * Serialized pieces of a sync packet, shared by all the clients of one broadcast.
110
+ * `SyncFragments` writes JSON objects, `PathSyncFragments` the path table format.
111
+ */
112
+ interface SyncPacketWriter {
113
+ field(key: string, value: any): string;
114
+ entity(collection: string, id: string, value: any, kind: "patch" | "full"): string;
115
+ deleted(collection: string, id: string): string;
116
+ /** A collection with its entity fragments. */
117
+ collection(key: string, entries: string[]): string;
118
+ /** Fields added for one client (`syncPacketHeader`). */
119
+ header(header: Record<string, any>): string[];
120
+ /** The whole packet of one client. */
121
+ packet(conn: Party.Connection, parts: string[], obj: any): string;
122
+ }
123
+
124
+ class SyncFragments implements SyncPacketWriter {
125
+ private fields = new Map<string, string>();
126
+ private patches = new Map<string, string>();
127
+ private fulls = new Map<string, string>();
128
+
129
+ field(key: string, value: any): string {
130
+ let fragment = this.fields.get(key);
131
+ if (fragment === undefined) {
132
+ fragment = `${JSON.stringify(key)}:${JSON.stringify(value)}`;
133
+ this.fields.set(key, fragment);
134
+ }
135
+ return fragment;
136
+ }
137
+
138
+ entity(collection: string, id: string, value: any, kind: "patch" | "full"): string {
139
+ const cache = kind === "patch" ? this.patches : this.fulls;
140
+ const cacheKey = collection + "\u0000" + id;
141
+ let fragment = cache.get(cacheKey);
142
+ if (fragment === undefined) {
143
+ fragment = `${JSON.stringify(id)}:${JSON.stringify(value)}`;
144
+ cache.set(cacheKey, fragment);
145
+ }
146
+ return fragment;
147
+ }
148
+
149
+ deleted(_collection: string, id: string): string {
150
+ return `${JSON.stringify(id)}:${JSON.stringify(DELETE_TOKEN)}`;
151
+ }
152
+
153
+ collection(key: string, entries: string[]): string {
154
+ return `${JSON.stringify(key)}:{${entries.join(",")}}`;
155
+ }
156
+
157
+ header(header: Record<string, any>): string[] {
158
+ const parts: string[] = [];
159
+ for (const key in header) {
160
+ parts.push(`${JSON.stringify(key)}:${JSON.stringify(header[key])}`);
161
+ }
162
+ return parts;
163
+ }
164
+
165
+ packet(_conn: Party.Connection, parts: string[], obj: any): string {
166
+ return `{"type":"sync","value":{${parts.join(",")}}` + otherPacketKeys(obj) + "}";
167
+ }
168
+ }
169
+
170
+ /** Keys of a packet other than `type` and `value` (for example `events`), as JSON fields. */
171
+ function otherPacketKeys(obj: any): string {
172
+ let data = "";
173
+ for (const key in obj) {
174
+ if (key === "type" || key === "value") continue;
175
+ data += `,${JSON.stringify(key)}:${JSON.stringify(obj[key])}`;
176
+ }
177
+ return data;
178
+ }
179
+
180
+ /** Path table pieces of a sync packet (see `PathTable` in `@signe/sync`). */
181
+ class PathSyncFragments implements SyncPacketWriter {
182
+ private fields = new Map<string, string>();
183
+ private patches = new Map<string, string>();
184
+ private fulls = new Map<string, string>();
185
+
186
+ constructor(private table: PathTable, private cursor: (conn: Party.Connection) => PathTableCursor) {
187
+ table.startPacket();
188
+ }
189
+
190
+ field(key: string, value: any): string {
191
+ let fragment = this.fields.get(key);
192
+ if (fragment === undefined) {
193
+ fragment = this.table.encode({ [key]: value });
194
+ this.fields.set(key, fragment);
195
+ }
196
+ return fragment;
197
+ }
198
+
199
+ entity(collection: string, id: string, value: any, kind: "patch" | "full"): string {
200
+ const cache = kind === "patch" ? this.patches : this.fulls;
201
+ const cacheKey = collection + "\u0000" + id;
202
+ let fragment = cache.get(cacheKey);
203
+ if (fragment === undefined) {
204
+ fragment = value !== null && typeof value === "object" && !Array.isArray(value)
205
+ ? this.table.encode(value, collection + "." + id)
206
+ : this.table.encodeLeaf(collection + "." + id, value);
207
+ cache.set(cacheKey, fragment);
208
+ }
209
+ return fragment;
210
+ }
211
+
212
+ deleted(collection: string, id: string): string {
213
+ return this.table.encodeLeaf(collection + "." + id, DELETE_TOKEN);
214
+ }
215
+
216
+ collection(_key: string, entries: string[]): string {
217
+ return joinPairs(entries);
218
+ }
219
+
220
+ header(header: Record<string, any>): string[] {
221
+ return [this.table.encode(header)];
222
+ }
223
+
224
+ packet(conn: Party.Connection, parts: string[], obj: any): string {
225
+ // The header comes last: the definitions must include the paths of this packet
226
+ const pairs = joinPairs(parts);
227
+ return `{"type":"sync",${this.table.header(this.cursor(conn))}"p":[${pairs}]` + otherPacketKeys(obj) + "}";
228
+ }
229
+ }
230
+
231
+ /** Joins lists of pairs, skipping empty ones. */
232
+ function joinPairs(parts: string[]): string {
233
+ let out = "";
234
+ for (const part of parts) {
235
+ if (part === "") continue;
236
+ out += out === "" ? part : "," + part;
237
+ }
238
+ return out;
239
+ }
240
+
241
+ /**
242
+ * Converts queued volatile events to a packet object and empties the queue.
243
+ * Returns undefined when there is nothing to send.
244
+ */
245
+ function takeEvents(queue: Map<string, any[]>): Record<string, any[]> | undefined {
246
+ if (queue.size === 0) return undefined;
247
+ const events = Object.fromEntries(queue);
248
+ queue.clear();
249
+ return events;
250
+ }
251
+
97
252
  /**
98
253
  * @class Server
99
254
  * @implements {Party.Server}
@@ -378,22 +533,269 @@ export class Server implements Party.Server {
378
533
  .some((conn) => this.getPrivateId(conn) === privateId);
379
534
  }
380
535
 
536
+ /**
537
+ * Whether `data` should be sent compressed to `conn`: the room enables compression,
538
+ * the client asked for it, the message is large enough, and (for packets returned by
539
+ * `interceptorPacket`) per-client compression is enabled.
540
+ */
541
+ private shouldCompress(conn: Party.Connection, subRoom: any, data: string, intercepted: boolean): boolean {
542
+ const compression = subRoom?.$compression;
543
+ if (!compression || !(conn.state as any)?.compression) return false;
544
+ if (intercepted && !compression.intercepted) return false;
545
+ return data.length >= compression.threshold;
546
+ }
547
+
381
548
  async send(conn: Party.Connection, obj: any, subRoom: any) {
382
- obj = structuredClone(obj);
383
- if (subRoom.interceptorPacket) {
549
+ if (this.usesSyncVisibility(obj, subRoom)) {
550
+ this.sendPerClient(conn, this.buildVisibleSyncPacket(conn, obj, subRoom, this.syncWriter(conn, subRoom, {})), subRoom);
551
+ return;
552
+ }
553
+ const intercepted = !!subRoom?.interceptorPacket;
554
+ if (subRoom?.interceptorPacket) {
555
+ // The interceptor may modify the packet: give it its own copy, unless the room says it does not
556
+ if (subRoom.copyPacketForInterceptor !== false) {
557
+ obj = structuredClone(obj);
558
+ }
384
559
  const signal = this.getUsersProperty(subRoom);
385
560
  const { publicId } = conn.state as any;
386
561
  const user = signal?.()[publicId];
387
562
  obj = await awaitReturn(subRoom["interceptorPacket"]?.(user, obj, conn));
388
563
  if (obj === null) return;
389
564
  }
390
- conn.send(JSON.stringify(obj));
565
+ let data: string;
566
+ if (this.usesPathFormat(conn, obj)) {
567
+ const table = this.pathTable(subRoom);
568
+ table.startPacket();
569
+ const body = this.pathPacketBody(obj, table.encode(obj.value));
570
+ data = this.pathPacket(conn, table, body);
571
+ } else {
572
+ data = JSON.stringify(obj);
573
+ }
574
+ conn.send(
575
+ this.shouldCompress(conn, subRoom, data, intercepted)
576
+ ? this.compressForClient(conn, subRoom, data)
577
+ : data
578
+ );
579
+ }
580
+
581
+ /** Compressors of the connections that read stream messages (see `createMessageCompressor`). */
582
+ private compressors = new WeakMap<Party.Connection, MessageCompressor>();
583
+
584
+ /**
585
+ * Compresses a message built for this client only: with the connection's stream when the
586
+ * client reads stream messages (3 times cheaper and 2 times smaller on small packets,
587
+ * since the stream is set up once and messages refer to the previous ones), otherwise alone.
588
+ */
589
+ private compressForClient(conn: Party.Connection, subRoom: any, data: string): Uint8Array {
590
+ const compression = subRoom.$compression;
591
+ if (compression.stream === false || !(conn.state as any)?.compressionStream) {
592
+ return compressMessage(data, compression.level);
593
+ }
594
+ let compressor = this.compressors.get(conn);
595
+ if (!compressor) {
596
+ compressor = createMessageCompressor({
597
+ level: compression.level,
598
+ windowBits: compression.windowBits,
599
+ memLevel: compression.memLevel,
600
+ });
601
+ this.compressors.set(conn, compressor);
602
+ }
603
+ return compressor.compress(data);
391
604
  }
392
605
 
393
- broadcast(obj: any, subRoom: any) {
606
+ /**
607
+ * Sends a packet to every connection (except `exclude`).
608
+ * Without `interceptorPacket`, the packet is serialized once and the same string is sent to all.
609
+ */
610
+ broadcast(obj: any, subRoom: any, exclude?: Set<Party.Connection>) {
611
+ if (this.usesSyncVisibility(obj, subRoom)) {
612
+ // Each entity is serialized once per broadcast (per format), then assembled per client
613
+ const writers = {};
614
+ for (let conn of this.room.getConnections()) {
615
+ if (exclude?.has(conn)) continue;
616
+ this.sendPerClient(conn, this.buildVisibleSyncPacket(conn, obj, subRoom, this.syncWriter(conn, subRoom, writers)), subRoom);
617
+ }
618
+ return;
619
+ }
620
+ if (subRoom?.interceptorPacket) {
621
+ for (let conn of this.room.getConnections()) {
622
+ if (exclude?.has(conn)) continue;
623
+ this.send(conn, obj, subRoom);
624
+ }
625
+ return;
626
+ }
627
+ let data: string | undefined;
628
+ let compressed: Uint8Array | undefined;
629
+ // Path table format: the pairs are encoded once; only the definitions a client misses differ
630
+ let pathBody: string | undefined;
631
+ let pathCompressed: Map<string, Uint8Array> | undefined;
394
632
  for (let conn of this.room.getConnections()) {
395
- this.send(conn, obj, subRoom);
633
+ if (exclude?.has(conn)) continue;
634
+ if (this.usesPathFormat(conn, obj)) {
635
+ const table = this.pathTable(subRoom);
636
+ if (pathBody === undefined) {
637
+ table.startPacket();
638
+ pathBody = this.pathPacketBody(obj, table.encode(obj.value));
639
+ }
640
+ const header = table.header(this.pathCursor(conn));
641
+ const pathData = `{"type":"sync",${header}${pathBody}`;
642
+ if (this.shouldCompress(conn, subRoom, pathData, false)) {
643
+ // Clients with the same missing definitions share the same bytes
644
+ pathCompressed ??= new Map();
645
+ let bytes = pathCompressed.get(header);
646
+ if (!bytes) {
647
+ bytes = compressMessage(pathData, subRoom.$compression.level);
648
+ pathCompressed.set(header, bytes);
649
+ }
650
+ conn.send(bytes);
651
+ } else {
652
+ conn.send(pathData);
653
+ }
654
+ continue;
655
+ }
656
+ data ??= JSON.stringify(obj);
657
+ if (this.shouldCompress(conn, subRoom, data, false)) {
658
+ // Compressed once, then the same bytes are sent to every client that asked for it
659
+ compressed ??= compressMessage(data, subRoom.$compression.level);
660
+ conn.send(compressed);
661
+ } else {
662
+ conn.send(data);
663
+ }
664
+ }
665
+ }
666
+
667
+ /**
668
+ * Sends a packet built for this client only. Like intercepted packets, it is compressed only
669
+ * with `compression.intercepted`, since each client needs its own compression.
670
+ */
671
+ private sendPerClient(conn: Party.Connection, data: string, subRoom: any) {
672
+ conn.send(
673
+ this.shouldCompress(conn, subRoom, data, true)
674
+ ? this.compressForClient(conn, subRoom, data)
675
+ : data
676
+ );
677
+ }
678
+
679
+ /** Path cursor of each connection: the path definitions it already received. */
680
+ private pathCursors = new WeakMap<Party.Connection, PathTableCursor>();
681
+
682
+ /** Whether this sync packet is sent to `conn` in the path table format (asked by the client). */
683
+ private usesPathFormat(conn: Party.Connection, obj: any): boolean {
684
+ return obj?.type === "sync"
685
+ && !!(conn.state as any)?.pathFormat
686
+ && obj.value !== null
687
+ && typeof obj.value === "object";
688
+ }
689
+
690
+ private pathTable(subRoom: any): PathTable {
691
+ return (subRoom.$pathTable ??= new PathTable(subRoom.pathTableLimit));
692
+ }
693
+
694
+ private pathCursor = (conn: Party.Connection): PathTableCursor => {
695
+ let cursor = this.pathCursors.get(conn);
696
+ if (!cursor) {
697
+ cursor = { epoch: -1, known: 0 };
698
+ this.pathCursors.set(conn, cursor);
699
+ }
700
+ return cursor;
701
+ };
702
+
703
+ /** End of a path table packet: pairs and the other keys of the packet. */
704
+ private pathPacketBody(obj: any, pairs: string): string {
705
+ return `"p":[${pairs}]` + otherPacketKeys(obj) + "}";
706
+ }
707
+
708
+ private pathPacket(conn: Party.Connection, table: PathTable, body: string): string {
709
+ return `{"type":"sync",${table.header(this.pathCursor(conn))}${body}`;
710
+ }
711
+
712
+ /** Writer of `conn`'s format, shared through `writers` by the clients of one broadcast. */
713
+ private syncWriter(conn: Party.Connection, subRoom: any, writers: { json?: SyncFragments; paths?: PathSyncFragments }): SyncPacketWriter {
714
+ if ((conn.state as any)?.pathFormat) {
715
+ return (writers.paths ??= new PathSyncFragments(this.pathTable(subRoom), this.pathCursor));
716
+ }
717
+ return (writers.json ??= new SyncFragments());
718
+ }
719
+
720
+ /** Sync packets of a room that defines `syncVisibility` are filtered per client. */
721
+ private usesSyncVisibility(obj: any, subRoom: any): boolean {
722
+ return obj?.type === "sync" && typeof subRoom?.syncVisibility === "function";
723
+ }
724
+
725
+ /**
726
+ * Builds the sync packet of one client for a room that defines `syncVisibility`.
727
+ *
728
+ * For each collection returned by `syncVisibility(user, conn, patch)`:
729
+ * - an entity that stays visible gets its patch (if it changed);
730
+ * - an entity that becomes visible gets its full state, from `$memoryAll`;
731
+ * - an entity that is no longer visible (or was deleted) gets `"$delete"`.
732
+ * Other keys of the packet are sent to everyone. `syncPacketHeader(user, conn, patch)` adds
733
+ * per-client fields. Fragments are serialized once per broadcast and shared between clients.
734
+ */
735
+ private buildVisibleSyncPacket(conn: Party.Connection, obj: any, subRoom: any, fragments: SyncPacketWriter): string {
736
+ const user = this.getUsersProperty(subRoom)?.()[(conn.state as any)?.publicId];
737
+ const value = obj.value && typeof obj.value === "object" ? obj.value : {};
738
+ const visibility: Record<string, Iterable<string> | null | undefined> =
739
+ subRoom.syncVisibility(user, conn, value) ?? {};
740
+
741
+ const states: Map<string, Map<string, Set<string>>> = (subRoom.$syncVisibleEntities ??= new Map());
742
+ let state = states.get(conn.id);
743
+ if (!state) {
744
+ state = new Map();
745
+ states.set(conn.id, state);
746
+ }
747
+
748
+ const parts: string[] = [];
749
+ for (const key in value) {
750
+ if (visibility[key] != null) continue;
751
+ parts.push(fragments.field(key, value[key]));
752
+ }
753
+
754
+ for (const key in visibility) {
755
+ const visibleIds = visibility[key];
756
+ if (visibleIds == null) continue;
757
+ const patch = value[key];
758
+ const patchEntries = patch && typeof patch === "object" && !Array.isArray(patch) ? patch : undefined;
759
+ const memory = subRoom.$memoryAll?.[key];
760
+ const previous = state.get(key);
761
+ const visible = new Set<string>();
762
+ const entries: string[] = [];
763
+
764
+ for (const id of visibleIds) {
765
+ if (visible.has(id)) continue;
766
+ if (previous?.has(id)) {
767
+ const entityPatch = patchEntries?.[id];
768
+ // Deleted entities are removed below, with the ones that left the view
769
+ if (entityPatch === DELETE_TOKEN) continue;
770
+ visible.add(id);
771
+ if (entityPatch !== undefined) {
772
+ entries.push(fragments.entity(key, id, entityPatch, "patch"));
773
+ }
774
+ } else {
775
+ const snapshot = memory?.[id];
776
+ if (snapshot === undefined) continue; // does not exist (anymore)
777
+ visible.add(id);
778
+ entries.push(fragments.entity(key, id, snapshot, "full"));
779
+ }
780
+ }
781
+ if (previous) {
782
+ for (const id of previous) {
783
+ if (!visible.has(id)) entries.push(fragments.deleted(key, id));
784
+ }
785
+ }
786
+ if (entries.length > 0) {
787
+ parts.push(fragments.collection(key, entries));
788
+ }
789
+ state.set(key, visible);
396
790
  }
791
+
792
+ const header = subRoom.syncPacketHeader?.(user, conn, value);
793
+ if (header) {
794
+ // Added last: like `{ ...value, ...header }`, a header field wins over a packet field
795
+ parts.push(...fragments.header(header));
796
+ }
797
+
798
+ return fragments.packet(conn, parts, obj);
397
799
  }
398
800
 
399
801
  /**
@@ -771,10 +1173,20 @@ export class Server implements Party.Server {
771
1173
  };
772
1174
 
773
1175
  instance.$memoryAll = {}
1176
+ const compressionOption = instance["compression"];
1177
+ instance.$compression = compressionOption
1178
+ ? {
1179
+ threshold: 512,
1180
+ level: 1,
1181
+ intercepted: false,
1182
+ ...(typeof compressionOption === "object" ? compressionOption : {}),
1183
+ }
1184
+ : null;
774
1185
  instance.$storageMetrics = this.createStorageMetrics();
775
1186
  const shouldPersistState = instance["persistState"] !== false;
776
1187
  instance.$autoSync = instance["autoSync"] !== false; // Default to true
777
1188
  instance.$pendingSync = new Map<string, any>();
1189
+ instance.$pendingEvents = new Map<string, any[]>(); // Volatile events waiting for $applySync() when autoSync is disabled
778
1190
  instance.$pendingInitialSync = new Map<Party.Connection, string>(); // Store connections waiting for initial sync with their publicId
779
1191
  instance.$send = (conn: Party.Connection, obj: any) => {
780
1192
  return this.send(conn, obj, instance)
@@ -806,11 +1218,13 @@ export class Server implements Party.Server {
806
1218
  * ```
807
1219
  */
808
1220
  instance.$applySync = () => {
1221
+ // Changes made in the current task are still waiting for the batched sync:
1222
+ // take them now, so that `x.set(1); $applySync()` sends them.
1223
+ flushBatchedSync();
809
1224
  let packet: any;
1225
+ const events = takeEvents(instance.$pendingEvents);
810
1226
  if (instance.$pendingSync.size > 0) {
811
- if (options.getMemoryAll) {
812
- buildObject(instance.$pendingSync, instance.$memoryAll);
813
- }
1227
+ // buildObject also merges the changes into $memoryAll
814
1228
  packet = buildObject(instance.$pendingSync, instance.$memoryAll);
815
1229
  instance.$pendingSync.clear();
816
1230
  } else {
@@ -819,27 +1233,26 @@ export class Server implements Party.Server {
819
1233
  }
820
1234
 
821
1235
  // Send initial sync to connections that were waiting for it (with their pId)
822
- const pendingConnections = new Set(instance.$pendingInitialSync.keys());
1236
+ const pendingConnections = new Set<Party.Connection>(instance.$pendingInitialSync.keys());
823
1237
  for (const [conn, publicId] of instance.$pendingInitialSync) {
1238
+ // A client waiting for its initial sync needs the whole state, not only the changes
824
1239
  this.send(conn, {
825
1240
  type: "sync",
826
1241
  value: {
827
1242
  pId: publicId,
828
- ...packet,
1243
+ ...instance.$memoryAll,
829
1244
  },
1245
+ ...(events ? { events } : {}),
830
1246
  }, instance);
831
1247
  }
832
1248
  instance.$pendingInitialSync.clear();
833
1249
 
834
1250
  // Broadcast to all other connections (excluding those that just received initial sync)
835
- for (const conn of this.room.getConnections()) {
836
- if (!pendingConnections.has(conn)) {
837
- this.send(conn, {
838
- type: "sync",
839
- value: packet,
840
- }, instance);
841
- }
842
- }
1251
+ this.broadcast({
1252
+ type: "sync",
1253
+ value: packet,
1254
+ ...(events ? { events } : {}),
1255
+ }, instance, pendingConnections);
843
1256
  }
844
1257
  instance.$sessionTransfer = async (conn: Party.Connection, targetRoomId: string) => {
845
1258
  let user: any;
@@ -907,14 +1320,22 @@ export class Server implements Party.Server {
907
1320
  }
908
1321
  };
909
1322
 
910
- // Sync callback: Broadcast changes to all clients or store them for manual sync
911
- const syncCb = (values) => {
912
- if (options.getMemoryAll) {
1323
+ // Sync callback: Broadcast changes to all clients or store them for manual sync.
1324
+ // Volatile events (`event()`) travel in the same packet under `events`
1325
+ // and are never merged into $memoryAll nor persisted.
1326
+ const syncCb = (values: Map<string, any>, eventsQueue: Map<string, any[]>) => {
1327
+ if (values.size === 0 && eventsQueue.size === 0) {
1328
+ return;
1329
+ }
1330
+ const skipInit = init && this.isHibernate;
1331
+ // The broadcast path below merges into $memoryAll itself (buildObject)
1332
+ if (options.getMemoryAll && (skipInit || !instance.$autoSync)) {
913
1333
  buildObject(values, instance.$memoryAll);
914
1334
  }
915
1335
  // During initialization in hibernate mode, skip entirely
916
- if (init && this.isHibernate) {
1336
+ if (skipInit) {
917
1337
  init = false;
1338
+ eventsQueue.clear();
918
1339
  return;
919
1340
  }
920
1341
 
@@ -925,21 +1346,33 @@ export class Server implements Party.Server {
925
1346
  instance.$pendingSync.set(path, value);
926
1347
  }
927
1348
  values.clear();
1349
+ for (const [path, payloads] of eventsQueue) {
1350
+ const pending = instance.$pendingEvents.get(path);
1351
+ if (pending) {
1352
+ pending.push(...payloads);
1353
+ } else {
1354
+ instance.$pendingEvents.set(path, [...payloads]);
1355
+ }
1356
+ }
1357
+ eventsQueue.clear();
928
1358
  return;
929
1359
  }
930
1360
 
931
1361
  // Auto sync: broadcast immediately (even during init if autoSync is enabled)
932
1362
  const packet = buildObject(values, instance.$memoryAll);
1363
+ const events = takeEvents(eventsQueue);
933
1364
  this.broadcast(
934
1365
  {
935
1366
  type: "sync",
936
1367
  value: packet,
1368
+ ...(events ? { events } : {}),
937
1369
  },
938
1370
  instance
939
1371
  );
940
1372
  values.clear();
941
1373
  }
942
1374
 
1375
+
943
1376
  const flushPersist = async (values: Map<string, any>) => {
944
1377
  const startedAt = Date.now();
945
1378
  const stateWrites: Record<string, any> = {};
@@ -993,68 +1426,56 @@ export class Server implements Party.Server {
993
1426
  await persistQueue;
994
1427
  }
995
1428
 
996
- const debouncePersist = (wait: number) => {
997
- let timeout: ReturnType<typeof setTimeout> | null = null;
998
- let flushing = false;
999
- const pending = new Map<string, any>();
1000
-
1001
- const schedule = () => {
1002
- if (timeout) {
1003
- clearTimeout(timeout);
1004
- }
1005
- timeout = setTimeout(() => {
1006
- void flush();
1007
- }, wait);
1008
- };
1009
-
1010
- const flush = async () => {
1011
- timeout = null;
1012
- if (flushing) {
1013
- schedule();
1014
- return;
1015
- }
1016
-
1017
- const values = new Map(pending);
1018
- pending.clear();
1019
- if (!values.size) {
1020
- return;
1021
- }
1022
-
1023
- flushing = true;
1024
- try {
1025
- await persistCb(values);
1026
- } finally {
1027
- flushing = false;
1028
- if (pending.size) {
1029
- schedule();
1030
- }
1031
- }
1032
- };
1033
-
1034
- return (values: Map<string, any>) => {
1035
- if (initPersist) {
1036
- values.clear();
1037
- return;
1038
- }
1039
-
1040
- for (const [path, value] of values) {
1041
- pending.set(path, value);
1042
- }
1429
+ // Persist changes in batches. Without throttleStorage, all changes of the same task are
1430
+ // written together. With throttleStorage, writes are debounced, but never delayed more than
1431
+ // throttleStorageMaxWait (default 10 × throttleStorage) while the state keeps changing.
1432
+ let persistValuesRef: Map<string, any> | null = null;
1433
+ const flushPersistValues = () => {
1434
+ if (persistValuesRef?.size) {
1435
+ void persistCb(persistValuesRef);
1436
+ }
1437
+ };
1438
+ const throttleStorage = instance["throttleStorage"] || 0;
1439
+ const schedulePersist = throttleStorage > 0
1440
+ ? debounce(
1441
+ flushPersistValues,
1442
+ throttleStorage,
1443
+ instance["throttleStorageMaxWait"] ?? throttleStorage * 10
1444
+ )
1445
+ : batch(flushPersistValues);
1446
+ const batchedPersist = (values: Map<string, any>) => {
1447
+ if (initPersist) {
1043
1448
  values.clear();
1044
- schedule();
1045
- };
1449
+ return;
1450
+ }
1451
+ persistValuesRef = values;
1452
+ schedulePersist();
1046
1453
  };
1047
1454
 
1048
1455
  const disabledPersist = (values: Map<string, any>) => {
1049
1456
  values.clear();
1050
1457
  };
1051
1458
 
1052
- // Set up syncing and persistence with throttling to optimize performance
1459
+ // Changes made in the same task are sent as one packet (at the end of the task),
1460
+ // and with throttleSync at most one packet per window. State changes and events
1461
+ // share this flush, so an event and the state change emitted with it arrive together.
1462
+ let syncValuesRef: Map<string, any> = new Map();
1463
+ let syncEventsRef: Map<string, any[]> = new Map();
1464
+ const flushBatchedSync = () => {
1465
+ syncCb(syncValuesRef, syncEventsRef);
1466
+ };
1467
+ const scheduleSync = batch(flushBatchedSync, instance["throttleSync"] || 0);
1468
+
1053
1469
  syncClass(instance, {
1054
- onSync: instance["throttleSync"] ? throttle(syncCb, instance["throttleSync"]) : syncCb,
1055
- onPersist: shouldPersistState
1056
- ? instance["throttleStorage"] ? debouncePersist(instance["throttleStorage"]) : persistCb
1057
- : disabledPersist,
1470
+ onSync: (values) => {
1471
+ syncValuesRef = values;
1472
+ scheduleSync();
1473
+ },
1474
+ onEvent: (events) => {
1475
+ syncEventsRef = events;
1476
+ scheduleSync();
1477
+ },
1478
+ onPersist: shouldPersistState ? batchedPersist : disabledPersist,
1058
1479
  });
1059
1480
 
1060
1481
  if (shouldPersistState) {
@@ -1333,9 +1754,15 @@ export class Server implements Party.Server {
1333
1754
 
1334
1755
  // Handle session transfer
1335
1756
  let transferToken = null;
1757
+ let wantsCompression = false;
1758
+ let readsCompressionStream = false;
1759
+ let wantsPathFormat = false;
1336
1760
  if (ctx.request?.url) {
1337
1761
  const url = new URL(ctx.request.url);
1338
1762
  transferToken = url.searchParams.get('transferToken');
1763
+ wantsCompression = url.searchParams.get(COMPRESSION_QUERY_PARAM) === COMPRESSION_QUERY_VALUE;
1764
+ readsCompressionStream = url.searchParams.get(COMPRESSION_STREAM_QUERY_PARAM) === COMPRESSION_STREAM_QUERY_VALUE;
1765
+ wantsPathFormat = url.searchParams.get(PATH_FORMAT_QUERY_PARAM) === PATH_FORMAT_QUERY_VALUE;
1339
1766
  }
1340
1767
  let transferData: any = null;
1341
1768
  if (transferToken) {
@@ -1416,7 +1843,13 @@ export class Server implements Party.Server {
1416
1843
  conn.setState({
1417
1844
  ...conn.state,
1418
1845
  publicId,
1419
- privateId
1846
+ privateId,
1847
+ // The client accepts compressed messages (only used if the room enables compression)
1848
+ ...(wantsCompression ? { compression: true } : {}),
1849
+ // ... and reads stream messages (one DEFLATE stream per connection)
1850
+ ...(wantsCompression && readsCompressionStream ? { compressionStream: true } : {}),
1851
+ // The client reads sync packets in the path table format
1852
+ ...(wantsPathFormat ? { pathFormat: true } : {}),
1420
1853
  });
1421
1854
 
1422
1855
  // Call the room's onJoin method if it exists
@@ -1818,6 +2251,11 @@ export class Server implements Party.Server {
1818
2251
  if (subRoom.$pendingInitialSync) {
1819
2252
  subRoom.$pendingInitialSync.delete(conn);
1820
2253
  }
2254
+ // Forget what this connection could see (syncVisibility)
2255
+ subRoom.$syncVisibleEntities?.delete(conn.id);
2256
+ // Free its compression stream
2257
+ this.compressors.get(conn)?.close();
2258
+ this.compressors.delete(conn);
1821
2259
 
1822
2260
  const signal = this.getUsersProperty(subRoom);
1823
2261