@table-games-engine/nakama-adapter 0.0.0-stage → 0.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/LICENSE.md +105 -0
- package/README.md +322 -2
- package/dist/broadcast.d.ts +27 -0
- package/dist/idempotency.d.ts +54 -0
- package/dist/index.d.ts +25 -0
- package/dist/index.js +1224 -0
- package/dist/match-handler.d.ts +76 -0
- package/dist/persistence-bridge.d.ts +78 -0
- package/dist/plugins.d.ts +76 -0
- package/dist/register-plugin.d.ts +7 -0
- package/dist/registry.d.ts +84 -0
- package/dist/serialization.d.ts +135 -0
- package/dist/timeouts.d.ts +33 -0
- package/dist/types.d.ts +108 -0
- package/package.json +32 -4
package/LICENSE.md
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
# Functional Source License, Version 1.1, ALv2 Future License
|
|
2
|
+
|
|
3
|
+
## Abbreviation
|
|
4
|
+
|
|
5
|
+
FSL-1.1-ALv2
|
|
6
|
+
|
|
7
|
+
## Notice
|
|
8
|
+
|
|
9
|
+
Copyright 2026 Dmitry Kucher
|
|
10
|
+
|
|
11
|
+
## Terms and Conditions
|
|
12
|
+
|
|
13
|
+
### Licensor ("We")
|
|
14
|
+
|
|
15
|
+
The party offering the Software under these Terms and Conditions.
|
|
16
|
+
|
|
17
|
+
### The Software
|
|
18
|
+
|
|
19
|
+
The "Software" is each version of the software that we make available under
|
|
20
|
+
these Terms and Conditions, as indicated by our inclusion of these Terms and
|
|
21
|
+
Conditions with the Software.
|
|
22
|
+
|
|
23
|
+
### License Grant
|
|
24
|
+
|
|
25
|
+
Subject to your compliance with this License Grant and the Patents,
|
|
26
|
+
Redistribution and Trademark clauses below, we hereby grant you the right to
|
|
27
|
+
use, copy, modify, create derivative works, publicly perform, publicly display
|
|
28
|
+
and redistribute the Software for any Permitted Purpose identified below.
|
|
29
|
+
|
|
30
|
+
### Permitted Purpose
|
|
31
|
+
|
|
32
|
+
A Permitted Purpose is any purpose other than a Competing Use. A Competing Use
|
|
33
|
+
means making the Software available to others in a commercial product or
|
|
34
|
+
service that:
|
|
35
|
+
|
|
36
|
+
1. substitutes for the Software;
|
|
37
|
+
|
|
38
|
+
2. substitutes for any other product or service we offer using the Software
|
|
39
|
+
that exists as of the date we make the Software available; or
|
|
40
|
+
|
|
41
|
+
3. offers the same or substantially similar functionality as the Software.
|
|
42
|
+
|
|
43
|
+
Permitted Purposes specifically include using the Software:
|
|
44
|
+
|
|
45
|
+
1. for your internal use and access;
|
|
46
|
+
|
|
47
|
+
2. for non-commercial education;
|
|
48
|
+
|
|
49
|
+
3. for non-commercial research; and
|
|
50
|
+
|
|
51
|
+
4. in connection with professional services that you provide to a licensee
|
|
52
|
+
using the Software in accordance with these Terms and Conditions.
|
|
53
|
+
|
|
54
|
+
### Patents
|
|
55
|
+
|
|
56
|
+
To the extent your use for a Permitted Purpose would necessarily infringe our
|
|
57
|
+
patents, the license grant above includes a license under our patents. If you
|
|
58
|
+
make a claim against any party that the Software infringes or contributes to
|
|
59
|
+
the infringement of any patent, then your patent license to the Software ends
|
|
60
|
+
immediately.
|
|
61
|
+
|
|
62
|
+
### Redistribution
|
|
63
|
+
|
|
64
|
+
The Terms and Conditions apply to all copies, modifications and derivatives of
|
|
65
|
+
the Software.
|
|
66
|
+
|
|
67
|
+
If you redistribute any copies, modifications or derivatives of the Software,
|
|
68
|
+
you must include a copy of or a link to these Terms and Conditions and not
|
|
69
|
+
remove any copyright notices provided in or with the Software.
|
|
70
|
+
|
|
71
|
+
### Disclaimer
|
|
72
|
+
|
|
73
|
+
THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR
|
|
74
|
+
IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR
|
|
75
|
+
PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT.
|
|
76
|
+
|
|
77
|
+
IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO THE
|
|
78
|
+
SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES,
|
|
79
|
+
EVEN IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE.
|
|
80
|
+
|
|
81
|
+
### Trademarks
|
|
82
|
+
|
|
83
|
+
Except for displaying the License Details and identifying us as the origin of
|
|
84
|
+
the Software, you have no right under these Terms and Conditions to use our
|
|
85
|
+
trademarks, trade names, service marks or product names.
|
|
86
|
+
|
|
87
|
+
## Grant of Future License
|
|
88
|
+
|
|
89
|
+
We hereby irrevocably grant you an additional license to use the Software under
|
|
90
|
+
the Apache License, Version 2.0 that is effective on the second anniversary of
|
|
91
|
+
the date we make the Software available. On or after that date, you may use the
|
|
92
|
+
Software under the Apache License, Version 2.0, in which case the following
|
|
93
|
+
will apply:
|
|
94
|
+
|
|
95
|
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
|
|
96
|
+
this file except in compliance with the License.
|
|
97
|
+
|
|
98
|
+
You may obtain a copy of the License at
|
|
99
|
+
|
|
100
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
101
|
+
|
|
102
|
+
Unless required by applicable law or agreed to in writing, software distributed
|
|
103
|
+
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
|
|
104
|
+
CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
|
105
|
+
specific language governing permissions and limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,323 @@
|
|
|
1
|
-
#
|
|
1
|
+
# `@table-games-engine/nakama-adapter`
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Nakama runtime bindings for the `@table-games-engine/core` engine.
|
|
4
|
+
|
|
5
|
+
This package wires the deterministic, in-process `Engine` from
|
|
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`.
|
|
10
|
+
|
|
11
|
+
For the **normative behaviour contract** (lifecycle, sequential processing,
|
|
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.
|
|
17
|
+
|
|
18
|
+
---
|
|
19
|
+
|
|
20
|
+
## What this package gives you
|
|
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`.
|
|
37
|
+
|
|
38
|
+
---
|
|
39
|
+
|
|
40
|
+
## Wiring into a Nakama TypeScript runtime
|
|
41
|
+
|
|
42
|
+
Nakama runs your TS code via the `nakama-runtime` Node host, with an
|
|
43
|
+
`InitModule(ctx, logger, nk, initializer)` entry point. A minimal
|
|
44
|
+
`init.ts` looks like this:
|
|
45
|
+
|
|
46
|
+
```ts
|
|
47
|
+
// init.ts
|
|
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';
|
|
59
|
+
|
|
60
|
+
const registry = new GameRegistry();
|
|
61
|
+
registerMyGame(registry); // calls registry.register({ gameId, manifest, handlers, setup, winChecker })
|
|
62
|
+
|
|
63
|
+
const idempotencyCache = new IdempotencyCache();
|
|
64
|
+
|
|
65
|
+
const adapter = new SqliteAdapter({
|
|
66
|
+
path: process.env['ENGINE_DB_PATH'] ?? '/data/engine.db',
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
const handler = createMatchHandler({
|
|
70
|
+
registry,
|
|
71
|
+
idempotencyCache,
|
|
72
|
+
adapter,
|
|
73
|
+
policy: everyNTransitions(50),
|
|
74
|
+
ownerNode: process.env['NAKAMA_NODE_ID'] ?? 'node-A',
|
|
75
|
+
leaseSeconds: 60,
|
|
76
|
+
timeout: { timeoutMs: 30_000 },
|
|
77
|
+
plugins: [
|
|
78
|
+
/* analytics, audit, etc. — see "Plugins" below */
|
|
79
|
+
],
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
function InitModule(
|
|
83
|
+
_ctx: nkruntime.Context,
|
|
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);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
!InitModule && InitModule;
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
Then create a match from your matchmaker / API hook:
|
|
96
|
+
|
|
97
|
+
```ts
|
|
98
|
+
const matchId = nk.matchCreate(MATCH_HANDLER_NAME, {
|
|
99
|
+
gameId: 'my-game',
|
|
100
|
+
// optional — handler will mint one via `matchIdFactory` or `match-<now>` if absent
|
|
101
|
+
matchId: 'duel-12345',
|
|
102
|
+
// comma-separated; setup() receives them
|
|
103
|
+
playerIds: 'alice,bob',
|
|
104
|
+
config: JSON.stringify({ /* game-instance options */ }),
|
|
105
|
+
});
|
|
106
|
+
```
|
|
107
|
+
|
|
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.
|
|
189
|
+
|
|
190
|
+
Rejoiners are detected when either (a) the userId is already in
|
|
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).
|
|
194
|
+
|
|
195
|
+
---
|
|
196
|
+
|
|
197
|
+
## Plugins
|
|
198
|
+
|
|
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
|
+
```ts
|
|
205
|
+
import type { NakamaPlatformPlugin } from '@table-games-engine/nakama-adapter';
|
|
206
|
+
|
|
207
|
+
const analytics: NakamaPlatformPlugin = {
|
|
208
|
+
name: 'analytics',
|
|
209
|
+
async onMatchCreated(ctx) {
|
|
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
|
+
},
|
|
223
|
+
};
|
|
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
|
+
```
|
|
277
|
+
|
|
278
|
+
See `__tests__/e2e.test.ts` for the full pipeline exercised end-to-end.
|
|
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
|
|
315
|
+
|
|
316
|
+
- **Phase A** — wire format, registry, idempotency, harness. Done.
|
|
317
|
+
- **Phase B** — full match handler, broadcast, timeouts, signals. Done.
|
|
318
|
+
- **Phase C** — persistence wiring, plugins, reconnection, e2e test,
|
|
319
|
+
this README. Done.
|
|
320
|
+
|
|
321
|
+
For the normative compliance contract (what any Nakama-based adapter
|
|
322
|
+
MUST guarantee, regardless of implementation), see
|
|
323
|
+
[`docs/normative/platforms/nakama.md`](../../docs/normative/platforms/nakama.md).
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { GameManifest, LegalMove, MatchState, PlayerId } from '@table-games-engine/core';
|
|
2
|
+
import type { NkMatchDispatcher, NkPresence } from './types.js';
|
|
3
|
+
/**
|
|
4
|
+
* Opcode allocation for the adapter.
|
|
5
|
+
*
|
|
6
|
+
* STATE_UPDATE = 1 per-player full snapshot (`OutboundState`)
|
|
7
|
+
* ACK = 2 per-action acknowledgement (`OutboundAck`)
|
|
8
|
+
* BROADCAST = 3 broadcast events (`OutboundBroadcast`)
|
|
9
|
+
* MATCH_ENDED = 4 terminal `match-ended`
|
|
10
|
+
* TRANSITION = 5 incremental transition deltas (future use)
|
|
11
|
+
*/
|
|
12
|
+
export declare const OPCODES: {
|
|
13
|
+
readonly STATE_UPDATE: 1;
|
|
14
|
+
readonly ACK: 2;
|
|
15
|
+
readonly BROADCAST: 3;
|
|
16
|
+
readonly MATCH_ENDED: 4;
|
|
17
|
+
readonly TRANSITION: 5;
|
|
18
|
+
};
|
|
19
|
+
export type Opcode = (typeof OPCODES)[keyof typeof OPCODES];
|
|
20
|
+
/**
|
|
21
|
+
* Compute and dispatch a filtered `state-update` envelope to each presence.
|
|
22
|
+
*
|
|
23
|
+
* Players whose `userId` is not registered as a `PlayerId` in `state.players`
|
|
24
|
+
* are skipped — they may be observers (Phase B doesn't model them) and we
|
|
25
|
+
* never broadcast a `PlayerView` for an unknown viewer.
|
|
26
|
+
*/
|
|
27
|
+
export declare function broadcastViews(state: MatchState, manifest: GameManifest, dispatcher: NkMatchDispatcher, presences: ReadonlyArray<NkPresence>, legalMovesFor?: (playerId: PlayerId) => ReadonlyArray<LegalMove>): void;
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Per-match idempotency cache: when a client retries a message
|
|
3
|
+
* with the same `clientId`, the adapter should replay the original outbound
|
|
4
|
+
* response instead of executing the action twice.
|
|
5
|
+
*
|
|
6
|
+
* Cache layout:
|
|
7
|
+
* matchId -> Map<clientId, { response: OutboundEnvelope; expiresAt }>
|
|
8
|
+
*
|
|
9
|
+
* Entries expire after `ttlMs` (default 5 min). The clock is injectable for
|
|
10
|
+
* deterministic tests. Pruning runs on every `get` / `set` for the affected
|
|
11
|
+
* match — it stays cheap because each match's map is small (one entry per
|
|
12
|
+
* recent action) and we only walk one match at a time.
|
|
13
|
+
*/
|
|
14
|
+
import type { OutboundEnvelope } from './serialization.js';
|
|
15
|
+
/** A single cache entry. */
|
|
16
|
+
export interface IdempotencyEntry {
|
|
17
|
+
readonly response: OutboundEnvelope;
|
|
18
|
+
readonly expiresAt: number;
|
|
19
|
+
}
|
|
20
|
+
/** Constructor options for `IdempotencyCache`. */
|
|
21
|
+
export interface IdempotencyCacheOptions {
|
|
22
|
+
/** Entry lifetime in milliseconds. Defaults to 5 minutes. */
|
|
23
|
+
readonly ttlMs?: number;
|
|
24
|
+
/** Clock source (ms epoch). Defaults to `Date.now`. */
|
|
25
|
+
readonly now?: () => number;
|
|
26
|
+
}
|
|
27
|
+
export declare class IdempotencyCache {
|
|
28
|
+
private readonly buckets;
|
|
29
|
+
private readonly ttlMs;
|
|
30
|
+
private readonly now;
|
|
31
|
+
constructor(options?: IdempotencyCacheOptions);
|
|
32
|
+
/**
|
|
33
|
+
* Look up a cached response. Prunes expired entries for the match as a
|
|
34
|
+
* side effect, so a stale entry is never returned.
|
|
35
|
+
*/
|
|
36
|
+
get(matchId: string, clientId: string): OutboundEnvelope | null;
|
|
37
|
+
/**
|
|
38
|
+
* Cache `response` under `(matchId, clientId)` with TTL. Replaces any
|
|
39
|
+
* existing entry for the same key.
|
|
40
|
+
*/
|
|
41
|
+
set(matchId: string, clientId: string, response: OutboundEnvelope): void;
|
|
42
|
+
/**
|
|
43
|
+
* Drop the entire bucket for `matchId`. Use when a match terminates so
|
|
44
|
+
* we don't hold the response payloads in memory.
|
|
45
|
+
*/
|
|
46
|
+
clear(matchId: string): void;
|
|
47
|
+
/**
|
|
48
|
+
* Walk every bucket and drop expired entries. Empty buckets are removed.
|
|
49
|
+
*/
|
|
50
|
+
prune(): void;
|
|
51
|
+
/** Total number of live entries across all buckets. Test-only helper. */
|
|
52
|
+
get size(): number;
|
|
53
|
+
private pruneBucket;
|
|
54
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Public barrel for `@table-games-engine/nakama-adapter`.
|
|
3
|
+
*
|
|
4
|
+
* This package wraps the pure `EngineOperations` from `@table-games-engine/core`
|
|
5
|
+
* (and the persistence layer from `@table-games-engine/persistence`) behind a
|
|
6
|
+
* Nakama match handler so that multiple players can connect via WebSocket.
|
|
7
|
+
*/
|
|
8
|
+
export type { NkLogger, NkPresence, NkMatchData, NkMatchDispatcher, NkMatchState, NkMatchHandler, } from './types.js';
|
|
9
|
+
export { parseInbound, serializeOutbound, } from './serialization.js';
|
|
10
|
+
export type { InboundEnvelope, OutboundEnvelope, InboundAction, InboundPass, InboundConcede, InboundChooseTargets, InboundOrderTriggers, InboundAdminPause, InboundAdminResume, InboundMalformed, OutboundState, OutboundTransition, OutboundAck, OutboundBroadcast, OutboundMatchEnded, } from './serialization.js';
|
|
11
|
+
export { GameRegistry, RegistryError } from './registry.js';
|
|
12
|
+
export { registerPlugin } from './register-plugin.js';
|
|
13
|
+
export type { RegisteredGame, RegisterArgs, GameSetup, } from './registry.js';
|
|
14
|
+
export { IdempotencyCache } from './idempotency.js';
|
|
15
|
+
export type { IdempotencyEntry, IdempotencyCacheOptions, } from './idempotency.js';
|
|
16
|
+
export { createMatchHandler } from './match-handler.js';
|
|
17
|
+
export type { MatchStatus, NkMatchInternalState, CreateMatchHandlerOptions, } from './match-handler.js';
|
|
18
|
+
export { broadcastViews, OPCODES } from './broadcast.js';
|
|
19
|
+
export type { Opcode } from './broadcast.js';
|
|
20
|
+
export { checkTimeouts } from './timeouts.js';
|
|
21
|
+
export type { TimeoutOptions } from './timeouts.js';
|
|
22
|
+
export { createPersistenceBridge } from './persistence-bridge.js';
|
|
23
|
+
export type { PersistenceBridge, CreatePersistenceBridgeArgs, } from './persistence-bridge.js';
|
|
24
|
+
export { invokePluginHook, dispatchPluginHook, } from './plugins.js';
|
|
25
|
+
export type { NakamaPlatformPlugin, PluginContext, } from './plugins.js';
|