@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 +78 -0
- package/dist/index.d.ts +103 -2
- package/dist/index.js +476 -88
- package/dist/index.js.map +1 -1
- package/examples/cloudflare/CHANGELOG.md +22 -0
- package/examples/cloudflare/package.json +1 -1
- package/examples/node/CHANGELOG.md +22 -0
- package/examples/node/package.json +2 -2
- package/examples/node-game/CHANGELOG.md +22 -0
- package/examples/node-game/package.json +2 -2
- package/examples/node-shard/CHANGELOG.md +22 -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/server.ts +517 -79
- package/src/utils.ts +84 -6
package/dist/index.js
CHANGED
|
@@ -43,7 +43,15 @@ function Room(options) {
|
|
|
43
43
|
target.prototype.maxUsers = options.maxUsers;
|
|
44
44
|
target.prototype.persistState = options.persistState ?? true;
|
|
45
45
|
target.prototype.throttleStorage = options.throttleStorage;
|
|
46
|
+
target.prototype.throttleStorageMaxWait = options.throttleStorageMaxWait;
|
|
46
47
|
target.prototype.throttleSync = options.throttleSync;
|
|
48
|
+
if (options.copyPacketForInterceptor !== void 0) {
|
|
49
|
+
target.prototype.copyPacketForInterceptor = options.copyPacketForInterceptor;
|
|
50
|
+
}
|
|
51
|
+
target.prototype.compression = options.compression;
|
|
52
|
+
if (options.pathTableLimit !== void 0) {
|
|
53
|
+
target.prototype.pathTableLimit = options.pathTableLimit;
|
|
54
|
+
}
|
|
47
55
|
target.prototype.sessionExpiryTime = options.sessionExpiryTime ?? 5 * 60 * 1e3;
|
|
48
56
|
if (options.guards) {
|
|
49
57
|
target["_roomGuards"] = options.guards;
|
|
@@ -129,7 +137,16 @@ import {
|
|
|
129
137
|
syncClass,
|
|
130
138
|
DELETE_TOKEN,
|
|
131
139
|
generateShortUUID as generateShortUUID2,
|
|
132
|
-
createStatesSnapshotDeep
|
|
140
|
+
createStatesSnapshotDeep,
|
|
141
|
+
compressMessage,
|
|
142
|
+
createMessageCompressor,
|
|
143
|
+
COMPRESSION_QUERY_PARAM,
|
|
144
|
+
COMPRESSION_QUERY_VALUE,
|
|
145
|
+
COMPRESSION_STREAM_QUERY_PARAM,
|
|
146
|
+
COMPRESSION_STREAM_QUERY_VALUE,
|
|
147
|
+
PathTable,
|
|
148
|
+
PATH_FORMAT_QUERY_PARAM,
|
|
149
|
+
PATH_FORMAT_QUERY_VALUE
|
|
133
150
|
} from "@signe/sync";
|
|
134
151
|
|
|
135
152
|
// src/utils.ts
|
|
@@ -143,21 +160,38 @@ async function awaitReturn(val) {
|
|
|
143
160
|
function isClass(obj) {
|
|
144
161
|
return typeof obj === "function" && obj.prototype && obj.prototype.constructor === obj;
|
|
145
162
|
}
|
|
146
|
-
function
|
|
163
|
+
function debounce(fn, wait, maxWait = Infinity) {
|
|
147
164
|
let timeout = null;
|
|
148
|
-
let
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
165
|
+
let firstCallAt = null;
|
|
166
|
+
const run = () => {
|
|
167
|
+
timeout = null;
|
|
168
|
+
firstCallAt = null;
|
|
169
|
+
fn();
|
|
170
|
+
};
|
|
171
|
+
return () => {
|
|
172
|
+
const now = Date.now();
|
|
173
|
+
if (firstCallAt === null) firstCallAt = now;
|
|
174
|
+
if (timeout) clearTimeout(timeout);
|
|
175
|
+
const delay = Math.max(0, Math.min(wait, firstCallAt + maxWait - now));
|
|
176
|
+
timeout = setTimeout(run, delay);
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
function batch(fn, wait = 0) {
|
|
180
|
+
let scheduled = false;
|
|
181
|
+
let lastRun = -Infinity;
|
|
182
|
+
const run = () => {
|
|
183
|
+
scheduled = false;
|
|
184
|
+
lastRun = Date.now();
|
|
185
|
+
fn();
|
|
186
|
+
};
|
|
187
|
+
return () => {
|
|
188
|
+
if (scheduled) return;
|
|
189
|
+
scheduled = true;
|
|
190
|
+
const delay = wait > 0 ? lastRun + wait - Date.now() : 0;
|
|
191
|
+
if (delay > 0) {
|
|
192
|
+
setTimeout(run, delay);
|
|
159
193
|
} else {
|
|
160
|
-
|
|
194
|
+
queueMicrotask(run);
|
|
161
195
|
}
|
|
162
196
|
};
|
|
163
197
|
}
|
|
@@ -192,15 +226,28 @@ function dremove(obj, keys) {
|
|
|
192
226
|
delete t[k];
|
|
193
227
|
}
|
|
194
228
|
}
|
|
229
|
+
var PATH_KEYS_CACHE_LIMIT = 1e4;
|
|
230
|
+
var pathKeysCache = /* @__PURE__ */ new Map();
|
|
231
|
+
function splitPath(path) {
|
|
232
|
+
let keys = pathKeysCache.get(path);
|
|
233
|
+
if (!keys) {
|
|
234
|
+
if (pathKeysCache.size >= PATH_KEYS_CACHE_LIMIT) {
|
|
235
|
+
pathKeysCache.clear();
|
|
236
|
+
}
|
|
237
|
+
keys = path.split(".");
|
|
238
|
+
pathKeysCache.set(path, keys);
|
|
239
|
+
}
|
|
240
|
+
return keys;
|
|
241
|
+
}
|
|
195
242
|
function buildObject(valuesMap, allMemory) {
|
|
196
|
-
|
|
197
|
-
for (
|
|
198
|
-
const
|
|
199
|
-
dset(memoryObj,
|
|
243
|
+
const memoryObj = {};
|
|
244
|
+
for (const [path, value] of valuesMap) {
|
|
245
|
+
const keys = splitPath(path);
|
|
246
|
+
dset(memoryObj, keys, value);
|
|
200
247
|
if (value === "$delete") {
|
|
201
|
-
dremove(allMemory,
|
|
248
|
+
dremove(allMemory, keys);
|
|
202
249
|
} else {
|
|
203
|
-
dset(allMemory,
|
|
250
|
+
dset(allMemory, keys, value);
|
|
204
251
|
}
|
|
205
252
|
}
|
|
206
253
|
return memoryObj;
|
|
@@ -462,6 +509,110 @@ var INTERNAL_PREFIX = "$room:";
|
|
|
462
509
|
var SESSION_GC_LAST_RUN_KEY = `${INTERNAL_PREFIX}session-gc:last-run`;
|
|
463
510
|
var TRANSFER_GC_LAST_RUN_KEY = `${INTERNAL_PREFIX}transfer-gc:last-run`;
|
|
464
511
|
var DEFAULT_TRANSFER_EXPIRY_MS = 5 * 60 * 1e3;
|
|
512
|
+
var SyncFragments = class {
|
|
513
|
+
constructor() {
|
|
514
|
+
this.fields = /* @__PURE__ */ new Map();
|
|
515
|
+
this.patches = /* @__PURE__ */ new Map();
|
|
516
|
+
this.fulls = /* @__PURE__ */ new Map();
|
|
517
|
+
}
|
|
518
|
+
field(key, value) {
|
|
519
|
+
let fragment = this.fields.get(key);
|
|
520
|
+
if (fragment === void 0) {
|
|
521
|
+
fragment = `${JSON.stringify(key)}:${JSON.stringify(value)}`;
|
|
522
|
+
this.fields.set(key, fragment);
|
|
523
|
+
}
|
|
524
|
+
return fragment;
|
|
525
|
+
}
|
|
526
|
+
entity(collection, id2, value, kind) {
|
|
527
|
+
const cache = kind === "patch" ? this.patches : this.fulls;
|
|
528
|
+
const cacheKey = collection + "\0" + id2;
|
|
529
|
+
let fragment = cache.get(cacheKey);
|
|
530
|
+
if (fragment === void 0) {
|
|
531
|
+
fragment = `${JSON.stringify(id2)}:${JSON.stringify(value)}`;
|
|
532
|
+
cache.set(cacheKey, fragment);
|
|
533
|
+
}
|
|
534
|
+
return fragment;
|
|
535
|
+
}
|
|
536
|
+
deleted(_collection, id2) {
|
|
537
|
+
return `${JSON.stringify(id2)}:${JSON.stringify(DELETE_TOKEN)}`;
|
|
538
|
+
}
|
|
539
|
+
collection(key, entries) {
|
|
540
|
+
return `${JSON.stringify(key)}:{${entries.join(",")}}`;
|
|
541
|
+
}
|
|
542
|
+
header(header) {
|
|
543
|
+
const parts = [];
|
|
544
|
+
for (const key in header) {
|
|
545
|
+
parts.push(`${JSON.stringify(key)}:${JSON.stringify(header[key])}`);
|
|
546
|
+
}
|
|
547
|
+
return parts;
|
|
548
|
+
}
|
|
549
|
+
packet(_conn, parts, obj) {
|
|
550
|
+
return `{"type":"sync","value":{${parts.join(",")}}` + otherPacketKeys(obj) + "}";
|
|
551
|
+
}
|
|
552
|
+
};
|
|
553
|
+
function otherPacketKeys(obj) {
|
|
554
|
+
let data = "";
|
|
555
|
+
for (const key in obj) {
|
|
556
|
+
if (key === "type" || key === "value") continue;
|
|
557
|
+
data += `,${JSON.stringify(key)}:${JSON.stringify(obj[key])}`;
|
|
558
|
+
}
|
|
559
|
+
return data;
|
|
560
|
+
}
|
|
561
|
+
var PathSyncFragments = class {
|
|
562
|
+
constructor(table, cursor) {
|
|
563
|
+
this.table = table;
|
|
564
|
+
this.cursor = cursor;
|
|
565
|
+
this.fields = /* @__PURE__ */ new Map();
|
|
566
|
+
this.patches = /* @__PURE__ */ new Map();
|
|
567
|
+
this.fulls = /* @__PURE__ */ new Map();
|
|
568
|
+
table.startPacket();
|
|
569
|
+
}
|
|
570
|
+
field(key, value) {
|
|
571
|
+
let fragment = this.fields.get(key);
|
|
572
|
+
if (fragment === void 0) {
|
|
573
|
+
fragment = this.table.encode({ [key]: value });
|
|
574
|
+
this.fields.set(key, fragment);
|
|
575
|
+
}
|
|
576
|
+
return fragment;
|
|
577
|
+
}
|
|
578
|
+
entity(collection, id2, value, kind) {
|
|
579
|
+
const cache = kind === "patch" ? this.patches : this.fulls;
|
|
580
|
+
const cacheKey = collection + "\0" + id2;
|
|
581
|
+
let fragment = cache.get(cacheKey);
|
|
582
|
+
if (fragment === void 0) {
|
|
583
|
+
fragment = value !== null && typeof value === "object" && !Array.isArray(value) ? this.table.encode(value, collection + "." + id2) : this.table.encodeLeaf(collection + "." + id2, value);
|
|
584
|
+
cache.set(cacheKey, fragment);
|
|
585
|
+
}
|
|
586
|
+
return fragment;
|
|
587
|
+
}
|
|
588
|
+
deleted(collection, id2) {
|
|
589
|
+
return this.table.encodeLeaf(collection + "." + id2, DELETE_TOKEN);
|
|
590
|
+
}
|
|
591
|
+
collection(_key, entries) {
|
|
592
|
+
return joinPairs(entries);
|
|
593
|
+
}
|
|
594
|
+
header(header) {
|
|
595
|
+
return [this.table.encode(header)];
|
|
596
|
+
}
|
|
597
|
+
packet(conn, parts, obj) {
|
|
598
|
+
const pairs = joinPairs(parts);
|
|
599
|
+
return `{"type":"sync",${this.table.header(this.cursor(conn))}"p":[${pairs}]` + otherPacketKeys(obj) + "}";
|
|
600
|
+
}
|
|
601
|
+
};
|
|
602
|
+
function joinPairs(parts) {
|
|
603
|
+
let out = "";
|
|
604
|
+
for (const part of parts) {
|
|
605
|
+
if (part === "") continue;
|
|
606
|
+
out += out === "" ? part : "," + part;
|
|
607
|
+
}
|
|
608
|
+
return out;
|
|
609
|
+
}
|
|
610
|
+
function takeEvents(queue) {
|
|
611
|
+
if (queue.size === 0) return void 0;
|
|
612
|
+
const events = Object.fromEntries(queue);
|
|
613
|
+
queue.clear();
|
|
614
|
+
return events;
|
|
615
|
+
}
|
|
465
616
|
var Server = class {
|
|
466
617
|
/**
|
|
467
618
|
* @constructor
|
|
@@ -476,6 +627,18 @@ var Server = class {
|
|
|
476
627
|
this.room = room;
|
|
477
628
|
this.subRoom = null;
|
|
478
629
|
this.rooms = [];
|
|
630
|
+
/** Compressors of the connections that read stream messages (see `createMessageCompressor`). */
|
|
631
|
+
this.compressors = /* @__PURE__ */ new WeakMap();
|
|
632
|
+
/** Path cursor of each connection: the path definitions it already received. */
|
|
633
|
+
this.pathCursors = /* @__PURE__ */ new WeakMap();
|
|
634
|
+
this.pathCursor = (conn) => {
|
|
635
|
+
let cursor = this.pathCursors.get(conn);
|
|
636
|
+
if (!cursor) {
|
|
637
|
+
cursor = { epoch: -1, known: 0 };
|
|
638
|
+
this.pathCursors.set(conn, cursor);
|
|
639
|
+
}
|
|
640
|
+
return cursor;
|
|
641
|
+
};
|
|
479
642
|
}
|
|
480
643
|
/**
|
|
481
644
|
* @readonly
|
|
@@ -675,22 +838,223 @@ var Server = class {
|
|
|
675
838
|
hasActiveSessionConnection(privateId) {
|
|
676
839
|
return Array.from(this.room.getConnections()).some((conn) => this.getPrivateId(conn) === privateId);
|
|
677
840
|
}
|
|
841
|
+
/**
|
|
842
|
+
* Whether `data` should be sent compressed to `conn`: the room enables compression,
|
|
843
|
+
* the client asked for it, the message is large enough, and (for packets returned by
|
|
844
|
+
* `interceptorPacket`) per-client compression is enabled.
|
|
845
|
+
*/
|
|
846
|
+
shouldCompress(conn, subRoom, data, intercepted) {
|
|
847
|
+
const compression = subRoom?.$compression;
|
|
848
|
+
if (!compression || !conn.state?.compression) return false;
|
|
849
|
+
if (intercepted && !compression.intercepted) return false;
|
|
850
|
+
return data.length >= compression.threshold;
|
|
851
|
+
}
|
|
678
852
|
async send(conn, obj, subRoom) {
|
|
679
|
-
|
|
680
|
-
|
|
853
|
+
if (this.usesSyncVisibility(obj, subRoom)) {
|
|
854
|
+
this.sendPerClient(conn, this.buildVisibleSyncPacket(conn, obj, subRoom, this.syncWriter(conn, subRoom, {})), subRoom);
|
|
855
|
+
return;
|
|
856
|
+
}
|
|
857
|
+
const intercepted = !!subRoom?.interceptorPacket;
|
|
858
|
+
if (subRoom?.interceptorPacket) {
|
|
859
|
+
if (subRoom.copyPacketForInterceptor !== false) {
|
|
860
|
+
obj = structuredClone(obj);
|
|
861
|
+
}
|
|
681
862
|
const signal2 = this.getUsersProperty(subRoom);
|
|
682
863
|
const { publicId } = conn.state;
|
|
683
864
|
const user = signal2?.()[publicId];
|
|
684
865
|
obj = await awaitReturn(subRoom["interceptorPacket"]?.(user, obj, conn));
|
|
685
866
|
if (obj === null) return;
|
|
686
867
|
}
|
|
687
|
-
|
|
868
|
+
let data;
|
|
869
|
+
if (this.usesPathFormat(conn, obj)) {
|
|
870
|
+
const table = this.pathTable(subRoom);
|
|
871
|
+
table.startPacket();
|
|
872
|
+
const body = this.pathPacketBody(obj, table.encode(obj.value));
|
|
873
|
+
data = this.pathPacket(conn, table, body);
|
|
874
|
+
} else {
|
|
875
|
+
data = JSON.stringify(obj);
|
|
876
|
+
}
|
|
877
|
+
conn.send(
|
|
878
|
+
this.shouldCompress(conn, subRoom, data, intercepted) ? this.compressForClient(conn, subRoom, data) : data
|
|
879
|
+
);
|
|
688
880
|
}
|
|
689
|
-
|
|
881
|
+
/**
|
|
882
|
+
* Compresses a message built for this client only: with the connection's stream when the
|
|
883
|
+
* client reads stream messages (3 times cheaper and 2 times smaller on small packets,
|
|
884
|
+
* since the stream is set up once and messages refer to the previous ones), otherwise alone.
|
|
885
|
+
*/
|
|
886
|
+
compressForClient(conn, subRoom, data) {
|
|
887
|
+
const compression = subRoom.$compression;
|
|
888
|
+
if (compression.stream === false || !conn.state?.compressionStream) {
|
|
889
|
+
return compressMessage(data, compression.level);
|
|
890
|
+
}
|
|
891
|
+
let compressor = this.compressors.get(conn);
|
|
892
|
+
if (!compressor) {
|
|
893
|
+
compressor = createMessageCompressor({
|
|
894
|
+
level: compression.level,
|
|
895
|
+
windowBits: compression.windowBits,
|
|
896
|
+
memLevel: compression.memLevel
|
|
897
|
+
});
|
|
898
|
+
this.compressors.set(conn, compressor);
|
|
899
|
+
}
|
|
900
|
+
return compressor.compress(data);
|
|
901
|
+
}
|
|
902
|
+
/**
|
|
903
|
+
* Sends a packet to every connection (except `exclude`).
|
|
904
|
+
* Without `interceptorPacket`, the packet is serialized once and the same string is sent to all.
|
|
905
|
+
*/
|
|
906
|
+
broadcast(obj, subRoom, exclude) {
|
|
907
|
+
if (this.usesSyncVisibility(obj, subRoom)) {
|
|
908
|
+
const writers = {};
|
|
909
|
+
for (let conn of this.room.getConnections()) {
|
|
910
|
+
if (exclude?.has(conn)) continue;
|
|
911
|
+
this.sendPerClient(conn, this.buildVisibleSyncPacket(conn, obj, subRoom, this.syncWriter(conn, subRoom, writers)), subRoom);
|
|
912
|
+
}
|
|
913
|
+
return;
|
|
914
|
+
}
|
|
915
|
+
if (subRoom?.interceptorPacket) {
|
|
916
|
+
for (let conn of this.room.getConnections()) {
|
|
917
|
+
if (exclude?.has(conn)) continue;
|
|
918
|
+
this.send(conn, obj, subRoom);
|
|
919
|
+
}
|
|
920
|
+
return;
|
|
921
|
+
}
|
|
922
|
+
let data;
|
|
923
|
+
let compressed;
|
|
924
|
+
let pathBody;
|
|
925
|
+
let pathCompressed;
|
|
690
926
|
for (let conn of this.room.getConnections()) {
|
|
691
|
-
|
|
927
|
+
if (exclude?.has(conn)) continue;
|
|
928
|
+
if (this.usesPathFormat(conn, obj)) {
|
|
929
|
+
const table = this.pathTable(subRoom);
|
|
930
|
+
if (pathBody === void 0) {
|
|
931
|
+
table.startPacket();
|
|
932
|
+
pathBody = this.pathPacketBody(obj, table.encode(obj.value));
|
|
933
|
+
}
|
|
934
|
+
const header = table.header(this.pathCursor(conn));
|
|
935
|
+
const pathData = `{"type":"sync",${header}${pathBody}`;
|
|
936
|
+
if (this.shouldCompress(conn, subRoom, pathData, false)) {
|
|
937
|
+
pathCompressed ??= /* @__PURE__ */ new Map();
|
|
938
|
+
let bytes = pathCompressed.get(header);
|
|
939
|
+
if (!bytes) {
|
|
940
|
+
bytes = compressMessage(pathData, subRoom.$compression.level);
|
|
941
|
+
pathCompressed.set(header, bytes);
|
|
942
|
+
}
|
|
943
|
+
conn.send(bytes);
|
|
944
|
+
} else {
|
|
945
|
+
conn.send(pathData);
|
|
946
|
+
}
|
|
947
|
+
continue;
|
|
948
|
+
}
|
|
949
|
+
data ??= JSON.stringify(obj);
|
|
950
|
+
if (this.shouldCompress(conn, subRoom, data, false)) {
|
|
951
|
+
compressed ??= compressMessage(data, subRoom.$compression.level);
|
|
952
|
+
conn.send(compressed);
|
|
953
|
+
} else {
|
|
954
|
+
conn.send(data);
|
|
955
|
+
}
|
|
692
956
|
}
|
|
693
957
|
}
|
|
958
|
+
/**
|
|
959
|
+
* Sends a packet built for this client only. Like intercepted packets, it is compressed only
|
|
960
|
+
* with `compression.intercepted`, since each client needs its own compression.
|
|
961
|
+
*/
|
|
962
|
+
sendPerClient(conn, data, subRoom) {
|
|
963
|
+
conn.send(
|
|
964
|
+
this.shouldCompress(conn, subRoom, data, true) ? this.compressForClient(conn, subRoom, data) : data
|
|
965
|
+
);
|
|
966
|
+
}
|
|
967
|
+
/** Whether this sync packet is sent to `conn` in the path table format (asked by the client). */
|
|
968
|
+
usesPathFormat(conn, obj) {
|
|
969
|
+
return obj?.type === "sync" && !!conn.state?.pathFormat && obj.value !== null && typeof obj.value === "object";
|
|
970
|
+
}
|
|
971
|
+
pathTable(subRoom) {
|
|
972
|
+
return subRoom.$pathTable ??= new PathTable(subRoom.pathTableLimit);
|
|
973
|
+
}
|
|
974
|
+
/** End of a path table packet: pairs and the other keys of the packet. */
|
|
975
|
+
pathPacketBody(obj, pairs) {
|
|
976
|
+
return `"p":[${pairs}]` + otherPacketKeys(obj) + "}";
|
|
977
|
+
}
|
|
978
|
+
pathPacket(conn, table, body) {
|
|
979
|
+
return `{"type":"sync",${table.header(this.pathCursor(conn))}${body}`;
|
|
980
|
+
}
|
|
981
|
+
/** Writer of `conn`'s format, shared through `writers` by the clients of one broadcast. */
|
|
982
|
+
syncWriter(conn, subRoom, writers) {
|
|
983
|
+
if (conn.state?.pathFormat) {
|
|
984
|
+
return writers.paths ??= new PathSyncFragments(this.pathTable(subRoom), this.pathCursor);
|
|
985
|
+
}
|
|
986
|
+
return writers.json ??= new SyncFragments();
|
|
987
|
+
}
|
|
988
|
+
/** Sync packets of a room that defines `syncVisibility` are filtered per client. */
|
|
989
|
+
usesSyncVisibility(obj, subRoom) {
|
|
990
|
+
return obj?.type === "sync" && typeof subRoom?.syncVisibility === "function";
|
|
991
|
+
}
|
|
992
|
+
/**
|
|
993
|
+
* Builds the sync packet of one client for a room that defines `syncVisibility`.
|
|
994
|
+
*
|
|
995
|
+
* For each collection returned by `syncVisibility(user, conn, patch)`:
|
|
996
|
+
* - an entity that stays visible gets its patch (if it changed);
|
|
997
|
+
* - an entity that becomes visible gets its full state, from `$memoryAll`;
|
|
998
|
+
* - an entity that is no longer visible (or was deleted) gets `"$delete"`.
|
|
999
|
+
* Other keys of the packet are sent to everyone. `syncPacketHeader(user, conn, patch)` adds
|
|
1000
|
+
* per-client fields. Fragments are serialized once per broadcast and shared between clients.
|
|
1001
|
+
*/
|
|
1002
|
+
buildVisibleSyncPacket(conn, obj, subRoom, fragments) {
|
|
1003
|
+
const user = this.getUsersProperty(subRoom)?.()[conn.state?.publicId];
|
|
1004
|
+
const value = obj.value && typeof obj.value === "object" ? obj.value : {};
|
|
1005
|
+
const visibility = subRoom.syncVisibility(user, conn, value) ?? {};
|
|
1006
|
+
const states = subRoom.$syncVisibleEntities ??= /* @__PURE__ */ new Map();
|
|
1007
|
+
let state = states.get(conn.id);
|
|
1008
|
+
if (!state) {
|
|
1009
|
+
state = /* @__PURE__ */ new Map();
|
|
1010
|
+
states.set(conn.id, state);
|
|
1011
|
+
}
|
|
1012
|
+
const parts = [];
|
|
1013
|
+
for (const key in value) {
|
|
1014
|
+
if (visibility[key] != null) continue;
|
|
1015
|
+
parts.push(fragments.field(key, value[key]));
|
|
1016
|
+
}
|
|
1017
|
+
for (const key in visibility) {
|
|
1018
|
+
const visibleIds = visibility[key];
|
|
1019
|
+
if (visibleIds == null) continue;
|
|
1020
|
+
const patch = value[key];
|
|
1021
|
+
const patchEntries = patch && typeof patch === "object" && !Array.isArray(patch) ? patch : void 0;
|
|
1022
|
+
const memory = subRoom.$memoryAll?.[key];
|
|
1023
|
+
const previous = state.get(key);
|
|
1024
|
+
const visible = /* @__PURE__ */ new Set();
|
|
1025
|
+
const entries = [];
|
|
1026
|
+
for (const id2 of visibleIds) {
|
|
1027
|
+
if (visible.has(id2)) continue;
|
|
1028
|
+
if (previous?.has(id2)) {
|
|
1029
|
+
const entityPatch = patchEntries?.[id2];
|
|
1030
|
+
if (entityPatch === DELETE_TOKEN) continue;
|
|
1031
|
+
visible.add(id2);
|
|
1032
|
+
if (entityPatch !== void 0) {
|
|
1033
|
+
entries.push(fragments.entity(key, id2, entityPatch, "patch"));
|
|
1034
|
+
}
|
|
1035
|
+
} else {
|
|
1036
|
+
const snapshot = memory?.[id2];
|
|
1037
|
+
if (snapshot === void 0) continue;
|
|
1038
|
+
visible.add(id2);
|
|
1039
|
+
entries.push(fragments.entity(key, id2, snapshot, "full"));
|
|
1040
|
+
}
|
|
1041
|
+
}
|
|
1042
|
+
if (previous) {
|
|
1043
|
+
for (const id2 of previous) {
|
|
1044
|
+
if (!visible.has(id2)) entries.push(fragments.deleted(key, id2));
|
|
1045
|
+
}
|
|
1046
|
+
}
|
|
1047
|
+
if (entries.length > 0) {
|
|
1048
|
+
parts.push(fragments.collection(key, entries));
|
|
1049
|
+
}
|
|
1050
|
+
state.set(key, visible);
|
|
1051
|
+
}
|
|
1052
|
+
const header = subRoom.syncPacketHeader?.(user, conn, value);
|
|
1053
|
+
if (header) {
|
|
1054
|
+
parts.push(...fragments.header(header));
|
|
1055
|
+
}
|
|
1056
|
+
return fragments.packet(conn, parts, obj);
|
|
1057
|
+
}
|
|
694
1058
|
/**
|
|
695
1059
|
* @method onStart
|
|
696
1060
|
* @async
|
|
@@ -991,10 +1355,18 @@ var Server = class {
|
|
|
991
1355
|
metrics.loadMs = Date.now() - startedAt;
|
|
992
1356
|
};
|
|
993
1357
|
instance.$memoryAll = {};
|
|
1358
|
+
const compressionOption = instance["compression"];
|
|
1359
|
+
instance.$compression = compressionOption ? {
|
|
1360
|
+
threshold: 512,
|
|
1361
|
+
level: 1,
|
|
1362
|
+
intercepted: false,
|
|
1363
|
+
...typeof compressionOption === "object" ? compressionOption : {}
|
|
1364
|
+
} : null;
|
|
994
1365
|
instance.$storageMetrics = this.createStorageMetrics();
|
|
995
1366
|
const shouldPersistState = instance["persistState"] !== false;
|
|
996
1367
|
instance.$autoSync = instance["autoSync"] !== false;
|
|
997
1368
|
instance.$pendingSync = /* @__PURE__ */ new Map();
|
|
1369
|
+
instance.$pendingEvents = /* @__PURE__ */ new Map();
|
|
998
1370
|
instance.$pendingInitialSync = /* @__PURE__ */ new Map();
|
|
999
1371
|
instance.$send = (conn, obj) => {
|
|
1000
1372
|
return this.send(conn, obj, instance);
|
|
@@ -1003,11 +1375,10 @@ var Server = class {
|
|
|
1003
1375
|
return this.broadcast(obj, instance);
|
|
1004
1376
|
};
|
|
1005
1377
|
instance.$applySync = () => {
|
|
1378
|
+
flushBatchedSync();
|
|
1006
1379
|
let packet;
|
|
1380
|
+
const events = takeEvents(instance.$pendingEvents);
|
|
1007
1381
|
if (instance.$pendingSync.size > 0) {
|
|
1008
|
-
if (options.getMemoryAll) {
|
|
1009
|
-
buildObject(instance.$pendingSync, instance.$memoryAll);
|
|
1010
|
-
}
|
|
1011
1382
|
packet = buildObject(instance.$pendingSync, instance.$memoryAll);
|
|
1012
1383
|
instance.$pendingSync.clear();
|
|
1013
1384
|
} else {
|
|
@@ -1019,19 +1390,17 @@ var Server = class {
|
|
|
1019
1390
|
type: "sync",
|
|
1020
1391
|
value: {
|
|
1021
1392
|
pId: publicId,
|
|
1022
|
-
...
|
|
1023
|
-
}
|
|
1393
|
+
...instance.$memoryAll
|
|
1394
|
+
},
|
|
1395
|
+
...events ? { events } : {}
|
|
1024
1396
|
}, instance);
|
|
1025
1397
|
}
|
|
1026
1398
|
instance.$pendingInitialSync.clear();
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
}, instance);
|
|
1033
|
-
}
|
|
1034
|
-
}
|
|
1399
|
+
this.broadcast({
|
|
1400
|
+
type: "sync",
|
|
1401
|
+
value: packet,
|
|
1402
|
+
...events ? { events } : {}
|
|
1403
|
+
}, instance, pendingConnections);
|
|
1035
1404
|
};
|
|
1036
1405
|
instance.$sessionTransfer = async (conn, targetRoomId) => {
|
|
1037
1406
|
let user;
|
|
@@ -1084,12 +1453,17 @@ var Server = class {
|
|
|
1084
1453
|
return null;
|
|
1085
1454
|
}
|
|
1086
1455
|
};
|
|
1087
|
-
const syncCb = (values) => {
|
|
1088
|
-
if (
|
|
1456
|
+
const syncCb = (values, eventsQueue) => {
|
|
1457
|
+
if (values.size === 0 && eventsQueue.size === 0) {
|
|
1458
|
+
return;
|
|
1459
|
+
}
|
|
1460
|
+
const skipInit = init && this.isHibernate;
|
|
1461
|
+
if (options.getMemoryAll && (skipInit || !instance.$autoSync)) {
|
|
1089
1462
|
buildObject(values, instance.$memoryAll);
|
|
1090
1463
|
}
|
|
1091
|
-
if (
|
|
1464
|
+
if (skipInit) {
|
|
1092
1465
|
init = false;
|
|
1466
|
+
eventsQueue.clear();
|
|
1093
1467
|
return;
|
|
1094
1468
|
}
|
|
1095
1469
|
if (!instance.$autoSync) {
|
|
@@ -1097,13 +1471,24 @@ var Server = class {
|
|
|
1097
1471
|
instance.$pendingSync.set(path, value);
|
|
1098
1472
|
}
|
|
1099
1473
|
values.clear();
|
|
1474
|
+
for (const [path, payloads] of eventsQueue) {
|
|
1475
|
+
const pending = instance.$pendingEvents.get(path);
|
|
1476
|
+
if (pending) {
|
|
1477
|
+
pending.push(...payloads);
|
|
1478
|
+
} else {
|
|
1479
|
+
instance.$pendingEvents.set(path, [...payloads]);
|
|
1480
|
+
}
|
|
1481
|
+
}
|
|
1482
|
+
eventsQueue.clear();
|
|
1100
1483
|
return;
|
|
1101
1484
|
}
|
|
1102
1485
|
const packet = buildObject(values, instance.$memoryAll);
|
|
1486
|
+
const events = takeEvents(eventsQueue);
|
|
1103
1487
|
this.broadcast(
|
|
1104
1488
|
{
|
|
1105
1489
|
type: "sync",
|
|
1106
|
-
value: packet
|
|
1490
|
+
value: packet,
|
|
1491
|
+
...events ? { events } : {}
|
|
1107
1492
|
},
|
|
1108
1493
|
instance
|
|
1109
1494
|
);
|
|
@@ -1153,57 +1538,45 @@ var Server = class {
|
|
|
1153
1538
|
);
|
|
1154
1539
|
await persistQueue;
|
|
1155
1540
|
};
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
if (flushing) {
|
|
1171
|
-
schedule();
|
|
1172
|
-
return;
|
|
1173
|
-
}
|
|
1174
|
-
const values = new Map(pending);
|
|
1175
|
-
pending.clear();
|
|
1176
|
-
if (!values.size) {
|
|
1177
|
-
return;
|
|
1178
|
-
}
|
|
1179
|
-
flushing = true;
|
|
1180
|
-
try {
|
|
1181
|
-
await persistCb(values);
|
|
1182
|
-
} finally {
|
|
1183
|
-
flushing = false;
|
|
1184
|
-
if (pending.size) {
|
|
1185
|
-
schedule();
|
|
1186
|
-
}
|
|
1187
|
-
}
|
|
1188
|
-
};
|
|
1189
|
-
return (values) => {
|
|
1190
|
-
if (initPersist) {
|
|
1191
|
-
values.clear();
|
|
1192
|
-
return;
|
|
1193
|
-
}
|
|
1194
|
-
for (const [path, value] of values) {
|
|
1195
|
-
pending.set(path, value);
|
|
1196
|
-
}
|
|
1541
|
+
let persistValuesRef = null;
|
|
1542
|
+
const flushPersistValues = () => {
|
|
1543
|
+
if (persistValuesRef?.size) {
|
|
1544
|
+
void persistCb(persistValuesRef);
|
|
1545
|
+
}
|
|
1546
|
+
};
|
|
1547
|
+
const throttleStorage = instance["throttleStorage"] || 0;
|
|
1548
|
+
const schedulePersist = throttleStorage > 0 ? debounce(
|
|
1549
|
+
flushPersistValues,
|
|
1550
|
+
throttleStorage,
|
|
1551
|
+
instance["throttleStorageMaxWait"] ?? throttleStorage * 10
|
|
1552
|
+
) : batch(flushPersistValues);
|
|
1553
|
+
const batchedPersist = (values) => {
|
|
1554
|
+
if (initPersist) {
|
|
1197
1555
|
values.clear();
|
|
1198
|
-
|
|
1199
|
-
}
|
|
1556
|
+
return;
|
|
1557
|
+
}
|
|
1558
|
+
persistValuesRef = values;
|
|
1559
|
+
schedulePersist();
|
|
1200
1560
|
};
|
|
1201
1561
|
const disabledPersist = (values) => {
|
|
1202
1562
|
values.clear();
|
|
1203
1563
|
};
|
|
1564
|
+
let syncValuesRef = /* @__PURE__ */ new Map();
|
|
1565
|
+
let syncEventsRef = /* @__PURE__ */ new Map();
|
|
1566
|
+
const flushBatchedSync = () => {
|
|
1567
|
+
syncCb(syncValuesRef, syncEventsRef);
|
|
1568
|
+
};
|
|
1569
|
+
const scheduleSync = batch(flushBatchedSync, instance["throttleSync"] || 0);
|
|
1204
1570
|
syncClass(instance, {
|
|
1205
|
-
onSync:
|
|
1206
|
-
|
|
1571
|
+
onSync: (values) => {
|
|
1572
|
+
syncValuesRef = values;
|
|
1573
|
+
scheduleSync();
|
|
1574
|
+
},
|
|
1575
|
+
onEvent: (events) => {
|
|
1576
|
+
syncEventsRef = events;
|
|
1577
|
+
scheduleSync();
|
|
1578
|
+
},
|
|
1579
|
+
onPersist: shouldPersistState ? batchedPersist : disabledPersist
|
|
1207
1580
|
});
|
|
1208
1581
|
if (shouldPersistState) {
|
|
1209
1582
|
await loadMemory();
|
|
@@ -1447,9 +1820,15 @@ var Server = class {
|
|
|
1447
1820
|
}
|
|
1448
1821
|
}
|
|
1449
1822
|
let transferToken = null;
|
|
1823
|
+
let wantsCompression = false;
|
|
1824
|
+
let readsCompressionStream = false;
|
|
1825
|
+
let wantsPathFormat = false;
|
|
1450
1826
|
if (ctx.request?.url) {
|
|
1451
1827
|
const url = new URL(ctx.request.url);
|
|
1452
1828
|
transferToken = url.searchParams.get("transferToken");
|
|
1829
|
+
wantsCompression = url.searchParams.get(COMPRESSION_QUERY_PARAM) === COMPRESSION_QUERY_VALUE;
|
|
1830
|
+
readsCompressionStream = url.searchParams.get(COMPRESSION_STREAM_QUERY_PARAM) === COMPRESSION_STREAM_QUERY_VALUE;
|
|
1831
|
+
wantsPathFormat = url.searchParams.get(PATH_FORMAT_QUERY_PARAM) === PATH_FORMAT_QUERY_VALUE;
|
|
1453
1832
|
}
|
|
1454
1833
|
let transferData = null;
|
|
1455
1834
|
if (transferToken) {
|
|
@@ -1511,7 +1890,13 @@ var Server = class {
|
|
|
1511
1890
|
conn.setState({
|
|
1512
1891
|
...conn.state,
|
|
1513
1892
|
publicId,
|
|
1514
|
-
privateId
|
|
1893
|
+
privateId,
|
|
1894
|
+
// The client accepts compressed messages (only used if the room enables compression)
|
|
1895
|
+
...wantsCompression ? { compression: true } : {},
|
|
1896
|
+
// ... and reads stream messages (one DEFLATE stream per connection)
|
|
1897
|
+
...wantsCompression && readsCompressionStream ? { compressionStream: true } : {},
|
|
1898
|
+
// The client reads sync packets in the path table format
|
|
1899
|
+
...wantsPathFormat ? { pathFormat: true } : {}
|
|
1515
1900
|
});
|
|
1516
1901
|
await awaitReturn(subRoom["onJoin"]?.(user, conn, ctx));
|
|
1517
1902
|
if (subRoom.$autoSync) {
|
|
@@ -1837,6 +2222,9 @@ var Server = class {
|
|
|
1837
2222
|
if (subRoom.$pendingInitialSync) {
|
|
1838
2223
|
subRoom.$pendingInitialSync.delete(conn);
|
|
1839
2224
|
}
|
|
2225
|
+
subRoom.$syncVisibleEntities?.delete(conn.id);
|
|
2226
|
+
this.compressors.get(conn)?.close();
|
|
2227
|
+
this.compressors.delete(conn);
|
|
1840
2228
|
const signal2 = this.getUsersProperty(subRoom);
|
|
1841
2229
|
if (!conn.state) {
|
|
1842
2230
|
return;
|