@zaisma/game-server 1.39.0 → 1.41.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/README.md +1 -1
- package/bench/glass.js +938 -942
- package/bin/like-zaisma.d.ts +15 -0
- package/bin/like-zaisma.js +252 -0
- package/bin/local-play-runner.js +35 -7
- package/bin/local-play.js +19 -1
- package/bin/node-parts.js +32 -3
- package/bin/node.js +76 -0
- package/package.json +1 -1
- package/sdk/zaisma.d.ts +18 -2
- package/sdk/zaisma.js +227 -11
- package/src/internal.d.ts +1 -0
- package/src/internal.js +1 -0
- package/src/room.d.ts +21 -2
- package/src/room.js +72 -5
- package/src/sandbox-limits.d.ts +32 -0
- package/src/sandbox-limits.js +41 -0
package/sdk/zaisma.js
CHANGED
|
@@ -22,9 +22,9 @@
|
|
|
22
22
|
|
|
23
23
|
// What each call takes. Anything else is refused, so a misspelled or old option never goes quietly unused.
|
|
24
24
|
var SET_UP_OFF_ZAISMA_OPTIONS = ["gameSlug", "playerToken"];
|
|
25
|
-
var JOIN_OPTIONS = ["roomCode", "serverUrl", "transport", "isListed", "friendJoinsEnabled", "name", "labels", "joinData", "idleTimeoutSec", "idleCheckEnabled", "isSpectator"];
|
|
25
|
+
var JOIN_OPTIONS = ["roomCode", "serverUrl", "transport", "isListed", "friendJoinsEnabled", "name", "labels", "joinData", "idleTimeoutSec", "idleCheckEnabled", "isSpectator", "sendCombiningEnabled", "unchangedSkippingEnabled"];
|
|
26
26
|
// quickJoin finds Zaisma rooms, so it takes no serverUrl.
|
|
27
|
-
var QUICK_JOIN_OPTIONS = ["isListed", "friendJoinsEnabled", "name", "labels", "joinData", "idleTimeoutSec", "idleCheckEnabled", "region"];
|
|
27
|
+
var QUICK_JOIN_OPTIONS = ["isListed", "friendJoinsEnabled", "name", "labels", "joinData", "idleTimeoutSec", "idleCheckEnabled", "sendCombiningEnabled", "unchangedSkippingEnabled", "region"];
|
|
28
28
|
var LIST_OPTIONS = ["region", "labels"];
|
|
29
29
|
// move.join joins the room the move names, on this room's server and over its transport, as a player: the game server moves only players.
|
|
30
30
|
var MOVE_JOIN_OPTIONS = JOIN_OPTIONS.filter(function (name) { return name !== "roomCode" && name !== "serverUrl" && name !== "transport" && name !== "isSpectator"; });
|
|
@@ -70,6 +70,20 @@
|
|
|
70
70
|
var VERSION_UPDATE_CLOSE_CODE = 4004;
|
|
71
71
|
/** A real-time room's ping from this on shows as a weak connection beside the game. */
|
|
72
72
|
var WEAK_PING_MS = 150;
|
|
73
|
+
/**
|
|
74
|
+
* Combining (joinRoom's sendCombiningEnabled, on unless the game turns it off, in a room whose welcome says
|
|
75
|
+
* canCombineMessages): what a game sends at once leaves as one frame of up to this many messages, and frames
|
|
76
|
+
* keep under the room's 30 a second with a burst of 60, here 25 with a burst of 40, leaving room for Zaisma's own.
|
|
77
|
+
* Past it, sends wait and go combined in the next frame instead of coming back too_fast.
|
|
78
|
+
*/
|
|
79
|
+
var MAXIMUM_COMBINED_MESSAGE_COUNT = 8;
|
|
80
|
+
var PACED_FRAMES_PER_SEC = 25;
|
|
81
|
+
var PACED_FRAME_BURST_COUNT = 40;
|
|
82
|
+
/** The messages inside those frames, under the room's 120 a second with a burst of 240. */
|
|
83
|
+
var PACED_MESSAGES_PER_SEC = 100;
|
|
84
|
+
var PACED_MESSAGE_BURST_COUNT = 200;
|
|
85
|
+
/** An unchanged latest-only send still goes as a datagram this often on the fast lane, since a datagram can be lost. */
|
|
86
|
+
var UNCHANGED_DATAGRAM_INTERVAL_MS = 250;
|
|
73
87
|
/** A latest-only send waits while the socket holds this much not yet sent, checked every LATEST_CHECK_MS. */
|
|
74
88
|
var BACKED_UP_SIZE_BYTES = 64 * 1024;
|
|
75
89
|
var LATEST_CHECK_MS = 50;
|
|
@@ -191,6 +205,8 @@
|
|
|
191
205
|
var passKey = "zaisma:pass:" + config.game;
|
|
192
206
|
var passPromise = null;
|
|
193
207
|
var keyPromise = null;
|
|
208
|
+
// The page's last key gave no pass (refused, spent or run out): the next ask says so, and the page gets a fresh one.
|
|
209
|
+
var isKeySpent = false;
|
|
194
210
|
var UNCHECKED = "Zaisma couldn't check this browser, so it can't play online. Reload the game to try again.";
|
|
195
211
|
var NO_ONLINE_PLAY_IN_PREVIEW = "Online play is off in a preview of a version players don't have yet. Test online play with npx @zaisma/cli play-locally, or publish the version and play it through a tester link.";
|
|
196
212
|
|
|
@@ -201,6 +217,7 @@
|
|
|
201
217
|
*/
|
|
202
218
|
function roomKey() {
|
|
203
219
|
if (!keyPromise) {
|
|
220
|
+
var isAgain = isKeySpent;
|
|
204
221
|
keyPromise = new Promise(function (resolve, reject) {
|
|
205
222
|
function fail(message) { reject(codedError("unchecked", message)); }
|
|
206
223
|
function failInPreview(message) { reject(codedError("no_online_play_in_preview", message)); }
|
|
@@ -217,12 +234,24 @@
|
|
|
217
234
|
else fail(UNCHECKED);
|
|
218
235
|
}
|
|
219
236
|
addEventListener("message", onMessage);
|
|
220
|
-
window.parent.postMessage({ type: "zaisma:room-key" }, config.site);
|
|
237
|
+
window.parent.postMessage(isAgain ? { type: "zaisma:room-key", is_again: true } : { type: "zaisma:room-key" }, config.site);
|
|
221
238
|
});
|
|
239
|
+
// A key that didn't come isn't kept: the next join asks the page again, so one failed check doesn't hold the tab until a reload.
|
|
240
|
+
keyPromise.catch(function () { keyPromise = null; isKeySpent = true; });
|
|
222
241
|
}
|
|
223
242
|
return keyPromise;
|
|
224
243
|
}
|
|
225
244
|
|
|
245
|
+
/** A pass from the page's key; a key Zaisma no longer takes (its passes spent, or run out) is swapped for a fresh one, once. */
|
|
246
|
+
function passFromKey(given, isRetry) {
|
|
247
|
+
return post("/v1/pass", { gameSlug: config.game, roomKey: given.key }).catch(function (error) {
|
|
248
|
+
if (isRetry || !error || error.code !== "unchecked") throw error;
|
|
249
|
+
keyPromise = null;
|
|
250
|
+
isKeySpent = true;
|
|
251
|
+
return roomKey().then(function (fresh) { return passFromKey(fresh, true); });
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
|
|
226
255
|
/**
|
|
227
256
|
* What a Zaisma room or request hears about where this player plays from on the meter: the word /v1/pass gave beside the pass, which
|
|
228
257
|
* this SDK can't read, and two things an honest browser can say. Nothing that tells this person from anyone else. Only rooms read them.
|
|
@@ -288,7 +317,8 @@
|
|
|
288
317
|
// and blocks as they are now; the account's player ID is the same either way.
|
|
289
318
|
var kept = keptPass();
|
|
290
319
|
if (kept && kept.kind === "guest" && given.playerKind === "guest") return kept;
|
|
291
|
-
return
|
|
320
|
+
return passFromKey(given, false).then(function (answer) {
|
|
321
|
+
isKeySpent = false;
|
|
292
322
|
var mine = { id: answer.player.id, name: answer.player.name, kind: answer.player.kind, pass: answer.pass, expiresAt: answer.expiresAt };
|
|
293
323
|
keptPlayShare = answer.playShare || null;
|
|
294
324
|
try {
|
|
@@ -562,6 +592,19 @@
|
|
|
562
592
|
// Latest-only sends waiting for the socket to drain, by "<kind>:<latestKey>", least recently replaced first.
|
|
563
593
|
this._slots = new Map();
|
|
564
594
|
this._slotTimer = null;
|
|
595
|
+
// Combining: whether the game left it on, whether this connection's room takes combined frames (from welcome),
|
|
596
|
+
// the game messages waiting for the end of this task or for the pace ({ dataText, latestKey }), and the pace's bucket.
|
|
597
|
+
this._sendCombiningEnabled = setup.sendCombiningEnabled !== false;
|
|
598
|
+
this._canCombine = false;
|
|
599
|
+
this._outbox = [];
|
|
600
|
+
this._isOutboxDue = false;
|
|
601
|
+
this._outboxTimer = null;
|
|
602
|
+
this._paceTokenCount = PACED_FRAME_BURST_COUNT;
|
|
603
|
+
this._messageTokenCount = PACED_MESSAGE_BURST_COUNT;
|
|
604
|
+
this._pacedAtMs = Date.now();
|
|
605
|
+
// Unchanged latest-only sends are skipped (unchangedSkippingEnabled): the last one given for each slot on this connection.
|
|
606
|
+
this._unchangedSkippingEnabled = setup.unchangedSkippingEnabled !== false;
|
|
607
|
+
this._lastLatest = new Map();
|
|
565
608
|
// Reliable sends waiting for the connection, in order, and whether this outage already said some were dropped.
|
|
566
609
|
this._queue = [];
|
|
567
610
|
this._flushTimer = null;
|
|
@@ -741,6 +784,8 @@
|
|
|
741
784
|
|
|
742
785
|
/** Send a message to the room if the connection is open. */
|
|
743
786
|
Room.prototype._say = function (message) {
|
|
787
|
+
// Game messages waiting in the outbox go first, so the room hears everything in the order it was said.
|
|
788
|
+
if (this._isWelcomed) this._flushOutbox(true);
|
|
744
789
|
if (!this._ws || this._ws.readyState !== 1) return;
|
|
745
790
|
this._ws.send(JSON.stringify(message));
|
|
746
791
|
this._sentAtMs = Date.now();
|
|
@@ -823,6 +868,10 @@
|
|
|
823
868
|
room._probeIntervalSec = typeof message.probeIntervalSec === "number" ? message.probeIntervalSec : null;
|
|
824
869
|
room.spectatorCount = typeof message.spectatorCount === "number" ? message.spectatorCount : 0;
|
|
825
870
|
room.canChat = message.canChat === true && !room.isSpectator;
|
|
871
|
+
// A room that doesn't say so (an older game server of the game's own) gets one message a frame, as before.
|
|
872
|
+
room._canCombine = message.canCombineMessages === true;
|
|
873
|
+
// A new connection: the first latest-only send of each kind goes, whatever went before.
|
|
874
|
+
room._lastLatest = new Map();
|
|
826
875
|
room._away = room._gone = room._idleSent = room._coming = room._offered = room._isReloadingForVersion = false;
|
|
827
876
|
room.awayReason = null;
|
|
828
877
|
room._isQueueFullSaid = false;
|
|
@@ -1039,19 +1088,158 @@
|
|
|
1039
1088
|
/**
|
|
1040
1089
|
* Send a message to the game server. Plain JSON, up to 16 KB. Send input when it changes, not every frame.
|
|
1041
1090
|
* While the connection isn't open or the player is away, reliable sends wait, in order (up to 60).
|
|
1042
|
-
* { delivery: "latest_only", latestKey } may drop it for a newer one with the same latestKey
|
|
1091
|
+
* { delivery: "latest_only", latestKey } may drop it for a newer one with the same latestKey, and one the same as
|
|
1092
|
+
* the last for its latestKey isn't sent (joinRoom's unchangedSkippingEnabled). What the game sends at once goes in
|
|
1093
|
+
* one frame, kept under the room's limit (joinRoom's sendCombiningEnabled). False once the room is gone.
|
|
1043
1094
|
*/
|
|
1044
1095
|
Room.prototype.send = function (message, sendOptions) {
|
|
1045
1096
|
if (this.isSpectator) throw spectatorCannotSend();
|
|
1046
1097
|
var latestKey = readDelivery(sendOptions, "room.send");
|
|
1047
|
-
var
|
|
1098
|
+
var dataText = JSON.stringify(message);
|
|
1099
|
+
var payload = dataText === undefined ? JSON.stringify({ type: "message" }) : '{"type":"message","data":' + dataText + "}";
|
|
1048
1100
|
checkSendSize(payload);
|
|
1049
1101
|
if (this._done) return false;
|
|
1050
|
-
|
|
1102
|
+
var isCombined = dataText !== undefined && this._combines();
|
|
1103
|
+
if (latestKey !== null) {
|
|
1104
|
+
var slotKey = "message:" + latestKey;
|
|
1105
|
+
if (this._isUnchanged(slotKey, payload)) return true;
|
|
1106
|
+
// On the fast lane a latest-only send goes as a datagram, which is never held for a frame.
|
|
1107
|
+
if (isCombined && !this._ws.sendDatagram) this._putInOutbox(dataText, latestKey);
|
|
1108
|
+
else this._sendLatest(slotKey, payload);
|
|
1109
|
+
} else if (isCombined) this._putInOutbox(dataText, null);
|
|
1051
1110
|
else this._sendReliable(payload);
|
|
1052
1111
|
return true;
|
|
1053
1112
|
};
|
|
1054
1113
|
|
|
1114
|
+
/** Whether a game message goes through the outbox now: combining on, the room takes it, and nothing waiting for the connection. */
|
|
1115
|
+
Room.prototype._combines = function () {
|
|
1116
|
+
return this._sendCombiningEnabled && this._canCombine && this._canSend() && !this._queue.length;
|
|
1117
|
+
};
|
|
1118
|
+
|
|
1119
|
+
/**
|
|
1120
|
+
* Whether a latest-only send is the same as the last one given for its slot on this connection, so it needn't go.
|
|
1121
|
+
* Noted either way: what was given last is what goes, now or from its slot. A datagram may be lost, so one repeats now and then.
|
|
1122
|
+
*/
|
|
1123
|
+
Room.prototype._isUnchanged = function (slotKey, sentValue) {
|
|
1124
|
+
if (!this._unchangedSkippingEnabled) return false;
|
|
1125
|
+
var nowMs = Date.now();
|
|
1126
|
+
var last = this._lastLatest.get(slotKey);
|
|
1127
|
+
var isDatagram = Boolean(this._ws && this._ws.sendDatagram);
|
|
1128
|
+
if (last && sameValue(last.sentValue, sentValue) && !(last.isDatagram && nowMs - last.givenAtMs >= UNCHANGED_DATAGRAM_INTERVAL_MS)) return true;
|
|
1129
|
+
this._lastLatest.set(slotKey, { sentValue: sentValue, givenAtMs: nowMs, isDatagram: isDatagram });
|
|
1130
|
+
return false;
|
|
1131
|
+
};
|
|
1132
|
+
/** Text or bytes, the same. */
|
|
1133
|
+
function sameValue(first, second) {
|
|
1134
|
+
if (typeof first === "string" || typeof second === "string") return first === second;
|
|
1135
|
+
if (first.byteLength !== second.byteLength) return false;
|
|
1136
|
+
var firstBytes = new Uint8Array(first);
|
|
1137
|
+
var secondBytes = new Uint8Array(second);
|
|
1138
|
+
for (var i = 0; i < firstBytes.length; i++) if (firstBytes[i] !== secondBytes[i]) return false;
|
|
1139
|
+
return true;
|
|
1140
|
+
}
|
|
1141
|
+
|
|
1142
|
+
/** The pace's tokens now, refilled at PACED_FRAMES_PER_SEC up to PACED_FRAME_BURST_COUNT. */
|
|
1143
|
+
Room.prototype._paceTokens = function () {
|
|
1144
|
+
var nowMs = Date.now();
|
|
1145
|
+
var elapsedSec = (nowMs - this._pacedAtMs) / 1000;
|
|
1146
|
+
this._paceTokenCount = Math.min(PACED_FRAME_BURST_COUNT, this._paceTokenCount + elapsedSec * PACED_FRAMES_PER_SEC);
|
|
1147
|
+
this._messageTokenCount = Math.min(PACED_MESSAGE_BURST_COUNT, this._messageTokenCount + elapsedSec * PACED_MESSAGES_PER_SEC);
|
|
1148
|
+
this._pacedAtMs = nowMs;
|
|
1149
|
+
return this._paceTokenCount;
|
|
1150
|
+
};
|
|
1151
|
+
/**
|
|
1152
|
+
* Frames that went, combined or not, and the messages in them: they count against the pace, so bytes and JSON together keep
|
|
1153
|
+
* under the room's limit. Never below empty: what went without waiting (bytes, datagrams) doesn't hold the outbox back for long.
|
|
1154
|
+
*/
|
|
1155
|
+
Room.prototype._spendPace = function (frameCount, messageCount) {
|
|
1156
|
+
this._paceTokens();
|
|
1157
|
+
this._paceTokenCount = Math.max(0, this._paceTokenCount - frameCount);
|
|
1158
|
+
this._messageTokenCount = Math.max(0, this._messageTokenCount - (messageCount || 0));
|
|
1159
|
+
};
|
|
1160
|
+
|
|
1161
|
+
/** A game message into the outbox: a latest-only one replaces a waiting one with its latestKey, and reliable ones wait up to 60. */
|
|
1162
|
+
Room.prototype._putInOutbox = function (dataText, latestKey) {
|
|
1163
|
+
var waiting = latestKey === null ? null : this._outbox.filter(function (entry) { return entry.latestKey === latestKey; })[0];
|
|
1164
|
+
if (waiting) waiting.dataText = dataText;
|
|
1165
|
+
else this._outbox.push({ dataText: dataText, latestKey: latestKey });
|
|
1166
|
+
var reliable = this._outbox.filter(function (entry) { return entry.latestKey === null; });
|
|
1167
|
+
if (reliable.length > MAXIMUM_QUEUED_SEND_COUNT) {
|
|
1168
|
+
this._outbox.splice(this._outbox.indexOf(reliable[0]), 1);
|
|
1169
|
+
if (!this._isQueueFullSaid) {
|
|
1170
|
+
this._isQueueFullSaid = true;
|
|
1171
|
+
this._emit("error", { code: "send_queue_full", message: "Up to " + MAXIMUM_QUEUED_SEND_COUNT + " sends wait to go; older ones were dropped. Send less often." });
|
|
1172
|
+
}
|
|
1173
|
+
}
|
|
1174
|
+
if (this._isOutboxDue || this._outboxTimer !== null) return;
|
|
1175
|
+
this._isOutboxDue = true;
|
|
1176
|
+
var room = this;
|
|
1177
|
+
queueMicrotask(function () {
|
|
1178
|
+
room._isOutboxDue = false;
|
|
1179
|
+
room._flushOutbox(false);
|
|
1180
|
+
});
|
|
1181
|
+
};
|
|
1182
|
+
|
|
1183
|
+
/**
|
|
1184
|
+
* The outbox goes: combined into frames of up to 8 messages and 16 KB, as many frames as the pace allows, the rest at its
|
|
1185
|
+
* next token. Forced (before a send that isn't combined, to keep the order), all of it now. With the connection gone,
|
|
1186
|
+
* its messages wait as uncombined sends do.
|
|
1187
|
+
*/
|
|
1188
|
+
Room.prototype._flushOutbox = function (isForced) {
|
|
1189
|
+
if (!this._outbox.length) return;
|
|
1190
|
+
var entries;
|
|
1191
|
+
var room = this;
|
|
1192
|
+
if (this._done || !this._canSend() || this._queue.length) {
|
|
1193
|
+
entries = this._outbox;
|
|
1194
|
+
this._outbox = [];
|
|
1195
|
+
this._clearOutboxTimer();
|
|
1196
|
+
if (this._done) return;
|
|
1197
|
+
entries.forEach(function (entry) {
|
|
1198
|
+
var payload = '{"type":"message","data":' + entry.dataText + "}";
|
|
1199
|
+
if (entry.latestKey === null) room._sendReliable(payload);
|
|
1200
|
+
else room._slotLatest("message:" + entry.latestKey, payload);
|
|
1201
|
+
});
|
|
1202
|
+
return;
|
|
1203
|
+
}
|
|
1204
|
+
// Latest-only messages wait in their slots while the socket is backed up, as uncombined ones do.
|
|
1205
|
+
if (this._ws.bufferedAmount >= BACKED_UP_SIZE_BYTES) {
|
|
1206
|
+
this._outbox = this._outbox.filter(function (entry) {
|
|
1207
|
+
if (entry.latestKey === null) return true;
|
|
1208
|
+
room._slotLatest("message:" + entry.latestKey, '{"type":"message","data":' + entry.dataText + "}");
|
|
1209
|
+
return false;
|
|
1210
|
+
});
|
|
1211
|
+
}
|
|
1212
|
+
while (this._outbox.length && (isForced || (this._paceTokens() >= 1 && this._messageTokenCount >= 1))) {
|
|
1213
|
+
var frame = [];
|
|
1214
|
+
var frameSizeBytes = '{"type":"messages","data":[]}'.length;
|
|
1215
|
+
var maximumMessageCount = isForced ? MAXIMUM_COMBINED_MESSAGE_COUNT : Math.min(MAXIMUM_COMBINED_MESSAGE_COUNT, Math.floor(this._messageTokenCount));
|
|
1216
|
+
while (this._outbox.length && frame.length < maximumMessageCount) {
|
|
1217
|
+
var sizeBytes = utf8SizeOf(this._outbox[0].dataText) + 1;
|
|
1218
|
+
if (frame.length && frameSizeBytes + sizeBytes > MAXIMUM_SEND_SIZE_BYTES) break;
|
|
1219
|
+
frame.push(this._outbox.shift().dataText);
|
|
1220
|
+
frameSizeBytes += sizeBytes;
|
|
1221
|
+
}
|
|
1222
|
+
this._ws.send(frame.length === 1 ? '{"type":"message","data":' + frame[0] + "}" : '{"type":"messages","data":[' + frame.join(",") + "]}");
|
|
1223
|
+
this._spendPace(1, frame.length);
|
|
1224
|
+
this._sentAtMs = Date.now();
|
|
1225
|
+
}
|
|
1226
|
+
this._clearOutboxTimer();
|
|
1227
|
+
if (!this._outbox.length) return;
|
|
1228
|
+
this._outboxTimer = setTimeout(function () {
|
|
1229
|
+
room._outboxTimer = null;
|
|
1230
|
+
room._flushOutbox(false);
|
|
1231
|
+
}, Math.max(1, Math.ceil(Math.max((1 - this._paceTokenCount) / PACED_FRAMES_PER_SEC, (1 - this._messageTokenCount) / PACED_MESSAGES_PER_SEC) * 1000)));
|
|
1232
|
+
};
|
|
1233
|
+
Room.prototype._clearOutboxTimer = function () {
|
|
1234
|
+
if (this._outboxTimer === null) return;
|
|
1235
|
+
clearTimeout(this._outboxTimer);
|
|
1236
|
+
this._outboxTimer = null;
|
|
1237
|
+
};
|
|
1238
|
+
/** Text's size in UTF-8, measured only when it could matter. */
|
|
1239
|
+
function utf8SizeOf(text) {
|
|
1240
|
+
return text.length * 3 <= 1024 ? text.length * 3 : new TextEncoder().encode(text).length;
|
|
1241
|
+
}
|
|
1242
|
+
|
|
1055
1243
|
/**
|
|
1056
1244
|
* Send bytes to the game server (its onBytes), like a compact input: an ArrayBuffer or any typed array,
|
|
1057
1245
|
* up to 16 KB, counted with messages (30 a second). Takes the same sendOptions as room.send.
|
|
@@ -1064,8 +1252,10 @@
|
|
|
1064
1252
|
if (this._done) return false;
|
|
1065
1253
|
// A copy: the game may reuse its buffer while this one waits.
|
|
1066
1254
|
var copy = ArrayBuffer.isView(bytes) ? bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) : bytes.slice(0);
|
|
1067
|
-
if (latestKey !== null)
|
|
1068
|
-
|
|
1255
|
+
if (latestKey !== null) {
|
|
1256
|
+
if (this._isUnchanged("bytes:" + latestKey, copy)) return true;
|
|
1257
|
+
this._sendLatest("bytes:" + latestKey, copy);
|
|
1258
|
+
} else this._sendReliable(copy);
|
|
1069
1259
|
return true;
|
|
1070
1260
|
};
|
|
1071
1261
|
|
|
@@ -1081,8 +1271,11 @@
|
|
|
1081
1271
|
|
|
1082
1272
|
/** A reliable send: now, or in order once the connection is open again, dropping the oldest past 60. */
|
|
1083
1273
|
Room.prototype._sendReliable = function (payload) {
|
|
1274
|
+
// Game messages waiting in the outbox go first, so everything keeps its order.
|
|
1275
|
+
this._flushOutbox(true);
|
|
1084
1276
|
if (this._canSend() && !this._queue.length) {
|
|
1085
1277
|
this._ws.send(payload);
|
|
1278
|
+
this._spendPace(1);
|
|
1086
1279
|
this._sentAtMs = Date.now();
|
|
1087
1280
|
return;
|
|
1088
1281
|
}
|
|
@@ -1099,7 +1292,9 @@
|
|
|
1099
1292
|
var room = this;
|
|
1100
1293
|
var ws = this._ws;
|
|
1101
1294
|
function send(sendCount) {
|
|
1102
|
-
room._queue.splice(0, sendCount)
|
|
1295
|
+
var sent = room._queue.splice(0, sendCount);
|
|
1296
|
+
sent.forEach(function (payload) { ws.send(payload); });
|
|
1297
|
+
room._spendPace(sent.length);
|
|
1103
1298
|
room._sentAtMs = Date.now();
|
|
1104
1299
|
}
|
|
1105
1300
|
send(FLUSH_NOW_COUNT);
|
|
@@ -1130,20 +1325,32 @@
|
|
|
1130
1325
|
|
|
1131
1326
|
/** A latest-only send: now, after anything still waiting, or into its slot while the socket is backed up. */
|
|
1132
1327
|
Room.prototype._sendLatest = function (slotKey, payload) {
|
|
1328
|
+
this._flushOutbox(true);
|
|
1133
1329
|
// On the fast lane, a datagram: a late one is lost rather than waited for, so it skips the slots.
|
|
1134
1330
|
if (this._canSend() && !this._queue.length && this._ws.sendDatagram && this._ws.sendDatagram(payload)) {
|
|
1331
|
+
this._spendPace(1);
|
|
1135
1332
|
this._sentAtMs = Date.now();
|
|
1136
1333
|
return;
|
|
1137
1334
|
}
|
|
1138
1335
|
if (this._canSend() && !this._queue.length && !(this._ws.bufferedAmount >= BACKED_UP_SIZE_BYTES)) {
|
|
1139
1336
|
this._sendWaiting();
|
|
1140
1337
|
this._ws.send(payload);
|
|
1338
|
+
this._spendPace(1);
|
|
1141
1339
|
this._sentAtMs = Date.now();
|
|
1142
1340
|
return;
|
|
1143
1341
|
}
|
|
1342
|
+
this._slotLatest(slotKey, payload);
|
|
1343
|
+
};
|
|
1344
|
+
/** A latest-only send into its slot, to go once the socket drains: the slot keeps only the newest. */
|
|
1345
|
+
Room.prototype._slotLatest = function (slotKey, payload) {
|
|
1144
1346
|
this._slots.delete(slotKey);
|
|
1145
1347
|
this._slots.set(slotKey, payload);
|
|
1146
|
-
if (this._slots.size > MAXIMUM_LATEST_ONLY_SLOT_COUNT)
|
|
1348
|
+
if (this._slots.size > MAXIMUM_LATEST_ONLY_SLOT_COUNT) {
|
|
1349
|
+
var evictedKey = this._slots.keys().next().value;
|
|
1350
|
+
this._slots.delete(evictedKey);
|
|
1351
|
+
// It never went: the next send with its latestKey goes, the same or not.
|
|
1352
|
+
this._lastLatest.delete(evictedKey);
|
|
1353
|
+
}
|
|
1147
1354
|
if (this._slotTimer === null) {
|
|
1148
1355
|
var room = this;
|
|
1149
1356
|
this._slotTimer = setInterval(function () {
|
|
@@ -1158,6 +1365,7 @@
|
|
|
1158
1365
|
if (!this._slots.size || !this._canSend() || this._queue.length) return;
|
|
1159
1366
|
var ws = this._ws;
|
|
1160
1367
|
this._slots.forEach(function (payload) { ws.send(payload); });
|
|
1368
|
+
this._spendPace(this._slots.size);
|
|
1161
1369
|
this._slots.clear();
|
|
1162
1370
|
this._sentAtMs = Date.now();
|
|
1163
1371
|
};
|
|
@@ -1346,6 +1554,8 @@
|
|
|
1346
1554
|
this._views = [];
|
|
1347
1555
|
this._slots.clear();
|
|
1348
1556
|
this._queue = [];
|
|
1557
|
+
this._outbox = [];
|
|
1558
|
+
this._clearOutboxTimer();
|
|
1349
1559
|
this._sayRoomToPage();
|
|
1350
1560
|
this._setConnectionStatus("connecting");
|
|
1351
1561
|
this._emit("moved", { roomCode: roomCode, fromRoomCode: fromRoomCode });
|
|
@@ -1618,6 +1828,8 @@
|
|
|
1618
1828
|
if (!this._done) left(this);
|
|
1619
1829
|
this._done = true;
|
|
1620
1830
|
this._queue = [];
|
|
1831
|
+
this._outbox = [];
|
|
1832
|
+
this._clearOutboxTimer();
|
|
1621
1833
|
this._failChats();
|
|
1622
1834
|
if (this._ws) this._ws.close(1000, "Left");
|
|
1623
1835
|
};
|
|
@@ -1637,6 +1849,8 @@
|
|
|
1637
1849
|
var isOffZaisma = !config.rooms;
|
|
1638
1850
|
var idleTimeoutSec = joinOptions.idleTimeoutSec;
|
|
1639
1851
|
if (idleTimeoutSec !== undefined && !(typeof idleTimeoutSec === "number" && idleTimeoutSec >= MINIMUM_IDLE_TIMEOUT_SEC && idleTimeoutSec <= MAXIMUM_IDLE_TIMEOUT_SEC)) return Promise.reject(codedError("bad_idle_timeout", "idleTimeoutSec runs from " + MINIMUM_IDLE_TIMEOUT_SEC + " to " + MAXIMUM_IDLE_TIMEOUT_SEC + "."));
|
|
1852
|
+
var badSwitch = ["sendCombiningEnabled", "unchangedSkippingEnabled"].filter(function (name) { return joinOptions[name] !== undefined && typeof joinOptions[name] !== "boolean"; })[0];
|
|
1853
|
+
if (badSwitch) return Promise.reject(codedError("unknown_option", badSwitch + " is " + JSON.stringify(joinOptions[badSwitch]) + ". Give true (the default) or false."));
|
|
1640
1854
|
if (serverUrl && !SERVER_URL.test(serverUrl)) return Promise.reject(codedError("bad_server_url", "serverUrl takes a full address starting with wss://, ws://, https:// or http://, like \"wss://play.example.com\"."));
|
|
1641
1855
|
if (joinOptions.transport !== undefined && TRANSPORTS.indexOf(joinOptions.transport) === -1) return Promise.reject(codedError("bad_transport", "transport is " + JSON.stringify(joinOptions.transport) + '. Give "websocket" (the default) or "webtransport" (the fast lane to your own server).'));
|
|
1642
1856
|
if (roomCode && !ROOM_CODE.test(roomCode)) return Promise.reject(codedError("bad_room_code", JSON.stringify(roomCode) + " isn't a room code: room codes are six characters like \"K7Q2MX\", from 2 to 9 and A to Z without I or O."));
|
|
@@ -1663,6 +1877,8 @@
|
|
|
1663
1877
|
labels: joinOptions.labels,
|
|
1664
1878
|
joinData: joinOptions.joinData,
|
|
1665
1879
|
clientIdle: clientIdle(joinOptions),
|
|
1880
|
+
sendCombiningEnabled: joinOptions.sendCombiningEnabled,
|
|
1881
|
+
unchangedSkippingEnabled: joinOptions.unchangedSkippingEnabled,
|
|
1666
1882
|
serverUrl: serverUrl,
|
|
1667
1883
|
isSpectator: joinOptions.isSpectator === true,
|
|
1668
1884
|
});
|
package/src/internal.d.ts
CHANGED
package/src/internal.js
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
// Never published or locked: games and developers' servers use the package's index.
|
|
3
3
|
export * from "./room.js";
|
|
4
4
|
export * from "./room-calls.js";
|
|
5
|
+
export * from "./sandbox-limits.js";
|
|
5
6
|
export * from "./state-sync.js";
|
|
6
7
|
export * from "./database.js";
|
|
7
8
|
export * from "./dump.js";
|
package/src/room.d.ts
CHANGED
|
@@ -823,7 +823,7 @@ export declare const GAME_SERVER_LIMITS: {
|
|
|
823
823
|
readonly maximumMemorySizeBytes: number;
|
|
824
824
|
};
|
|
825
825
|
export declare const ROOM_LIMITS: {
|
|
826
|
-
/** Players in one room: what one room carries at 60 ticks a second (test/load/room-load.test.ts). */
|
|
826
|
+
/** Players in one room: what one room carries at 60 ticks a second in the local test (test/load/room-load.test.ts); in the first runs on Cloudflare, a room held 60 up to about 50 players and made about 40 past 70. */
|
|
827
827
|
readonly maximumPlayerCount: 100;
|
|
828
828
|
readonly defaultMaximumPlayerCount: 8;
|
|
829
829
|
/** Spectators in one room: each send costs the room time, so its audience is bounded like its players. Bigger audiences are a stream. */
|
|
@@ -850,6 +850,11 @@ export declare const ROOM_LIMITS: {
|
|
|
850
850
|
*/
|
|
851
851
|
readonly maximumGameMessagesPerSec: 30;
|
|
852
852
|
readonly maximumGameMessageBurstCount: 60;
|
|
853
|
+
/** Game messages one combined frame ({ type: "messages" }) carries at most: the frame takes one of the 30 a second. */
|
|
854
|
+
readonly maximumCombinedMessageCount: 8;
|
|
855
|
+
/** The messages inside combined frames, per second per player, with a burst: what bounds a player's onMessage calls. */
|
|
856
|
+
readonly maximumCombinedGameMessagesPerSec: 120;
|
|
857
|
+
readonly maximumCombinedGameMessageBurstCount: 240;
|
|
853
858
|
/** The idle check's default and range (idleTimeoutSec, joinRoom({ idleTimeoutSec })). */
|
|
854
859
|
readonly defaultIdleTimeoutSec: 600;
|
|
855
860
|
readonly minimumIdleTimeoutSec: 30;
|
|
@@ -948,7 +953,9 @@ export interface RoomSettings {
|
|
|
948
953
|
* Clients send {type: "hello", protocolVersionNumber, pass, joinData?, room?: {isListed?, friendJoinsEnabled?, name?, labels?}, idleTimeoutSec?,
|
|
949
954
|
* idleCheckEnabled?} first (ClientMessage; joinData is for canJoin and onJoin; the room's settings only count from
|
|
950
955
|
* the player who makes it, and a room is listed only when its first player's hello says isListed: true;
|
|
951
|
-
* the idle fields only where the game server's idleCheck is "client"), then {type: "message", data}
|
|
956
|
+
* the idle fields only where the game server's idleCheck is "client"), then {type: "message", data}, or, where
|
|
957
|
+
* welcome says canCombineMessages, {type: "messages", data: [2 to 8 messages]}: what the game sent at once, each
|
|
958
|
+
* reaching onMessage in order, the frame counting once toward the 30 a second and each message toward 120 a second.
|
|
952
959
|
* With hostControlsEnabled, the host may also send {type: "room", room: {isListed?, isOpen?,
|
|
953
960
|
* friendJoinsEnabled?, name?, labels?}} and {type: "kick", playerId, keepOut?}. hostPlayerId is null without host controls.
|
|
954
961
|
*
|
|
@@ -1033,6 +1040,8 @@ export type ServerMessage = {
|
|
|
1033
1040
|
probeIntervalSec: number | null;
|
|
1034
1041
|
protocolVersionNumber: number;
|
|
1035
1042
|
canChat: boolean;
|
|
1043
|
+
/** The room takes { type: "messages", data: [...] }: the SDK combines what a game sends at once only where this says so. */
|
|
1044
|
+
canCombineMessages: boolean;
|
|
1036
1045
|
} | {
|
|
1037
1046
|
type: "probe";
|
|
1038
1047
|
probeNumber: number;
|
|
@@ -1456,6 +1465,7 @@ export declare const ROOM_MESSAGE_DOORS: {
|
|
|
1456
1465
|
readonly shown: DoorContract;
|
|
1457
1466
|
readonly back: DoorContract;
|
|
1458
1467
|
readonly message: DoorContract;
|
|
1468
|
+
readonly messages: DoorContract;
|
|
1459
1469
|
readonly bytes: {
|
|
1460
1470
|
readonly whoMayCall: "room_player";
|
|
1461
1471
|
readonly reaches: "room";
|
|
@@ -1610,6 +1620,7 @@ export declare class RoomCore<S = any> {
|
|
|
1610
1620
|
/** When this room took room messages, within the last second (ROOM_MESSAGE_LIMITS.maximumReceivedRoomMessagesPerSec). */
|
|
1611
1621
|
private roomReceivedAtMs;
|
|
1612
1622
|
private buckets;
|
|
1623
|
+
private combinedBuckets;
|
|
1613
1624
|
/** Probes this room has sent, to every player: each probe's number. */
|
|
1614
1625
|
private probeCount;
|
|
1615
1626
|
/** What each player was last sent of the state (stateSyncEnabled), unless the game server runs state sync itself (SYNCS_STATE). */
|
|
@@ -1883,6 +1894,12 @@ export declare class RoomCore<S = any> {
|
|
|
1883
1894
|
* game has been hidden too long in a real-time room, walk away; held seats that ran out are freed,
|
|
1884
1895
|
* and those players' connections close.
|
|
1885
1896
|
*/
|
|
1897
|
+
/**
|
|
1898
|
+
* When sweep next has something to do, in epoch milliseconds, or null: the earliest idle walk-away, held or
|
|
1899
|
+
* expected seat running out, probe answer timing out or reconnect running out. A host that sleeps between
|
|
1900
|
+
* sweeps (Zaisma's rooms) wakes for this instead of on a fixed timer. A stale ping waits for the next wake.
|
|
1901
|
+
*/
|
|
1902
|
+
nextSweepAtMs(): number | null;
|
|
1886
1903
|
sweep(): void;
|
|
1887
1904
|
/** A raw text message from a client. Returns an error code if it was refused. */
|
|
1888
1905
|
receive(playerId: string, text: string): RoomErrorCode | null;
|
|
@@ -2060,6 +2077,8 @@ export declare class RoomCore<S = any> {
|
|
|
2060
2077
|
*/
|
|
2061
2078
|
private dropBehind;
|
|
2062
2079
|
/** Token bucket per player: a short burst is fine, a flood is dropped. */
|
|
2080
|
+
/** The second bucket, for the messages inside combined frames: each takes one, so combining never lifts how often onMessage runs past its own limit. */
|
|
2081
|
+
private takeCombined;
|
|
2063
2082
|
private take;
|
|
2064
2083
|
/** A handler's answer becomes the state if it is one (a plain object or an array); nothing keeps the state, and anything else is a mistake that leaves it. */
|
|
2065
2084
|
private keepAnswer;
|
package/src/room.js
CHANGED
|
@@ -162,7 +162,7 @@ export const GAME_SERVER_LIMITS = {
|
|
|
162
162
|
maximumMemorySizeBytes: 128 * 1024 * 1024,
|
|
163
163
|
};
|
|
164
164
|
export const ROOM_LIMITS = {
|
|
165
|
-
/** Players in one room: what one room carries at 60 ticks a second (test/load/room-load.test.ts). */
|
|
165
|
+
/** Players in one room: what one room carries at 60 ticks a second in the local test (test/load/room-load.test.ts); in the first runs on Cloudflare, a room held 60 up to about 50 players and made about 40 past 70. */
|
|
166
166
|
maximumPlayerCount: 100,
|
|
167
167
|
defaultMaximumPlayerCount: 8,
|
|
168
168
|
/** Spectators in one room: each send costs the room time, so its audience is bounded like its players. Bigger audiences are a stream. */
|
|
@@ -189,6 +189,11 @@ export const ROOM_LIMITS = {
|
|
|
189
189
|
*/
|
|
190
190
|
maximumGameMessagesPerSec: 30,
|
|
191
191
|
maximumGameMessageBurstCount: 60,
|
|
192
|
+
/** Game messages one combined frame ({ type: "messages" }) carries at most: the frame takes one of the 30 a second. */
|
|
193
|
+
maximumCombinedMessageCount: 8,
|
|
194
|
+
/** The messages inside combined frames, per second per player, with a burst: what bounds a player's onMessage calls. */
|
|
195
|
+
maximumCombinedGameMessagesPerSec: 120,
|
|
196
|
+
maximumCombinedGameMessageBurstCount: 240,
|
|
192
197
|
/** The idle check's default and range (idleTimeoutSec, joinRoom({ idleTimeoutSec })). */
|
|
193
198
|
defaultIdleTimeoutSec: 600,
|
|
194
199
|
minimumIdleTimeoutSec: 30,
|
|
@@ -581,7 +586,7 @@ const wirePlayers = { type: "array", items: looseObject };
|
|
|
581
586
|
const WIRE_DATA = {};
|
|
582
587
|
export const ROOM_FRAME = {
|
|
583
588
|
anyOf: [
|
|
584
|
-
frameOf("welcome", { me: looseObject, isSpectator: wireYesOrNo, players: wirePlayers, room: looseObject, spectatorCount: wireNumber, hostPlayerId: wireNullable("string"), awayChecks: looseObject, endsAt: wireNullable("string"), probeIntervalSec: wireNullable("number"), protocolVersionNumber: wireNumber, canChat: wireYesOrNo }),
|
|
589
|
+
frameOf("welcome", { me: looseObject, isSpectator: wireYesOrNo, players: wirePlayers, room: looseObject, spectatorCount: wireNumber, hostPlayerId: wireNullable("string"), awayChecks: looseObject, endsAt: wireNullable("string"), probeIntervalSec: wireNullable("number"), protocolVersionNumber: wireNumber, canChat: wireYesOrNo, canCombineMessages: wireYesOrNo }),
|
|
585
590
|
frameOf("probe", { probeNumber: wireNumber, serverTimeMs: wireNumber, pingDurationMs: wireNullable("number") }),
|
|
586
591
|
frameOf("ending", { endsAt: wireText }),
|
|
587
592
|
frameOf("ending_cancelled"),
|
|
@@ -669,6 +674,7 @@ export const ROOM_MESSAGE_DOORS = {
|
|
|
669
674
|
shown: roomMessage("room_player"),
|
|
670
675
|
back: roomMessage("room_player", { joinData: gameData(ROOM_LIMITS.maximumJoinDataSizeBytes * 2), ...IDLE_FIELDS }),
|
|
671
676
|
message: roomMessage("room_player", { data: gameData(ROOM_LIMITS.maximumGameMessageSizeBytes) }),
|
|
677
|
+
messages: roomMessage("room_player", { data: listOf(gameData(ROOM_LIMITS.maximumGameMessageSizeBytes), ROOM_LIMITS.maximumCombinedMessageCount, 2) }, ["data"]),
|
|
672
678
|
bytes: {
|
|
673
679
|
whoMayCall: "room_player",
|
|
674
680
|
reaches: "room",
|
|
@@ -834,6 +840,7 @@ export class RoomCore {
|
|
|
834
840
|
/** When this room took room messages, within the last second (ROOM_MESSAGE_LIMITS.maximumReceivedRoomMessagesPerSec). */
|
|
835
841
|
roomReceivedAtMs = [];
|
|
836
842
|
buckets = new Map();
|
|
843
|
+
combinedBuckets = new Map();
|
|
837
844
|
/** Probes this room has sent, to every player: each probe's number. */
|
|
838
845
|
probeCount = 0;
|
|
839
846
|
/** What each player was last sent of the state (stateSyncEnabled), unless the game server runs state sync itself (SYNCS_STATE). */
|
|
@@ -1642,7 +1649,7 @@ export class RoomCore {
|
|
|
1642
1649
|
this.remember(player.id);
|
|
1643
1650
|
this.presence.set(player.id, newPresence(this.now(), joinOptions.clientIdle === undefined ? (this.presence.get(player.id)?.clientIdle ?? {}) : clientIdle(joinOptions.clientIdle)));
|
|
1644
1651
|
const probeIntervalSec = this.ticking ? ROOM_TUNING.probeIntervalSec : null;
|
|
1645
|
-
this.sendText(player.id, JSON.stringify({ type: "welcome", me: shownPlayer(player), isSpectator: false, players: this.list(), room: this.settings(), spectatorCount: this.spectators.size, hostPlayerId: this.hostPlayerId, awayChecks: this.checks(player.id), endsAt: this.endsAt, probeIntervalSec, protocolVersionNumber: PROTOCOL_VERSION_NUMBER, canChat: this.canChat(player.id) }));
|
|
1652
|
+
this.sendText(player.id, JSON.stringify({ type: "welcome", me: shownPlayer(player), isSpectator: false, players: this.list(), room: this.settings(), spectatorCount: this.spectators.size, hostPlayerId: this.hostPlayerId, awayChecks: this.checks(player.id), endsAt: this.endsAt, probeIntervalSec, protocolVersionNumber: PROTOCOL_VERSION_NUMBER, canChat: this.canChat(player.id), canCombineMessages: true }));
|
|
1646
1653
|
// Every room gets a first ping and clock sample right away, ticking or not.
|
|
1647
1654
|
this.probe(player.id);
|
|
1648
1655
|
// A new connection starts with nothing of the state: a full copy comes with the next round.
|
|
@@ -1681,7 +1688,7 @@ export class RoomCore {
|
|
|
1681
1688
|
this.spectators.set(spectator.id, spectator);
|
|
1682
1689
|
this.presence.set(spectator.id, newPresence(this.now(), {}));
|
|
1683
1690
|
const probeIntervalSec = this.ticking ? ROOM_TUNING.probeIntervalSec : null;
|
|
1684
|
-
this.sendText(spectator.id, JSON.stringify({ type: "welcome", me: shownPlayer(spectator), isSpectator: true, players: this.list(), room: this.settings(), spectatorCount: this.spectators.size, hostPlayerId: this.hostPlayerId, awayChecks: { idleTimeoutSec: null, hiddenTimeoutSec: null }, endsAt: this.endsAt, probeIntervalSec, protocolVersionNumber: PROTOCOL_VERSION_NUMBER, canChat: false }));
|
|
1691
|
+
this.sendText(spectator.id, JSON.stringify({ type: "welcome", me: shownPlayer(spectator), isSpectator: true, players: this.list(), room: this.settings(), spectatorCount: this.spectators.size, hostPlayerId: this.hostPlayerId, awayChecks: { idleTimeoutSec: null, hiddenTimeoutSec: null }, endsAt: this.endsAt, probeIntervalSec, protocolVersionNumber: PROTOCOL_VERSION_NUMBER, canChat: false, canCombineMessages: true }));
|
|
1685
1692
|
this.probe(spectator.id);
|
|
1686
1693
|
// A new connection starts with nothing of the state: a full copy comes with the next round.
|
|
1687
1694
|
if (this.server.stateSyncEnabled) {
|
|
@@ -1772,6 +1779,7 @@ export class RoomCore {
|
|
|
1772
1779
|
this.reconnectUntilMs.delete(playerId);
|
|
1773
1780
|
this.presence.delete(playerId);
|
|
1774
1781
|
this.buckets.delete(playerId);
|
|
1782
|
+
this.combinedBuckets.delete(playerId);
|
|
1775
1783
|
this.listingChanged = true;
|
|
1776
1784
|
this.dirty = true;
|
|
1777
1785
|
}
|
|
@@ -1893,6 +1901,36 @@ export class RoomCore {
|
|
|
1893
1901
|
* game has been hidden too long in a real-time room, walk away; held seats that ran out are freed,
|
|
1894
1902
|
* and those players' connections close.
|
|
1895
1903
|
*/
|
|
1904
|
+
/**
|
|
1905
|
+
* When sweep next has something to do, in epoch milliseconds, or null: the earliest idle walk-away, held or
|
|
1906
|
+
* expected seat running out, probe answer timing out or reconnect running out. A host that sleeps between
|
|
1907
|
+
* sweeps (Zaisma's rooms) wakes for this instead of on a fixed timer. A stale ping waits for the next wake.
|
|
1908
|
+
*/
|
|
1909
|
+
nextSweepAtMs() {
|
|
1910
|
+
if (this.ended)
|
|
1911
|
+
return null;
|
|
1912
|
+
const dueAtMs = [];
|
|
1913
|
+
const reconnectAtMs = this.nextReconnectDeadlineMs();
|
|
1914
|
+
if (reconnectAtMs !== null)
|
|
1915
|
+
dueAtMs.push(reconnectAtMs);
|
|
1916
|
+
for (const [id, presence] of this.presence) {
|
|
1917
|
+
const oldestProbe = presence.unansweredProbes.values().next().value;
|
|
1918
|
+
if (oldestProbe)
|
|
1919
|
+
dueAtMs.push(oldestProbe.sentAtMs + ROOM_TUNING.probeAnswerTimeoutSec * 1000);
|
|
1920
|
+
if (this.kept.has(id) || this.spectators.has(id))
|
|
1921
|
+
continue;
|
|
1922
|
+
const idleTimeoutSec = this.idleTimeoutSecFor(id);
|
|
1923
|
+
if (idleTimeoutSec !== null)
|
|
1924
|
+
dueAtMs.push(presence.seenAtMs + idleTimeoutSec * 1000 + IDLE_ASK_MS + IDLE_GRACE_MS);
|
|
1925
|
+
if (this.ticking && presence.hiddenAtMs !== undefined)
|
|
1926
|
+
dueAtMs.push(presence.hiddenAtMs + ROOM_LIMITS.hiddenTimeoutSec * 1000);
|
|
1927
|
+
}
|
|
1928
|
+
for (const expected of this.expected.values())
|
|
1929
|
+
dueAtMs.push(expected.untilMs);
|
|
1930
|
+
for (const held of this.held.values())
|
|
1931
|
+
dueAtMs.push(held.untilMs);
|
|
1932
|
+
return dueAtMs.length ? Math.min(...dueAtMs) : null;
|
|
1933
|
+
}
|
|
1896
1934
|
sweep() {
|
|
1897
1935
|
if (this.ended)
|
|
1898
1936
|
return;
|
|
@@ -1954,7 +1992,13 @@ export class RoomCore {
|
|
|
1954
1992
|
if (message.type === "probe_answer" && this.answer(playerId, message.probeNumber))
|
|
1955
1993
|
return null;
|
|
1956
1994
|
this.messageCount++;
|
|
1957
|
-
|
|
1995
|
+
const combined = message.type === "messages" && Array.isArray(message.data) && message.data.length <= ROOM_LIMITS.maximumCombinedMessageCount ? message.data : null;
|
|
1996
|
+
// A combined frame is billed once, and each message in it counts by its own type, sharing the frame's size.
|
|
1997
|
+
if (combined && combined.length)
|
|
1998
|
+
for (const messageData of combined)
|
|
1999
|
+
this.countTraffic("inbound", messageTypeOf(messageData), 1, Math.round(sizeBytes / combined.length));
|
|
2000
|
+
else
|
|
2001
|
+
this.countTraffic("inbound", message.type === "message" ? messageTypeOf(message.data) : typeof message.type === "string" ? ZAISMA_MESSAGE_TYPE : NO_MESSAGE_TYPE, 1, sizeBytes);
|
|
1958
2002
|
if (isTooBig)
|
|
1959
2003
|
return "too_big";
|
|
1960
2004
|
if (!this.take(playerId))
|
|
@@ -1998,6 +2042,17 @@ export class RoomCore {
|
|
|
1998
2042
|
case "message":
|
|
1999
2043
|
this.input(() => this.server.onMessage?.(this.state, player, this.api, message.data), "onMessage");
|
|
2000
2044
|
return null;
|
|
2045
|
+
case "messages":
|
|
2046
|
+
if (!this.takeCombined(playerId, message.data.length))
|
|
2047
|
+
return "too_fast";
|
|
2048
|
+
// Several messages the player's game sent at once, in one frame: each reaches onMessage in order, as if sent alone.
|
|
2049
|
+
for (const messageData of message.data) {
|
|
2050
|
+
// A message before it may have ended the match, or kicked the player or walked them away: the rest go no further, as they wouldn't alone.
|
|
2051
|
+
if (this.ended || !this.players.has(playerId) || this.kept.has(playerId))
|
|
2052
|
+
break;
|
|
2053
|
+
this.input(() => this.server.onMessage?.(this.state, player, this.api, messageData), "onMessage");
|
|
2054
|
+
}
|
|
2055
|
+
return null;
|
|
2001
2056
|
case "chat":
|
|
2002
2057
|
// The room's host takes chat before it gets here (readChatMessage); a host that doesn't, doesn't take chat.
|
|
2003
2058
|
return "chat_not_here";
|
|
@@ -2754,6 +2809,18 @@ export class RoomCore {
|
|
|
2754
2809
|
this.soon(() => this.leave(playerId, "lost"));
|
|
2755
2810
|
}
|
|
2756
2811
|
/** Token bucket per player: a short burst is fine, a flood is dropped. */
|
|
2812
|
+
/** The second bucket, for the messages inside combined frames: each takes one, so combining never lifts how often onMessage runs past its own limit. */
|
|
2813
|
+
takeCombined(playerId, messageCount) {
|
|
2814
|
+
const nowMs = this.now();
|
|
2815
|
+
const bucket = this.combinedBuckets.get(playerId) ?? { tokenCount: ROOM_LIMITS.maximumCombinedGameMessageBurstCount, filledAtMs: nowMs };
|
|
2816
|
+
bucket.tokenCount = Math.min(ROOM_LIMITS.maximumCombinedGameMessageBurstCount, bucket.tokenCount + ((nowMs - bucket.filledAtMs) / 1000) * ROOM_LIMITS.maximumCombinedGameMessagesPerSec);
|
|
2817
|
+
bucket.filledAtMs = nowMs;
|
|
2818
|
+
this.combinedBuckets.set(playerId, bucket);
|
|
2819
|
+
if (bucket.tokenCount < messageCount)
|
|
2820
|
+
return false;
|
|
2821
|
+
bucket.tokenCount -= messageCount;
|
|
2822
|
+
return true;
|
|
2823
|
+
}
|
|
2757
2824
|
take(playerId) {
|
|
2758
2825
|
const nowMs = this.now();
|
|
2759
2826
|
const bucket = this.buckets.get(playerId) ?? { tokenCount: ROOM_LIMITS.maximumGameMessageBurstCount, filledAtMs: nowMs };
|