@zaisma/game-server 1.39.0 → 1.40.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/bench/glass.js +582 -390
- package/package.json +1 -1
- package/sdk/zaisma.d.ts +18 -2
- package/sdk/zaisma.js +209 -9
- package/src/room.d.ts +21 -2
- package/src/room.js +72 -5
package/package.json
CHANGED
package/sdk/zaisma.d.ts
CHANGED
|
@@ -918,7 +918,21 @@ declare namespace Zaisma {
|
|
|
918
918
|
* @example
|
|
919
919
|
* const room = await Zaisma.joinRoom({ isSpectator: Zaisma.rooms.isLinkedAsSpectator });
|
|
920
920
|
*/
|
|
921
|
-
isSpectator?: boolean;
|
|
921
|
+
isSpectator?: boolean; /**
|
|
922
|
+
* true (the default): what the game sends at once (in one frame of its loop, say) goes to the room as one
|
|
923
|
+
* message of up to 8, and sends keep under the room's 30 a second by themselves: past that, they wait a few
|
|
924
|
+
* milliseconds and go together instead of coming back "too_fast". Each still reaches the game server's
|
|
925
|
+
* onMessage on its own, in order. A room is billed for each message it gets, so this costs the game less.
|
|
926
|
+
* Rooms on your own server combine only when their game server says it can (game server 1.40 and later).
|
|
927
|
+
* false: every send goes alone and at once, as it's made.
|
|
928
|
+
*/
|
|
929
|
+
sendCombiningEnabled?: boolean;
|
|
930
|
+
/**
|
|
931
|
+
* true (the default): a { delivery: "latest_only" } send that's the same as the last one with its latestKey
|
|
932
|
+
* isn't sent, since the room already has it; the first after a reconnect always goes. Reliable sends always go.
|
|
933
|
+
* false: send every one, as when the game server expects a steady stream.
|
|
934
|
+
*/
|
|
935
|
+
unchangedSkippingEnabled?: boolean;
|
|
922
936
|
}
|
|
923
937
|
|
|
924
938
|
/**
|
|
@@ -1177,7 +1191,9 @@ declare namespace Zaisma {
|
|
|
1177
1191
|
* 30 a second at most. Send input when it changes, not every frame. While connectionStatus isn't "open"
|
|
1178
1192
|
* or the player is away, reliable sends wait and go in order once the room is back, up to 60: past that
|
|
1179
1193
|
* the oldest is dropped, and an "error" event says "send_queue_full" once. With
|
|
1180
|
-
* { delivery: "latest_only", latestKey }, a message may be dropped for a newer one (SendOptions)
|
|
1194
|
+
* { delivery: "latest_only", latestKey }, a message may be dropped for a newer one (SendOptions), and one
|
|
1195
|
+
* the same as the last with its latestKey isn't sent (JoinOptions.unchangedSkippingEnabled). What the game
|
|
1196
|
+
* sends at once goes as one message (JoinOptions.sendCombiningEnabled). A
|
|
1181
1197
|
* spectator can't send: it throws error.code "spectator_cannot_send". Returns false only when the room
|
|
1182
1198
|
* is gone (ended, kicked or left), so nothing will ever send.
|
|
1183
1199
|
*
|
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;
|
|
@@ -562,6 +576,19 @@
|
|
|
562
576
|
// Latest-only sends waiting for the socket to drain, by "<kind>:<latestKey>", least recently replaced first.
|
|
563
577
|
this._slots = new Map();
|
|
564
578
|
this._slotTimer = null;
|
|
579
|
+
// Combining: whether the game left it on, whether this connection's room takes combined frames (from welcome),
|
|
580
|
+
// the game messages waiting for the end of this task or for the pace ({ dataText, latestKey }), and the pace's bucket.
|
|
581
|
+
this._sendCombiningEnabled = setup.sendCombiningEnabled !== false;
|
|
582
|
+
this._canCombine = false;
|
|
583
|
+
this._outbox = [];
|
|
584
|
+
this._isOutboxDue = false;
|
|
585
|
+
this._outboxTimer = null;
|
|
586
|
+
this._paceTokenCount = PACED_FRAME_BURST_COUNT;
|
|
587
|
+
this._messageTokenCount = PACED_MESSAGE_BURST_COUNT;
|
|
588
|
+
this._pacedAtMs = Date.now();
|
|
589
|
+
// Unchanged latest-only sends are skipped (unchangedSkippingEnabled): the last one given for each slot on this connection.
|
|
590
|
+
this._unchangedSkippingEnabled = setup.unchangedSkippingEnabled !== false;
|
|
591
|
+
this._lastLatest = new Map();
|
|
565
592
|
// Reliable sends waiting for the connection, in order, and whether this outage already said some were dropped.
|
|
566
593
|
this._queue = [];
|
|
567
594
|
this._flushTimer = null;
|
|
@@ -741,6 +768,8 @@
|
|
|
741
768
|
|
|
742
769
|
/** Send a message to the room if the connection is open. */
|
|
743
770
|
Room.prototype._say = function (message) {
|
|
771
|
+
// Game messages waiting in the outbox go first, so the room hears everything in the order it was said.
|
|
772
|
+
if (this._isWelcomed) this._flushOutbox(true);
|
|
744
773
|
if (!this._ws || this._ws.readyState !== 1) return;
|
|
745
774
|
this._ws.send(JSON.stringify(message));
|
|
746
775
|
this._sentAtMs = Date.now();
|
|
@@ -823,6 +852,10 @@
|
|
|
823
852
|
room._probeIntervalSec = typeof message.probeIntervalSec === "number" ? message.probeIntervalSec : null;
|
|
824
853
|
room.spectatorCount = typeof message.spectatorCount === "number" ? message.spectatorCount : 0;
|
|
825
854
|
room.canChat = message.canChat === true && !room.isSpectator;
|
|
855
|
+
// A room that doesn't say so (an older game server of the game's own) gets one message a frame, as before.
|
|
856
|
+
room._canCombine = message.canCombineMessages === true;
|
|
857
|
+
// A new connection: the first latest-only send of each kind goes, whatever went before.
|
|
858
|
+
room._lastLatest = new Map();
|
|
826
859
|
room._away = room._gone = room._idleSent = room._coming = room._offered = room._isReloadingForVersion = false;
|
|
827
860
|
room.awayReason = null;
|
|
828
861
|
room._isQueueFullSaid = false;
|
|
@@ -1039,19 +1072,158 @@
|
|
|
1039
1072
|
/**
|
|
1040
1073
|
* Send a message to the game server. Plain JSON, up to 16 KB. Send input when it changes, not every frame.
|
|
1041
1074
|
* 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
|
|
1075
|
+
* { delivery: "latest_only", latestKey } may drop it for a newer one with the same latestKey, and one the same as
|
|
1076
|
+
* the last for its latestKey isn't sent (joinRoom's unchangedSkippingEnabled). What the game sends at once goes in
|
|
1077
|
+
* one frame, kept under the room's limit (joinRoom's sendCombiningEnabled). False once the room is gone.
|
|
1043
1078
|
*/
|
|
1044
1079
|
Room.prototype.send = function (message, sendOptions) {
|
|
1045
1080
|
if (this.isSpectator) throw spectatorCannotSend();
|
|
1046
1081
|
var latestKey = readDelivery(sendOptions, "room.send");
|
|
1047
|
-
var
|
|
1082
|
+
var dataText = JSON.stringify(message);
|
|
1083
|
+
var payload = dataText === undefined ? JSON.stringify({ type: "message" }) : '{"type":"message","data":' + dataText + "}";
|
|
1048
1084
|
checkSendSize(payload);
|
|
1049
1085
|
if (this._done) return false;
|
|
1050
|
-
|
|
1086
|
+
var isCombined = dataText !== undefined && this._combines();
|
|
1087
|
+
if (latestKey !== null) {
|
|
1088
|
+
var slotKey = "message:" + latestKey;
|
|
1089
|
+
if (this._isUnchanged(slotKey, payload)) return true;
|
|
1090
|
+
// On the fast lane a latest-only send goes as a datagram, which is never held for a frame.
|
|
1091
|
+
if (isCombined && !this._ws.sendDatagram) this._putInOutbox(dataText, latestKey);
|
|
1092
|
+
else this._sendLatest(slotKey, payload);
|
|
1093
|
+
} else if (isCombined) this._putInOutbox(dataText, null);
|
|
1051
1094
|
else this._sendReliable(payload);
|
|
1052
1095
|
return true;
|
|
1053
1096
|
};
|
|
1054
1097
|
|
|
1098
|
+
/** Whether a game message goes through the outbox now: combining on, the room takes it, and nothing waiting for the connection. */
|
|
1099
|
+
Room.prototype._combines = function () {
|
|
1100
|
+
return this._sendCombiningEnabled && this._canCombine && this._canSend() && !this._queue.length;
|
|
1101
|
+
};
|
|
1102
|
+
|
|
1103
|
+
/**
|
|
1104
|
+
* Whether a latest-only send is the same as the last one given for its slot on this connection, so it needn't go.
|
|
1105
|
+
* 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.
|
|
1106
|
+
*/
|
|
1107
|
+
Room.prototype._isUnchanged = function (slotKey, sentValue) {
|
|
1108
|
+
if (!this._unchangedSkippingEnabled) return false;
|
|
1109
|
+
var nowMs = Date.now();
|
|
1110
|
+
var last = this._lastLatest.get(slotKey);
|
|
1111
|
+
var isDatagram = Boolean(this._ws && this._ws.sendDatagram);
|
|
1112
|
+
if (last && sameValue(last.sentValue, sentValue) && !(last.isDatagram && nowMs - last.givenAtMs >= UNCHANGED_DATAGRAM_INTERVAL_MS)) return true;
|
|
1113
|
+
this._lastLatest.set(slotKey, { sentValue: sentValue, givenAtMs: nowMs, isDatagram: isDatagram });
|
|
1114
|
+
return false;
|
|
1115
|
+
};
|
|
1116
|
+
/** Text or bytes, the same. */
|
|
1117
|
+
function sameValue(first, second) {
|
|
1118
|
+
if (typeof first === "string" || typeof second === "string") return first === second;
|
|
1119
|
+
if (first.byteLength !== second.byteLength) return false;
|
|
1120
|
+
var firstBytes = new Uint8Array(first);
|
|
1121
|
+
var secondBytes = new Uint8Array(second);
|
|
1122
|
+
for (var i = 0; i < firstBytes.length; i++) if (firstBytes[i] !== secondBytes[i]) return false;
|
|
1123
|
+
return true;
|
|
1124
|
+
}
|
|
1125
|
+
|
|
1126
|
+
/** The pace's tokens now, refilled at PACED_FRAMES_PER_SEC up to PACED_FRAME_BURST_COUNT. */
|
|
1127
|
+
Room.prototype._paceTokens = function () {
|
|
1128
|
+
var nowMs = Date.now();
|
|
1129
|
+
var elapsedSec = (nowMs - this._pacedAtMs) / 1000;
|
|
1130
|
+
this._paceTokenCount = Math.min(PACED_FRAME_BURST_COUNT, this._paceTokenCount + elapsedSec * PACED_FRAMES_PER_SEC);
|
|
1131
|
+
this._messageTokenCount = Math.min(PACED_MESSAGE_BURST_COUNT, this._messageTokenCount + elapsedSec * PACED_MESSAGES_PER_SEC);
|
|
1132
|
+
this._pacedAtMs = nowMs;
|
|
1133
|
+
return this._paceTokenCount;
|
|
1134
|
+
};
|
|
1135
|
+
/**
|
|
1136
|
+
* Frames that went, combined or not, and the messages in them: they count against the pace, so bytes and JSON together keep
|
|
1137
|
+
* under the room's limit. Never below empty: what went without waiting (bytes, datagrams) doesn't hold the outbox back for long.
|
|
1138
|
+
*/
|
|
1139
|
+
Room.prototype._spendPace = function (frameCount, messageCount) {
|
|
1140
|
+
this._paceTokens();
|
|
1141
|
+
this._paceTokenCount = Math.max(0, this._paceTokenCount - frameCount);
|
|
1142
|
+
this._messageTokenCount = Math.max(0, this._messageTokenCount - (messageCount || 0));
|
|
1143
|
+
};
|
|
1144
|
+
|
|
1145
|
+
/** A game message into the outbox: a latest-only one replaces a waiting one with its latestKey, and reliable ones wait up to 60. */
|
|
1146
|
+
Room.prototype._putInOutbox = function (dataText, latestKey) {
|
|
1147
|
+
var waiting = latestKey === null ? null : this._outbox.filter(function (entry) { return entry.latestKey === latestKey; })[0];
|
|
1148
|
+
if (waiting) waiting.dataText = dataText;
|
|
1149
|
+
else this._outbox.push({ dataText: dataText, latestKey: latestKey });
|
|
1150
|
+
var reliable = this._outbox.filter(function (entry) { return entry.latestKey === null; });
|
|
1151
|
+
if (reliable.length > MAXIMUM_QUEUED_SEND_COUNT) {
|
|
1152
|
+
this._outbox.splice(this._outbox.indexOf(reliable[0]), 1);
|
|
1153
|
+
if (!this._isQueueFullSaid) {
|
|
1154
|
+
this._isQueueFullSaid = true;
|
|
1155
|
+
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." });
|
|
1156
|
+
}
|
|
1157
|
+
}
|
|
1158
|
+
if (this._isOutboxDue || this._outboxTimer !== null) return;
|
|
1159
|
+
this._isOutboxDue = true;
|
|
1160
|
+
var room = this;
|
|
1161
|
+
queueMicrotask(function () {
|
|
1162
|
+
room._isOutboxDue = false;
|
|
1163
|
+
room._flushOutbox(false);
|
|
1164
|
+
});
|
|
1165
|
+
};
|
|
1166
|
+
|
|
1167
|
+
/**
|
|
1168
|
+
* 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
|
|
1169
|
+
* next token. Forced (before a send that isn't combined, to keep the order), all of it now. With the connection gone,
|
|
1170
|
+
* its messages wait as uncombined sends do.
|
|
1171
|
+
*/
|
|
1172
|
+
Room.prototype._flushOutbox = function (isForced) {
|
|
1173
|
+
if (!this._outbox.length) return;
|
|
1174
|
+
var entries;
|
|
1175
|
+
var room = this;
|
|
1176
|
+
if (this._done || !this._canSend() || this._queue.length) {
|
|
1177
|
+
entries = this._outbox;
|
|
1178
|
+
this._outbox = [];
|
|
1179
|
+
this._clearOutboxTimer();
|
|
1180
|
+
if (this._done) return;
|
|
1181
|
+
entries.forEach(function (entry) {
|
|
1182
|
+
var payload = '{"type":"message","data":' + entry.dataText + "}";
|
|
1183
|
+
if (entry.latestKey === null) room._sendReliable(payload);
|
|
1184
|
+
else room._slotLatest("message:" + entry.latestKey, payload);
|
|
1185
|
+
});
|
|
1186
|
+
return;
|
|
1187
|
+
}
|
|
1188
|
+
// Latest-only messages wait in their slots while the socket is backed up, as uncombined ones do.
|
|
1189
|
+
if (this._ws.bufferedAmount >= BACKED_UP_SIZE_BYTES) {
|
|
1190
|
+
this._outbox = this._outbox.filter(function (entry) {
|
|
1191
|
+
if (entry.latestKey === null) return true;
|
|
1192
|
+
room._slotLatest("message:" + entry.latestKey, '{"type":"message","data":' + entry.dataText + "}");
|
|
1193
|
+
return false;
|
|
1194
|
+
});
|
|
1195
|
+
}
|
|
1196
|
+
while (this._outbox.length && (isForced || (this._paceTokens() >= 1 && this._messageTokenCount >= 1))) {
|
|
1197
|
+
var frame = [];
|
|
1198
|
+
var frameSizeBytes = '{"type":"messages","data":[]}'.length;
|
|
1199
|
+
var maximumMessageCount = isForced ? MAXIMUM_COMBINED_MESSAGE_COUNT : Math.min(MAXIMUM_COMBINED_MESSAGE_COUNT, Math.floor(this._messageTokenCount));
|
|
1200
|
+
while (this._outbox.length && frame.length < maximumMessageCount) {
|
|
1201
|
+
var sizeBytes = utf8SizeOf(this._outbox[0].dataText) + 1;
|
|
1202
|
+
if (frame.length && frameSizeBytes + sizeBytes > MAXIMUM_SEND_SIZE_BYTES) break;
|
|
1203
|
+
frame.push(this._outbox.shift().dataText);
|
|
1204
|
+
frameSizeBytes += sizeBytes;
|
|
1205
|
+
}
|
|
1206
|
+
this._ws.send(frame.length === 1 ? '{"type":"message","data":' + frame[0] + "}" : '{"type":"messages","data":[' + frame.join(",") + "]}");
|
|
1207
|
+
this._spendPace(1, frame.length);
|
|
1208
|
+
this._sentAtMs = Date.now();
|
|
1209
|
+
}
|
|
1210
|
+
this._clearOutboxTimer();
|
|
1211
|
+
if (!this._outbox.length) return;
|
|
1212
|
+
this._outboxTimer = setTimeout(function () {
|
|
1213
|
+
room._outboxTimer = null;
|
|
1214
|
+
room._flushOutbox(false);
|
|
1215
|
+
}, Math.max(1, Math.ceil(Math.max((1 - this._paceTokenCount) / PACED_FRAMES_PER_SEC, (1 - this._messageTokenCount) / PACED_MESSAGES_PER_SEC) * 1000)));
|
|
1216
|
+
};
|
|
1217
|
+
Room.prototype._clearOutboxTimer = function () {
|
|
1218
|
+
if (this._outboxTimer === null) return;
|
|
1219
|
+
clearTimeout(this._outboxTimer);
|
|
1220
|
+
this._outboxTimer = null;
|
|
1221
|
+
};
|
|
1222
|
+
/** Text's size in UTF-8, measured only when it could matter. */
|
|
1223
|
+
function utf8SizeOf(text) {
|
|
1224
|
+
return text.length * 3 <= 1024 ? text.length * 3 : new TextEncoder().encode(text).length;
|
|
1225
|
+
}
|
|
1226
|
+
|
|
1055
1227
|
/**
|
|
1056
1228
|
* Send bytes to the game server (its onBytes), like a compact input: an ArrayBuffer or any typed array,
|
|
1057
1229
|
* up to 16 KB, counted with messages (30 a second). Takes the same sendOptions as room.send.
|
|
@@ -1064,8 +1236,10 @@
|
|
|
1064
1236
|
if (this._done) return false;
|
|
1065
1237
|
// A copy: the game may reuse its buffer while this one waits.
|
|
1066
1238
|
var copy = ArrayBuffer.isView(bytes) ? bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) : bytes.slice(0);
|
|
1067
|
-
if (latestKey !== null)
|
|
1068
|
-
|
|
1239
|
+
if (latestKey !== null) {
|
|
1240
|
+
if (this._isUnchanged("bytes:" + latestKey, copy)) return true;
|
|
1241
|
+
this._sendLatest("bytes:" + latestKey, copy);
|
|
1242
|
+
} else this._sendReliable(copy);
|
|
1069
1243
|
return true;
|
|
1070
1244
|
};
|
|
1071
1245
|
|
|
@@ -1081,8 +1255,11 @@
|
|
|
1081
1255
|
|
|
1082
1256
|
/** A reliable send: now, or in order once the connection is open again, dropping the oldest past 60. */
|
|
1083
1257
|
Room.prototype._sendReliable = function (payload) {
|
|
1258
|
+
// Game messages waiting in the outbox go first, so everything keeps its order.
|
|
1259
|
+
this._flushOutbox(true);
|
|
1084
1260
|
if (this._canSend() && !this._queue.length) {
|
|
1085
1261
|
this._ws.send(payload);
|
|
1262
|
+
this._spendPace(1);
|
|
1086
1263
|
this._sentAtMs = Date.now();
|
|
1087
1264
|
return;
|
|
1088
1265
|
}
|
|
@@ -1099,7 +1276,9 @@
|
|
|
1099
1276
|
var room = this;
|
|
1100
1277
|
var ws = this._ws;
|
|
1101
1278
|
function send(sendCount) {
|
|
1102
|
-
room._queue.splice(0, sendCount)
|
|
1279
|
+
var sent = room._queue.splice(0, sendCount);
|
|
1280
|
+
sent.forEach(function (payload) { ws.send(payload); });
|
|
1281
|
+
room._spendPace(sent.length);
|
|
1103
1282
|
room._sentAtMs = Date.now();
|
|
1104
1283
|
}
|
|
1105
1284
|
send(FLUSH_NOW_COUNT);
|
|
@@ -1130,20 +1309,32 @@
|
|
|
1130
1309
|
|
|
1131
1310
|
/** A latest-only send: now, after anything still waiting, or into its slot while the socket is backed up. */
|
|
1132
1311
|
Room.prototype._sendLatest = function (slotKey, payload) {
|
|
1312
|
+
this._flushOutbox(true);
|
|
1133
1313
|
// On the fast lane, a datagram: a late one is lost rather than waited for, so it skips the slots.
|
|
1134
1314
|
if (this._canSend() && !this._queue.length && this._ws.sendDatagram && this._ws.sendDatagram(payload)) {
|
|
1315
|
+
this._spendPace(1);
|
|
1135
1316
|
this._sentAtMs = Date.now();
|
|
1136
1317
|
return;
|
|
1137
1318
|
}
|
|
1138
1319
|
if (this._canSend() && !this._queue.length && !(this._ws.bufferedAmount >= BACKED_UP_SIZE_BYTES)) {
|
|
1139
1320
|
this._sendWaiting();
|
|
1140
1321
|
this._ws.send(payload);
|
|
1322
|
+
this._spendPace(1);
|
|
1141
1323
|
this._sentAtMs = Date.now();
|
|
1142
1324
|
return;
|
|
1143
1325
|
}
|
|
1326
|
+
this._slotLatest(slotKey, payload);
|
|
1327
|
+
};
|
|
1328
|
+
/** A latest-only send into its slot, to go once the socket drains: the slot keeps only the newest. */
|
|
1329
|
+
Room.prototype._slotLatest = function (slotKey, payload) {
|
|
1144
1330
|
this._slots.delete(slotKey);
|
|
1145
1331
|
this._slots.set(slotKey, payload);
|
|
1146
|
-
if (this._slots.size > MAXIMUM_LATEST_ONLY_SLOT_COUNT)
|
|
1332
|
+
if (this._slots.size > MAXIMUM_LATEST_ONLY_SLOT_COUNT) {
|
|
1333
|
+
var evictedKey = this._slots.keys().next().value;
|
|
1334
|
+
this._slots.delete(evictedKey);
|
|
1335
|
+
// It never went: the next send with its latestKey goes, the same or not.
|
|
1336
|
+
this._lastLatest.delete(evictedKey);
|
|
1337
|
+
}
|
|
1147
1338
|
if (this._slotTimer === null) {
|
|
1148
1339
|
var room = this;
|
|
1149
1340
|
this._slotTimer = setInterval(function () {
|
|
@@ -1158,6 +1349,7 @@
|
|
|
1158
1349
|
if (!this._slots.size || !this._canSend() || this._queue.length) return;
|
|
1159
1350
|
var ws = this._ws;
|
|
1160
1351
|
this._slots.forEach(function (payload) { ws.send(payload); });
|
|
1352
|
+
this._spendPace(this._slots.size);
|
|
1161
1353
|
this._slots.clear();
|
|
1162
1354
|
this._sentAtMs = Date.now();
|
|
1163
1355
|
};
|
|
@@ -1346,6 +1538,8 @@
|
|
|
1346
1538
|
this._views = [];
|
|
1347
1539
|
this._slots.clear();
|
|
1348
1540
|
this._queue = [];
|
|
1541
|
+
this._outbox = [];
|
|
1542
|
+
this._clearOutboxTimer();
|
|
1349
1543
|
this._sayRoomToPage();
|
|
1350
1544
|
this._setConnectionStatus("connecting");
|
|
1351
1545
|
this._emit("moved", { roomCode: roomCode, fromRoomCode: fromRoomCode });
|
|
@@ -1618,6 +1812,8 @@
|
|
|
1618
1812
|
if (!this._done) left(this);
|
|
1619
1813
|
this._done = true;
|
|
1620
1814
|
this._queue = [];
|
|
1815
|
+
this._outbox = [];
|
|
1816
|
+
this._clearOutboxTimer();
|
|
1621
1817
|
this._failChats();
|
|
1622
1818
|
if (this._ws) this._ws.close(1000, "Left");
|
|
1623
1819
|
};
|
|
@@ -1637,6 +1833,8 @@
|
|
|
1637
1833
|
var isOffZaisma = !config.rooms;
|
|
1638
1834
|
var idleTimeoutSec = joinOptions.idleTimeoutSec;
|
|
1639
1835
|
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 + "."));
|
|
1836
|
+
var badSwitch = ["sendCombiningEnabled", "unchangedSkippingEnabled"].filter(function (name) { return joinOptions[name] !== undefined && typeof joinOptions[name] !== "boolean"; })[0];
|
|
1837
|
+
if (badSwitch) return Promise.reject(codedError("unknown_option", badSwitch + " is " + JSON.stringify(joinOptions[badSwitch]) + ". Give true (the default) or false."));
|
|
1640
1838
|
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
1839
|
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
1840
|
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 +1861,8 @@
|
|
|
1663
1861
|
labels: joinOptions.labels,
|
|
1664
1862
|
joinData: joinOptions.joinData,
|
|
1665
1863
|
clientIdle: clientIdle(joinOptions),
|
|
1864
|
+
sendCombiningEnabled: joinOptions.sendCombiningEnabled,
|
|
1865
|
+
unchangedSkippingEnabled: joinOptions.unchangedSkippingEnabled,
|
|
1666
1866
|
serverUrl: serverUrl,
|
|
1667
1867
|
isSpectator: joinOptions.isSpectator === true,
|
|
1668
1868
|
});
|
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 };
|