diff --git a/Dockerfile b/Dockerfile index a8025f0..fbcc2bb 100644 --- a/Dockerfile +++ b/Dockerfile @@ -42,7 +42,9 @@ RUN echo "OS patches as of ${OS_PATCHES}" \ && apt-get update \ && apt-get upgrade -y \ && rm -rf /var/lib/apt/lists/* \ - && useradd --system --uid 10001 --no-create-home bela + && useradd --system --uid 10001 --no-create-home bela \ + # The open rooms are saved here across restarts; mount a volume on it (docker-compose.yml) to keep them. + && mkdir /data && chown bela:bela /data WORKDIR /app COPY --from=build /src/server/build/install/server ./server @@ -50,6 +52,7 @@ COPY --from=build /src/web/build/dist/wasmJs/productionExecutable ./web ENV PORT=8080 \ WEB_ROOT=/app/web \ + DATA_DIR=/data \ JAVA_OPTS="-XX:MaxRAMPercentage=75 -XX:+UseSerialGC -XX:+ExitOnOutOfMemoryError" USER bela EXPOSE 8080 diff --git a/README.md b/README.md index f975da8..c0d95c1 100644 --- a/README.md +++ b/README.md @@ -76,13 +76,16 @@ S početnog ekrana ("Trening brojanja"). Svaka runda je hrpa osvojenih štihova 3. Server vodi cijelu partiju (`engine`) i svakom igraču šalje samo njegov pogled: svoje karte, za ostale samo broj karata. Tempo je isti kao lokalno (`Pacing`). 4. Kad veza pukne, igrač se vraća na svoje mjesto (kod sobe i token se pamte, pa radi i nakon zatvaranja aplikacije ili osvježavanja stranice). Ako ne stigne za 10 s, za njega igra računalo dok se ne vrati; nakon 10 minuta gubi mjesto. Sljedeća ruka kreće kad su svi spojeni igrači spremni. -Sobe su u memoriji servera: ponovno pokretanje servera prekida partije u tijeku. +Ponovno pokretanje servera (nova verzija, restart računala) ne prekida partije. Server zapisuje otvorene sobe u `$DATA_DIR/rooms.json`: svakih nekoliko sekundi kad se nešto promijeni i još jednom kad se gasi (`docker stop` šalje SIGTERM). Pri pokretanju ih učita prije nego što primi prvu vezu. Klijenti se sami ponovno spoje i nastave s istim kartama i rezultatom; računalo ih čeka 30 s prije nego što odigra umjesto njih. Spremljene sobe starije od 10 minuta se ne učitavaju. Ako `DATA_DIR` nije postavljen (npr. `gradlew :server:run`), sobe žive samo u memoriji. + +- Spremanje i učitavanje: `server/.../RoomStore.kt` (datoteka), `Rooms.kt` (kada), `Room.kt` (`snapshot`, `restore`). Partija se sprema kao sjeme i popis poteza (`GameRecord`, isti zapis kao spremljena lokalna igra) i ponovno odigra pri učitavanju. +- Ako se pravila u novoj verziji promijene tako da se stara partija ne može ponovno odigrati, soba ostaje, ali bez partije: igrači se vrate u čekaonicu i domaćin pokrene novu. ## Server, Docker i Gitea Actions Jedna Docker slika (`Dockerfile`) gradi web i server (uz testove) i pokreće server koji poslužuje web na `/`, igru na `/ws` i `/health`. Gitea Actions (`.gitea/workflows/release.yml`, isto kao Keep) na svaki push na `main` gradi sliku, skenira je Trivyjem i objavljuje kao `git.mariosem.es/msemes/bela:` i `:latest`. Za objavu repozitorij treba tajnu `REGISTRY_TOKEN` (osobni token s `write:package`). -Postavljanje: `docker compose pull && docker compose up -d` s `docker-compose.yml` iz repozitorija. TLS i domenu `bela.mariosem.es` rješava vanjski ingress, koji mora propuštati WebSocket na `/ws`. +Postavljanje: `docker compose pull && docker compose up -d` s `docker-compose.yml` iz repozitorija. TLS i domenu `bela.mariosem.es` rješava vanjski ingress, koji mora propuštati WebSocket na `/ws`. Sobe se čuvaju na imenovanom volumenu `bela-data` (`/data` u kontejneru, vlasnik je korisnik `bela`, uid 10001). Ako umjesto njega montiraš mapu s hosta, ta mapa mora biti zapisiva za uid 10001; inače server javi upozorenje u logu i radi dalje, samo bez spremanja. ## Izdanja i ažuriranje diff --git a/docker-compose.yml b/docker-compose.yml index f030ad4..790e278 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,8 +1,11 @@ # Bela — single-container deployment at bela.mariosem.es. # One image serves the web app and runs the game server (online rooms over WebSocket /ws). External # ingress/TLS is handled outside this compose: route https://bela.mariosem.es to this port and allow -# WebSocket upgrades on /ws. Rooms live in memory: a restart ends the games in progress (players see -# "Soba više ne postoji" and open a new room). +# WebSocket upgrades on /ws. +# +# Restarts and new releases do not end games: the server saves the open rooms to /data (the bela-data +# volume) while it runs and when it stops, and loads them on start; players reconnect to their seats +# within a few seconds. Without the volume, a restart ends the games in progress. # # Deploy: `docker compose pull && docker compose up -d` (the image is built and published to the Gitea # registry by .gitea/workflows/release.yml). To build locally instead: @@ -20,8 +23,12 @@ services: options: max-size: "10m" max-file: "3" + # Time to save the rooms on `docker compose down` or a redeploy (it takes well under a second). + stop_grace_period: 15s environment: PORT: "8080" + volumes: + - bela-data:/data ports: - "${PORT:-8080}:8080" healthcheck: @@ -30,3 +37,6 @@ services: timeout: 5s retries: 5 start_period: 20s + +volumes: + bela-data: diff --git a/server/src/main/kotlin/hr/bela/server/Main.kt b/server/src/main/kotlin/hr/bela/server/Main.kt index 81eabbb..23d9268 100644 --- a/server/src/main/kotlin/hr/bela/server/Main.kt +++ b/server/src/main/kotlin/hr/bela/server/Main.kt @@ -6,6 +6,7 @@ import hr.bela.protocol.ServerMessage import io.ktor.http.CacheControl import io.ktor.http.ContentType import io.ktor.server.application.Application +import io.ktor.server.application.ApplicationStopping import io.ktor.server.application.install import io.ktor.server.engine.embeddedServer import io.ktor.server.http.content.CompressedFileType @@ -33,15 +34,23 @@ import kotlin.time.Duration.Companion.seconds * Environment: * PORT port to listen on (8080) * WEB_ROOT directory with the web app (web/build/dist/wasmJs/productionExecutable); /app/web in the image + * DATA_DIR where the open rooms are kept across restarts (rooms.json); /data in the image. Unset: rooms live + * in memory only, and a restart ends the games in progress. */ fun main() { val port = System.getenv("PORT")?.toIntOrNull() ?: 8080 val webRoot = File(System.getenv("WEB_ROOT") ?: "web") - embeddedServer(Netty, port = port) { bela(webRoot) }.start(wait = true) + val store = System.getenv("DATA_DIR")?.takeIf { it.isNotBlank() }?.let { RoomStore(File(it, "rooms.json")) } + // The engine stops on SIGTERM (docker stop) through Ktor's shutdown hook, which saves the rooms (ApplicationStopping). + embeddedServer(Netty, port = port) { bela(webRoot, store = store) }.start(wait = true) } -fun Application.bela(webRoot: File?, timing: Timing = Timing()) { - val rooms = Rooms(this, timing) +fun Application.bela(webRoot: File?, timing: Timing = Timing(), store: RoomStore? = null) { + val log = LoggerFactory.getLogger("bela") + if (store == null) log.info("No DATA_DIR: open rooms will not survive a restart") else log.info("Open rooms are kept in {}", store.file) + // Loaded here, before the server takes connections, so returning players find their rooms. + val rooms = Rooms(this, timing, store = store) + monitor.subscribe(ApplicationStopping) { rooms.stop() } install(CallLogging) { level = Level.INFO @@ -143,7 +152,7 @@ fun Application.bela(webRoot: File?, timing: Timing = Timing()) { } } } else { - LoggerFactory.getLogger("bela").warn("No web app at {}; serving the game server only", webRoot?.absolutePath) + log.warn("No web app at {}; serving the game server only", webRoot?.absolutePath) } } } diff --git a/server/src/main/kotlin/hr/bela/server/Room.kt b/server/src/main/kotlin/hr/bela/server/Room.kt index 7ce6cb4..8c779ab 100644 --- a/server/src/main/kotlin/hr/bela/server/Room.kt +++ b/server/src/main/kotlin/hr/bela/server/Room.kt @@ -3,6 +3,7 @@ package hr.bela.server import hr.bela.engine.Action import hr.bela.engine.Bela import hr.bela.engine.BotStrategy +import hr.bela.engine.GameRecord import hr.bela.engine.GameState import hr.bela.engine.HeuristicBot import hr.bela.engine.Pacing @@ -38,6 +39,10 @@ data class Timing( /** A player away for this long loses their seat (a bot keeps playing it meanwhile). */ val dropAfter: Long = 10 * 60_000L, val sweepEvery: Long = 30_000L, + /** After a restart, players get this long to reconnect before bots play their seats. */ + val restoreGrace: Long = 30_000L, + /** How often the open rooms are written to disk (when something changed). */ + val saveEvery: Long = 5_000L, ) /** A person in a room. [token] proves it is them when they come back after a lost connection. */ @@ -52,12 +57,16 @@ class Member(val token: String, val name: String, var seat: Int) { * * Online games keep the rhythm of the local game: bots wait before every move, and after a trick or a trump call * the table is locked for as long as the clients show it ([Timing]). + * + * A room from before a restart starts from [saved]: the same people and tokens, all of them away until they + * reconnect, and the game replayed from its record. */ class Room( val code: String, private val scope: CoroutineScope, private val timing: Timing, private val onClosed: (Room) -> Unit, + saved: SavedRoom? = null, private val clock: () -> Long = System::currentTimeMillis, private val bot: BotStrategy = HeuristicBot, ) { @@ -76,6 +85,17 @@ class Room( private var host: Member? = null private var game: GameState? = null + /** The game as its seed and moves, which is how it is saved. */ + private var record: GameRecord? = null + + /** The room as it would be saved, as of the last event; read from outside the room ([Rooms] saving). */ + @Volatile + var snapshot: SavedRoom = SavedRoom(code, emptyList()) + private set + + /** Bots wait for the players until then (they reconnect after a restart). */ + private var graceUntil = 0L + /** No moves until then: a finished trick or a trump call is on show. */ private var lockedUntil = 0L @@ -93,6 +113,8 @@ class Room( private val sweeper: Job init { + if (saved != null) restore(saved) + snapshot = snapshotNow() scope.launch { for (event in events) { try { @@ -100,6 +122,7 @@ class Room( } catch (e: Exception) { log.error("Event failed: $event", e) } + snapshot = snapshotNow() } } sweeper = scope.launch { @@ -260,7 +283,9 @@ class Room( // ------------------------------------------------------------ game private fun startGame() { - game = Bela.newGame() + val game = Bela.newGame() + this.game = game + record = GameRecord(game.seed) ready.clear() lockedUntil = 0 dealPauseGiven = null @@ -274,6 +299,7 @@ class Room( val before = game ?: return val after = before.apply(action) game = after + record = record?.plus(action) val now = clock() if (action is Action.Play && after.hand.tricks.size > before.hand.tricks.size) { lockedUntil = now + timing.trickPause @@ -310,8 +336,8 @@ class Room( val deal = game.seed to game.hand.number if (game.phase == Phase.BIDDING && game.hand.bids.isEmpty() && dealPauseGiven != deal) at += timing.dealPause at += if (game.phase == Phase.BIDDING) timing.bidDelay else timing.playDelay - // A player who just lost the connection (a reload, a tunnel) gets a moment to come back first. - memberAt(seat)?.let { away -> at = max(at, away.awaySince + timing.botTakeover) } + // A player who just lost the connection (a reload, a tunnel, a restart) gets a moment to come back first. + memberAt(seat)?.let { away -> at = maxOf(at, away.awaySince + timing.botTakeover, graceUntil) } plannedAt = at } val tick = Event.Tick(generation) @@ -334,6 +360,32 @@ class Room( act(action) } + // ------------------------------------------------------------ saving + + private fun snapshotNow(): SavedRoom = SavedRoom( + code = code, + members = members.map { SavedMember(it.token, it.name, it.seat, if (it.connection == null) it.awaySince else 0) }, + host = host?.token, + game = record?.encode(), + ) + + private fun restore(saved: SavedRoom) { + val now = clock() + for (m in saved.members) { + require(m.seat in 0..3 && memberAt(m.seat) == null && members.none { it.token == m.token }) { "Bad seat ${m.seat}" } + members += Member(m.token, Protocol.cleanName(m.name), m.seat).also { + it.awaySince = if (m.awaySince > 0) m.awaySince else now + } + } + host = members.find { it.token == saved.host } ?: members.firstOrNull() + val record = saved.game?.let { GameRecord.decode(it) ?: error("Unreadable game") } + // The rules may have changed since the game was saved; then the game cannot go on, but the room can. + game = record?.let { runCatching { it.replay() }.onFailure { e -> log.warn("Game not restored: {}", e.message) }.getOrNull() } + this.record = record.takeIf { game != null } + graceUntil = now + timing.restoreGrace + log.info("Restored with {} player(s){}", members.size, if (game != null) ", game in progress" else "") + } + // ------------------------------------------------------------ sending private fun seatInfos(): List = (0..3).map { seat -> diff --git a/server/src/main/kotlin/hr/bela/server/RoomStore.kt b/server/src/main/kotlin/hr/bela/server/RoomStore.kt new file mode 100644 index 0000000..0b79281 --- /dev/null +++ b/server/src/main/kotlin/hr/bela/server/RoomStore.kt @@ -0,0 +1,69 @@ +package hr.bela.server + +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.Json +import org.slf4j.LoggerFactory +import java.io.File +import java.nio.file.Files +import java.nio.file.StandardCopyOption + +/** A player's seat as saved: [awaySince] is 0 for a player who was connected. */ +@Serializable +data class SavedMember(val token: String, val name: String, val seat: Int, val awaySince: Long = 0) + +/** A room as saved: its people, the host (by token) and the game so far ([hr.bela.engine.GameRecord.encode]). */ +@Serializable +data class SavedRoom( + val code: String, + val members: List, + val host: String? = null, + val game: String? = null, +) + +@Serializable +data class SavedRooms(val version: Int = VERSION, val savedAt: Long, val rooms: List) { + companion object { + const val VERSION = 1 + } +} + +/** + * The open rooms on disk, so a restart (a new release) does not end the games in progress: the server writes them + * while it runs and when it stops, and reads them back when it starts. One small JSON file. + */ +class RoomStore(val file: File) { + private val log = LoggerFactory.getLogger("store") + private val json = Json { ignoreUnknownKeys = true } + + /** What was saved, or null when there is nothing (or nothing usable) to read. */ + fun load(): SavedRooms? { + if (!file.exists()) return null + return try { + val saved = json.decodeFromString(SavedRooms.serializer(), file.readText()) + if (saved.version == SavedRooms.VERSION) { + saved + } else { + log.warn("{} is from another version; starting without saved rooms", file) + null + } + } catch (e: Exception) { + // Keep the file for a look, out of the way of the next save. + val aside = File(file.path + ".bad") + log.warn("Could not read {} ({}); moved to {}", file, e.message, aside.name) + runCatching { Files.move(file.toPath(), aside.toPath(), StandardCopyOption.REPLACE_EXISTING) } + null + } + } + + /** Writes [rooms] in one step: a crash mid-write leaves the previous file whole. */ + fun save(rooms: SavedRooms) { + file.parentFile?.mkdirs() + val temp = File(file.path + ".tmp") + temp.writeText(json.encodeToString(SavedRooms.serializer(), rooms)) + try { + Files.move(temp.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE) + } catch (_: java.nio.file.AtomicMoveNotSupportedException) { + Files.move(temp.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING) + } + } +} diff --git a/server/src/main/kotlin/hr/bela/server/Rooms.kt b/server/src/main/kotlin/hr/bela/server/Rooms.kt index 5da6b6d..1215d4b 100644 --- a/server/src/main/kotlin/hr/bela/server/Rooms.kt +++ b/server/src/main/kotlin/hr/bela/server/Rooms.kt @@ -7,24 +7,53 @@ import io.ktor.websocket.DefaultWebSocketSession import io.ktor.websocket.Frame import io.ktor.websocket.close import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.delay +import kotlinx.coroutines.isActive import kotlinx.coroutines.job import kotlinx.coroutines.launch import org.slf4j.LoggerFactory import java.security.SecureRandom import java.util.concurrent.ConcurrentHashMap -/** All open rooms, by code. */ -class Rooms(parent: CoroutineScope, private val timing: Timing = Timing(), private val maxRooms: Int = 2000) { +/** + * All open rooms, by code. With a [store], the rooms outlive a restart: they are read back on start, written every + * [Timing.saveEvery] while something changes, and written once more by [stop]. + */ +class Rooms( + parent: CoroutineScope, + private val timing: Timing = Timing(), + private val maxRooms: Int = 2000, + private val store: RoomStore? = null, + private val clock: () -> Long = System::currentTimeMillis, +) { private val log = LoggerFactory.getLogger("rooms") private val scope = CoroutineScope(parent.coroutineContext + SupervisorJob(parent.coroutineContext.job)) private val rooms = ConcurrentHashMap() private val random = SecureRandom() + /** What the store holds (the rooms of the last write) and when it was written. */ + private var written: List? = null + private var writtenAt = 0L + private var stopped = false + private var failing = false + val size: Int get() = rooms.size + init { + if (store != null) { + store.load()?.let(::restore) + scope.launch(Dispatchers.IO) { + while (isActive) { + delay(timing.saveEvery) + save(force = false) + } + } + } + } + operator fun get(code: String): Room? = rooms[code] /** A new empty room, or null when the server already has [maxRooms]. */ @@ -34,20 +63,85 @@ class Rooms(parent: CoroutineScope, private val timing: Timing = Timing(), priva val code = (1..Protocol.CODE_LENGTH).map { Protocol.CODE_ALPHABET[random.nextInt(Protocol.CODE_ALPHABET.length)] } .joinToString("") if (rooms.containsKey(code)) return@repeat - val roomScope = CoroutineScope(scope.coroutineContext + SupervisorJob(scope.coroutineContext.job)) - // A closed room finishes its own coroutines (it drains its queue, so nobody waits on it forever). - val room = Room(code, roomScope, timing, onClosed = { closed -> - rooms.remove(closed.code, closed) - log.info("Room {} closed ({} open)", closed.code, rooms.size) - }) - if (rooms.putIfAbsent(code, room) == null) { + val room = open(code, saved = null) + if (room != null) { log.info("Room {} opened ({} open)", code, rooms.size) return room } - roomScope.coroutineContext.job.cancel() } return null } + + /** Writes the rooms one last time; the server is stopping. */ + fun stop() { + if (store == null) return + if (save(force = true)) log.info("Saved {} room(s) for the restart", written?.size ?: 0) + synchronized(this) { stopped = true } + } + + private fun open(code: String, saved: SavedRoom?): Room? { + val roomScope = CoroutineScope(scope.coroutineContext + SupervisorJob(scope.coroutineContext.job)) + // A closed room finishes its own coroutines (it drains its queue, so nobody waits on it forever). + val room = try { + Room(code, roomScope, timing, saved = saved, onClosed = { closed -> + rooms.remove(closed.code, closed) + log.info("Room {} closed ({} open)", closed.code, rooms.size) + }) + } catch (e: Exception) { + roomScope.coroutineContext.job.cancel() + throw e + } + if (rooms.putIfAbsent(code, room) == null) return room + roomScope.coroutineContext.job.cancel() + return null + } + + private fun restore(saved: SavedRooms) { + // Players away that long would have lost their seats anyway. + if (clock() - saved.savedAt > timing.dropAfter) { + log.info("Saved rooms are from {} min ago; not restoring them", (clock() - saved.savedAt) / 60_000) + return + } + var games = 0 + for (room in saved.rooms) { + if (Protocol.cleanCode(room.code) != room.code || room.members.isEmpty()) continue + try { + val restored = open(room.code, room) ?: continue + if (restored.snapshot.game != null) games++ + } catch (e: Exception) { + log.warn("Room {} not restored: {}", room.code, e.message) + } + } + log.info("Restored {} room(s), {} with a game in progress", rooms.size, games) + } + + /** + * Writes the rooms when they changed since the last write (or it is a minute old, to keep [SavedRooms.savedAt] + * fresh). True if the store holds the current rooms. + */ + private fun save(force: Boolean): Boolean { + val store = store ?: return false + synchronized(this) { + if (stopped) return false + val now = clock() + val snapshot = rooms.values.map { it.snapshot }.filter { it.members.isNotEmpty() }.sortedBy { it.code } + val stale = snapshot.isNotEmpty() && now - writtenAt >= 60_000 + if (!force && snapshot == written && !stale) return true + return try { + store.save(SavedRooms(savedAt = now, rooms = snapshot)) + written = snapshot + writtenAt = now + if (failing) log.info("Saving the rooms to {} works again", store.file) + failing = false + true + } catch (e: Exception) { + // Once, not every few seconds: the games go on, they just would not survive a restart. + if (!failing) log.warn("Could not save the rooms to {}: {}", store.file, e.toString()) + failing = true + false + } + } + } } /** diff --git a/server/src/test/kotlin/hr/bela/server/ServerTest.kt b/server/src/test/kotlin/hr/bela/server/ServerTest.kt index e4a13ce..e6a0f1a 100644 --- a/server/src/test/kotlin/hr/bela/server/ServerTest.kt +++ b/server/src/test/kotlin/hr/bela/server/ServerTest.kt @@ -2,6 +2,7 @@ package hr.bela.server import hr.bela.engine.Phase import hr.bela.engine.Suit +import hr.bela.engine.TableView import hr.bela.protocol.ClientMessage import hr.bela.protocol.Protocol import hr.bela.protocol.ServerMessage @@ -19,9 +20,13 @@ import kotlinx.coroutines.async import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.withTimeout import org.junit.Test +import java.io.File +import java.nio.file.Files import kotlin.test.assertEquals +import kotlin.test.assertFalse import kotlin.test.assertIs import kotlin.test.assertNotNull +import kotlin.test.assertNull import kotlin.test.assertTrue class ServerTest { @@ -48,10 +53,15 @@ class ServerTest { } } - /** Plays as a simple human until the game is over: the first legal card, trump only when it must. */ - private suspend fun DefaultClientWebSocketSession.playUntilGameOver(): ServerMessage.Table { + /** + * Plays as a simple human until the game is over: the first legal card, trump only when it must. [first] is a + * table already received (it may be our turn on it). + */ + private suspend fun DefaultClientWebSocketSession.playUntilGameOver(first: ServerMessage.Table? = null): ServerMessage.Table { + var next = first while (true) { - val table = expect() + val table = next ?: expect() + next = null val view = table.view assertTrue(view.myCards.size <= view.cardCounts[0], "only your own cards are sent") when { @@ -119,7 +129,8 @@ class ServerTest { // Ivo sits at seat 2, so in his view the host (Ana) is his partner across the table. assertEquals("Ana", first.view.seats[2].name) assertTrue(first.view.seats[1].bot && first.view.seats[3].bot) - withTimeout(120_000) { playUntilGameOver() } + // Ivo may call first (the dealer is random): his first table counts. + withTimeout(120_000) { playUntilGameOver(first) } } } host.await() @@ -156,4 +167,58 @@ class ServerTest { assertTrue(error.fatal, "the room closed when its last player left") } } + + @Test + fun aGameInProgressSurvivesARestart() { + val store = RoomStore(File(Files.createTempDirectory("bela").toFile(), "rooms.json")) + var code = "" + var token = "" + var before: TableView? = null + testApplication { + application { bela(webRoot = null, timing = fast, store = store) } + val ws = createClient { install(WebSockets) } + ws.webSocket("/ws") { + send(ClientMessage.CreateRoom("Ana")) + val joined = expect() + code = joined.code + token = joined.token + send(ClientMessage.Start) + // Call trump when asked, then stop on our first card: the game waits for us from then on. + withTimeout(30_000) { + while (before == null) { + val view = expect().view + when { + view.toAct != 0 -> Unit + view.phase == Phase.BIDDING -> send(ClientMessage.Call(Suit.HERC)) + view.phase == Phase.PLAYING -> before = view + } + } + } + } + } // the server stops (a new release): the rooms are written to the store + assertTrue(store.file.exists()) + testApplication { + application { bela(webRoot = null, timing = fast, store = store) } + val ws = createClient { install(WebSockets) } + ws.webSocket("/ws") { + send(ClientMessage.Resume(code, token)) + assertEquals(code, expect().code) + assertTrue(expect().room.playing) + assertEquals(before, expect().view, "the same table: hand, trick, score, our cards") + send(ClientMessage.Play(before!!.legalMoves.first())) + withTimeout(120_000) { playUntilGameOver() } + } + } + } + + @Test + fun anUnreadableStoreIsSetAside() { + val store = RoomStore(File(Files.createTempDirectory("bela").toFile(), "rooms.json")) + store.file.writeText("{ not json") + assertNull(store.load()) + assertFalse(store.file.exists()) + assertTrue(File(store.file.path + ".bad").exists()) + store.save(SavedRooms(savedAt = 1, rooms = listOf(SavedRoom("T2UT", listOf(SavedMember("t", "Ana", 0)))))) + assertEquals("Ana", store.load()?.rooms?.single()?.members?.single()?.name) + } }