@signe/room 3.2.1 → 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/CHANGELOG.md CHANGED
@@ -1,5 +1,83 @@
1
1
  # @signe/room
2
2
 
3
+ ## 3.3.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 8e48eba: Faster per-client packets:
8
+
9
+ - New `copyPacketForInterceptor` room option (default `true`). Set it to `false` when `interceptorPacket` never modifies the packet it receives: the `structuredClone` per client and per packet is skipped.
10
+ - New `syncVisibility(user, conn, patch)` room hook: return the ids each client can see, by collection. For sync packets, entities that stay visible get their changes, entities that become visible get their full state, and entities that leave the view (or are deleted) get `"$delete"`. The initial sync is filtered too. Optional `syncPacketHeader(user, conn, patch)` adds per-client fields. Each entity is serialized once per broadcast and the packet of each client is assembled from these pieces. Sync packets of a room with `syncVisibility` no longer go through `interceptorPacket`.
11
+
12
+ With 100 players and 50 clients each seeing 30 players: about 3.4 ms → 0.77 ms per tick without the copy, and 0.12 ms with `syncVisibility`, for the same packet size.
13
+
14
+ - 379cdfc: Faster synchronization and safer storage batching:
15
+
16
+ - **Sync packets are batched by default.** All changes made in the same task are sent as one `sync` packet at the end of the task, instead of one packet per `set()`. `throttleSync` now sets a minimum interval between packets, and the first packet of a burst also groups the changes of its task. Clients receive the same state, in fewer packets.
17
+ - **Broadcasts are serialized once.** Without `interceptorPacket`, a packet is stringified once and the same string is sent to every connection (no more `structuredClone` + `JSON.stringify` per connection). With `interceptorPacket`, each connection still gets its own copy.
18
+ - **Storage writes are batched by default.** Without `throttleStorage`, changes of the same task are written together instead of one write per change.
19
+ - **`throttleStorage` can no longer postpone writes forever.** Writes are still debounced, but they happen at the latest after `throttleStorageMaxWait` (new option, default 10 × `throttleStorage`). Before, a state changing more often than `throttleStorage` was never persisted.
20
+ - `$memoryAll` is no longer rebuilt twice per packet when `getMemoryAll` is used.
21
+
22
+ Benchmark (100 players moving, 50 clients, one tick): 73 ms → 0.9 ms with default options, 9.7 ms → 0.9 ms compared to `throttleSync`.
23
+
24
+ - 7e4ab67: Stream compression for per-client packets: one DEFLATE stream per connection, flushed after each message.
25
+
26
+ - `@signe/sync`: new `createMessageCompressor()` and `createMessageDecoder()` (one per connection), and message formats 2 and 3 (stream messages). `connectionRoom(..., { compression: true })` asks for stream messages (`?compressionStream=1`) and decodes them. `decodeMessage()` is unchanged and refuses stream messages.
27
+ - `@signe/room`: packets built for one client (`syncVisibility`, `interceptorPacket` with `compression.intercepted`) are compressed with the connection's stream when the client reads it. New `compression.stream` (default `true`), `windowBits` and `memLevel` options. Older clients keep receiving messages compressed alone.
28
+
29
+ On RPG-JS packets (2 KB, 30 players around): about 26 µs per packet instead of 66 µs on the server, and about 370 bytes instead of 700. Uses about 48 KB of memory per connection. Needs the native zlib of Node.js; in other runtimes, each message is compressed alone as before.
30
+
31
+ - 02de0d1: Optional compression of messages (DEFLATE, binary frames):
32
+
33
+ - `@signe/room`: new `compression` room option (`true` or `{ threshold, level, intercepted }`). Clients that ask for it receive messages larger than `threshold` (default 512) compressed; other clients keep receiving JSON text. A broadcast is compressed once for all clients. Packets returned by `interceptorPacket` are not compressed unless `intercepted: true`.
34
+ - `@signe/sync`: `connectionRoom(..., { compression: true })` asks for compressed messages and decodes them. New `compressMessage()` and `decodeMessage()` helpers. Native zlib is used when available (Node.js 20.16+ / 22.3+), fflate otherwise.
35
+ - `@signe/sync/client`: each message is decoded once for all listeners, and `off()` now removes the listener registered by `on()` (it removed nothing before).
36
+
37
+ With 100 moving players: ~3 KB → ~1.1 KB per tick, ~50 µs of server CPU per tick whatever the number of clients.
38
+
39
+ - 1b2a267: Optional path table format for sync packets: a flat list of path ids and values instead of nested objects, faster to parse and to apply on the client.
40
+
41
+ - `@signe/sync`: new `PathTable` (encoder) and `PathTableDecoder`. The decoder keeps the signal of each path and writes values to it directly; it looks signals up again after a change of the state's structure. `connectionRoom(..., { pathFormat: true })` asks for this format.
42
+ - `@signe/room`: clients that ask for it (`?format=paths`) receive sync packets in this format, also with `compression`, `interceptorPacket` and `syncVisibility`. A broadcast is encoded once. New `pathTableLimit` room option (default 65536).
43
+ - `load()` counts the changes of a state's structure (`getStructureVersion()`), used by the decoder.
44
+
45
+ With 100 moving players and an effect per player: parsing and applying a tick on the client is about 2 times faster (about 155 µs → 75 µs), with about 30 % fewer bytes without compression (8 % with it). Encoding costs about 30 µs per broadcast on the server (12 µs for `JSON.stringify`).
46
+
47
+ `connectionRoom` now keeps its `compression` and `pathFormat` query flags when the application replaces the query with `conn.updateProperties({ query })` (as RPG-JS does when the player changes room). Before, the next room connection lost them.
48
+
49
+ - c26a8fe: Add volatile sync events with `event()` ([#2](https://github.com/RSamaium/signe/issues/2)).
50
+
51
+ An `event()` declared with `@sync()` has no stored value: `emit(payload)` sends it once to clients, where `on(listener)` is called after the state of the same packet is applied. Events are never persisted, never kept in `$memoryAll`, and never sent to late joiners.
52
+
53
+ - `@signe/sync`: new `event()`, `isSyncEvent()` and `loadEvents()`; `syncClass()` accepts an `onEvent` callback; the client dispatches `packet.events` after `load()`.
54
+ - `@signe/room`: sync packets carry an `events` key; events emitted with `autoSync` disabled wait in `$pendingEvents` until `$applySync()`; events and state share the same `throttleSync` flush.
55
+
56
+ ### Patch Changes
57
+
58
+ - 2beee7d: Fix `$applySync()` with `autoSync = false`:
59
+
60
+ - Changes made in the same task as `$applySync()` (`room.count.set(1); room.$applySync()`) are sent by this call. Since sync packets are batched per task, they were otherwise sent by the next `$applySync()` only.
61
+ - Clients waiting for their initial sync now receive the whole state. When changes were pending, they only received those changes.
62
+
63
+ - 28e9bbc: Bump `dset` to 3.1.4.
64
+ - a62e883: Lower the server cost of each synchronized change:
65
+
66
+ - `@signe/sync`: the full path of a synchronized signal is built once and reused while the instance path does not change (it was rebuilt on every change, and the change maps had to hash a new string each time). The signal kind is resolved once. Persisted changes are no longer collected when `syncClass()` has no `onPersist` callback.
67
+ - `@signe/room`: `buildObject` splits each path once for the packet and `$memoryAll`, and keeps split paths in a bounded cache.
68
+
69
+ Benchmark (100 players moving, one tick): 0.44 ms → 0.28 ms; `buildObject` alone 115 µs → 47 µs.
70
+
71
+ - Updated dependencies [4a21285]
72
+ - Updated dependencies [7dc34ed]
73
+ - Updated dependencies [7e4ab67]
74
+ - Updated dependencies [02de0d1]
75
+ - Updated dependencies [a62e883]
76
+ - Updated dependencies [1b2a267]
77
+ - Updated dependencies [dac5737]
78
+ - Updated dependencies [c26a8fe]
79
+ - @signe/sync@3.2.0
80
+
3
81
  ## 3.2.1
4
82
 
5
83
  ### Patch Changes
package/dist/index.d.ts CHANGED
@@ -21,12 +21,66 @@ interface RequestOptions {
21
21
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'OPTIONS' | 'HEAD';
22
22
  }
23
23
  declare function Request(options: RequestOptions, bodyValidation?: z.ZodSchema): (target: any, propertyKey: string) => void;
24
+ interface RoomCompressionOptions {
25
+ /** Minimum size (characters of JSON) of a message to compress. Default: 512. */
26
+ threshold?: number;
27
+ /** DEFLATE level, 1 (fastest) to 9. Default: 1, which keeps most of the gain for half the CPU. */
28
+ level?: number;
29
+ /**
30
+ * Also compress messages returned by `interceptorPacket`. Each client then has its own
31
+ * packet, so this costs one compression per client and per message. Default: false.
32
+ * Also applies to the per-client packets of `syncVisibility`.
33
+ */
34
+ intercepted?: boolean;
35
+ /**
36
+ * Compress per-client messages with one DEFLATE stream per connection, for clients that can
37
+ * read it (`@signe/sync` client with `compression: true`). Each message is set up faster and
38
+ * refers to the previous ones: on small game packets, about 3 times less CPU and 2 times fewer
39
+ * bytes than compressing each message alone. Costs about 48 KB of memory per connection.
40
+ * Default: true.
41
+ */
42
+ stream?: boolean;
43
+ /** History of the stream: 2^windowBits bytes (9 to 15). Default: 13 (8 KB). */
44
+ windowBits?: number;
45
+ /** Memory of the stream's match finder (1 to 9). Default: 5. */
46
+ memLevel?: number;
47
+ }
24
48
  interface RoomOptions {
25
49
  path: string;
26
50
  maxUsers?: number;
27
51
  persistState?: boolean;
52
+ /**
53
+ * Debounce window (ms) for storage writes: changes are written once no change happened for this long.
54
+ */
28
55
  throttleStorage?: number;
56
+ /**
57
+ * Upper bound (ms) on how long changes can wait for a storage write while the state keeps changing.
58
+ * Defaults to 10 × `throttleStorage`.
59
+ */
60
+ throttleStorageMaxWait?: number;
61
+ /**
62
+ * Minimum interval (ms) between two sync packets. Changes made in the same task are always
63
+ * grouped into one packet, even without this option.
64
+ */
29
65
  throttleSync?: number;
66
+ /**
67
+ * Give `interceptorPacket` its own copy of each packet (default: true). Set to false when
68
+ * the interceptor never modifies the packet it receives (it returns a new object instead):
69
+ * this removes a `structuredClone` per client and per packet.
70
+ */
71
+ copyPacketForInterceptor?: boolean;
72
+ /**
73
+ * Send compressed messages (binary frames, DEFLATE) to clients that ask for them
74
+ * (`connectionRoom(..., { compression: true })`). Other clients keep receiving JSON text.
75
+ * A broadcast is compressed once for all clients. Default: disabled.
76
+ */
77
+ compression?: boolean | RoomCompressionOptions;
78
+ /**
79
+ * Number of paths after which the path table (sync packets of clients that asked for
80
+ * `pathFormat`) starts over. Paths of deleted entities stay in the table until then.
81
+ * Default: 65536.
82
+ */
83
+ pathTableLimit?: number;
30
84
  hibernate?: boolean;
31
85
  guards?: RoomGuardFn[];
32
86
  sessionExpiryTime?: number;
@@ -134,8 +188,55 @@ declare class Server implements Server$1 {
134
188
  private getTransferExpiryTime;
135
189
  private getPrivateId;
136
190
  private hasActiveSessionConnection;
191
+ /**
192
+ * Whether `data` should be sent compressed to `conn`: the room enables compression,
193
+ * the client asked for it, the message is large enough, and (for packets returned by
194
+ * `interceptorPacket`) per-client compression is enabled.
195
+ */
196
+ private shouldCompress;
137
197
  send(conn: Connection, obj: any, subRoom: any): Promise<void>;
138
- broadcast(obj: any, subRoom: any): void;
198
+ /** Compressors of the connections that read stream messages (see `createMessageCompressor`). */
199
+ private compressors;
200
+ /**
201
+ * Compresses a message built for this client only: with the connection's stream when the
202
+ * client reads stream messages (3 times cheaper and 2 times smaller on small packets,
203
+ * since the stream is set up once and messages refer to the previous ones), otherwise alone.
204
+ */
205
+ private compressForClient;
206
+ /**
207
+ * Sends a packet to every connection (except `exclude`).
208
+ * Without `interceptorPacket`, the packet is serialized once and the same string is sent to all.
209
+ */
210
+ broadcast(obj: any, subRoom: any, exclude?: Set<Connection>): void;
211
+ /**
212
+ * Sends a packet built for this client only. Like intercepted packets, it is compressed only
213
+ * with `compression.intercepted`, since each client needs its own compression.
214
+ */
215
+ private sendPerClient;
216
+ /** Path cursor of each connection: the path definitions it already received. */
217
+ private pathCursors;
218
+ /** Whether this sync packet is sent to `conn` in the path table format (asked by the client). */
219
+ private usesPathFormat;
220
+ private pathTable;
221
+ private pathCursor;
222
+ /** End of a path table packet: pairs and the other keys of the packet. */
223
+ private pathPacketBody;
224
+ private pathPacket;
225
+ /** Writer of `conn`'s format, shared through `writers` by the clients of one broadcast. */
226
+ private syncWriter;
227
+ /** Sync packets of a room that defines `syncVisibility` are filtered per client. */
228
+ private usesSyncVisibility;
229
+ /**
230
+ * Builds the sync packet of one client for a room that defines `syncVisibility`.
231
+ *
232
+ * For each collection returned by `syncVisibility(user, conn, patch)`:
233
+ * - an entity that stays visible gets its patch (if it changed);
234
+ * - an entity that becomes visible gets its full state, from `$memoryAll`;
235
+ * - an entity that is no longer visible (or was deleted) gets `"$delete"`.
236
+ * Other keys of the packet are sent to everyone. `syncPacketHeader(user, conn, patch)` adds
237
+ * per-client fields. Fragments are serialized once per broadcast and shared between clients.
238
+ */
239
+ private buildVisibleSyncPacket;
139
240
  /**
140
241
  * @method onStart
141
242
  * @async
@@ -827,4 +928,4 @@ declare function createRequireSessionGuard(storage: Storage$1): (sender: Connect
827
928
  */
828
929
  declare const requireSession: (sender: Connection, value: any, room: Room$1) => Promise<boolean>;
829
930
 
830
- export { Action, ClientIo, Guard, MockConnection, Request, type RequestOptions, Room, RoomGuard, type RoomInterceptorPacket, type RoomMethods, type RoomOnJoin, type RoomOnLeave, type RoomOptions, Server, ServerIo, ServerResponse, Shard, type ShardOptions, type StorageRestoreContext, UnhandledAction, type UserStorageRestoreContext, WorldRoom, createRequireSessionGuard, request, requireSession, testRoom, tick };
931
+ export { Action, ClientIo, Guard, MockConnection, Request, type RequestOptions, Room, type RoomCompressionOptions, RoomGuard, type RoomInterceptorPacket, type RoomMethods, type RoomOnJoin, type RoomOnLeave, type RoomOptions, Server, ServerIo, ServerResponse, Shard, type ShardOptions, type StorageRestoreContext, UnhandledAction, type UserStorageRestoreContext, WorldRoom, createRequireSessionGuard, request, requireSession, testRoom, tick };