@table-games-engine/nakama-adapter 0.1.0 → 0.1.1
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 +37 -282
- package/package.json +14 -4
package/README.md
CHANGED
|
@@ -1,323 +1,78 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @table-games-engine/nakama-adapter
|
|
2
2
|
|
|
3
|
-
Nakama runtime bindings for the `@table-games-engine/
|
|
3
|
+
Nakama runtime bindings for `@table-games-engine/core`: wraps the engine (and `@table-games-engine/persistence`) in a Nakama TypeScript-runtime match handler so players can connect over WebSocket and play your game.
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
`@table-games-engine/core` (and the persistence layer from
|
|
7
|
-
`@table-games-engine/persistence`) into a Nakama TypeScript-runtime
|
|
8
|
-
`MatchHandler<T>` so that multiple players can connect via WebSocket and
|
|
9
|
-
play a turn-based card / tabletop game implemented as a `GameManifest`.
|
|
5
|
+
Most game authors don't install this directly: it comes with [`@table-games-engine/game-kit`](https://www.npmjs.com/package/@table-games-engine/game-kit), whose `preview` command and the [Logigra](https://logigra.ru) store host your game for you. Install it to run your own Nakama server.
|
|
10
6
|
|
|
11
|
-
|
|
12
|
-
persistence, recovery, timeouts) see
|
|
13
|
-
[`docs/normative/platforms/nakama.md`](../../docs/normative/platforms/nakama.md).
|
|
14
|
-
This README is the **operator-facing usage guide** — how to wire the
|
|
15
|
-
module into Nakama, what to configure, and how to extend it with
|
|
16
|
-
platform plugins.
|
|
7
|
+
## Install
|
|
17
8
|
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
- A factory `createMatchHandler(opts)` that returns a Nakama
|
|
23
|
-
`MatchHandler<NkMatchInternalState>` implementing every callback
|
|
24
|
-
Nakama needs (`matchInit`, `matchJoinAttempt`, `matchJoin`,
|
|
25
|
-
`matchLeave`, `matchLoop`, `matchSignal`, `matchTerminate`).
|
|
26
|
-
- A `GameRegistry` for resolving `gameId -> { manifest, handlers, setup }`
|
|
27
|
-
at `matchInit` time, so a single Nakama runtime can host multiple
|
|
28
|
-
game definitions.
|
|
29
|
-
- An `IdempotencyCache` for absorbing client retries.
|
|
30
|
-
- A `parseInbound`/`serializeOutbound` JSON wire format, opcode
|
|
31
|
-
constants (`OPCODES`), per-presence broadcast filtering
|
|
32
|
-
(`broadcastViews`), action timeouts (`checkTimeouts`),
|
|
33
|
-
reconnection-aware joins, and a `NakamaPlatformPlugin` extension hook.
|
|
34
|
-
- Persistence wiring to `@table-games-engine/persistence`: every engine
|
|
35
|
-
transition's events are appended; snapshots are written per the
|
|
36
|
-
configured `SnapshotPolicy`.
|
|
9
|
+
```sh
|
|
10
|
+
npm install @table-games-engine/nakama-adapter
|
|
11
|
+
```
|
|
37
12
|
|
|
38
|
-
|
|
13
|
+
## What you get
|
|
39
14
|
|
|
40
|
-
|
|
15
|
+
- `createMatchHandler(opts)` returns a Nakama `MatchHandler` implementing `matchInit`, `matchJoinAttempt`, `matchJoin`, `matchLeave`, `matchLoop`, `matchSignal` and `matchTerminate`.
|
|
16
|
+
- `GameRegistry` resolves `gameId` to `{ manifest, handlers, setup }` at `matchInit`, so one runtime can host many games (`registerPlugin` registers a `GamePlugin`).
|
|
17
|
+
- `IdempotencyCache` absorbs client retries.
|
|
18
|
+
- JSON wire format (`parseInbound`, `serializeOutbound`, `OPCODES`), per-player filtered broadcasts (`broadcastViews`), action timeouts (`checkTimeouts`), reconnection-aware joins.
|
|
19
|
+
- Persistence wiring: events are appended per transition and snapshots follow a `SnapshotPolicy`.
|
|
20
|
+
- `NakamaPlatformPlugin` hooks for analytics, audit and similar.
|
|
41
21
|
|
|
42
|
-
|
|
43
|
-
`InitModule(ctx, logger, nk, initializer)` entry point. A minimal
|
|
44
|
-
`init.ts` looks like this:
|
|
22
|
+
## Wiring into Nakama
|
|
45
23
|
|
|
46
24
|
```ts
|
|
47
|
-
|
|
48
|
-
import {
|
|
49
|
-
createMatchHandler,
|
|
50
|
-
GameRegistry,
|
|
51
|
-
IdempotencyCache,
|
|
52
|
-
} from '@table-games-engine/nakama-adapter';
|
|
53
|
-
import { SqliteAdapter } from '@table-games-engine/persistence';
|
|
54
|
-
import { everyNTransitions } from '@table-games-engine/persistence';
|
|
55
|
-
|
|
56
|
-
import { registerMyGame } from './games/my-game.js';
|
|
57
|
-
|
|
58
|
-
const MATCH_HANDLER_NAME = 'tabletop_match';
|
|
25
|
+
import { createMatchHandler, registerPlugin, GameRegistry, IdempotencyCache } from '@table-games-engine/nakama-adapter';
|
|
26
|
+
import { SqliteAdapter, everyNTransitions } from '@table-games-engine/persistence';
|
|
59
27
|
|
|
60
28
|
const registry = new GameRegistry();
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
const idempotencyCache = new IdempotencyCache();
|
|
64
|
-
|
|
65
|
-
const adapter = new SqliteAdapter({
|
|
66
|
-
path: process.env['ENGINE_DB_PATH'] ?? '/data/engine.db',
|
|
67
|
-
});
|
|
29
|
+
registerPlugin(registry, myGamePlugin); // a GamePlugin; or registry.register({ gameId, manifest, handlers, setup }) by hand
|
|
68
30
|
|
|
69
31
|
const handler = createMatchHandler({
|
|
70
32
|
registry,
|
|
71
|
-
idempotencyCache,
|
|
72
|
-
adapter,
|
|
33
|
+
idempotencyCache: new IdempotencyCache(),
|
|
34
|
+
adapter: new SqliteAdapter('/data/engine.db'),
|
|
73
35
|
policy: everyNTransitions(50),
|
|
74
|
-
ownerNode:
|
|
36
|
+
ownerNode: 'node-A',
|
|
75
37
|
leaseSeconds: 60,
|
|
76
38
|
timeout: { timeoutMs: 30_000 },
|
|
77
|
-
plugins: [
|
|
78
|
-
/* analytics, audit, etc. — see "Plugins" below */
|
|
79
|
-
],
|
|
39
|
+
plugins: [],
|
|
80
40
|
});
|
|
81
41
|
|
|
82
|
-
function InitModule(
|
|
83
|
-
|
|
84
|
-
logger: nkruntime.Logger,
|
|
85
|
-
_nk: nkruntime.Nakama,
|
|
86
|
-
initializer: nkruntime.Initializer,
|
|
87
|
-
): void {
|
|
88
|
-
initializer.registerMatch(MATCH_HANDLER_NAME, handler);
|
|
89
|
-
logger.info('registered match handler %s', MATCH_HANDLER_NAME);
|
|
42
|
+
function InitModule(_ctx: nkruntime.Context, logger: nkruntime.Logger, _nk: nkruntime.Nakama, initializer: nkruntime.Initializer): void {
|
|
43
|
+
initializer.registerMatch('tabletop_match', handler);
|
|
90
44
|
}
|
|
91
|
-
|
|
92
|
-
!InitModule && InitModule;
|
|
93
45
|
```
|
|
94
46
|
|
|
95
|
-
|
|
47
|
+
Create a match from your own server code:
|
|
96
48
|
|
|
97
49
|
```ts
|
|
98
|
-
|
|
50
|
+
nk.matchCreate('tabletop_match', {
|
|
99
51
|
gameId: 'my-game',
|
|
100
|
-
//
|
|
101
|
-
|
|
102
|
-
// comma-separated; setup() receives them
|
|
103
|
-
playerIds: 'alice,bob',
|
|
104
|
-
config: JSON.stringify({ /* game-instance options */ }),
|
|
52
|
+
playerIds: 'alice,bob', // comma-separated; passed to setup()
|
|
53
|
+
config: JSON.stringify({ /* game options */ }),
|
|
105
54
|
});
|
|
106
55
|
```
|
|
107
56
|
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
## Environment variables
|
|
111
|
-
|
|
112
|
-
The adapter itself reads no env vars directly — they're conventions for
|
|
113
|
-
the `init.ts` shim above. Recommended:
|
|
114
|
-
|
|
115
|
-
| Variable | Purpose |
|
|
116
|
-
| -------------------- | ----------------------------------------------------------------------- |
|
|
117
|
-
| `ENGINE_DB_PATH` | Path to the SQLite DB used by `SqliteAdapter` for events + snapshots. |
|
|
118
|
-
| `ENGINE_DB_DSN` | If using a network-backed adapter (e.g. Postgres), connection DSN. |
|
|
119
|
-
| `NAKAMA_NODE_ID` | Node identifier passed to `acquireOwnership(matchId, node, leaseSec)`. |
|
|
120
|
-
| `ENGINE_SNAPSHOT_N` | Override `everyNTransitions(N)` cadence at boot. |
|
|
121
|
-
| `ENGINE_TIMEOUT_MS` | Default per-action timeout for `checkTimeouts`. |
|
|
122
|
-
| `ENGINE_LEASE_SEC` | Ownership lease duration in seconds (default 60). |
|
|
123
|
-
|
|
124
|
-
These are NOT consumed by the package — your `init.ts` is responsible
|
|
125
|
-
for plumbing them into `createMatchHandler`'s options. The package
|
|
126
|
-
stays config-agnostic.
|
|
127
|
-
|
|
128
|
-
---
|
|
129
|
-
|
|
130
|
-
## Game registration pattern
|
|
131
|
-
|
|
132
|
-
A "game" is the triple `(manifest, handlers, setup)` registered against
|
|
133
|
-
a `gameId`. Call `registry.register` once at module init:
|
|
134
|
-
|
|
135
|
-
```ts
|
|
136
|
-
import { GameRegistry } from '@table-games-engine/nakama-adapter';
|
|
137
|
-
import { manifest, handlers, setup, winChecker } from './my-game.js';
|
|
138
|
-
|
|
139
|
-
export function registerMyGame(registry: GameRegistry): void {
|
|
140
|
-
registry.register({
|
|
141
|
-
gameId: 'my-game',
|
|
142
|
-
manifest,
|
|
143
|
-
handlers,
|
|
144
|
-
setup, // (matchId, playerIds, config, { now }) => MatchState
|
|
145
|
-
winChecker, // optional WinConditionChecker
|
|
146
|
-
});
|
|
147
|
-
}
|
|
148
|
-
```
|
|
149
|
-
|
|
150
|
-
Multiple games can coexist behind a single Nakama match-handler name —
|
|
151
|
-
`matchInit` resolves the entry by the `gameId` parameter.
|
|
152
|
-
|
|
153
|
-
---
|
|
154
|
-
|
|
155
|
-
## Persistence
|
|
156
|
-
|
|
157
|
-
When `adapter` is supplied to `createMatchHandler`:
|
|
158
|
-
|
|
159
|
-
- `matchInit` persists the initial state as **snapshot v0**
|
|
160
|
-
(`adapter.persistSnapshot(matchId, state, checksum)`).
|
|
161
|
-
- If `ownerNode` is also set, `matchInit` calls
|
|
162
|
-
`adapter.acquireOwnership(matchId, ownerNode, leaseSeconds)`. Failures
|
|
163
|
-
are logged via `logger.error` but do not abort match creation; for
|
|
164
|
-
hard-fail semantics, pre-acquire the lease in your matchmaker.
|
|
165
|
-
- Each engine transition (player action, stack drain, timeouts, ejects)
|
|
166
|
-
appends events via `adapter.appendEvents(matchId, transition.toVersion,
|
|
167
|
-
transition.events)` and may snapshot per the configured `SnapshotPolicy`
|
|
168
|
-
(default `everyNTransitions(50)`).
|
|
169
|
-
- `matchTerminate` releases the ownership lease but does **NOT** close
|
|
170
|
-
the adapter — the same adapter typically hosts other matches in the
|
|
171
|
-
same Node process.
|
|
172
|
-
|
|
173
|
-
To recover after a crash, use
|
|
174
|
-
[`replayMatch(adapter, matchId, toVersion?)`](../persistence/src/replay.ts)
|
|
175
|
-
to rebuild the latest snapshot at or before `toVersion`.
|
|
176
|
-
|
|
177
|
-
---
|
|
178
|
-
|
|
179
|
-
## Reconnection
|
|
180
|
-
|
|
181
|
-
When the same `userId` rejoins a match (a new `sessionId` for an existing
|
|
182
|
-
user), the handler:
|
|
183
|
-
|
|
184
|
-
1. Replaces the old presence in `state.presences` with the new one.
|
|
185
|
-
2. Sends a fresh, filtered `state` view to the rejoiner only — other
|
|
186
|
-
players are **not** re-broadcast to.
|
|
187
|
-
3. Preserves the per-match idempotency cache, so any in-flight client
|
|
188
|
-
retries from before the disconnect resolve to their cached responses.
|
|
57
|
+
The adapter reads no environment variables; plumb configuration into the options yourself.
|
|
189
58
|
|
|
190
|
-
|
|
191
|
-
`state.presences` or (b) the engine has a `PlayerState` for that
|
|
192
|
-
`userId` (covers the case where the player completed a turn before
|
|
193
|
-
disconnecting).
|
|
59
|
+
## Persistence and reconnection
|
|
194
60
|
|
|
195
|
-
|
|
61
|
+
With `adapter` set, `matchInit` stores snapshot v0 (and takes an ownership lease if `ownerNode` is set), each transition appends its events and may snapshot, and `matchTerminate` releases the lease without closing the adapter. When the same user rejoins with a new session, the handler swaps the presence, sends a fresh filtered state to that player only, and keeps the idempotency cache.
|
|
196
62
|
|
|
197
63
|
## Plugins
|
|
198
64
|
|
|
199
|
-
Platform plugins are an extension hook for things that don't belong
|
|
200
|
-
inside the deterministic engine: analytics, leaderboards, audit
|
|
201
|
-
logging, push notifications, anti-cheat sampling, achievement
|
|
202
|
-
emission, etc.
|
|
203
|
-
|
|
204
65
|
```ts
|
|
205
66
|
import type { NakamaPlatformPlugin } from '@table-games-engine/nakama-adapter';
|
|
206
67
|
|
|
207
|
-
const
|
|
208
|
-
name: '
|
|
209
|
-
async
|
|
210
|
-
await analytics.track('match_created', { matchId: ctx.matchId });
|
|
211
|
-
},
|
|
212
|
-
async onMatchEnded(ctx, result) {
|
|
213
|
-
await analytics.track('match_ended', { matchId: ctx.matchId, winners: result.winners });
|
|
214
|
-
},
|
|
215
|
-
async onPlayerAction(ctx, input, transition) {
|
|
216
|
-
await analytics.track('action', {
|
|
217
|
-
matchId: ctx.matchId,
|
|
218
|
-
playerId: input.playerId,
|
|
219
|
-
actionTypeId: input.type === 'action' ? input.data.actionTypeId : input.type,
|
|
220
|
-
version: transition.toVersion,
|
|
221
|
-
});
|
|
222
|
-
},
|
|
68
|
+
const audit: NakamaPlatformPlugin = {
|
|
69
|
+
name: 'audit',
|
|
70
|
+
async onMatchEnded(ctx, result) { /* ... */ },
|
|
223
71
|
};
|
|
224
|
-
|
|
225
|
-
createMatchHandler({ /* ... */, plugins: [analytics] });
|
|
226
|
-
```
|
|
227
|
-
|
|
228
|
-
### Plugin contract
|
|
229
|
-
|
|
230
|
-
- All callbacks are **optional** — implement only what you need.
|
|
231
|
-
- All callbacks are **async** and invoked **fire-and-forget** by the
|
|
232
|
-
match handler. The match loop does NOT await plugin promises.
|
|
233
|
-
- Plugin failures (sync throws or rejected promises) are caught and
|
|
234
|
-
logged via `logger.error('plugin %s hook %s rejected: %s', name, hook, err)`.
|
|
235
|
-
A failing plugin **never** crashes the match.
|
|
236
|
-
- Plugins are invoked in registration order, but their promises run in
|
|
237
|
-
parallel (no serialization).
|
|
238
|
-
- Plugins receive a `PluginContext` (`{ matchId, gameId, state, now }`) —
|
|
239
|
-
treat `state` as readonly.
|
|
240
|
-
|
|
241
|
-
### Hook coverage
|
|
242
|
-
|
|
243
|
-
| Hook | Fires when |
|
|
244
|
-
| -------------------- | ----------------------------------------------------------------------- |
|
|
245
|
-
| `onMatchCreated` | `matchInit` completes. |
|
|
246
|
-
| `onMatchStarted` | Match transitions `lobby -> active` (enough seats filled). |
|
|
247
|
-
| `onPlayerJoined` | Each presence in a `matchJoin` (fresh joins and reconnects). |
|
|
248
|
-
| `onPlayerLeft` | Each presence in a `matchLeave`. |
|
|
249
|
-
| `onPlayerAction` | A player-driven `applyAction` transition succeeded (one per action). |
|
|
250
|
-
| `onStateTransition` | Every successful transition (player actions, stack drain, timeouts). |
|
|
251
|
-
| `onMatchEnded` | `checkWinConditions` reports `ended: true`. |
|
|
252
|
-
|
|
253
|
-
---
|
|
254
|
-
|
|
255
|
-
## Determinism and tests
|
|
256
|
-
|
|
257
|
-
The adapter accepts an injectable `now: () => number` so tests can use a
|
|
258
|
-
monotonic harness clock instead of wall-clock time. Pair it with the
|
|
259
|
-
in-package harness (`__tests__/harness.ts`) and `InMemoryAdapter` from
|
|
260
|
-
`@table-games-engine/persistence` to drive whole matches without Nakama:
|
|
261
|
-
|
|
262
|
-
```ts
|
|
263
|
-
import { createHarness } from '@table-games-engine/nakama-adapter/__tests__/harness';
|
|
264
|
-
import { InMemoryAdapter, always } from '@table-games-engine/persistence';
|
|
265
|
-
|
|
266
|
-
const adapter = new InMemoryAdapter(() => 0);
|
|
267
|
-
const harness = createHarness();
|
|
268
|
-
const handler = createMatchHandler({
|
|
269
|
-
registry, idempotencyCache, adapter,
|
|
270
|
-
now: () => harness.tick.now(),
|
|
271
|
-
policy: always(),
|
|
272
|
-
});
|
|
273
|
-
|
|
274
|
-
const init = handler.matchInit({}, harness.logger, {}, { gameId, matchId, playerIds: 'alice,bob' });
|
|
275
|
-
// ...drive matchJoin, matchLoop, matchLeave, matchTerminate...
|
|
276
72
|
```
|
|
277
73
|
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
---
|
|
281
|
-
|
|
282
|
-
## Public API
|
|
283
|
-
|
|
284
|
-
```ts
|
|
285
|
-
// Wire format
|
|
286
|
-
parseInbound, serializeOutbound,
|
|
287
|
-
InboundEnvelope, OutboundEnvelope,
|
|
288
|
-
|
|
289
|
-
// Match handler
|
|
290
|
-
createMatchHandler, NkMatchInternalState, CreateMatchHandlerOptions,
|
|
291
|
-
|
|
292
|
-
// Registry
|
|
293
|
-
GameRegistry, RegistryError,
|
|
294
|
-
|
|
295
|
-
// Idempotency
|
|
296
|
-
IdempotencyCache,
|
|
297
|
-
|
|
298
|
-
// Broadcast
|
|
299
|
-
broadcastViews, OPCODES,
|
|
300
|
-
|
|
301
|
-
// Timeouts
|
|
302
|
-
checkTimeouts, TimeoutOptions,
|
|
303
|
-
|
|
304
|
-
// Persistence bridge (lower-level; createMatchHandler uses it under the hood)
|
|
305
|
-
createPersistenceBridge, PersistenceBridge,
|
|
306
|
-
|
|
307
|
-
// Plugins
|
|
308
|
-
NakamaPlatformPlugin, PluginContext,
|
|
309
|
-
invokePluginHook, dispatchPluginHook,
|
|
310
|
-
```
|
|
311
|
-
|
|
312
|
-
---
|
|
313
|
-
|
|
314
|
-
## Status
|
|
74
|
+
Hooks: `onMatchCreated`, `onMatchStarted`, `onPlayerJoined`, `onPlayerLeft`, `onPlayerAction`, `onStateTransition`, `onMatchEnded`. All are optional and async. They are fire-and-forget: the match loop never waits for them, and a failing plugin is logged but never crashes the match.
|
|
315
75
|
|
|
316
|
-
|
|
317
|
-
- **Phase B** — full match handler, broadcast, timeouts, signals. Done.
|
|
318
|
-
- **Phase C** — persistence wiring, plugins, reconnection, e2e test,
|
|
319
|
-
this README. Done.
|
|
76
|
+
## Licence
|
|
320
77
|
|
|
321
|
-
|
|
322
|
-
MUST guarantee, regardless of implementation), see
|
|
323
|
-
[`docs/normative/platforms/nakama.md`](../../docs/normative/platforms/nakama.md).
|
|
78
|
+
FSL-1.1-ALv2 (Functional Source License, converts to Apache-2.0 after two years). See `LICENSE.md` in the package.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@table-games-engine/nakama-adapter",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.1",
|
|
4
4
|
"publishConfig": {
|
|
5
5
|
"access": "public"
|
|
6
6
|
},
|
|
@@ -23,12 +23,22 @@
|
|
|
23
23
|
"typecheck": "tsc --noEmit"
|
|
24
24
|
},
|
|
25
25
|
"dependencies": {
|
|
26
|
-
"@table-games-engine/core": "^0.1.
|
|
27
|
-
"@table-games-engine/persistence": "^0.1.
|
|
26
|
+
"@table-games-engine/core": "^0.1.1",
|
|
27
|
+
"@table-games-engine/persistence": "^0.1.1"
|
|
28
28
|
},
|
|
29
29
|
"devDependencies": {
|
|
30
30
|
"typescript": "^5.4.0",
|
|
31
31
|
"vitest": "^2.0.0"
|
|
32
32
|
},
|
|
33
|
-
"license": "FSL-1.1-ALv2"
|
|
33
|
+
"license": "FSL-1.1-ALv2",
|
|
34
|
+
"description": "Nakama runtime match handler for table-games-engine games.",
|
|
35
|
+
"keywords": [
|
|
36
|
+
"table-games",
|
|
37
|
+
"turn-based",
|
|
38
|
+
"multiplayer",
|
|
39
|
+
"game-engine",
|
|
40
|
+
"nakama",
|
|
41
|
+
"boardgame"
|
|
42
|
+
],
|
|
43
|
+
"homepage": "https://www.npmjs.com/package/@table-games-engine/nakama-adapter"
|
|
34
44
|
}
|