@inglorious/server 21.0.11 → 21.1.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 CHANGED
@@ -1,89 +1,141 @@
1
1
  # Inglorious Server
2
2
 
3
- A real-time, lightweight server designed to enable multiplayer experiences for games built with the Inglorious Engine. This server is built on Node.js and uses WebSockets to handle real-time communication, ensuring low-latency updates for all connected clients.
3
+ A multiplayer server for games and apps built on [`@inglorious/store`](https://www.npmjs.com/package/@inglorious/store) and the [Inglorious Engine](https://inglorious.dev/engine/). Each room has an authoritative store that ticks like the engine. Clients send it events, and the server stamps each event with its sender and relays it to the other players.
4
4
 
5
- ## Features
5
+ - **A library.** Importing it does nothing. Attach it to your own HTTP server to serve your build and the WebSocket from the same port, or let it make one.
6
+ - **Player identity.** Every event a client sends carries the sender's `playerId`, which the server stamps itself, so a client can't speak for another. Players join and leave as store events (`playerJoin`, `playerLeave`).
7
+ - **Reconnection.** A client that drops comes back as the same player. If the same player connects again, the newer socket replaces the older one.
8
+ - **Safe defaults.** You choose which events clients may send, and the server never accepts its own events from a client. There are limits on message size and rate and on players per room, and a heartbeat cuts dead connections.
9
+ - **Rooms.** Optionally, one store per room code. Empty rooms are dropped after a while.
6
10
 
7
- - **Real-Time Communication**: Uses WebSockets to provide bidirectional, low-latency communication between the server and clients.
8
- - **Server-Authoritative Game State**: Manages a central game state using the `@inglorious/store` and acts as the single source of truth for all clients.
9
- - **Scalable Architecture**: The server's logic is modular and split into dedicated files for handling game loading, the main game loop, and WebSocket events.
10
- - **Dynamic Game Loading**: Supports loading game data from a specified JavaScript module, allowing you to easily run different game worlds without changing the server code.
11
- - **Production-Ready Logging**: Uses `pino` for fast, structured logging, making it easy to monitor and debug in a production environment.
11
+ Works with `@inglorious/store` 12.10+ and `@inglorious/engine` 24.17.1+ (their `multiplayer` client). Node 26+.
12
12
 
13
- ## Getting Started
13
+ ## Install
14
14
 
15
- ### Prerequisites
15
+ ```sh
16
+ pnpm add @inglorious/server @inglorious/store @inglorious/utils
17
+ ```
16
18
 
17
- - [Node.js](https://nodejs.org/) (version 22 or higher)
18
- - [pnpm](https://pnpm.io/) (used for package management)
19
+ ## Use
19
20
 
20
- ### Installation
21
+ A game config is the one you give the store or the engine: `types`, `entities`, `systems`. The server ticks it at `fps`, notifying `update` with the seconds passed, as the engine does.
21
22
 
22
- 1. Clone the Inglorious Forge repository:
23
+ ```javascript
24
+ // server.js
25
+ import http from "node:http"
23
26
 
24
- ```sh
25
- git clone https://github.com/IngloriousCoderz/inglorious-forge.git
26
- ```
27
+ import { createServer } from "@inglorious/server"
28
+ import sirv from "sirv" // or any static file handler
27
29
 
28
- 2. Navigate to the `@inglorious/server` directory:
30
+ import game from "./src/game.js"
29
31
 
30
- ```sh
31
- cd packages/server
32
- ```
32
+ const httpServer = http.createServer(sirv("dist", { single: true }))
33
33
 
34
- 3. Install the dependencies:
34
+ createServer({
35
+ game,
36
+ server: httpServer,
37
+ path: "/ws",
38
+ acceptedEvents: ["cardPlay", "chatSend"],
39
+ maxPlayers: 8,
40
+ rooms: true,
41
+ })
35
42
 
36
- ```sh
37
- pnpm install
43
+ httpServer.listen(process.env.PORT ?? 3000)
38
44
  ```
39
45
 
40
- ## Usage
46
+ Without `server`, it makes its own: `const port = await createServer({ game }).listen(3000)`.
41
47
 
42
- The server can be started using the `start` or `dev` scripts. You can optionally provide a path to a game module to load a specific game state.
48
+ The client is the store's multiplayer middleware. In an engine game it's the `multiplayer` option of the `game` entity:
43
49
 
44
- ### Running in Development Mode
45
-
46
- To run the server with automatic restarts on file changes, use the `dev` script.
50
+ ```javascript
51
+ game: {
52
+ type: "Game",
53
+ multiplayer: {
54
+ serverUrl: `wss://${location.host}/ws`,
55
+ whitelist: ["cardPlay", "chatSend"],
56
+ },
57
+ }
58
+ ```
47
59
 
48
- ```sh
49
- pnpm dev
60
+ ### Who did what
61
+
62
+ Handlers see only the payload, so the sender goes there. Every event a client sends arrives with `playerId` in its payload. The server overwrites any `playerId` the client put there. The client stamps its own events the same way, so every store applies the same payload. Only payloads that are plain objects, or missing, are stamped: send `{ cell: 4 }` rather than `4` if you need to know who sent it.
63
+
64
+ ```javascript
65
+ const Board = {
66
+ sessionStart(board, { playerId }) {
67
+ board.me = playerId // this client's player
68
+ },
69
+ playerJoin(board, { playerId }) {
70
+ board.players[playerId] = { isOnline: true }
71
+ },
72
+ playerLeave(board, { playerId }) {
73
+ board.players[playerId].isOnline = false // they may come back
74
+ },
75
+ cardPlay(board, { card, playerId }) {
76
+ if (board.turn !== playerId) return
77
+ // ...
78
+ },
79
+ }
50
80
  ```
51
81
 
52
- ### Running in Production Mode
82
+ ### Events
53
83
 
54
- To run the server in a production environment, use the `start` script.
84
+ | Event | Sent by | Payload |
85
+ | -------------- | ---------------------------------------------------------------------- | ----------------------------------------------------- |
86
+ | `playerJoin` | the server, to everyone, when a player connects or comes back | `{ playerId }` |
87
+ | `playerLeave` | the server, to everyone, when a player's connection closes | `{ playerId }` |
88
+ | `sessionStart` | the client middleware, locally, when the server has said who it is | `{ playerId, room }` |
89
+ | `sessionEnd` | the client middleware, locally, when the server turns it away for good | `{ reason }`: `"full"`, `"replaced"`, `"roomMissing"` |
55
90
 
56
- ```sh
57
- pnpm start
58
- ```
91
+ A player who leaves keeps their slot for `reserveSeconds`. If they reconnect within that time, `playerJoin` comes again with the same `playerId`. It's up to the game when to give up on an absent player.
59
92
 
60
- ### Loading a Specific Game
93
+ ### Rooms
61
94
 
62
- By default, the server will attempt to load a `./default-game.js` file. To load a different game, provide the file path as a command-line argument.
95
+ With `rooms: true`, a client that asks for no room gets a new one with a 4-letter code (no I or O). A client asking for an existing code joins it, and a client asking for a code that doesn't exist is closed with `sessionEnd` `"roomMissing"`. Clients pass the code with the middleware's `room` option, and learn it from `sessionStart`. Every room starts from its own copy of `game`. For a different config per room, pass a function: `game: (room) => config`.
63
96
 
64
- ```sh
65
- pnpm start ./path/to/your-game.js
66
- ```
97
+ ## Options
67
98
 
68
- ## Project Structure
99
+ | Option | Default | |
100
+ | ------------------ | ----------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
101
+ | `game` | required | Store config, or `(room) => config` |
102
+ | `server` | its own | An HTTP server to attach to |
103
+ | `path` | any | Only upgrade requests on this path, such as `"/ws"` |
104
+ | `acceptedEvents` | all but the reserved | Event types clients may send, or `(event) => boolean`. `playerJoin`, `playerLeave`, `stateInit`, `stateSync`, `update`, `create` and `destroy` are never accepted |
105
+ | `maxPlayers` | `Infinity` | Per room, reserved slots included. Over it: close code 4001 |
106
+ | `maxPayloadBytes` | `16384` | Bigger messages close the socket (1009) |
107
+ | `rate` | `{ perSecond: 30, burst: 60, graceSeconds: 5 }` | Token bucket per socket. Excess messages are dropped, and after `graceSeconds` of steady excess the socket is closed (4008) |
108
+ | `reserveSeconds` | `60` | How long a disconnected player's slot waits |
109
+ | `heartbeatSeconds` | `25` | Ping interval. A socket that misses a pong is cut |
110
+ | `rooms` | `false` | `true`, or `{ idleSeconds: 600, codeLength: 4 }` |
111
+ | `snapshotSeconds` | `0` | Send everyone the whole state this often, to undo drift. `0` never |
112
+ | `fps` | `60` | Server ticks per second. `0` never ticks |
113
+ | `logger` | `console` | Anything with `info`, `warn`, `error` (pino works) |
69
114
 
70
- The server's code is split into several files to maintain a clear separation of concerns.
115
+ `createServer` returns `{ httpServer, rooms, listen(port), close() }`. `rooms` maps each code to `{ code, store }`. Without rooms, the only room is `""`.
71
116
 
72
- - `src/index.js`: The main entry point for the server. It orchestrates the setup of the HTTP and WebSocket servers and initializes the game store and its core handlers.
73
- - `src/game-loader.js`: Handles the dynamic loading of the initial game state from a JavaScript module. It also includes a fallback state if the game file is not found.
74
- - `src/game-loop.js`: Contains the core setInterval loop that drives the game logic by calling the store.update() function at a fixed tick rate (60 updates per second).
75
- - `src/websocket-handler.js`: Manages all WebSocket events, including new connections, incoming messages, and disconnections. It dispatches client events to the store and broadcasts changes to all clients.
117
+ Without `acceptedEvents`, clients may send any event except the reserved ones, including `add` and `remove`. That's fine for a prototype among friends, but set the list before anyone else plays.
76
118
 
77
- ## Dependencies
119
+ ## How it stays in sync
78
120
 
79
- - `@inglorious/store`: The state management solution for the game engine.
80
- - `ws`: A simple and fast WebSocket library.
81
- - `pino`: A highly performant logger for Node.js.
121
+ Each client runs the same handlers on the same events, as in lockstep. When a client connects, it gets the whole state (`stateInit`). After that it gets the events other players send, plus `playerJoin`/`playerLeave`. Events that handlers notify are not relayed, because every store notifies them for itself. Anything random or time-based in a handler makes stores drift apart, so use a seeded random generator kept in the state. If drift can't be avoided, turn on `snapshotSeconds`.
82
122
 
83
- ## License
123
+ ## Command line
124
+
125
+ For a quick try with no server code:
126
+
127
+ ```sh
128
+ npx inglorious-server ./src/game.js # PORT=4000 to change the port
129
+ ```
84
130
 
85
- **MIT License - Free and open source**
131
+ The game path is resolved against the folder you run it from. The CLI accepts every event except the reserved ones.
86
132
 
87
- Created by [Matteo Antony Mistretta](https://github.com/IngloriousCoderz)
133
+ ## Close codes
88
134
 
89
- You're free to use, modify, and distribute this software. See [LICENSE](./LICENSE) for details.
135
+ | Code | Meaning | Client reconnects? |
136
+ | ---- | ------------------------------------------------- | ------------------------------------------------------------------- |
137
+ | 4001 | Room full | No (`sessionEnd` `"full"`) |
138
+ | 4002 | Replaced by a newer connection of the same player | No (`sessionEnd` `"replaced"`) |
139
+ | 4004 | Room doesn't exist | No (`sessionEnd` `"roomMissing"`, and the stored room is forgotten) |
140
+ | 4008 | Too many messages | Yes, with backoff |
141
+ | 1009 | Message too big | Yes, with backoff |
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@inglorious/server",
3
- "version": "21.0.11",
4
- "description": "A real-time, lightweight server designed to enable multiplayer experiences for games built with the Inglorious Engine.",
3
+ "version": "21.1.0",
4
+ "description": "A multiplayer server for Inglorious Store and Engine games: an authoritative store per room, safe defaults, player identity and reconnection.",
5
5
  "author": "Matteo Antony Mistretta <antony.mistretta@gmail.com> (https://ingloriouscoderz.it)",
6
6
  "license": "MIT",
7
7
  "repository": {
@@ -9,7 +9,7 @@
9
9
  "url": "git+https://github.com/IngloriousCoderz/inglorious-forge.git",
10
10
  "directory": "packages/server"
11
11
  },
12
- "homepage": "https://inglorious-engine.vercel.app/",
12
+ "homepage": "https://inglorious.dev/engine/",
13
13
  "bugs": {
14
14
  "url": "https://github.com/IngloriousCoderz/inglorious-forge/issues"
15
15
  },
@@ -26,40 +26,46 @@
26
26
  "type": "module",
27
27
  "main": "./src/index.js",
28
28
  "bin": {
29
- "inglorious-server": "./src/index.js"
29
+ "inglorious-server": "./src/cli.js"
30
30
  },
31
31
  "exports": {
32
- ".": "./src/index.js"
32
+ ".": {
33
+ "types": "./types/index.d.ts",
34
+ "import": "./src/index.js"
35
+ }
33
36
  },
34
37
  "files": [
35
- "src"
38
+ "src",
39
+ "types",
40
+ "!src/**/*.test.js"
36
41
  ],
37
42
  "publishConfig": {
38
43
  "access": "public"
39
44
  },
40
45
  "sideEffects": false,
41
46
  "dependencies": {
42
- "pino": "^10.3.1",
43
- "ws": "^8.21.3"
47
+ "ws": "^8.23.0"
44
48
  },
45
49
  "peerDependencies": {
46
- "@inglorious/store": "^12.1.1",
47
- "@inglorious/utils": "^5.1.0"
50
+ "@inglorious/store": "^12.10.0",
51
+ "@inglorious/utils": "^5.13.0"
48
52
  },
49
53
  "devDependencies": {
50
- "@inglorious/eslint-config": "1.2.0",
51
- "@inglorious/store": "12.1.1",
52
- "@inglorious/utils": "5.1.0",
53
- "nodemon": "^3.1.14",
54
- "prettier": "^3.9.6"
54
+ "@inglorious/eslint-config": "1.2.2",
55
+ "@inglorious/store": "12.10.0",
56
+ "@inglorious/utils": "5.13.0",
57
+ "prettier": "^3.10.1",
58
+ "typescript": "~7.0.2",
59
+ "vitest": "^5.1.2"
55
60
  },
56
61
  "engines": {
57
- "node": ">= 22"
62
+ "node": ">= 26"
58
63
  },
59
64
  "scripts": {
60
65
  "format": "prettier --write .",
61
66
  "lint": "eslint .",
62
- "start": "node src/index.js",
63
- "dev": "nodemon src/index.js"
67
+ "test:watch": "vitest",
68
+ "test": "vitest run && tsc -p type-tests",
69
+ "test:types": "tsc -p type-tests"
64
70
  }
65
71
  }
package/src/cli.js ADDED
@@ -0,0 +1,27 @@
1
+ #!/usr/bin/env node
2
+ import path from "node:path"
3
+ import process from "node:process"
4
+ import { pathToFileURL } from "node:url"
5
+
6
+ import { createServer } from "./server.js"
7
+
8
+ const DEFAULT_PORT = 3000
9
+ const ERROR_CODE = 1
10
+
11
+ const [, , gameFilePath] = process.argv
12
+ if (!gameFilePath) {
13
+ console.error("Usage: inglorious-server <game.js> (PORT sets the port)")
14
+ process.exit(ERROR_CODE)
15
+ }
16
+
17
+ // Resolved against where the command runs, not this package's folder.
18
+ const gameUrl = pathToFileURL(path.resolve(process.cwd(), gameFilePath))
19
+ const { default: game } = await import(gameUrl.href)
20
+
21
+ const server = createServer({ game })
22
+ const port = await server.listen(Number(process.env.PORT ?? DEFAULT_PORT))
23
+ process.stdout.write(`Inglorious Server listening on ws://localhost:${port}\n`)
24
+
25
+ for (const signal of ["SIGINT", "SIGTERM"]) {
26
+ process.once(signal, () => server.close().then(() => process.exit()))
27
+ }
package/src/index.js CHANGED
@@ -1,36 +1 @@
1
- import http from "node:http"
2
-
3
- import { createStore } from "@inglorious/store"
4
- import pino from "pino"
5
-
6
- import { loadGame } from "./game-loader.js"
7
- import * as gameLoop from "./game-loop.js"
8
- import * as wsHandler from "./ws-handler.js"
9
-
10
- const ERROR_CODE = 1
11
- const DEFAULT_PORT = 3000
12
-
13
- const logger = pino({ name: "Inglorious Server", level: "info" })
14
-
15
- bootstrap().catch((error) => {
16
- logger.error(error, "Failed to start the server.")
17
- process.exit(ERROR_CODE)
18
- })
19
-
20
- async function bootstrap() {
21
- let [, , gameFilePath] = process.argv
22
- const gameConfig = await loadGame(gameFilePath, logger)
23
-
24
- const store = createStore(gameConfig)
25
-
26
- const httpServer = http.createServer()
27
-
28
- wsHandler.setup(httpServer, store, logger)
29
-
30
- gameLoop.start(store)
31
-
32
- const port = process.env.PORT || DEFAULT_PORT
33
- httpServer.listen(port, () => {
34
- logger.info(`Listening on http://localhost:${port}`)
35
- })
36
- }
1
+ export { createServer } from "./server.js"
@@ -0,0 +1,43 @@
1
+ const ONE_SECOND = 1000
2
+ const QUIET_MS = ONE_SECOND
3
+ const TOKEN = 1
4
+
5
+ /**
6
+ * A token bucket: `burst` messages at once, refilled at `perSecond`. A client
7
+ * that keeps going over for `graceMs` should be closed, not just slowed down.
8
+ *
9
+ * Token bucket rather than a fixed window, which lets twice the rate through
10
+ * across a window's edge: https://en.wikipedia.org/wiki/Token_bucket
11
+ *
12
+ * @param {{ perSecond: number, burst: number, graceMs: number, now: () => number }} options
13
+ * @returns {{ allow: () => boolean, shouldClose: () => boolean }}
14
+ */
15
+ export function createRateLimiter({ perSecond, burst, graceMs, now }) {
16
+ let tokens = burst
17
+ let updatedAt = now()
18
+ let excessSince = null
19
+ let lastDropAt = -Infinity
20
+
21
+ return {
22
+ allow() {
23
+ const time = now()
24
+ tokens = Math.min(
25
+ burst,
26
+ tokens + ((time - updatedAt) * perSecond) / ONE_SECOND,
27
+ )
28
+ updatedAt = time
29
+ if (tokens >= TOKEN) {
30
+ tokens -= TOKEN
31
+ return true
32
+ }
33
+ // A token refilled amid ongoing drops does not end a flood: only a quiet second does.
34
+ if (time - lastDropAt > QUIET_MS) excessSince = time
35
+ lastDropAt = time
36
+ return false
37
+ },
38
+
39
+ shouldClose() {
40
+ return excessSince !== null && lastDropAt - excessSince >= graceMs
41
+ },
42
+ }
43
+ }
package/src/room.js ADDED
@@ -0,0 +1,147 @@
1
+ import { randomUUID } from "node:crypto"
2
+
3
+ import { createStore } from "@inglorious/store"
4
+ import { stampSender } from "@inglorious/store/client/sender.js"
5
+ import { serialize } from "@inglorious/utils/data-structures/object.js"
6
+ import { WebSocket } from "ws"
7
+
8
+ const MAX_BUFFERED_BYTES = 1_048_576 // 1 MiB
9
+ const NOT_EMPTY = 0
10
+
11
+ /** Close code for a socket a newer one with the same token took over from. */
12
+ export const CLOSE_REPLACED = 4002
13
+
14
+ /**
15
+ * One store and the players sharing it. Players are kept by a secret token,
16
+ * which a client sends back to reconnect, and known to everyone by a public
17
+ * `playerId`: anyone who sees a `playerJoin` learns the id, so the id alone
18
+ * must never be enough to take a player's place.
19
+ *
20
+ * @param {string} code - The room's code, `""` without rooms.
21
+ * @param {Object} config - A store config: `types`, `entities`, `systems`...
22
+ * @param {Object} options
23
+ * @param {number} options.maxPlayers - Players at once, reserved slots included.
24
+ * @param {number} options.reserveMs - How long a disconnected player's slot is kept.
25
+ * @param {() => number} options.now - The clock, in milliseconds.
26
+ */
27
+ export function createRoom(code, config, { maxPlayers, reserveMs, now }) {
28
+ const store = createStore({ ...config, updateMode: "manual" })
29
+ const slots = new Map()
30
+ let emptySince = now()
31
+
32
+ return { code, store, join, leave, receive, tick, sync, emptyFor }
33
+
34
+ /**
35
+ * Seats a socket, in its old slot when the token is known, and sends it the state.
36
+ * @returns {boolean} `false` when the room is full.
37
+ */
38
+ function join(ws, token) {
39
+ const time = now()
40
+ for (const [key, slot] of slots) {
41
+ if (!slot.ws && slot.expiresAt <= time) slots.delete(key)
42
+ }
43
+
44
+ let slot = slots.get(token)
45
+ if (!slot) {
46
+ if (slots.size >= maxPlayers) return false
47
+ token = randomUUID()
48
+ slot = { playerId: randomUUID(), ws: null, expiresAt: Infinity }
49
+ slots.set(token, slot)
50
+ }
51
+
52
+ const previous = slot.ws
53
+ slot.ws = ws
54
+ emptySince = null
55
+
56
+ // Events already relayed to the others must be in the state the newcomer gets.
57
+ store.update()
58
+ send(ws, {
59
+ type: "stateInit",
60
+ payload: store.getState(),
61
+ playerId: slot.playerId,
62
+ token,
63
+ room: code,
64
+ })
65
+
66
+ if (previous) {
67
+ previous.close(CLOSE_REPLACED, "replaced")
68
+ } else {
69
+ dispatch({ type: "playerJoin", payload: { playerId: slot.playerId } })
70
+ }
71
+
72
+ return true
73
+ }
74
+
75
+ /** Frees a socket's seat, keeping its slot for `reserveMs`. */
76
+ function leave(ws) {
77
+ const slot = slotOf(ws)
78
+ if (!slot) return
79
+
80
+ slot.ws = null
81
+ slot.expiresAt = now() + reserveMs
82
+ if (![...slots.values()].some(({ ws }) => ws)) emptySince = now()
83
+ dispatch({ type: "playerLeave", payload: { playerId: slot.playerId } })
84
+ }
85
+
86
+ /** An accepted event from a player, stamped with who sent it and relayed to the others. */
87
+ function receive(ws, { type, payload }) {
88
+ const slot = slotOf(ws)
89
+ if (!slot) return
90
+
91
+ dispatch({ type, payload: stampSender(payload, slot.playerId) }, ws)
92
+ }
93
+
94
+ /** Runs one frame, as the engine does: `update` with the seconds passed, then the queue. */
95
+ function tick(dt) {
96
+ store.notify("update", dt)
97
+ store.update()
98
+ }
99
+
100
+ /** Sends everyone the whole state, to undo any drift between stores. */
101
+ function sync() {
102
+ store.update()
103
+ broadcast(serialize({ type: "stateSync", payload: store.getState() }))
104
+ }
105
+
106
+ /** @returns {number} Milliseconds since the last player left, `0` while someone is in. */
107
+ function emptyFor() {
108
+ return emptySince === null ? NOT_EMPTY : now() - emptySince
109
+ }
110
+
111
+ function dispatch(event, sender) {
112
+ store.dispatch(event)
113
+ broadcast(serialize(event), sender)
114
+ }
115
+
116
+ function broadcast(message, except) {
117
+ for (const { ws } of slots.values()) {
118
+ if (ws && ws !== except) sendRaw(ws, message)
119
+ }
120
+ }
121
+
122
+ function slotOf(ws) {
123
+ for (const slot of slots.values()) {
124
+ if (slot.ws === ws) return slot
125
+ }
126
+ return null
127
+ }
128
+ }
129
+
130
+ /** Sends a message to one socket, if it is still there. */
131
+ export function send(ws, message) {
132
+ sendRaw(ws, serialize(message))
133
+ }
134
+
135
+ /**
136
+ * Cuts a client that stopped reading: its queue would otherwise grow without
137
+ * limit in the server's memory.
138
+ * https://github.com/websockets/ws/blob/master/doc/ws.md#websocketbufferedamount
139
+ */
140
+ function sendRaw(ws, message) {
141
+ if (ws.readyState !== WebSocket.OPEN) return
142
+ if (ws.bufferedAmount > MAX_BUFFERED_BYTES) {
143
+ ws.terminate()
144
+ return
145
+ }
146
+ ws.send(message)
147
+ }
package/src/server.js ADDED
@@ -0,0 +1,269 @@
1
+ import { randomInt } from "node:crypto"
2
+ import http from "node:http"
3
+ import { performance } from "node:perf_hooks"
4
+
5
+ import { deserialize } from "@inglorious/utils/data-structures/object.js"
6
+ import { WebSocketServer } from "ws"
7
+
8
+ import { createRateLimiter } from "./rate-limit.js"
9
+ import { createRoom } from "./room.js"
10
+
11
+ const ONE_SECOND = 1000
12
+ const DEFAULT_FPS = 60
13
+ const MAX_DT = 0.25
14
+ const DEFAULT_MAX_PAYLOAD_BYTES = 16_384 // 16 KiB
15
+ const DEFAULT_RATE = { perSecond: 30, burst: 60, graceSeconds: 5 }
16
+ const DEFAULT_RESERVE_SECONDS = 60
17
+ const DEFAULT_HEARTBEAT_SECONDS = 25
18
+ const DEFAULT_IDLE_SECONDS = 600
19
+ const DEFAULT_CODE_LENGTH = 4
20
+ const ROOM_CHECK_SECONDS = 10
21
+ const MAX_TOKEN_LENGTH = 64
22
+ const MAX_CODE_LENGTH = 32
23
+ // No I or O, which read as 1 and 0 when a code is said aloud or written on a board.
24
+ const CODE_LETTERS = "ABCDEFGHJKLMNPQRSTUVWXYZ"
25
+ const NO_ROOM = ""
26
+ const NEVER = 0
27
+ const ANY_PORT = 0
28
+ const FROM_START = 0
29
+
30
+ // Application close codes live in 4000-4999: https://www.rfc-editor.org/rfc/rfc6455#section-7.4.2
31
+ const CLOSE_FULL = 4001
32
+ const CLOSE_ROOM_MISSING = 4004
33
+ const CLOSE_FLOOD = 4008
34
+
35
+ // Events only the server may send: a client sending one would speak for the server.
36
+ const SERVER_EVENTS = ["playerJoin", "playerLeave", "stateInit", "stateSync"]
37
+ // Events every store makes for itself, which would run twice if relayed.
38
+ const LOCAL_EVENTS = ["update", "create", "destroy"]
39
+
40
+ /**
41
+ * A multiplayer server: one authoritative store per room, ticking like the
42
+ * engine, receiving the events clients send, stamping each with its sender and
43
+ * relaying it to the others. Importing it does nothing; call `listen`, or attach
44
+ * it to a server of your own with `server`.
45
+ *
46
+ * @param {import("../types/index.d.ts").ServerOptions} options
47
+ * @returns {import("../types/index.d.ts").MultiplayerServer}
48
+ */
49
+ export function createServer({
50
+ game,
51
+ server,
52
+ path,
53
+ acceptedEvents,
54
+ maxPlayers = Infinity,
55
+ maxPayloadBytes = DEFAULT_MAX_PAYLOAD_BYTES,
56
+ rate = DEFAULT_RATE,
57
+ reserveSeconds = DEFAULT_RESERVE_SECONDS,
58
+ heartbeatSeconds = DEFAULT_HEARTBEAT_SECONDS,
59
+ rooms = false,
60
+ snapshotSeconds = NEVER,
61
+ fps = DEFAULT_FPS,
62
+ logger = console,
63
+ now = Date.now,
64
+ } = {}) {
65
+ if (!game) throw new TypeError("createServer needs a `game`")
66
+
67
+ const httpServer = server ?? http.createServer()
68
+ const wss = new WebSocketServer({
69
+ server: httpServer,
70
+ path,
71
+ maxPayload: maxPayloadBytes,
72
+ })
73
+ const isAccepted = acceptance(acceptedEvents)
74
+ const { perSecond, burst, graceSeconds } = { ...DEFAULT_RATE, ...rate }
75
+ const idleMs = (rooms?.idleSeconds ?? DEFAULT_IDLE_SECONDS) * ONE_SECOND
76
+ const codeLength = rooms?.codeLength ?? DEFAULT_CODE_LENGTH
77
+ const roomOptions = {
78
+ maxPlayers,
79
+ reserveMs: reserveSeconds * ONE_SECOND,
80
+ now,
81
+ }
82
+
83
+ const roomsByCode = new Map()
84
+ const alive = new WeakMap()
85
+ const timers = []
86
+
87
+ if (!rooms) openRoom(NO_ROOM)
88
+
89
+ wss.on("connection", connect)
90
+
91
+ if (fps > NEVER) {
92
+ let lastTime = performance.now()
93
+ every(ONE_SECOND / fps, () => {
94
+ const time = performance.now()
95
+ const dt = Math.min((time - lastTime) / ONE_SECOND, MAX_DT)
96
+ lastTime = time
97
+ for (const room of roomsByCode.values()) room.tick(dt)
98
+ })
99
+ }
100
+ if (snapshotSeconds > NEVER) {
101
+ every(snapshotSeconds * ONE_SECOND, () => {
102
+ for (const room of roomsByCode.values()) room.sync()
103
+ })
104
+ }
105
+ if (rooms) {
106
+ every(Math.min(idleMs, ROOM_CHECK_SECONDS * ONE_SECOND), dropIdleRooms)
107
+ }
108
+ every(heartbeatSeconds * ONE_SECOND, beat)
109
+
110
+ return {
111
+ httpServer,
112
+ rooms: roomsByCode,
113
+
114
+ listen(port = ANY_PORT) {
115
+ return new Promise((resolve, reject) => {
116
+ httpServer.once("error", reject)
117
+ httpServer.listen(port, () => {
118
+ httpServer.off("error", reject)
119
+ resolve(httpServer.address().port)
120
+ })
121
+ })
122
+ },
123
+
124
+ close() {
125
+ timers.forEach(clearInterval)
126
+ for (const ws of wss.clients) ws.terminate()
127
+ roomsByCode.clear()
128
+ return new Promise((resolve) => {
129
+ wss.close(() => {
130
+ if (server || !httpServer.listening) return resolve()
131
+ httpServer.close(() => resolve())
132
+ })
133
+ })
134
+ },
135
+ }
136
+
137
+ function connect(ws, req) {
138
+ const query = new URL(req.url, "http://localhost").searchParams
139
+ const room = roomFor(query.get("room"))
140
+ if (!room) {
141
+ ws.close(CLOSE_ROOM_MISSING, "room missing")
142
+ return
143
+ }
144
+
145
+ const token = query.get("token")?.slice(FROM_START, MAX_TOKEN_LENGTH)
146
+ if (!room.join(ws, token)) {
147
+ ws.close(CLOSE_FULL, "room full")
148
+ return
149
+ }
150
+
151
+ const limiter = createRateLimiter({
152
+ perSecond,
153
+ burst,
154
+ graceMs: graceSeconds * ONE_SECOND,
155
+ now,
156
+ })
157
+ alive.set(ws, true)
158
+
159
+ ws.on("pong", () => alive.set(ws, true))
160
+ ws.on("error", (error) => {
161
+ logger.warn("WebSocket error", error)
162
+ ws.terminate()
163
+ })
164
+ ws.on("close", () => room.leave(ws))
165
+ ws.on("message", (raw, isBinary) => {
166
+ if (!limiter.allow()) {
167
+ if (limiter.shouldClose()) ws.close(CLOSE_FLOOD, "too many messages")
168
+ return
169
+ }
170
+ if (isBinary) return
171
+
172
+ const event = parse(raw.toString())
173
+ if (event && isAccepted(event)) room.receive(ws, event)
174
+ })
175
+ }
176
+
177
+ /** The room a client asked for; a new one when rooms are on and it asked for none. */
178
+ function roomFor(code) {
179
+ if (!rooms) return roomsByCode.get(NO_ROOM)
180
+ if (!code) return openRoom(newCode())
181
+ return roomsByCode.get(
182
+ code.slice(FROM_START, MAX_CODE_LENGTH).toUpperCase(),
183
+ )
184
+ }
185
+
186
+ function openRoom(code) {
187
+ const config = typeof game === "function" ? game(code) : copyGame(game)
188
+ const room = createRoom(code, config, roomOptions)
189
+ roomsByCode.set(code, room)
190
+ if (code) logger.info(`Room ${code} opened`)
191
+ return room
192
+ }
193
+
194
+ function newCode() {
195
+ let code
196
+ do {
197
+ code = Array.from(
198
+ { length: codeLength },
199
+ () => CODE_LETTERS[randomInt(CODE_LETTERS.length)],
200
+ ).join("")
201
+ } while (roomsByCode.has(code))
202
+ return code
203
+ }
204
+
205
+ function dropIdleRooms() {
206
+ for (const [code, room] of roomsByCode) {
207
+ if (room.emptyFor() >= idleMs) {
208
+ roomsByCode.delete(code)
209
+ logger.info(`Room ${code} closed`)
210
+ }
211
+ }
212
+ }
213
+
214
+ /**
215
+ * Pings every socket and cuts those that did not answer the last ping: a
216
+ * client that vanished without closing (a phone going to sleep, a dropped
217
+ * Wi-Fi) would otherwise hold its seat forever.
218
+ * https://github.com/websockets/ws#how-to-detect-and-close-broken-connections
219
+ */
220
+ function beat() {
221
+ for (const ws of wss.clients) {
222
+ if (!alive.get(ws)) {
223
+ ws.terminate()
224
+ continue
225
+ }
226
+ alive.set(ws, false)
227
+ ws.ping()
228
+ }
229
+ }
230
+
231
+ function every(ms, callback) {
232
+ const timer = setInterval(callback, ms)
233
+ timer.unref()
234
+ timers.push(timer)
235
+ }
236
+ }
237
+
238
+ /**
239
+ * Which client events go into the store. Without a list, every event but the
240
+ * server's own and those each store makes for itself.
241
+ */
242
+ function acceptance(acceptedEvents) {
243
+ if (typeof acceptedEvents === "function") {
244
+ return (event) => isClientEvent(event) && acceptedEvents(event)
245
+ }
246
+ if (Array.isArray(acceptedEvents)) {
247
+ const accepted = new Set(acceptedEvents)
248
+ return (event) => isClientEvent(event) && accepted.has(event.type)
249
+ }
250
+ return isClientEvent
251
+ }
252
+
253
+ function isClientEvent({ type }) {
254
+ return !SERVER_EVENTS.includes(type) && !LOCAL_EVENTS.includes(type)
255
+ }
256
+
257
+ function parse(text) {
258
+ try {
259
+ const event = deserialize(text)
260
+ return typeof event?.type === "string" ? event : null
261
+ } catch {
262
+ return null
263
+ }
264
+ }
265
+
266
+ /** A room's own entities, so rooms made from one config never share them. */
267
+ function copyGame(game) {
268
+ return { ...game, entities: structuredClone(game.entities ?? {}) }
269
+ }
@@ -0,0 +1,80 @@
1
+ import type { BaseEntity, Store, StoreConfig } from "@inglorious/store"
2
+
3
+ /** Node's `http.Server`, or anything `ws` can attach to. */
4
+ export interface HttpServer {
5
+ listen(...args: unknown[]): unknown
6
+ close(callback?: (error?: Error) => void): unknown
7
+ address(): unknown
8
+ }
9
+
10
+ /** An event a client sent, as the server reads it. */
11
+ export interface ClientEvent {
12
+ type: string
13
+ payload?: unknown
14
+ }
15
+
16
+ export interface Logger {
17
+ info(...args: unknown[]): void
18
+ warn(...args: unknown[]): void
19
+ error(...args: unknown[]): void
20
+ }
21
+
22
+ export interface ServerOptions<TEntity extends BaseEntity = BaseEntity> {
23
+ /** The store config each room starts from, or a function making one per room code. */
24
+ game: StoreConfig<TEntity> | ((room: string) => StoreConfig<TEntity>)
25
+ /** Attach to this HTTP server (to serve your build from the same port) instead of making one. */
26
+ server?: HttpServer
27
+ /** Only upgrade requests on this path, such as `"/ws"`. Defaults to any path. */
28
+ path?: string
29
+ /**
30
+ * The event types clients may send, or a predicate. Defaults to every event
31
+ * but the server's own (`playerJoin`, `playerLeave`, `stateInit`, `stateSync`)
32
+ * and those each store makes for itself (`update`, `create`, `destroy`), which
33
+ * are never accepted.
34
+ */
35
+ acceptedEvents?: string[] | ((event: ClientEvent) => boolean)
36
+ /** Players per room at once, disconnected players' reserved slots included. @default Infinity */
37
+ maxPlayers?: number
38
+ /** Bigger messages close the socket (code 1009). @default 16384 */
39
+ maxPayloadBytes?: number
40
+ /** Token bucket per socket; after `graceSeconds` of steady excess the socket is closed (code 4008). @default { perSecond: 30, burst: 60, graceSeconds: 5 } */
41
+ rate?: { perSecond?: number; burst?: number; graceSeconds?: number }
42
+ /** How long a disconnected player's slot waits for them to reconnect. @default 60 */
43
+ reserveSeconds?: number
44
+ /** Ping interval; a socket missing one pong is cut. @default 25 */
45
+ heartbeatSeconds?: number
46
+ /**
47
+ * A store per room code. A client asking for no room gets a new one; one
48
+ * asking for a code that doesn't exist is closed (code 4004). Empty rooms
49
+ * are dropped after `idleSeconds`.
50
+ * @default false
51
+ */
52
+ rooms?: boolean | { idleSeconds?: number; codeLength?: number }
53
+ /** Every so many seconds, send everyone the whole state to undo drift. `0` never. @default 0 */
54
+ snapshotSeconds?: number
55
+ /** Ticks per second, each notifying `update` with the seconds passed. `0` never. @default 60 */
56
+ fps?: number
57
+ /** @default console */
58
+ logger?: Logger
59
+ /** The clock, in milliseconds, for tests. @default Date.now */
60
+ now?: () => number
61
+ }
62
+
63
+ export interface Room<TEntity extends BaseEntity = BaseEntity> {
64
+ code: string
65
+ store: Store<TEntity>
66
+ }
67
+
68
+ export interface MultiplayerServer<TEntity extends BaseEntity = BaseEntity> {
69
+ httpServer: HttpServer
70
+ /** The open rooms by code; the only room is `""` without rooms. */
71
+ rooms: Map<string, Room<TEntity>>
72
+ /** Starts listening; `0` picks a free port. Resolves to the port. */
73
+ listen(port?: number): Promise<number>
74
+ /** Stops ticking, closes every socket, and the HTTP server if it made it. */
75
+ close(): Promise<void>
76
+ }
77
+
78
+ export function createServer<TEntity extends BaseEntity = BaseEntity>(
79
+ options: ServerOptions<TEntity>,
80
+ ): MultiplayerServer<TEntity>
@@ -1,38 +0,0 @@
1
- import path from "node:path"
2
- import { fileURLToPath } from "node:url"
3
-
4
- /**
5
- * Dynamically loads the initial game state from a module and provides a fallback.
6
- * @param {string} gameFilePath The path to the game module.
7
- * @param {object} logger A Pino logger instance.
8
- * @returns {Promise<{initialTypes: object, initialEntities: object}>} The initial game state.
9
- */
10
- export async function loadGame(gameFilePath, logger) {
11
- let gameConfig = {}
12
-
13
- try {
14
- if (!gameFilePath) {
15
- return gameConfig
16
- }
17
-
18
- const __filename = fileURLToPath(import.meta.url)
19
- const __dirname = path.dirname(__filename)
20
- const modulePath = path.resolve(__dirname, gameFilePath)
21
- const module = await import(`file://${modulePath}`)
22
-
23
- logger.info(`Loaded game data from ${gameFilePath}`)
24
- gameConfig = module.default
25
- return gameConfig
26
- } catch (error) {
27
- logger.error(`Failed to load game module: ${gameFilePath}`)
28
- logger.error(error)
29
-
30
- // Fallback to a basic initial state if loading fails.
31
- logger.warn("Using default game state as a fallback.")
32
- gameConfig = {}
33
- return gameConfig
34
- } finally {
35
- gameConfig.types ??= {}
36
- gameConfig.entities ??= {}
37
- }
38
- }
package/src/game-loop.js DELETED
@@ -1,24 +0,0 @@
1
- import { performance } from "node:perf_hooks"
2
-
3
- const ONE_SECOND = 1000
4
- const TICK_RATE = 60 // 60 updates per second
5
- const TICK_INTERVAL = ONE_SECOND / TICK_RATE // ~16.67ms
6
- let lastTime = performance.now()
7
-
8
- /**
9
- * Starts the main server-side game loop.
10
- * @param {object} store The game store instance.
11
- * @param {object} api The game API with broadcast functionality.
12
- */
13
- export function start(store, api) {
14
- // The main server-side game loop.
15
- setInterval(() => {
16
- const currentTime = performance.now()
17
- const dt = (currentTime - lastTime) / ONE_SECOND // Convert to seconds
18
- lastTime = currentTime
19
-
20
- // The store's update function is the heart of the game loop.
21
- // It processes events and advances the game state.
22
- store.update(dt, api)
23
- }, TICK_INTERVAL)
24
- }
package/src/ws-handler.js DELETED
@@ -1,43 +0,0 @@
1
- import { serialize } from "@inglorious/utils/object.js"
2
- import { WebSocketServer } from "ws"
3
-
4
- /**
5
- * Initializes the WebSocket server and sets up event handlers.
6
- * @param {object} httpServer The HTTP server instance to attach to.
7
- * @param {object} store The game store instance.
8
- * @param {object} logger A Pino logger instance.
9
- * @returns {void}
10
- */
11
- export function setup(httpServer, store, logger) {
12
- const wss = new WebSocketServer({ server: httpServer })
13
-
14
- wss.on("connection", (ws) => {
15
- logger.info("A new client has connected.")
16
-
17
- ws.send(serialize({ type: "stateInit", payload: store.getState() }))
18
-
19
- ws.on("message", (rawData) => {
20
- try {
21
- const eventString = rawData.toString()
22
- const event = JSON.parse(eventString)
23
- store.dispatch(event)
24
-
25
- for (const client of wss.clients) {
26
- if (client !== ws && client.readyState === WebSocket.OPEN) {
27
- client.send(eventString)
28
- }
29
- }
30
- } catch (error) {
31
- logger.error({ error }, "Failed to parse message.")
32
- }
33
- })
34
-
35
- ws.on("close", (code, reason) => {
36
- logger.info(`Client disconnected. Code: ${code}, Reason: ${reason}`)
37
- })
38
-
39
- ws.on("error", (error) => {
40
- logger.error({ error }, "WebSocket error occurred.")
41
- })
42
- })
43
- }