turnbase-session 0.1.0

The Session port for Turnbase: in-memory and file-backed hosts behind one request/response interface
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
//! [`FileSession`]: a stateless, file-backed adapter over [`LocalSession`].
//!
//! Not itself a [`Session`] implementation: it is a thin adapter that, per
//! call, loads a [`LocalSession`] from a JSON save file, submits one typed
//! request, and (only if an action was applied) saves it back. This is the
//! shape a headless CLI drives: one process invocation per request, with the
//! whole game resumed from a single self-describing file.
//!
//! Only the *state* (plus the version and chance sampler) is serialized into
//! the save file; the typed request and response pass through unserialized.
//! Actions and views only ever need serializing at a real wire boundary, which
//! is a future transport's job.

use std::fmt;
use std::io;
use std::path::{Path, PathBuf};

use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use turnbase::{Game, PlayerId, Prng};
use turnbase_protocol::{PROTOCOL_VERSION, Request, Response};

use crate::{LocalSession, Session};

/// The on-disk envelope: everything needed to resume a game from one file.
///
/// It stores the [`Game`] value (its per-match configuration, e.g. player
/// count) alongside the state, so a resumed session cannot drift from the
/// config it was created with, and `query`/`act` need no configuration flags
/// of their own. `chance` is the committed-chance sampler's position, so deck
/// deals resolved across separate invocations do not resample. `protocol_version`
/// is stamped so a stale save fails fast on an explicit check (see
/// [`Error::ProtocolMismatch`]).
#[derive(Serialize, Deserialize)]
#[serde(bound(
    serialize = "G: Serialize, G::State: Serialize",
    deserialize = "G: Deserialize<'de>, G::State: Deserialize<'de>"
))]
struct SaveFile<G: Game> {
    protocol_version: u32,
    version: u64,
    chance: Prng,
    game: G,
    state: G::State,
}

/// A stateless, file-backed adapter over [`LocalSession`]: create a save, then
/// query or drive it across separate process invocations.
pub struct FileSession;

impl FileSession {
    /// Creates a new save file holding `game` at `state`, its chance sampler
    /// seeded from `seed`, and returns its resolved path. Any chance node the
    /// opening position starts on is resolved before the save is written.
    /// Never overwrites an existing file.
    ///
    /// `path`'s `None` case generates one under the system temp directory, so
    /// a caller need not name a file up front.
    ///
    /// # Errors
    /// Returns [`Error::AlreadyExists`] if `path` is `Some` and a file is
    /// already there, or [`Error::Io`]/[`Error::Serde`] if writing fails.
    pub fn create<G>(
        game: G,
        path: Option<PathBuf>,
        state: G::State,
        seed: u64,
    ) -> Result<PathBuf, Error>
    where
        G: Game + Serialize,
        G::State: Serialize,
    {
        let path = path.unwrap_or_else(generate_temp_path);
        if path.exists() {
            return Err(Error::AlreadyExists(path));
        }
        let (game, state, version, chance) = LocalSession::new(game, state, seed).into_parts();
        write_save(
            &path,
            &SaveFile {
                protocol_version: PROTOCOL_VERSION,
                version,
                chance,
                game,
                state,
            },
        )?;
        Ok(path)
    }

    /// Loads the save at `path`, applies `request` for `player`, saves back if
    /// an action was applied, and returns the response.
    ///
    /// A [`Request::Query`] and a rejected action leave the file untouched;
    /// only a successful apply ([`Response::Ack`]) is persisted.
    ///
    /// # Errors
    /// Returns [`Error::NotFound`] if `path` does not exist,
    /// [`Error::ProtocolMismatch`] if the save was written by an incompatible
    /// protocol version, [`Error::Serde`] if it does not parse, or
    /// [`Error::Io`] if reading or writing fails.
    pub fn handle<G>(
        path: &Path,
        player: PlayerId,
        request: Request<G::Action>,
    ) -> Result<Response<G::View>, Error>
    where
        G: Game + Serialize + DeserializeOwned,
        G::State: Serialize + DeserializeOwned,
    {
        if !path.exists() {
            return Err(Error::NotFound(path.to_path_buf()));
        }
        let save: SaveFile<G> = read_save(path)?;
        let mut session = LocalSession::resume(save.game, save.state, save.version, save.chance);
        let response = session.submit(player, request);

        // Only an applied action changes state, version, or the chance sampler;
        // skip the write (and its serialization cost) on queries and rejects.
        if matches!(response, Response::Ack) {
            let (game, state, version, chance) = session.into_parts();
            write_save(
                path,
                &SaveFile {
                    protocol_version: PROTOCOL_VERSION,
                    version,
                    chance,
                    game,
                    state,
                },
            )?;
        }
        Ok(response)
    }
}

/// Errors from the file adapter itself.
///
/// Distinct from [`Response::Error`]: that is the *game* rejecting a request
/// (illegal action); these are the *file* misbehaving (missing, already
/// exists, unreadable, wrong protocol version).
#[derive(Debug)]
pub enum Error {
    /// [`FileSession::create`] was asked to write where a file already exists.
    AlreadyExists(PathBuf),
    /// [`FileSession::handle`] was asked to load a path with no file.
    NotFound(PathBuf),
    /// The save was written by an incompatible [`PROTOCOL_VERSION`].
    ProtocolMismatch {
        /// The version stamped in the save file.
        found: u32,
        /// The version this build understands.
        expected: u32,
    },
    /// Reading or writing the save file failed.
    Io(io::Error),
    /// The save file did not parse, or a state failed to serialize.
    Serde(serde_json::Error),
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::AlreadyExists(path) => write!(f, "session already exists at {}", path.display()),
            Self::NotFound(path) => write!(f, "no session found at {}", path.display()),
            Self::ProtocolMismatch { found, expected } => write!(
                f,
                "save file protocol version {found} is incompatible with {expected}"
            ),
            Self::Io(err) => write!(f, "session I/O error: {err}"),
            Self::Serde(err) => write!(f, "session data error: {err}"),
        }
    }
}

impl std::error::Error for Error {}

fn generate_temp_path() -> PathBuf {
    std::env::temp_dir().join(format!(
        "turnbase-{}-{}.json",
        std::process::id(),
        unique_nanos()
    ))
}

fn unique_nanos() -> u128 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_nanos()
}

fn read_save<G>(path: &Path) -> Result<SaveFile<G>, Error>
where
    G: Game + DeserializeOwned,
    G::State: DeserializeOwned,
{
    let bytes = std::fs::read(path).map_err(Error::Io)?;
    let save: SaveFile<G> = serde_json::from_slice(&bytes).map_err(Error::Serde)?;
    if save.protocol_version != PROTOCOL_VERSION {
        return Err(Error::ProtocolMismatch {
            found: save.protocol_version,
            expected: PROTOCOL_VERSION,
        });
    }
    Ok(save)
}

fn write_save<G>(path: &Path, save: &SaveFile<G>) -> Result<(), Error>
where
    G: Game + Serialize,
    G::State: Serialize,
{
    let bytes = serde_json::to_vec_pretty(save).map_err(Error::Serde)?;
    // Write to a sibling temp file then rename over the target, so a crash or a
    // concurrent reader never sees a half-written save (rename is atomic within
    // one filesystem).
    let tmp = path.with_extension(format!("tmp-{}-{}", std::process::id(), unique_nanos()));
    std::fs::write(&tmp, &bytes).map_err(Error::Io)?;
    std::fs::rename(&tmp, path).map_err(|err| {
        let _ = std::fs::remove_file(&tmp);
        Error::Io(err)
    })
}

#[cfg(test)]
mod tests {
    use super::{Error, FileSession};
    use serde::{Deserialize, Serialize};
    use turnbase::{ActivePlayers, Game, PlayerId};
    use turnbase_protocol::{Request, Response};

    const P0: PlayerId = PlayerId::new(0);
    const P1: PlayerId = PlayerId::new(1);

    /// Two seats alternately add 1 to a shared total; whoever reaches 3 wins.
    /// Only the game and its state need to serialize (for the save file); the
    /// action is passed typed, so `Bump` needs no serde derive.
    #[derive(Serialize, Deserialize)]
    struct CountToThree;

    #[derive(Clone, Copy, PartialEq, Eq, Debug)]
    struct Bump;

    impl Game for CountToThree {
        type State = u32;
        type Action = Bump;
        type View = u32;

        fn new_initial_state(&self, _seed: u64) -> Self::State {
            0
        }
        fn num_players(&self) -> usize {
            2
        }
        fn active_players(&self, state: &Self::State) -> ActivePlayers {
            if self.is_terminal(state) {
                ActivePlayers::none()
            } else {
                ActivePlayers::one(PlayerId::new(state % 2))
            }
        }
        fn legal_actions(&self, state: &Self::State, _player: PlayerId) -> Vec<Self::Action> {
            if self.is_terminal(state) {
                Vec::new()
            } else {
                vec![Bump]
            }
        }
        fn apply(&self, state: &mut Self::State, _player: PlayerId, _action: Self::Action) {
            *state += 1;
        }
        fn is_terminal(&self, state: &Self::State) -> bool {
            *state >= 3
        }
        fn reward(&self, state: &Self::State, player: PlayerId) -> f64 {
            let winner = (state + 1) % 2;
            if player.index() == winner { 1.0 } else { -1.0 }
        }
        fn view(&self, state: &Self::State, _viewer: Option<PlayerId>) -> Self::View {
            *state
        }
    }

    /// A pure-chance game: `CHANCE` reveals a value 0/1/2, then it is terminal.
    /// Serializable end to end so it can drive the file adapter.
    #[derive(Serialize, Deserialize)]
    struct Reveal;

    impl Game for Reveal {
        type State = Option<u8>;
        type Action = u8;
        type View = Option<u8>;

        fn new_initial_state(&self, _seed: u64) -> Self::State {
            None
        }
        fn num_players(&self) -> usize {
            0
        }
        fn active_players(&self, state: &Self::State) -> ActivePlayers {
            if state.is_some() {
                ActivePlayers::none()
            } else {
                ActivePlayers::one(PlayerId::CHANCE)
            }
        }
        fn legal_actions(&self, state: &Self::State, player: PlayerId) -> Vec<Self::Action> {
            if player.is_chance() && state.is_none() {
                vec![0, 1, 2]
            } else {
                Vec::new()
            }
        }
        fn apply(&self, state: &mut Self::State, _player: PlayerId, action: Self::Action) {
            *state = Some(action);
        }
        fn is_terminal(&self, state: &Self::State) -> bool {
            state.is_some()
        }
        fn reward(&self, _state: &Self::State, _player: PlayerId) -> f64 {
            0.0
        }
        fn view(&self, state: &Self::State, _viewer: Option<PlayerId>) -> Self::View {
            *state
        }
    }

    fn bump() -> Request<Bump> {
        Request::Act(Bump)
    }

    fn state_of(response: &Response<u32>) -> (u64, u32) {
        let Response::State { version, view } = response else {
            panic!("expected a State response, got {response:?}");
        };
        (*version, *view)
    }

    #[test]
    fn create_refuses_to_overwrite_an_existing_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("game.json");
        std::fs::write(&path, b"anything").unwrap();

        let result = FileSession::create(CountToThree, Some(path), 0, 0);
        assert!(matches!(result, Err(Error::AlreadyExists(_))));
    }

    #[test]
    fn handle_round_trips_state_and_bumps_version_only_on_apply() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("game.json");
        let path = FileSession::create(CountToThree, Some(path), 0, 0).unwrap();

        // A query is a no-op: version 0, total 0, file unchanged.
        let response = FileSession::handle::<CountToThree>(&path, P0, Request::Query).unwrap();
        assert_eq!(state_of(&response), (0, 0));

        // Applying an action acks and persists the bumped state.
        assert!(matches!(
            FileSession::handle::<CountToThree>(&path, P0, bump()).unwrap(),
            Response::Ack
        ));

        // Loading fresh from disk sees version 1 and total 1.
        let response = FileSession::handle::<CountToThree>(&path, P1, Request::Query).unwrap();
        assert_eq!(state_of(&response), (1, 1));
    }

    #[test]
    fn a_rejected_action_does_not_persist() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("game.json");
        let path = FileSession::create(CountToThree, Some(path), 0, 0).unwrap();

        // Seat 1 is not active first (total 0 -> seat 0), so this is rejected
        // and nothing is written.
        assert!(matches!(
            FileSession::handle::<CountToThree>(&path, P1, bump()).unwrap(),
            Response::Error(_)
        ));
        let response = FileSession::handle::<CountToThree>(&path, P0, Request::Query).unwrap();
        assert_eq!(state_of(&response), (0, 0), "version stayed at 0");
    }

    #[test]
    fn handle_errors_on_a_missing_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("missing.json");
        let result = FileSession::handle::<CountToThree>(&path, P0, Request::Query);
        assert!(matches!(result, Err(Error::NotFound(_))));
    }

    #[test]
    fn a_full_game_reaches_a_terminal_state_through_the_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("game.json");
        let path = FileSession::create(CountToThree, Some(path), 0, 0).unwrap();

        for round in 0..3 {
            let seat = PlayerId::new(round % 2);
            FileSession::handle::<CountToThree>(&path, seat, bump()).unwrap();
        }
        let response = FileSession::handle::<CountToThree>(&path, P0, Request::Query).unwrap();
        assert_eq!(
            state_of(&response),
            (3, 3),
            "three bumps, version 3, total 3"
        );
    }

    #[test]
    fn create_resolves_an_opening_chance_node_and_persists_it() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("chance.json");
        let path = FileSession::create(Reveal, Some(path), None, 5).unwrap();

        // The opening chance deal was resolved before the save was written, so
        // a fresh load already sees a terminal, revealed value at version 1.
        let response = FileSession::handle::<Reveal>(&path, P0, Request::Query).unwrap();
        let Response::State { version, view } = response else {
            panic!("expected a state response");
        };
        assert_eq!(version, 1);
        assert!(matches!(view, Some(0..=2)));
    }
}