@table-games-engine/persistence 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 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,164 @@
1
- # Temporary Holding Version
1
+ # `@table-games-engine/persistence`
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Persistence layer for the table-games engine. Implements the
4
+ `EngineAdapter` contract from `@table-games-engine/core` and provides
5
+ helpers for snapshotting, replay, and ownership leasing.
6
+
7
+ This package is internal to the workspace (`"private": true`) and is
8
+ imported by the runtime, the Nakama adapter (M3), and any host that
9
+ needs to keep matches alive across restarts.
10
+
11
+ ## What lives here
12
+
13
+ - **`InMemoryAdapter`** — reference adapter, no I/O. Used in tests and
14
+ for ephemeral sandbox runs.
15
+ - **`SqliteAdapter`** — SQLite-backed adapter via `better-sqlite3`.
16
+ Construct with a filesystem path or `':memory:'`. Migrations are
17
+ applied eagerly.
18
+ - **`checksumState`** — deterministic JSON-canonical FNV-1a 32-bit
19
+ checksum of a `MatchState`. Used by both adapters and by callers
20
+ that want to verify replayed state.
21
+ - **`createPersistedEngine`** — wraps an in-process `Engine` so every
22
+ transition is mirrored into the adapter (events appended, snapshots
23
+ taken per policy).
24
+ - **Snapshot policies** — `everyNTransitions`, `everyTTicks`, `always`,
25
+ `never`, `combine`.
26
+ - **`replayMatch` / `loadEventsBetween`** — reconstruction helpers.
27
+
28
+ ## Quick start
29
+
30
+ ```ts
31
+ import {
32
+ SqliteAdapter,
33
+ createPersistedEngine,
34
+ everyNTransitions,
35
+ replayMatch,
36
+ checksumState,
37
+ } from '@table-games-engine/persistence';
38
+ import { manifest, handlers, initialState } from './my-game';
39
+
40
+ const adapter = new SqliteAdapter('./match.db');
41
+
42
+ const engine = await createPersistedEngine({
43
+ manifest,
44
+ initialState,
45
+ handlers,
46
+ adapter,
47
+ matchId: 'match-42',
48
+ policy: everyNTransitions(50), // default, shown for clarity
49
+ ownerNode: 'node-A', // optional ownership lease
50
+ leaseSeconds: 60, // optional, defaults to 60
51
+ });
52
+
53
+ // Drive the game. Each call returns a Promise<Result<...>>.
54
+ const r = await engine.applyAction(myInput);
55
+ if (r.ok) {
56
+ await engine.resolveTopFrame();
57
+ }
58
+
59
+ // Optional: force a snapshot at the current state (e.g. on match end).
60
+ await engine.forceSnapshot();
61
+
62
+ // Recover from anywhere: latest snapshot at or before a given version.
63
+ const recovered = await replayMatch(adapter, 'match-42');
64
+
65
+ // Verify integrity (the adapter does this on load, but you may want
66
+ // to assert it matches the live engine before swapping).
67
+ checksumState(recovered!) === checksumState(engine.getState());
68
+
69
+ // Release the lease and close the DB handle.
70
+ await engine.close();
71
+ ```
72
+
73
+ ## Snapshot cadence
74
+
75
+ The persisted engine is policy-driven; pass `policy` when you construct
76
+ it. Built-in policies:
77
+
78
+ | Policy | When it fires |
79
+ | -------------------------- | -------------------------------------- |
80
+ | `everyNTransitions(n)` | After every `n` engine transitions |
81
+ | `everyTTicks(t)` | After every `t` logical ticks |
82
+ | `always()` | Every transition (deterministic tests) |
83
+ | `never()` | Never (benchmarks, audit-only engines) |
84
+ | `combine(...policies)` | If any sub-policy returns true |
85
+
86
+ Default is `everyNTransitions(50)`, matching the M2 plan's "snapshot
87
+ every ~50 transitions" guidance.
88
+
89
+ ### Cadence trade-offs
90
+
91
+ - **Frequent snapshots** (low N): faster recovery, smaller replay
92
+ windows, but more bytes written per second and higher checksum cost.
93
+ - **Sparse snapshots** (high N): cheaper writes, but larger windows
94
+ between recoverable points. With M2's design, you can only recover
95
+ to versions that were snapshotted (see "Replay contract" below).
96
+ - **`always()`** is the right default for **async-mode** games (every
97
+ action persists; players may be offline for hours/days) and for
98
+ tests that want deterministic post-conditions.
99
+ - **`combine(everyNTransitions(50), everyTTicks(60))`** mirrors the
100
+ M2 plan's "every N transitions OR every T seconds" hybrid.
101
+
102
+ ## Replay contract (M2 design)
103
+
104
+ `replayMatch(adapter, matchId, toVersion?)` returns the **latest
105
+ snapshot whose `state.version` is `<= toVersion`**, or the absolute
106
+ latest snapshot when `toVersion` is omitted, or `null` when nothing has
107
+ been persisted.
108
+
109
+ It does **not** replay events onto state. This is a deliberate M2
110
+ decision:
111
+
112
+ - The adapter stores **snapshots** (full state) and **events**
113
+ (game-domain events for triggers, audit, spectator catch-up).
114
+ - Events are NOT a derivation of `StateMutation`s. We cannot
115
+ reconstruct state at an arbitrary version V by "applying events" —
116
+ there is no such operation defined.
117
+ - To recover to an exact version V, configure a snapshot policy that
118
+ guarantees a snapshot at V (e.g. `always()` or a turn-aligned
119
+ cadence).
120
+ - For audit, use `loadEventsBetween(adapter, matchId, from, to)` to
121
+ fetch the half-open `(from, to]` slice of the event log.
122
+
123
+ M3 (Nakama adapter) will revisit this if cross-node failover requires
124
+ sub-snapshot precision. For now, snapshot density is the knob.
125
+
126
+ ## Sync/async boundary
127
+
128
+ The core `Engine` API is **synchronous**: `applyAction(input): Result<...>`.
129
+ The persisted wrapper exposes the same shape but each transition method
130
+ returns a `Promise<Result<...>>` because adapter writes are async.
131
+
132
+ Adapter failures (e.g. SQLite I/O error, network error in a future
133
+ remote adapter) **propagate to the caller as a rejected Promise**.
134
+ They do **not** roll back the in-memory state — by the time the adapter
135
+ write happens, the engine has already produced and applied the
136
+ transition. Callers that need all-or-nothing semantics must layer their
137
+ own retry / quarantine on top, or close the engine and recover from the
138
+ last good snapshot.
139
+
140
+ ## Ownership
141
+
142
+ If you pass `ownerNode` to `createPersistedEngine`, the wrapper
143
+ acquires an exclusive lease on `matchId` before doing anything else.
144
+ Construction throws if another node holds a non-expired lease.
145
+
146
+ Leases auto-expire after `leaseSeconds` seconds. Use `engine.close()`
147
+ or `engine.releaseOwnership()` to release explicitly.
148
+
149
+ ## Determinism guarantees
150
+
151
+ - The wrapper's behaviour matches the unwrapped `createEngine` exactly
152
+ for game logic. Tests assert byte-for-byte state equality.
153
+ - Checksums are deterministic across machines and processes.
154
+ - `SqliteAdapter` uses WAL mode and per-call transactions for atomic
155
+ writes.
156
+
157
+ ## Testing
158
+
159
+ ```bash
160
+ npm test --workspace=@table-games-engine/persistence
161
+ ```
162
+
163
+ Unit tests use `InMemoryAdapter` (no I/O); the round-trip integration
164
+ tests use `SqliteAdapter(':memory:')` for hermetic SQLite coverage.
@@ -0,0 +1,22 @@
1
+ /**
2
+ * @fileoverview Deterministic JSON checksum for `MatchState`.
3
+ *
4
+ * Algorithm:
5
+ * 1. Canonicalize the value to JSON with **sorted keys at every nesting
6
+ * level** (arrays preserve their order; objects are reserialized with
7
+ * lexicographically ordered keys).
8
+ * 2. Hash the canonical string with FNV-1a 32-bit (same primitive as
9
+ * `core/engine/rng`).
10
+ * 3. Format the hash as a lowercase 8-character hex string.
11
+ *
12
+ * Two states with semantically identical content produce identical checksums
13
+ * regardless of how their JS object literals were constructed (key insertion
14
+ * order is irrelevant). The function is pure and never mutates its input.
15
+ */
16
+ import type { MatchState } from '@table-games-engine/core';
17
+ /**
18
+ * Compute a deterministic 8-character lowercase-hex checksum of `state`.
19
+ *
20
+ * Pure: does not mutate the input.
21
+ */
22
+ export declare function checksumState(state: MatchState): string;
package/dist/core.d.ts ADDED
@@ -0,0 +1,9 @@
1
+ /**
2
+ * @fileoverview Nakama-safe subset of @table-games-engine/persistence: no
3
+ * SqliteAdapter (node:fs / better-sqlite3 are unavailable in Nakama's JS
4
+ * runtime). Bundlers alias '@table-games-engine/persistence' to this entry.
5
+ */
6
+ export { InMemoryAdapter } from './in-memory.js';
7
+ export { checksumState } from './checksum.js';
8
+ export { everyNTransitions, everyTTicks, always, never, combine } from './snapshots.js';
9
+ export type { SnapshotPolicy } from './snapshots.js';
package/dist/core.js ADDED
@@ -0,0 +1,239 @@
1
+ // src/checksum.ts
2
+ var FNV_OFFSET = 2166136261;
3
+ var FNV_PRIME = 16777619;
4
+ function fnv1a32(input) {
5
+ let h = FNV_OFFSET;
6
+ for (let i = 0; i < input.length; i++) {
7
+ h ^= input.charCodeAt(i);
8
+ h = Math.imul(h, FNV_PRIME);
9
+ }
10
+ return h >>> 0;
11
+ }
12
+ function canonicalize(value) {
13
+ if (value === null) return "null";
14
+ if (value === void 0) return "null";
15
+ const t = typeof value;
16
+ if (t === "number") {
17
+ if (!Number.isFinite(value)) return "null";
18
+ return JSON.stringify(value);
19
+ }
20
+ if (t === "string" || t === "boolean") return JSON.stringify(value);
21
+ if (Array.isArray(value)) {
22
+ return "[" + value.map((v) => canonicalize(v)).join(",") + "]";
23
+ }
24
+ if (t === "object") {
25
+ const obj = value;
26
+ const keys = Object.keys(obj).sort();
27
+ const parts = [];
28
+ for (const k of keys) {
29
+ const v = obj[k];
30
+ if (v === void 0) continue;
31
+ parts.push(JSON.stringify(k) + ":" + canonicalize(v));
32
+ }
33
+ return "{" + parts.join(",") + "}";
34
+ }
35
+ return "null";
36
+ }
37
+ function checksumState(state) {
38
+ const canonical = canonicalize(state);
39
+ const h = fnv1a32(canonical);
40
+ return h.toString(16).padStart(8, "0");
41
+ }
42
+
43
+ // src/in-memory.ts
44
+ var InMemoryAdapter = class {
45
+ matches = /* @__PURE__ */ new Map();
46
+ now;
47
+ closed = false;
48
+ constructor(now = () => Date.now()) {
49
+ this.now = now;
50
+ }
51
+ getOrCreate(matchId) {
52
+ let data = this.matches.get(matchId);
53
+ if (!data) {
54
+ data = {
55
+ snapshots: [],
56
+ events: [],
57
+ lastEventVersion: -1,
58
+ ownership: null
59
+ };
60
+ this.matches.set(matchId, data);
61
+ }
62
+ return data;
63
+ }
64
+ persistSnapshot(matchId, state, checksum) {
65
+ const data = this.getOrCreate(matchId);
66
+ const version = state.version;
67
+ const existing = data.snapshots.find((s) => s.version === version);
68
+ if (existing && existing.checksum !== checksum) {
69
+ return Promise.reject(
70
+ new Error(
71
+ `InMemoryAdapter: snapshot integrity violation for match ${String(
72
+ matchId
73
+ )} at version ${String(version)}: existing checksum ${existing.checksum} != new checksum ${checksum}`
74
+ )
75
+ );
76
+ }
77
+ if (!existing) {
78
+ data.snapshots.push({ version, state, checksum });
79
+ }
80
+ return Promise.resolve();
81
+ }
82
+ loadSnapshot(matchId, atVersion) {
83
+ const data = this.matches.get(matchId);
84
+ if (!data || data.snapshots.length === 0) return Promise.resolve(null);
85
+ let chosen = null;
86
+ if (atVersion === void 0) {
87
+ let bestIdx = -1;
88
+ let bestVersion = -Infinity;
89
+ for (let i = 0; i < data.snapshots.length; i++) {
90
+ const s = data.snapshots[i];
91
+ const v = s.version;
92
+ if (v >= bestVersion) {
93
+ bestVersion = v;
94
+ bestIdx = i;
95
+ }
96
+ }
97
+ chosen = bestIdx >= 0 ? data.snapshots[bestIdx] : null;
98
+ } else {
99
+ const target = atVersion;
100
+ let bestVersion = -Infinity;
101
+ for (const s of data.snapshots) {
102
+ const v = s.version;
103
+ if (v <= target && v >= bestVersion) {
104
+ bestVersion = v;
105
+ chosen = s;
106
+ }
107
+ }
108
+ }
109
+ if (!chosen) return Promise.resolve(null);
110
+ const computed = checksumState(chosen.state);
111
+ if (computed !== chosen.checksum) {
112
+ return Promise.reject(
113
+ new Error(
114
+ `InMemoryAdapter: checksum mismatch on load for match ${String(
115
+ matchId
116
+ )} at version ${String(chosen.version)}: stored ${chosen.checksum}, computed ${computed}`
117
+ )
118
+ );
119
+ }
120
+ return Promise.resolve(chosen.state);
121
+ }
122
+ appendEvents(matchId, transitionVersion, events) {
123
+ const data = this.getOrCreate(matchId);
124
+ const v = transitionVersion;
125
+ if (v <= data.lastEventVersion) {
126
+ return Promise.reject(
127
+ new Error(
128
+ `InMemoryAdapter: appendEvents version regression for match ${String(
129
+ matchId
130
+ )}: got ${v}, last was ${data.lastEventVersion}`
131
+ )
132
+ );
133
+ }
134
+ data.events.push({ version: transitionVersion, events });
135
+ data.lastEventVersion = v;
136
+ return Promise.resolve();
137
+ }
138
+ loadEvents(matchId, fromVersion, toVersion) {
139
+ const data = this.matches.get(matchId);
140
+ if (!data) return Promise.resolve([]);
141
+ const from = fromVersion;
142
+ const to = toVersion;
143
+ const out = [];
144
+ for (const batch of data.events) {
145
+ const v = batch.version;
146
+ if (v > from && v <= to) {
147
+ out.push(...batch.events);
148
+ }
149
+ }
150
+ return Promise.resolve(out);
151
+ }
152
+ acquireOwnership(matchId, ownerNode, leaseSeconds) {
153
+ const data = this.getOrCreate(matchId);
154
+ const now = this.now();
155
+ const current = data.ownership;
156
+ const expired = current === null || current.expiresAt <= now;
157
+ if (!expired && current.owner !== ownerNode) {
158
+ return Promise.resolve(false);
159
+ }
160
+ data.ownership = {
161
+ owner: ownerNode,
162
+ expiresAt: now + leaseSeconds * 1e3
163
+ };
164
+ return Promise.resolve(true);
165
+ }
166
+ releaseOwnership(matchId, ownerNode) {
167
+ const data = this.matches.get(matchId);
168
+ if (!data) return Promise.resolve();
169
+ if (data.ownership && data.ownership.owner === ownerNode) {
170
+ data.ownership = null;
171
+ }
172
+ return Promise.resolve();
173
+ }
174
+ close() {
175
+ this.closed = true;
176
+ void this.closed;
177
+ return Promise.resolve();
178
+ }
179
+ };
180
+
181
+ // src/snapshots.ts
182
+ function everyNTransitions(n) {
183
+ if (!Number.isInteger(n) || n < 1) {
184
+ throw new Error(
185
+ `everyNTransitions: n must be a positive integer (got ${String(n)})`
186
+ );
187
+ }
188
+ return {
189
+ shouldSnapshot(_state, sinceLast) {
190
+ return sinceLast.transitionsSince >= n;
191
+ }
192
+ };
193
+ }
194
+ function everyTTicks(t) {
195
+ if (!Number.isInteger(t) || t < 1) {
196
+ throw new Error(
197
+ `everyTTicks: t must be a positive integer (got ${String(t)})`
198
+ );
199
+ }
200
+ return {
201
+ shouldSnapshot(_state, sinceLast) {
202
+ return sinceLast.ticksSince >= t;
203
+ }
204
+ };
205
+ }
206
+ function always() {
207
+ return {
208
+ shouldSnapshot() {
209
+ return true;
210
+ }
211
+ };
212
+ }
213
+ function never() {
214
+ return {
215
+ shouldSnapshot() {
216
+ return false;
217
+ }
218
+ };
219
+ }
220
+ function combine(...policies) {
221
+ if (policies.length === 0) return never();
222
+ return {
223
+ shouldSnapshot(state, sinceLast) {
224
+ for (const p of policies) {
225
+ if (p.shouldSnapshot(state, sinceLast)) return true;
226
+ }
227
+ return false;
228
+ }
229
+ };
230
+ }
231
+ export {
232
+ InMemoryAdapter,
233
+ always,
234
+ checksumState,
235
+ combine,
236
+ everyNTransitions,
237
+ everyTTicks,
238
+ never
239
+ };
@@ -0,0 +1,28 @@
1
+ /**
2
+ * @fileoverview In-memory `EngineAdapter` reference implementation.
3
+ *
4
+ * Stores all data in JS data structures (no I/O). Useful as a reference
5
+ * implementation, for tests, and for ephemeral sandbox runs. Persistence
6
+ * across process restarts requires a real backend (e.g. SQLite — Phase B).
7
+ */
8
+ import type { EngineAdapter, MatchId, MatchState, StateVersion, GameEvent, ImmutableList } from '@table-games-engine/core';
9
+ /**
10
+ * In-memory `EngineAdapter`. Methods resolve immediately via `Promise.resolve`;
11
+ * no I/O is performed.
12
+ *
13
+ * Accepts an optional `now` function for deterministic lease testing.
14
+ */
15
+ export declare class InMemoryAdapter implements EngineAdapter {
16
+ private readonly matches;
17
+ private readonly now;
18
+ private closed;
19
+ constructor(now?: () => number);
20
+ private getOrCreate;
21
+ persistSnapshot(matchId: MatchId, state: MatchState, checksum: string): Promise<void>;
22
+ loadSnapshot(matchId: MatchId, atVersion?: StateVersion): Promise<MatchState | null>;
23
+ appendEvents(matchId: MatchId, transitionVersion: StateVersion, events: ImmutableList<GameEvent>): Promise<void>;
24
+ loadEvents(matchId: MatchId, fromVersion: StateVersion, toVersion: StateVersion): Promise<ImmutableList<GameEvent>>;
25
+ acquireOwnership(matchId: MatchId, ownerNode: string, leaseSeconds: number): Promise<boolean>;
26
+ releaseOwnership(matchId: MatchId, ownerNode: string): Promise<void>;
27
+ close(): Promise<void>;
28
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * @fileoverview Public barrel for `@table-games-engine/persistence`.
3
+ */
4
+ export { InMemoryAdapter } from './in-memory.js';
5
+ export { checksumState } from './checksum.js';
6
+ export { SqliteAdapter } from './sqlite/adapter.js';
7
+ export type { SqliteAdapterOptions } from './sqlite/adapter.js';
8
+ export { replayMatch, loadEventsBetween } from './replay.js';
9
+ export { everyNTransitions, everyTTicks, always, never, combine, } from './snapshots.js';
10
+ export type { SnapshotPolicy } from './snapshots.js';
11
+ export { createPersistedEngine } from './persisted-engine.js';
12
+ export type { PersistedEngine } from './persisted-engine.js';