@zaisma/game-server 1.38.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/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
- this.countTraffic("inbound", message.type === "message" ? messageTypeOf(message.data) : typeof message.type === "string" ? ZAISMA_MESSAGE_TYPE : NO_MESSAGE_TYPE, 1, sizeBytes);
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 };
@@ -1,62 +0,0 @@
1
- # Zaisma brand
2
-
3
- The Z is the brand: Julius's own drawing, based on Futura, made of glass. `npm run brand` (`scripts/brand.mjs`) makes every glass file here from the drawing, the ones the site's logo shows included; never edit one by hand.
4
-
5
- ## Which file to use
6
-
7
- | Use | File |
8
- |---|---|
9
- | The mark, on light surfaces | `zaisma-mark-glass-black.svg` (`-2048.png`) |
10
- | The mark, on dark surfaces | `zaisma-mark-glass-white.svg` (`-2048.png`) |
11
- | The wordmark, on light surfaces | `zaisma-wordmark-glass-black.svg` (`-2400.png`) |
12
- | The wordmark, on dark surfaces | `zaisma-wordmark-glass-white.svg` (`-2400.png`) |
13
- | One color (a stamp, a mask, a single-ink print) | `zaisma-mark-black.svg` / `zaisma-mark-white.svg`, `zaisma-wordmark-black.svg` / `zaisma-wordmark-white.svg` (`.png` copies at 2048 and 2400 px) |
14
- | App icon | `zaisma-icon-light.svg` (the default) and `zaisma-icon-dark.svg`; `app-icon-1024.png`, `app-icon-512.png`, `app-icon-192.png`, `app-icon-dark-512.png` |
15
- | Home screens | `apple-touch-icon.png` (square: the phone rounds it), `app-icon-maskable-512.png` (the Z inside the middle 80%), `manifest.webmanifest` |
16
- | Stripe's icon | `stripe-icon.png` (the Z inside the middle 80%, like the maskable icon: Stripe cuts it to a circle) |
17
- | Browser tab | `favicon.svg` (light and dark in one file), `favicon.ico` (16, 32 and 48 px), `favicon-32.png` |
18
- | A shared link with no picture of its own | `share-card-light.png` (1200 × 630, from `share-card-light.svg`); `share-card-dark.png` for places that take a dark card |
19
- | A friend invite link | `share-card-person-light.png` (the share card with the wordmark small at the bottom) and `share-card-letters.png` (a username's letters in Jost): the site draws the inviter's picture between them (`apps/site/src/person-card.ts`) |
20
- | Loading | `loader/` (see below) |
21
- | Zaisma Pro | `guild-seal-<px>.webp`, and `design/videos/guild-seal-forging.mp4` and `-resting.mp4`, from `npm run guild-seal`: the one drawing at every size, on its own dark circle |
22
-
23
- ## Rules
24
-
25
- 1. The mark is Julius's Z drawing, its three shards unchanged, made of glass: each shard bevelled and lit from the top left, with shaded walls. Never flat paint, metal or an outline. Black glass on light surfaces, white glass on dark ones.
26
- 2. The wordmark is the glass Z plus the shard letters "aisma" in the same glass, the letters shallower so the Z leads. Never retype it in a font.
27
- 3. The icon is the mark in front of the orange grid: a plane leaning back, rolled 35° along the Z's diagonal, strong near the viewer and gone by two-thirds up. Black Z on white and orange by default; white Z on black and the deeper orange for dark.
28
- 4. The share card is the full wordmark centered over the grid, the Relay far off to the right with its beam and lens flare, and players streaking toward it in orange. A person's card (a friend invite) is the same scene with their picture large in the middle and the wordmark small under it.
29
- 5. One Z at every size: never a second cut of it. The loader stays flat in the words' color. The flat black and white files are for one-color uses.
30
- 6. On pages, orange is only for what you press: the logo's orange lives in its icon and share card, never on the Z.
31
- 7. Leave clear space of at least the z's top-bar height. Don't rotate, stretch, recolor or add effects beyond these files.
32
- 8. The guild seal is Zaisma Pro's mark and nothing else's. Its Z is the one flat Z in brass: the one place the Z is recolored. Never a second drawing of it at another size.
33
-
34
- The bevel is 125 units in the Z's 4500-unit drawing (30 px in the Affinity file).
35
-
36
- ## Loader
37
-
38
- `loader/` holds the loading indicator: the Z building itself, one loop per second.
39
-
40
- - `zaisma-loader.svg` draws in `currentColor`; the site uses it as a CSS mask so it takes the text color. `-black` and `-white` are fixed-color copies.
41
- - `png/`, `webp/` and `gif/` are 128 px and 512 px exports, black and white, for places that can't run an animated SVG.
42
- - Use it only while something is actually loading, never as decoration.
43
-
44
- ## Typeface
45
-
46
- Headings use **Jost** (`fonts/jost.7726a5cd.woff2`, variable weight), a free geometric typeface close to Futura. It's under the SIL Open Font License (`fonts/OFL.txt`). Body text uses the system font. The file is named for its contents (the first 8 hex digits of its SHA-256), so browsers keep it for good (`_headers`): a changed font gets a new name, and `test/node/brand-files.test.ts` checks that every page asks for one that's there.
47
-
48
- ## Flags
49
-
50
- `flags/` holds a 60×45 PNG of each country's flag, shown beside rooms on game pages (where the room runs). They're rendered from [flag-icons](https://github.com/lipis/flag-icons) 7.5.0, under the MIT License (`flags/LICENSE`). They aren't part of the brand; they live here because this folder is what zaisma.com serves as files.
51
-
52
- ## License
53
-
54
- The code in this repo is MIT. The Zaisma name and logo are the project's identity: use them to refer to Zaisma, not to brand other products.
55
-
56
- ## The sign-in's pictures
57
-
58
- `sign-in/` holds the city's stills (`apps/site/src/components/city.ts`): renders of the live city's first frame, by day and by night, wide and for a phone, which stand in where the city can't run.
59
-
60
- ## Cover guide pictures
61
-
62
- `cover-guide/` holds the pictures zaisma.com/developers/covers shows (`apps/site/src/cover-guide.ts`, `docs/COVERS.md`): good covers made from real captures of the demo games Arena and Four in a Row, and stand-ins for made-up games. They are examples for developers, not Zaisma's brand.