@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/CHANGELOG.md +87 -0
- package/dist/cloudflare/index.d.ts +1 -1
- package/dist/index.d.ts +104 -3
- package/dist/index.js +476 -88
- package/dist/index.js.map +1 -1
- package/dist/node/index.d.ts +7 -3
- package/dist/node/index.js +6 -1
- package/dist/node/index.js.map +1 -1
- package/dist/{party-dNs-hqkq.d.ts → party-ChhPLN9B.d.ts} +2 -2
- package/examples/cloudflare/CHANGELOG.md +29 -0
- package/examples/cloudflare/package.json +1 -1
- package/examples/node/CHANGELOG.md +29 -0
- package/examples/node/package.json +2 -2
- package/examples/node-game/CHANGELOG.md +29 -0
- package/examples/node-game/package.json +2 -2
- package/examples/node-shard/CHANGELOG.md +29 -0
- package/examples/node-shard/package.json +2 -2
- package/package.json +8 -3
- package/readme.md +81 -3
- package/src/decorators.ts +63 -0
- package/src/node/index.ts +10 -5
- package/src/server.ts +517 -79
- package/src/types/party.ts +2 -2
- package/src/utils.ts +84 -6
package/readme.md
CHANGED
|
@@ -348,13 +348,50 @@ The `@Room` decorator accepts various configuration options:
|
|
|
348
348
|
@Room({
|
|
349
349
|
path: "game-{id}", // Dynamic path with parameters
|
|
350
350
|
maxUsers: 4, // Limit number of users
|
|
351
|
-
throttleStorage: 1000, //
|
|
352
|
-
|
|
351
|
+
throttleStorage: 1000, // Debounce storage writes (ms)
|
|
352
|
+
throttleStorageMaxWait: 10000, // Max delay of a storage write while state keeps changing (default: 10 × throttleStorage)
|
|
353
|
+
throttleSync: 100, // Minimum interval between sync packets (ms)
|
|
353
354
|
hibernate: false, // Enable/disable hibernation
|
|
354
355
|
guards: [isAuthenticated], // Room-level guards
|
|
355
356
|
})
|
|
356
357
|
```
|
|
357
358
|
|
|
359
|
+
**Sync batching.** All state changes made in the same task (for example one action, or one game tick) are sent as a single `sync` packet at the end of that task, even without `throttleSync`. With `throttleSync`, packets are also sent at most once per window, and changes in between are grouped into the next packet. Without `interceptorPacket`, a packet is serialized once and the same string is sent to every client.
|
|
360
|
+
|
|
361
|
+
**Compression.** With `compression: true`, clients that ask for it (`connectionRoom(..., { compression: true })`) receive large messages compressed (binary frames, DEFLATE); other clients keep receiving JSON text.
|
|
362
|
+
|
|
363
|
+
```ts
|
|
364
|
+
@Room({
|
|
365
|
+
path: "game",
|
|
366
|
+
compression: true,
|
|
367
|
+
// or: compression: { threshold: 512, level: 1, intercepted: false }
|
|
368
|
+
})
|
|
369
|
+
```
|
|
370
|
+
|
|
371
|
+
- A broadcast is compressed **once** and the same bytes are sent to every client that asked for it, so the cost does not grow with the number of clients.
|
|
372
|
+
- `threshold` (default 512 characters of JSON): smaller messages stay as text, where compression would not help.
|
|
373
|
+
- `level` (default 1): DEFLATE level. Level 1 keeps most of the size gain for about half the CPU of level 6.
|
|
374
|
+
- `intercepted` (default `false`): with `interceptorPacket` or `syncVisibility`, each client gets its own packet, so compressing costs one compression per client and per message. Enable it only if bandwidth matters more than CPU.
|
|
375
|
+
- `stream` (default `true`): these per-client packets are compressed with one DEFLATE stream per connection, for clients that read it (the `@signe/sync` client does). The stream is set up once and each packet can refer to the previous ones: on game packets of about 2 KB, about 3 times less CPU and 2 times fewer bytes than compressing each packet alone. It costs about 48 KB of memory per connection (`windowBits`, default 13, and `memLevel`, default 5, set the size). The stream is freed when the connection closes; after a Cloudflare hibernation, a new stream starts and the client follows. Needs the native zlib of Node.js; elsewhere each packet is compressed alone.
|
|
376
|
+
- Not applied through shards (`connectionWorld`): the shard connection does not ask for compression.
|
|
377
|
+
- Works on Cloudflare Workers (Durable Objects, including `webSocketMode: "hibernate"`: the client's choice is kept in the connection attachment). With the `nodejs_compat` flag, native zlib is used; without it, the pure-JS fallback (fflate) is used.
|
|
378
|
+
|
|
379
|
+
With 100 moving players, a tick goes from about 3 KB of JSON to about 1.1 KB, for about 50 µs of server CPU per tick (native zlib) and about 60 µs on the client to decompress and parse (fflate in browsers is slower to decompress: about 90 µs).
|
|
380
|
+
|
|
381
|
+
**Path table format.** Clients that ask for it (`connectionRoom(..., { pathFormat: true })`) receive sync packets as a flat list of path ids and values instead of nested objects. Each path gets a number the first time it is sent, and its name is sent once to each client:
|
|
382
|
+
|
|
383
|
+
```json
|
|
384
|
+
{"type":"sync","d":[12,"players.p1.x","players.p1.y"],"p":[12,10.5,13,20]}
|
|
385
|
+
```
|
|
386
|
+
|
|
387
|
+
- The client parses one array instead of one object per entity, and writes each value straight to the signal it found for this path the last time. With 100 moving players and an effect per player, parsing and applying a tick is about 2 times faster (about 155 µs → 75 µs in our benchmark).
|
|
388
|
+
- Packets are about 30 % smaller without compression (about 8 % with it, since DEFLATE already removes most repeated keys). It works with `compression`, `interceptorPacket` (the returned packet is encoded) and `syncVisibility` (fragments are encoded once per broadcast).
|
|
389
|
+
- The pairs of a broadcast are encoded once for all clients (about 30 µs for 100 moving players, against about 12 µs for `JSON.stringify`); only the definitions a client misses are added for it (the same ones for clients that joined at the same time).
|
|
390
|
+
- The table is shared by the room. Paths of deleted entities stay in it until it holds `pathTableLimit` paths (default 65536); then it starts over and clients are told to forget theirs.
|
|
391
|
+
- Other clients keep receiving JSON packets. `on("sync", cb)` receives no `value` with this format.
|
|
392
|
+
|
|
393
|
+
**Storage batching.** Without `throttleStorage`, all changes of the same task are written to storage together. With `throttleStorage`, writes wait until no change happened for that long, but never more than `throttleStorageMaxWait`, so a state that changes continuously is still persisted.
|
|
394
|
+
|
|
358
395
|
### Authentication & Authorization
|
|
359
396
|
|
|
360
397
|
You can implement authentication and authorization using guards:
|
|
@@ -518,9 +555,10 @@ class GameRoom {
|
|
|
518
555
|
**Instance Properties:**
|
|
519
556
|
- `$autoSync` (boolean): Controls whether synchronization happens automatically (default: `true`)
|
|
520
557
|
- `$pendingSync` (Map): Stores pending synchronization changes when `autoSync` is disabled
|
|
558
|
+
- `$pendingEvents` (Map): Stores pending `event()` emissions when `autoSync` is disabled; they are sent once by the next `$applySync()`
|
|
521
559
|
- `$applySync()` (method): Manually broadcasts all pending changes to all clients
|
|
522
560
|
|
|
523
|
-
**Note:** When `autoSync` is disabled, changes are stored in `$pendingSync` until you call `$applySync()`. If you call `$applySync()` with no pending changes, it will broadcast the current state from `$memoryAll`, which is useful for forcing a full state synchronization.
|
|
561
|
+
**Note:** When `autoSync` is disabled, changes are stored in `$pendingSync` until you call `$applySync()`. If you call `$applySync()` with no pending changes, it will broadcast the current state from `$memoryAll`, which is useful for forcing a full state synchronization. Volatile events (`event()` from `@signe/sync`) are never part of `$memoryAll`, so a full synchronization or a new connection never replays them.
|
|
524
562
|
|
|
525
563
|
### Connecting to World Service
|
|
526
564
|
|
|
@@ -820,6 +858,46 @@ The `interceptorPacket` method allows you to:
|
|
|
820
858
|
- Return `null` to prevent the packet from being sent to that user
|
|
821
859
|
- Implement user-specific filtering or censoring of data
|
|
822
860
|
|
|
861
|
+
By default each client's interceptor receives its own copy of the packet (`structuredClone`), so it may modify it. If your interceptor never modifies the packet it receives (it returns a new object instead), set `copyPacketForInterceptor: false` to skip that copy for every client and every packet:
|
|
862
|
+
|
|
863
|
+
```ts
|
|
864
|
+
@Room({ path: "game", copyPacketForInterceptor: false })
|
|
865
|
+
```
|
|
866
|
+
|
|
867
|
+
### Per-client visibility of entities
|
|
868
|
+
|
|
869
|
+
For sync packets, you can describe what each client sees instead of filtering packets yourself. The room then builds each client's packet from pieces serialized once per broadcast:
|
|
870
|
+
|
|
871
|
+
```ts
|
|
872
|
+
class MapRoom {
|
|
873
|
+
@users(Player) players = signal<Record<string, Player>>({});
|
|
874
|
+
@sync(Npc) npcs = signal<Record<string, Npc>>({});
|
|
875
|
+
|
|
876
|
+
// Ids each client can see, by collection. Called for each client and each sync packet,
|
|
877
|
+
// with the changes of the packet. Collections not returned are sent to everyone.
|
|
878
|
+
syncVisibility(user: Player, conn: Party.Connection, patch: any) {
|
|
879
|
+
return {
|
|
880
|
+
players: playersAround(user),
|
|
881
|
+
npcs: npcsAround(user),
|
|
882
|
+
};
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
// Optional fields added to each client's sync packet
|
|
886
|
+
syncPacketHeader(user: Player, conn: Party.Connection, patch: any) {
|
|
887
|
+
return { timestamp: Date.now() };
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
```
|
|
891
|
+
|
|
892
|
+
For each collection returned by `syncVisibility`:
|
|
893
|
+
- an entity that stays visible receives its changes, as usual;
|
|
894
|
+
- an entity that becomes visible is sent with its **full state** (from the room's synchronized state), so the client can create it;
|
|
895
|
+
- an entity that is no longer visible, or was deleted, is sent as `"$delete"`, so the client removes it.
|
|
896
|
+
|
|
897
|
+
The initial sync of a new client is filtered the same way. Sync packets of a room with `syncVisibility` do not go through `interceptorPacket`; other packets still do. Volatile events (`event()`) are sent with the packet. With `compression`, these per-client packets are compressed only with `compression.intercepted: true`. The room remembers what each connection sees and forgets it when the connection closes (after a Cloudflare hibernation, visible entities are sent again in full).
|
|
898
|
+
|
|
899
|
+
With 100 players and 50 clients each seeing 30 players, building the per-client packets goes from about 3.4 ms per tick (copy, interceptor and serialization per client) to about 0.12 ms, for the same packet size.
|
|
900
|
+
|
|
823
901
|
### Lifecycle Hooks
|
|
824
902
|
|
|
825
903
|
Rooms provide several lifecycle hooks:
|
package/src/decorators.ts
CHANGED
|
@@ -59,12 +59,67 @@ export function Request(options: RequestOptions, bodyValidation?: z.ZodSchema) {
|
|
|
59
59
|
};
|
|
60
60
|
}
|
|
61
61
|
|
|
62
|
+
export interface RoomCompressionOptions {
|
|
63
|
+
/** Minimum size (characters of JSON) of a message to compress. Default: 512. */
|
|
64
|
+
threshold?: number;
|
|
65
|
+
/** DEFLATE level, 1 (fastest) to 9. Default: 1, which keeps most of the gain for half the CPU. */
|
|
66
|
+
level?: number;
|
|
67
|
+
/**
|
|
68
|
+
* Also compress messages returned by `interceptorPacket`. Each client then has its own
|
|
69
|
+
* packet, so this costs one compression per client and per message. Default: false.
|
|
70
|
+
* Also applies to the per-client packets of `syncVisibility`.
|
|
71
|
+
*/
|
|
72
|
+
intercepted?: boolean;
|
|
73
|
+
/**
|
|
74
|
+
* Compress per-client messages with one DEFLATE stream per connection, for clients that can
|
|
75
|
+
* read it (`@signe/sync` client with `compression: true`). Each message is set up faster and
|
|
76
|
+
* refers to the previous ones: on small game packets, about 3 times less CPU and 2 times fewer
|
|
77
|
+
* bytes than compressing each message alone. Costs about 48 KB of memory per connection.
|
|
78
|
+
* Default: true.
|
|
79
|
+
*/
|
|
80
|
+
stream?: boolean;
|
|
81
|
+
/** History of the stream: 2^windowBits bytes (9 to 15). Default: 13 (8 KB). */
|
|
82
|
+
windowBits?: number;
|
|
83
|
+
/** Memory of the stream's match finder (1 to 9). Default: 5. */
|
|
84
|
+
memLevel?: number;
|
|
85
|
+
}
|
|
86
|
+
|
|
62
87
|
export interface RoomOptions {
|
|
63
88
|
path: string;
|
|
64
89
|
maxUsers?: number;
|
|
65
90
|
persistState?: boolean;
|
|
91
|
+
/**
|
|
92
|
+
* Debounce window (ms) for storage writes: changes are written once no change happened for this long.
|
|
93
|
+
*/
|
|
66
94
|
throttleStorage?: number;
|
|
95
|
+
/**
|
|
96
|
+
* Upper bound (ms) on how long changes can wait for a storage write while the state keeps changing.
|
|
97
|
+
* Defaults to 10 × `throttleStorage`.
|
|
98
|
+
*/
|
|
99
|
+
throttleStorageMaxWait?: number;
|
|
100
|
+
/**
|
|
101
|
+
* Minimum interval (ms) between two sync packets. Changes made in the same task are always
|
|
102
|
+
* grouped into one packet, even without this option.
|
|
103
|
+
*/
|
|
67
104
|
throttleSync?: number;
|
|
105
|
+
/**
|
|
106
|
+
* Give `interceptorPacket` its own copy of each packet (default: true). Set to false when
|
|
107
|
+
* the interceptor never modifies the packet it receives (it returns a new object instead):
|
|
108
|
+
* this removes a `structuredClone` per client and per packet.
|
|
109
|
+
*/
|
|
110
|
+
copyPacketForInterceptor?: boolean;
|
|
111
|
+
/**
|
|
112
|
+
* Send compressed messages (binary frames, DEFLATE) to clients that ask for them
|
|
113
|
+
* (`connectionRoom(..., { compression: true })`). Other clients keep receiving JSON text.
|
|
114
|
+
* A broadcast is compressed once for all clients. Default: disabled.
|
|
115
|
+
*/
|
|
116
|
+
compression?: boolean | RoomCompressionOptions;
|
|
117
|
+
/**
|
|
118
|
+
* Number of paths after which the path table (sync packets of clients that asked for
|
|
119
|
+
* `pathFormat`) starts over. Paths of deleted entities stay in the table until then.
|
|
120
|
+
* Default: 65536.
|
|
121
|
+
*/
|
|
122
|
+
pathTableLimit?: number;
|
|
68
123
|
hibernate?: boolean;
|
|
69
124
|
guards?: RoomGuardFn[];
|
|
70
125
|
sessionExpiryTime?: number;
|
|
@@ -76,7 +131,15 @@ export function Room(options: RoomOptions) {
|
|
|
76
131
|
target.prototype.maxUsers = options.maxUsers;
|
|
77
132
|
target.prototype.persistState = options.persistState ?? true;
|
|
78
133
|
target.prototype.throttleStorage = options.throttleStorage;
|
|
134
|
+
target.prototype.throttleStorageMaxWait = options.throttleStorageMaxWait;
|
|
79
135
|
target.prototype.throttleSync = options.throttleSync;
|
|
136
|
+
if (options.copyPacketForInterceptor !== undefined) {
|
|
137
|
+
target.prototype.copyPacketForInterceptor = options.copyPacketForInterceptor;
|
|
138
|
+
}
|
|
139
|
+
target.prototype.compression = options.compression;
|
|
140
|
+
if (options.pathTableLimit !== undefined) {
|
|
141
|
+
target.prototype.pathTableLimit = options.pathTableLimit;
|
|
142
|
+
}
|
|
80
143
|
target.prototype.sessionExpiryTime = options.sessionExpiryTime ?? 5 * 60 * 1000;
|
|
81
144
|
if (options.guards) {
|
|
82
145
|
target['_roomGuards'] = options.guards;
|
package/src/node/index.ts
CHANGED
|
@@ -744,7 +744,11 @@ export class NodeConnection<TState = unknown> {
|
|
|
744
744
|
readonly sessionId: string;
|
|
745
745
|
readonly socket: this = this;
|
|
746
746
|
readonly uri: string;
|
|
747
|
-
|
|
747
|
+
/**
|
|
748
|
+
* Application-owned state associated with this connection.
|
|
749
|
+
* Read it as immutable data and use `setState()` to replace it.
|
|
750
|
+
*/
|
|
751
|
+
state: Party.ConnectionState<TState> = null;
|
|
748
752
|
private attachment: unknown = null;
|
|
749
753
|
|
|
750
754
|
constructor(
|
|
@@ -766,11 +770,12 @@ export class NodeConnection<TState = unknown> {
|
|
|
766
770
|
this.webSocket.close(code, reason);
|
|
767
771
|
}
|
|
768
772
|
|
|
769
|
-
setState(state: TState | Party.ConnectionSetStateFn<TState> | null) {
|
|
770
|
-
|
|
771
|
-
? (state as Party.ConnectionSetStateFn<TState>)(this.state
|
|
773
|
+
setState(state: TState | Party.ConnectionSetStateFn<TState> | null): Party.ConnectionState<TState> {
|
|
774
|
+
const next = typeof state === "function"
|
|
775
|
+
? (state as Party.ConnectionSetStateFn<TState>)(this.state)
|
|
772
776
|
: state;
|
|
773
|
-
|
|
777
|
+
this.state = next as Party.ConnectionState<TState>;
|
|
778
|
+
return this.state;
|
|
774
779
|
}
|
|
775
780
|
|
|
776
781
|
serializeAttachment<T = unknown>(attachment: T): void {
|