diff --git a/app/src/main/java/cc/skysparkle/matewave/network/LineFraming.kt b/app/src/main/java/cc/skysparkle/matewave/network/LineFraming.kt new file mode 100644 index 0000000..4b74f08 --- /dev/null +++ b/app/src/main/java/cc/skysparkle/matewave/network/LineFraming.kt @@ -0,0 +1,26 @@ +package cc.skysparkle.matewave.network + +import java.io.Reader + +/** Result of reading one newline-delimited message from a socket. */ +sealed class LineResult { + data class Line(val text: String) : LineResult() + object TooLong : LineResult() + object EndOfStream : LineResult() +} + +/** Reads one line of at most [maxChars] characters; longer lines are reported, not buffered. */ +fun readBoundedLine(reader: Reader, maxChars: Int): LineResult { + val builder = StringBuilder() + while (true) { + val ch = reader.read() + if (ch == -1) { + return if (builder.isEmpty()) LineResult.EndOfStream + else LineResult.Line(builder.toString()) + } + if (ch == '\n'.code) return LineResult.Line(builder.toString()) + if (ch == '\r'.code) continue + if (builder.length >= maxChars) return LineResult.TooLong + builder.append(ch.toChar()) + } +} diff --git a/app/src/main/java/cc/skysparkle/matewave/spectate/FriendStatus.kt b/app/src/main/java/cc/skysparkle/matewave/spectate/FriendStatus.kt new file mode 100644 index 0000000..cd95801 --- /dev/null +++ b/app/src/main/java/cc/skysparkle/matewave/spectate/FriendStatus.kt @@ -0,0 +1,58 @@ +package cc.skysparkle.matewave.spectate + +enum class PresenceStatus { ONLINE, IN_GAME, OFFLINE } + +/** Where to watch a game: the host's address and spectator port. */ +data class SpectateTarget(val host: String, val port: Int, val gameTag: String) + +/** A player seen on the network, reduced to what spectating needs. */ +data class NearbyPlayerGame( + val playerId: String, + val host: String, + val gameTag: String, + val spectatePort: Int +) + +data class FriendGameStatus( + val status: PresenceStatus, + val target: SpectateTarget? = null, + /** Live count from the host, null until it has answered. */ + val spectators: Int? = null, + val max: Int = MAX_SPECTATORS +) { + val full: Boolean get() = spectators != null && spectators >= max +} + +/** + * Online, In game or Offline for one player, and where to watch. Both players of a game announce + * the same tag, but only the host serves spectators, so the guest's game is watched through the + * host. A host that says its game has ended overrides an announcement that is not updated yet. + */ +object FriendStatusResolver { + fun resolve( + playerId: String, + nearby: Map, + probes: Map + ): FriendGameStatus { + val player = nearby[playerId] ?: return FriendGameStatus(PresenceStatus.OFFLINE) + if (player.gameTag.isEmpty()) return FriendGameStatus(PresenceStatus.ONLINE) + val host = hostOf(player, nearby) ?: return FriendGameStatus(PresenceStatus.IN_GAME) + val target = SpectateTarget(host.host, host.spectatePort, host.gameTag) + val probe = probes[target] + if (probe != null && !probe.inGame) return FriendGameStatus(PresenceStatus.ONLINE) + return FriendGameStatus(PresenceStatus.IN_GAME, target, probe?.count, probe?.max ?: MAX_SPECTATORS) + } + + /** Every host worth asking for a live spectator count. */ + fun targets(nearby: Collection): Set = + nearby.filter { it.gameTag.isNotEmpty() && it.spectatePort > 0 && it.host.isNotEmpty() } + .map { SpectateTarget(it.host, it.spectatePort, it.gameTag) } + .toSet() + + private fun hostOf(player: NearbyPlayerGame, nearby: Map): NearbyPlayerGame? { + if (player.spectatePort > 0 && player.host.isNotEmpty()) return player + return nearby.values.firstOrNull { + it.playerId != player.playerId && it.gameTag == player.gameTag && it.spectatePort > 0 && it.host.isNotEmpty() + } + } +} diff --git a/app/src/main/java/cc/skysparkle/matewave/spectate/SpectatorAdvert.kt b/app/src/main/java/cc/skysparkle/matewave/spectate/SpectatorAdvert.kt new file mode 100644 index 0000000..157886c --- /dev/null +++ b/app/src/main/java/cc/skysparkle/matewave/spectate/SpectatorAdvert.kt @@ -0,0 +1,47 @@ +package cc.skysparkle.matewave.spectate + +/** + * What this device adds to its network announcement while it plays a watchable LAN game: a short + * tag shared by both players of the game, and, on the host, the spectator port. Older app versions + * ignore these attributes. + */ +object SpectatorAdvert { + const val KEY_GAME = "g" + const val KEY_PORT = "sp" + + data class State(val gameTag: String = "", val spectatePort: Int = 0) + + @Volatile var current = State() + private set + + /** Returns true when the announcement has to be published again. */ + @Synchronized + fun update(state: State): Boolean { + if (state == current) return false + current = state + return true + } + + fun clear(): Boolean = update(State()) + + fun attributes(state: State = current): Map = buildMap { + if (state.gameTag.isNotEmpty()) put(KEY_GAME, state.gameTag) + if (state.gameTag.isNotEmpty() && state.spectatePort > 0) put(KEY_PORT, state.spectatePort.toString()) + } + + /** Reads the attributes of a discovered player; anything malformed counts as absent. */ + fun parse(attribute: (String) -> String): State { + val tag = attribute(KEY_GAME).takeIf { TAG_PATTERN.matches(it) } ?: return State() + val port = attribute(KEY_PORT).toIntOrNull()?.takeIf { it in 1..65_535 } ?: 0 + return State(tag, port) + } + + /** Short tag of a game id, so the game id itself is not announced. */ + fun tagOf(gameId: String): String { + if (gameId.isEmpty()) return "" + val digest = java.security.MessageDigest.getInstance("SHA-256").digest(gameId.toByteArray(Charsets.UTF_8)) + return digest.take(4).joinToString("") { "%02x".format(it) } + } + + private val TAG_PATTERN = Regex("^[0-9a-f]{8}$") +} diff --git a/app/src/main/java/cc/skysparkle/matewave/spectate/SpectatorClient.kt b/app/src/main/java/cc/skysparkle/matewave/spectate/SpectatorClient.kt new file mode 100644 index 0000000..e544c18 --- /dev/null +++ b/app/src/main/java/cc/skysparkle/matewave/spectate/SpectatorClient.kt @@ -0,0 +1,189 @@ +package cc.skysparkle.matewave.spectate + +import cc.skysparkle.matewave.network.LineResult +import cc.skysparkle.matewave.network.readBoundedLine +import java.io.BufferedReader +import java.io.BufferedWriter +import java.io.IOException +import java.io.InputStreamReader +import java.io.OutputStreamWriter +import java.net.InetSocketAddress +import java.net.Socket +import java.util.concurrent.Executors +import java.util.concurrent.RejectedExecutionException + +/** + * One spectator's connection to a hosted game. Events arrive on a background thread, in order. + * Silence longer than [Timing.silenceTimeoutMs] (the host pings every few seconds) means the host + * is gone, which also covers Wi-Fi switching off on either side. + */ +class SpectatorClient( + private val host: String, + private val port: Int, + private val onEvent: (Event) -> Unit, + private val timing: Timing = Timing(), + private val version: Int = SpectatorProtocol.VERSION, + private val minVersion: Int = SpectatorProtocol.MIN_COMPATIBLE_VERSION +) { + data class Timing(val connectTimeoutMs: Int = 5_000, val silenceTimeoutMs: Int = 15_000) + + enum class Failure { UNREACHABLE, FULL, NO_GAME, UPDATE_THIS_APP, UPDATE_HOST_APP } + + sealed class Event { + data class Joined(val welcome: SpectatorMessage.Welcome) : Event() + data class Received(val message: SpectatorMessage) : Event() + data class JoinFailed(val failure: Failure) : Event() + + /** The connection ended after joining; [hostClosed] is true when the host said goodbye. */ + data class Disconnected(val hostClosed: Boolean) : Event() + } + + @Volatile private var socket: Socket? = null + @Volatile private var output: BufferedWriter? = null + @Volatile private var stopped = false + private val writer = Executors.newSingleThreadExecutor { r -> + Thread(r, "spectator-send").apply { isDaemon = true } + } + + fun start() { + Thread({ run() }, "spectator-receive").apply { isDaemon = true }.start() + } + + fun requestResync() = send(SpectatorMessage.Resync) + + fun stop() { + if (stopped) return + stopped = true + try { + writer.execute { + writeLine(SpectatorMessage.Leave) + closeSocket() + } + } catch (e: RejectedExecutionException) { + closeSocket() + } + writer.shutdown() + // A send stuck on a dead connection must not keep the socket open. + Thread({ + try { Thread.sleep(STOP_GRACE_MS) } catch (_: InterruptedException) {} + closeSocket() + }, "spectator-stop").apply { isDaemon = true }.start() + } + + private fun run() { + val s = Socket() + socket = s + val reader: BufferedReader + try { + if (stopped) throw IOException("Stopped") + s.tcpNoDelay = true + s.connect(InetSocketAddress(host, port), timing.connectTimeoutMs) + s.soTimeout = timing.silenceTimeoutMs + output = BufferedWriter(OutputStreamWriter(s.getOutputStream(), Charsets.UTF_8)) + reader = BufferedReader(InputStreamReader(s.getInputStream(), Charsets.UTF_8)) + } catch (e: IOException) { + closeSocket() + emit(Event.JoinFailed(Failure.UNREACHABLE)) + return + } + send(SpectatorMessage.Hello(minVersion)) + + var joined = false + var hostClosed = false + try { + while (!stopped) { + val read = readBoundedLine(reader, SpectatorProtocol.MAX_HOST_LINE_CHARS) + if (read !is LineResult.Line) break + val envelope = SpectatorProtocol.decode(read.text) ?: continue + val message = envelope.message + if (!joined) { + // reject keeps its shape across versions, so read it before the version gate. + if (message is SpectatorMessage.Reject) { + emit(Event.JoinFailed(failureOf(message))) + return + } + if (envelope.version < minVersion) { + emit(Event.JoinFailed(Failure.UPDATE_HOST_APP)) + return + } + if (message is SpectatorMessage.Welcome) { + joined = true + emit(Event.Joined(message)) + } + continue + } + when (message) { + null -> Unit + SpectatorMessage.Closing -> hostClosed = true + is SpectatorMessage.Ping -> { + send(SpectatorMessage.Pong) + emit(Event.Received(message)) + } + else -> emit(Event.Received(message)) + } + } + } catch (e: IOException) { + // Silence timeout or connection reset. + } finally { + closeSocket() + } + if (joined) emit(Event.Disconnected(hostClosed)) else emit(Event.JoinFailed(Failure.UNREACHABLE)) + } + + private fun failureOf(reject: SpectatorMessage.Reject): Failure = when (reject.reason) { + RejectReason.FULL -> Failure.FULL + RejectReason.NO_GAME -> Failure.NO_GAME + RejectReason.UPDATE_REQUIRED -> + if (version < reject.minVersion) Failure.UPDATE_THIS_APP else Failure.UPDATE_HOST_APP + RejectReason.OTHER -> Failure.UNREACHABLE + } + + private fun emit(event: Event) { + if (!stopped) onEvent(event) + } + + private fun send(message: SpectatorMessage) { + try { + writer.execute { writeLine(message) } + } catch (e: RejectedExecutionException) { + // Stopped. + } + } + + private fun writeLine(message: SpectatorMessage) { + val out = output ?: return + try { + out.write(SpectatorProtocol.encode(message, version)) + out.write("\n") + out.flush() + } catch (e: IOException) { + closeSocket() + } + } + + private fun closeSocket() { + try { socket?.close() } catch (_: IOException) {} + } + + private companion object { + const val STOP_GRACE_MS = 500L + } +} + +/** One-shot status query, used to show live spectator counts in the Friends list. */ +object SpectatorProbe { + fun query(host: String, port: Int, timeoutMs: Int = 2_000): SpectatorMessage.Status? = try { + Socket().use { s -> + s.connect(InetSocketAddress(host, port), timeoutMs) + s.soTimeout = timeoutMs + val out = s.getOutputStream() + out.write((SpectatorProtocol.encode(SpectatorMessage.StatusQuery) + "\n").toByteArray(Charsets.UTF_8)) + out.flush() + val reader = BufferedReader(InputStreamReader(s.getInputStream(), Charsets.UTF_8)) + val read = readBoundedLine(reader, SpectatorProtocol.MAX_HOST_LINE_CHARS) + (read as? LineResult.Line)?.let { SpectatorProtocol.decode(it.text)?.message as? SpectatorMessage.Status } + } + } catch (e: IOException) { + null + } +} diff --git a/app/src/main/java/cc/skysparkle/matewave/spectate/SpectatorGame.kt b/app/src/main/java/cc/skysparkle/matewave/spectate/SpectatorGame.kt new file mode 100644 index 0000000..53877c4 --- /dev/null +++ b/app/src/main/java/cc/skysparkle/matewave/spectate/SpectatorGame.kt @@ -0,0 +1,162 @@ +package cc.skysparkle.matewave.spectate + +import cc.skysparkle.matewave.engine.Board +import cc.skysparkle.matewave.engine.ChessEngine +import cc.skysparkle.matewave.engine.GameStatus +import cc.skysparkle.matewave.engine.Move +import cc.skysparkle.matewave.engine.Notation +import cc.skysparkle.matewave.engine.PieceColor +import cc.skysparkle.matewave.engine.opposite + +/** What a spectator sees of a game. */ +data class SpectatorView( + val gameId: String, + val white: SpectatorPlayer, + val black: SpectatorPlayer, + val startBoard: Board, + val board: Board, + val movesUci: List, + val moveSans: List, + val lastMove: Move?, + val initialSeconds: Int, + val incrementSeconds: Int, + val clock: SpectatorClock?, + val result: SpectatorResult? +) { + val ply: Int get() = movesUci.size +} + +/** + * The spectator's copy of the game, rebuilt from a snapshot and moved forward by live moves. Moves + * are checked against the rules; anything that does not follow on asks for a fresh snapshot. + */ +class SpectatorGame { + enum class Applied { APPLIED, IGNORED, NEEDS_RESYNC } + + var view: SpectatorView? = null + private set + + fun load(snapshot: SpectatorSnapshot): Boolean { + val start = Board.startPosition() + var board = start + val sans = ArrayList(snapshot.movesUci.size) + var last: Move? = null + for (uci in snapshot.movesUci) { + val move = resolve(board, uci) ?: return false + sans.add(Notation.toSan(board, move)) + board = ChessEngine.applyMove(board, move) + last = move + } + view = SpectatorView( + gameId = snapshot.gameId, + white = snapshot.white, + black = snapshot.black, + startBoard = start, + board = board, + movesUci = snapshot.movesUci, + moveSans = sans, + lastMove = last, + initialSeconds = snapshot.initialSeconds, + incrementSeconds = snapshot.incrementSeconds, + clock = snapshot.clock, + result = snapshot.result + ) + return true + } + + fun onMove(message: SpectatorMessage.MovePlayed): Applied { + val current = view ?: return Applied.NEEDS_RESYNC + if (message.gameId != current.gameId) return Applied.NEEDS_RESYNC + if (current.result != null || message.ply <= current.ply) return Applied.IGNORED + if (message.ply != current.ply + 1) return Applied.NEEDS_RESYNC + val move = resolve(current.board, message.uci) ?: return Applied.NEEDS_RESYNC + view = current.copy( + board = ChessEngine.applyMove(current.board, move), + movesUci = current.movesUci + move.toUci(), + moveSans = current.moveSans + Notation.toSan(current.board, move), + lastMove = move, + clock = message.clock ?: current.clock + ) + return Applied.APPLIED + } + + fun onGameOver(message: SpectatorMessage.GameOver): Applied { + val current = view ?: return Applied.NEEDS_RESYNC + if (message.gameId != current.gameId) return Applied.NEEDS_RESYNC + view = current.copy( + result = message.result, + clock = (message.clock ?: current.clock)?.copy(running = null) + ) + return Applied.APPLIED + } + + fun onClock(clock: SpectatorClock?) { + val current = view ?: return + if (clock == null || current.result != null) return + view = current.copy(clock = clock) + } + + private fun resolve(board: Board, uci: String): Move? { + if (uci.length !in 4..5) return null + val candidate = runCatching { Move.fromUci(uci) }.getOrNull() ?: return null + if (candidate.from !in 0..63 || candidate.to !in 0..63) return null + val matches = ChessEngine.legalMoves(board).filter { it.from == candidate.from && it.to == candidate.to } + return matches.firstOrNull { it.promotion == candidate.promotion } ?: matches.firstOrNull() + } +} + +/** Turns successive host snapshots into the messages spectators need to follow along. */ +object SpectatorDiff { + fun between(old: SpectatorSnapshot?, new: SpectatorSnapshot): List { + if (old == null) return emptyList() + if (old.gameId != new.gameId || old.white != new.white || old.black != new.black) { + return listOf(SpectatorMessage.NewGame(new)) + } + val events = ArrayList() + val before = old.movesUci + val after = new.movesUci + if (after != before) { + if (after.size <= before.size || after.subList(0, before.size) != before) { + return listOf(SpectatorMessage.NewGame(new)) + } + for (i in before.size until after.size) { + val isLast = i == after.lastIndex + events += SpectatorMessage.MovePlayed(new.gameId, i + 1, after[i], if (isLast) new.clock else null) + } + } + when { + old.result == null && new.result != null -> events += SpectatorMessage.GameOver(new.gameId, new.result, new.clock) + old.result != null && new.result != old.result -> return listOf(SpectatorMessage.NewGame(new)) + } + return events + } +} + +/** Result of a finished game as spectators are told it. */ +object SpectatorResults { + fun of( + status: GameStatus, + sideToMove: PieceColor, + timedOutSide: PieceColor?, + resignedSide: PieceColor?, + leftMidGame: Boolean + ): SpectatorResult? = when (status) { + GameStatus.ONGOING -> null + GameStatus.CHECKMATE -> SpectatorResult(SpectatorOutcome.CHECKMATE, sideToMove.opposite()) + GameStatus.STALEMATE -> SpectatorResult(SpectatorOutcome.STALEMATE, null) + GameStatus.DRAW_50_MOVES -> SpectatorResult(SpectatorOutcome.FIFTY_MOVES, null) + GameStatus.DRAW_REPETITION -> SpectatorResult(SpectatorOutcome.REPETITION, null) + GameStatus.DRAW_MATERIAL -> SpectatorResult(SpectatorOutcome.INSUFFICIENT_MATERIAL, null) + GameStatus.TIMEOUT -> SpectatorResult(SpectatorOutcome.TIMEOUT, timedOutSide?.opposite()) + GameStatus.TIMEOUT_DRAW -> SpectatorResult(SpectatorOutcome.TIMEOUT_DRAW, null) + GameStatus.RESIGNATION -> SpectatorResult( + if (leftMidGame) SpectatorOutcome.LEFT else SpectatorOutcome.RESIGNATION, + resignedSide?.opposite() + ) + GameStatus.DRAW_AGREEMENT -> SpectatorResult(SpectatorOutcome.AGREEMENT, null) + } + + fun leftBy(side: PieceColor) = SpectatorResult(SpectatorOutcome.LEFT, side.opposite()) + + val interrupted = SpectatorResult(SpectatorOutcome.INTERRUPTED, null) +} diff --git a/app/src/main/java/cc/skysparkle/matewave/spectate/SpectatorHub.kt b/app/src/main/java/cc/skysparkle/matewave/spectate/SpectatorHub.kt new file mode 100644 index 0000000..b316a53 --- /dev/null +++ b/app/src/main/java/cc/skysparkle/matewave/spectate/SpectatorHub.kt @@ -0,0 +1,364 @@ +package cc.skysparkle.matewave.spectate + +import cc.skysparkle.matewave.network.LineResult +import cc.skysparkle.matewave.network.readBoundedLine +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import java.io.BufferedReader +import java.io.BufferedWriter +import java.io.Closeable +import java.io.IOException +import java.io.InputStreamReader +import java.io.OutputStreamWriter +import java.net.InetAddress +import java.net.InetSocketAddress +import java.net.ServerSocket +import java.net.Socket +import java.net.SocketTimeoutException +import java.util.concurrent.ArrayBlockingQueue +import java.util.concurrent.Executors +import java.util.concurrent.RejectedExecutionException +import java.util.concurrent.ThreadFactory +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicInteger + +/** + * Runs on the host player's device and streams the game to up to [maxSpectators] spectators on + * its own listening socket; the players' connection is never touched. Each spectator gets its own + * bounded queue and writer thread, so a slow or vanished spectator is dropped without delaying + * the game or anyone else. Spectators can only listen: anything they send besides keepalives and + * resync requests is ignored. + */ +class SpectatorHub( + private val maxSpectators: Int = MAX_SPECTATORS, + private val timing: Timing = Timing(), + private val log: (String) -> Unit = {} +) { + data class Timing( + val helloTimeoutMs: Int = 5_000, + val pingIntervalMs: Long = 5_000, + /** A spectator that answers no ping for this long is gone (e.g. its Wi-Fi went off). */ + val silenceTimeoutMs: Int = 20_000, + val queueCapacity: Int = 512 + ) + + private val lock = Any() + private val spectators = LinkedHashSet() + private var latest: SpectatorSnapshot? = null + private var latestAtNanos = 0L + private var closed = false + private var server: ServerSocket? = null + private val handshaking = AtomicInteger() + + private val threads = Executors.newCachedThreadPool(daemonThreads("spectator")) + private val ticker = Executors.newSingleThreadScheduledExecutor(daemonThreads("spectator-ping")) + + private val _count = MutableStateFlow(0) + val count: StateFlow = _count + + val port: Int get() = server?.localPort ?: 0 + + /** Opens the spectator socket on [bindAddress] (all interfaces by default) and returns its port. */ + fun start(bindAddress: InetAddress? = null): Int { + val socket = synchronized(lock) { + check(!closed) { "Hub is closed" } + server?.let { return it.localPort } + ServerSocket().also { + it.reuseAddress = true + it.bind(InetSocketAddress(bindAddress, 0)) + server = it + } + } + threads.execute { acceptLoop(socket) } + ticker.scheduleAtFixedRate( + { runCatching { sendPings() } }, + timing.pingIntervalMs, timing.pingIntervalMs, TimeUnit.MILLISECONDS + ) + return socket.localPort + } + + /** Replaces the current game state and sends [events] to every spectator, atomically. */ + fun publish(snapshot: SpectatorSnapshot, events: List = emptyList()) { + synchronized(lock) { + if (closed) return + latest = snapshot + latestAtNanos = System.nanoTime() + if (events.isEmpty() || spectators.isEmpty()) return + val targets = spectators.toList() + events.forEach { deliver(targets, SpectatorProtocol.encode(it)) } + } + } + + /** Sends [finalEvents] and a goodbye to everyone, then stops accepting and closes. */ + fun close(finalEvents: List = emptyList()) { + val targets = synchronized(lock) { + if (closed) return + closed = true + spectators.toList().also { spectators.clear() } + } + _count.value = 0 + val lines = finalEvents.map { SpectatorProtocol.encode(it) } + SpectatorProtocol.encode(SpectatorMessage.Closing) + targets.forEach { spectator -> + lines.forEach { spectator.offer(it) } + spectator.finish() + } + closeQuietly(server) + ticker.shutdownNow() + threads.shutdown() + } + + private fun acceptLoop(socket: ServerSocket) { + while (!socket.isClosed) { + val client = try { + socket.accept() + } catch (e: IOException) { + if (socket.isClosed) return + log("Spectator accept failed: ${e.message}") + continue + } + if (handshaking.incrementAndGet() > MAX_HANDSHAKING) { + handshaking.decrementAndGet() + closeQuietly(client) + continue + } + try { + threads.execute { serve(client) } + } catch (e: RejectedExecutionException) { + handshaking.decrementAndGet() + closeQuietly(client) + } + } + } + + private fun serve(client: Socket) { + var spectator: Spectator? = null + var reader: BufferedReader? = null + try { + client.tcpNoDelay = true + client.soTimeout = timing.helloTimeoutMs + reader = BufferedReader(InputStreamReader(client.getInputStream(), Charsets.UTF_8)) + val first = readBoundedLine(reader, SpectatorProtocol.MAX_CLIENT_LINE_CHARS) + val envelope = (first as? LineResult.Line)?.let { SpectatorProtocol.decode(it.text) } + when (envelope?.message) { + SpectatorMessage.StatusQuery -> reply(client, status()) + is SpectatorMessage.Hello -> { + if (envelope.version < SpectatorProtocol.MIN_COMPATIBLE_VERSION) { + log("Spectator with protocol ${envelope.version} told to update") + reply(client, SpectatorMessage.Reject(RejectReason.UPDATE_REQUIRED, SpectatorProtocol.MIN_COMPATIBLE_VERSION)) + } else { + spectator = admit(client) + } + } + else -> Unit + } + } catch (e: IOException) { + // Timed out or closed before saying hello. + } finally { + handshaking.decrementAndGet() + if (spectator == null) closeQuietly(client) + } + val admitted = spectator ?: return + listen(admitted, reader ?: return) + } + + private fun admit(client: Socket): Spectator? { + var reject: RejectReason? = null + var spectator: Spectator? = null + synchronized(lock) { + val game = latest + when { + closed || game == null -> reject = RejectReason.NO_GAME + spectators.size >= maxSpectators -> reject = RejectReason.FULL + else -> { + val joined = Spectator(client, timing.queueCapacity) + val others = spectators.toList() + spectators.add(joined) + val n = spectators.size + _count.value = n + joined.offer(SpectatorProtocol.encode(SpectatorMessage.Welcome(n, maxSpectators, liveSnapshot(game)))) + deliver(others, SpectatorProtocol.encode(SpectatorMessage.Count(n, maxSpectators))) + spectator = joined + } + } + } + reject?.let { + reply(client, SpectatorMessage.Reject(it, SpectatorProtocol.MIN_COMPATIBLE_VERSION)) + return null + } + val joined = spectator ?: return null + try { + threads.execute { write(joined) } + } catch (e: RejectedExecutionException) { + drop(joined) + return null + } + return joined + } + + private fun listen(spectator: Spectator, reader: BufferedReader) { + try { + spectator.socket.soTimeout = timing.silenceTimeoutMs + while (true) { + val read = readBoundedLine(reader, SpectatorProtocol.MAX_CLIENT_LINE_CHARS) + if (read !is LineResult.Line) break + when (SpectatorProtocol.decode(read.text)?.message) { + SpectatorMessage.Resync -> synchronized(lock) { + val game = latest + if (game != null && !closed) { + deliver(listOf(spectator), SpectatorProtocol.encode(SpectatorMessage.NewGame(liveSnapshot(game)))) + } + } + SpectatorMessage.Leave -> break + else -> Unit + } + } + } catch (e: SocketTimeoutException) { + log("Spectator silent for ${timing.silenceTimeoutMs / 1000} s, dropped") + } catch (e: IOException) { + // Connection reset. + } finally { + drop(spectator) + } + } + + private fun write(spectator: Spectator) { + try { + val out = BufferedWriter(OutputStreamWriter(spectator.socket.getOutputStream(), Charsets.UTF_8)) + while (true) { + val item = spectator.queue.take() + if (item === POISON) break + out.write(item as String) + out.write("\n") + if (spectator.queue.isEmpty()) out.flush() + } + out.flush() + } catch (e: IOException) { + // Spectator went away. + } catch (e: InterruptedException) { + Thread.currentThread().interrupt() + } finally { + drop(spectator) + closeQuietly(spectator.socket) + } + } + + private fun sendPings() { + val line: String + val targets: List + synchronized(lock) { + if (closed || spectators.isEmpty()) return + line = SpectatorProtocol.encode(SpectatorMessage.Ping(liveClock())) + targets = spectators.toList() + } + deliver(targets, line) + } + + private fun deliver(targets: List, line: String) { + for (spectator in targets) { + if (!spectator.offer(line)) { + log("Spectator too slow, dropped") + drop(spectator) + } + } + } + + private fun drop(spectator: Spectator) { + val others: List + val remaining: Int + synchronized(lock) { + // Already dropped, or the hub is closing and its writer is flushing the goodbye. + if (!spectators.remove(spectator)) return + remaining = spectators.size + _count.value = remaining + others = spectators.toList() + } + spectator.shutdown() + if (!closed) deliver(others, SpectatorProtocol.encode(SpectatorMessage.Count(remaining, maxSpectators))) + } + + private fun status(): SpectatorMessage.Status = synchronized(lock) { + val game = latest + SpectatorMessage.Status( + inGame = !closed && game != null && game.result == null, + count = spectators.size, + max = maxSpectators, + minVersion = SpectatorProtocol.MIN_COMPATIBLE_VERSION + ) + } + + private fun elapsedMs(): Long = (System.nanoTime() - latestAtNanos) / 1_000_000L + + private fun liveClock(): SpectatorClock? = latest?.clock?.advancedBy(elapsedMs()) + + private fun liveSnapshot(game: SpectatorSnapshot): SpectatorSnapshot = + if (game.clock == null) game else game.copy(clock = game.clock.advancedBy(elapsedMs())) + + private fun reply(client: Socket, message: SpectatorMessage) { + try { + val out = client.getOutputStream() + out.write((SpectatorProtocol.encode(message) + "\n").toByteArray(Charsets.UTF_8)) + out.flush() + } catch (e: IOException) { + // Nothing more to tell a peer that is gone. + } + } + + /** One spectator's outgoing queue; one slot is kept free for the end marker. */ + private class Spectator(val socket: Socket, private val capacity: Int) { + val queue = ArrayBlockingQueue(capacity + 1) + private var open = true + + @Synchronized + fun offer(line: String): Boolean = open && queue.size < capacity && queue.offer(line) + + /** Lets the writer send what is queued, then close. */ + @Synchronized + fun finish() { + if (!open) return + open = false + queue.offer(POISON) + } + + /** Stops at once, discarding anything unsent. */ + @Synchronized + fun shutdown() { + open = false + queue.clear() + queue.offer(POISON) + closeQuietly(socket) + } + } + + private companion object { + val POISON = Any() + + /** Connections allowed to sit in the hello phase at once. */ + const val MAX_HANDSHAKING = 32 + + fun closeQuietly(c: Closeable?) { + try { c?.close() } catch (_: IOException) {} + } + + fun daemonThreads(name: String): ThreadFactory { + val n = AtomicInteger() + return ThreadFactory { r -> Thread(r, "$name-${n.incrementAndGet()}").apply { isDaemon = true } } + } + } +} + +/** Feeds a hub from the host's game: each new snapshot becomes the messages spectators need. */ +class SpectatorBroadcaster(val hub: SpectatorHub) { + private var last: SpectatorSnapshot? = null + + fun update(snapshot: SpectatorSnapshot) { + val events = SpectatorDiff.between(last, snapshot) + last = snapshot + hub.publish(snapshot, events) + } + + /** Stops spectating; [final] is the last state, e.g. the result of a game left midway. */ + fun close(final: SpectatorSnapshot? = null) { + val events = if (final != null) SpectatorDiff.between(last, final) else emptyList() + hub.close(events) + } +} diff --git a/app/src/main/java/cc/skysparkle/matewave/spectate/SpectatorProtocol.kt b/app/src/main/java/cc/skysparkle/matewave/spectate/SpectatorProtocol.kt new file mode 100644 index 0000000..60df130 --- /dev/null +++ b/app/src/main/java/cc/skysparkle/matewave/spectate/SpectatorProtocol.kt @@ -0,0 +1,250 @@ +package cc.skysparkle.matewave.spectate + +import cc.skysparkle.matewave.engine.PieceColor +import org.json.JSONArray +import org.json.JSONObject + +/** Most spectators one hosted game accepts at the same time. */ +const val MAX_SPECTATORS = 20 + +data class SpectatorPlayer(val id: String, val name: String, val elo: Int) + +data class SpectatorClock(val whiteMs: Long, val blackMs: Long, val running: PieceColor?) { + /** The same clock [elapsedMs] later. */ + fun advancedBy(elapsedMs: Long): SpectatorClock { + if (elapsedMs <= 0) return this + return when (running) { + PieceColor.WHITE -> copy(whiteMs = (whiteMs - elapsedMs).coerceAtLeast(0)) + PieceColor.BLACK -> copy(blackMs = (blackMs - elapsedMs).coerceAtLeast(0)) + null -> this + } + } +} + +enum class SpectatorOutcome(val wire: String) { + CHECKMATE("checkmate"), + STALEMATE("stalemate"), + FIFTY_MOVES("fifty"), + REPETITION("repetition"), + INSUFFICIENT_MATERIAL("material"), + TIMEOUT("timeout"), + TIMEOUT_DRAW("timeout_draw"), + RESIGNATION("resign"), + AGREEMENT("agreement"), + LEFT("left"), + INTERRUPTED("interrupted"), + UNKNOWN("unknown"); + + companion object { + fun fromWire(value: String): SpectatorOutcome = entries.firstOrNull { it.wire == value } ?: UNKNOWN + } +} + +/** How a game ended; [winner] is null for draws and interrupted games. */ +data class SpectatorResult(val outcome: SpectatorOutcome, val winner: PieceColor?) + +/** Everything a spectator needs to show a game from any point: players, moves, clocks, result. */ +data class SpectatorSnapshot( + val gameId: String, + val white: SpectatorPlayer, + val black: SpectatorPlayer, + val movesUci: List, + val initialSeconds: Int, + val incrementSeconds: Int, + val clock: SpectatorClock?, + val result: SpectatorResult? = null +) + +enum class RejectReason(val wire: String) { + FULL("full"), + UPDATE_REQUIRED("update"), + NO_GAME("no_game"), + OTHER("other"); + + companion object { + fun fromWire(value: String): RejectReason = entries.firstOrNull { it.wire == value } ?: OTHER + } +} + +sealed class SpectatorMessage { + // Spectator to host. + data class Hello(val minVersion: Int = SpectatorProtocol.MIN_COMPATIBLE_VERSION) : SpectatorMessage() + data object StatusQuery : SpectatorMessage() + data object Pong : SpectatorMessage() + data object Resync : SpectatorMessage() + data object Leave : SpectatorMessage() + + // Host to spectator. + data class Welcome(val count: Int, val max: Int, val game: SpectatorSnapshot) : SpectatorMessage() + data class Status(val inGame: Boolean, val count: Int, val max: Int, val minVersion: Int) : SpectatorMessage() + data class Reject(val reason: RejectReason, val minVersion: Int) : SpectatorMessage() + data class MovePlayed(val gameId: String, val ply: Int, val uci: String, val clock: SpectatorClock?) : SpectatorMessage() + data class GameOver(val gameId: String, val result: SpectatorResult, val clock: SpectatorClock?) : SpectatorMessage() + data class NewGame(val game: SpectatorSnapshot) : SpectatorMessage() + data class Count(val count: Int, val max: Int) : SpectatorMessage() + data class Ping(val clock: SpectatorClock?) : SpectatorMessage() + data object Closing : SpectatorMessage() +} + +/** One decoded line: the sender's protocol version and the message, or null for an unknown type. */ +data class SpectatorEnvelope(val version: Int, val message: SpectatorMessage?) + +/** + * Wire format between a hosted game and its spectators: one JSON object per line, each carrying + * the sender's protocol version in "sv". Unknown types are skipped, never fatal. + */ +object SpectatorProtocol { + /** + * Bump on incompatible changes and raise [MIN_COMPATIBLE_VERSION] to the oldest version still + * understood. hello, status and reject keep their shape so any two versions can still tell + * each other that an update is required. + */ + const val VERSION = 1 + const val MIN_COMPATIBLE_VERSION = 1 + + const val MAX_HOST_LINE_CHARS = 64_000 + const val MAX_CLIENT_LINE_CHARS = 1_024 + + private const val MAX_NAME_CHARS = 40 + private const val MAX_PLIES = 2_000 + + fun encode(message: SpectatorMessage, version: Int = VERSION): String { + val o = JSONObject() + o.put("sv", version) + when (message) { + is SpectatorMessage.Hello -> { o.put("type", "hello"); o.put("min", message.minVersion) } + SpectatorMessage.StatusQuery -> o.put("type", "query") + SpectatorMessage.Pong -> o.put("type", "pong") + SpectatorMessage.Resync -> o.put("type", "resync") + SpectatorMessage.Leave -> o.put("type", "leave") + is SpectatorMessage.Welcome -> { + o.put("type", "welcome"); o.put("n", message.count); o.put("max", message.max) + o.put("game", snapshotJson(message.game)) + } + is SpectatorMessage.Status -> { + o.put("type", "status"); o.put("live", message.inGame) + o.put("n", message.count); o.put("max", message.max); o.put("min", message.minVersion) + } + is SpectatorMessage.Reject -> { + o.put("type", "reject"); o.put("reason", message.reason.wire); o.put("min", message.minVersion) + } + is SpectatorMessage.MovePlayed -> { + o.put("type", "move"); o.put("gid", message.gameId); o.put("ply", message.ply); o.put("uci", message.uci) + message.clock?.let { o.put("clock", clockJson(it)) } + } + is SpectatorMessage.GameOver -> { + o.put("type", "end"); o.put("gid", message.gameId); o.put("result", resultJson(message.result)) + message.clock?.let { o.put("clock", clockJson(it)) } + } + is SpectatorMessage.NewGame -> { o.put("type", "game"); o.put("game", snapshotJson(message.game)) } + is SpectatorMessage.Count -> { o.put("type", "count"); o.put("n", message.count); o.put("max", message.max) } + is SpectatorMessage.Ping -> { + o.put("type", "ping") + message.clock?.let { o.put("clock", clockJson(it)) } + } + SpectatorMessage.Closing -> o.put("type", "closing") + } + return o.toString() + } + + /** Null when the line is not a protocol message at all. */ + fun decode(line: String): SpectatorEnvelope? { + val o = runCatching { JSONObject(line) }.getOrNull() ?: return null + val type = o.optString("type", "") + if (type.isEmpty()) return null + val version = o.optInt("sv", 0) + val message = runCatching { decodeMessage(type, o) }.getOrNull() + return SpectatorEnvelope(version, message) + } + + private fun decodeMessage(type: String, o: JSONObject): SpectatorMessage? = when (type) { + "hello" -> SpectatorMessage.Hello(o.optInt("min", o.optInt("sv", 0))) + "query" -> SpectatorMessage.StatusQuery + "pong" -> SpectatorMessage.Pong + "resync" -> SpectatorMessage.Resync + "leave" -> SpectatorMessage.Leave + "welcome" -> SpectatorMessage.Welcome(o.getInt("n"), o.getInt("max"), parseSnapshot(o.getJSONObject("game"))) + "status" -> SpectatorMessage.Status(o.getBoolean("live"), o.getInt("n"), o.getInt("max"), o.optInt("min", 0)) + "reject" -> SpectatorMessage.Reject(RejectReason.fromWire(o.getString("reason")), o.optInt("min", 0)) + "move" -> SpectatorMessage.MovePlayed( + o.getString("gid"), o.getInt("ply"), o.getString("uci"), o.optJSONObject("clock")?.let(::parseClock) + ) + "end" -> SpectatorMessage.GameOver( + o.getString("gid"), parseResult(o.getJSONObject("result")), o.optJSONObject("clock")?.let(::parseClock) + ) + "game" -> SpectatorMessage.NewGame(parseSnapshot(o.getJSONObject("game"))) + "count" -> SpectatorMessage.Count(o.getInt("n"), o.getInt("max")) + "ping" -> SpectatorMessage.Ping(o.optJSONObject("clock")?.let(::parseClock)) + "closing" -> SpectatorMessage.Closing + else -> null + } + + private fun sideWire(side: PieceColor?): String = when (side) { + PieceColor.WHITE -> "w" + PieceColor.BLACK -> "b" + null -> "" + } + + private fun sideOf(wire: String): PieceColor? = when (wire) { + "w" -> PieceColor.WHITE + "b" -> PieceColor.BLACK + else -> null + } + + private fun clockJson(c: SpectatorClock) = JSONObject().apply { + put("w", c.whiteMs); put("b", c.blackMs) + if (c.running != null) put("r", sideWire(c.running)) + } + + private fun parseClock(o: JSONObject) = SpectatorClock( + whiteMs = o.getLong("w").coerceAtLeast(0), + blackMs = o.getLong("b").coerceAtLeast(0), + running = sideOf(o.optString("r", "")) + ) + + private fun resultJson(r: SpectatorResult) = JSONObject().apply { + put("o", r.outcome.wire) + if (r.winner != null) put("w", sideWire(r.winner)) + } + + private fun parseResult(o: JSONObject) = SpectatorResult( + outcome = SpectatorOutcome.fromWire(o.getString("o")), + winner = sideOf(o.optString("w", "")) + ) + + private fun playerJson(p: SpectatorPlayer) = JSONObject().apply { + put("id", p.id); put("name", p.name); put("elo", p.elo) + } + + private fun parsePlayer(o: JSONObject) = SpectatorPlayer( + id = o.optString("id", "").take(64), + name = o.optString("name", "").take(MAX_NAME_CHARS), + elo = o.optInt("elo", 0) + ) + + private fun snapshotJson(s: SpectatorSnapshot) = JSONObject().apply { + put("gid", s.gameId) + put("wp", playerJson(s.white)) + put("bp", playerJson(s.black)) + put("moves", JSONArray().also { array -> s.movesUci.forEach { array.put(it) } }) + put("ti", s.initialSeconds) + put("tx", s.incrementSeconds) + s.clock?.let { put("clock", clockJson(it)) } + s.result?.let { put("result", resultJson(it)) } + } + + private fun parseSnapshot(o: JSONObject): SpectatorSnapshot { + val array = o.getJSONArray("moves") + require(array.length() <= MAX_PLIES) + return SpectatorSnapshot( + gameId = o.getString("gid"), + white = parsePlayer(o.getJSONObject("wp")), + black = parsePlayer(o.getJSONObject("bp")), + movesUci = List(array.length()) { array.getString(it) }, + initialSeconds = o.optInt("ti", 0), + incrementSeconds = o.optInt("tx", 0), + clock = o.optJSONObject("clock")?.let(::parseClock), + result = o.optJSONObject("result")?.let(::parseResult) + ) + } +} diff --git a/app/src/test/java/cc/skysparkle/matewave/FriendStatusTest.kt b/app/src/test/java/cc/skysparkle/matewave/FriendStatusTest.kt new file mode 100644 index 0000000..7b81ff8 --- /dev/null +++ b/app/src/test/java/cc/skysparkle/matewave/FriendStatusTest.kt @@ -0,0 +1,99 @@ +package cc.skysparkle.matewave + +import cc.skysparkle.matewave.spectate.FriendStatusResolver +import cc.skysparkle.matewave.spectate.MAX_SPECTATORS +import cc.skysparkle.matewave.spectate.NearbyPlayerGame +import cc.skysparkle.matewave.spectate.PresenceStatus +import cc.skysparkle.matewave.spectate.SpectateTarget +import cc.skysparkle.matewave.spectate.SpectatorAdvert +import cc.skysparkle.matewave.spectate.SpectatorMessage +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class FriendStatusTest { + private val tag = SpectatorAdvert.tagOf("game-1") + private val host = NearbyPlayerGame("host", "192.168.1.10", tag, 40_123) + private val guest = NearbyPlayerGame("guest", "192.168.1.11", tag, 0) + private val idle = NearbyPlayerGame("idle", "192.168.1.12", "", 0) + private val nearby = listOf(host, guest, idle).associateBy { it.playerId } + private val target = SpectateTarget("192.168.1.10", 40_123, tag) + + private fun status(count: Int, live: Boolean = true) = SpectatorMessage.Status(live, count, MAX_SPECTATORS, 1) + + @Test + fun notVisibleIsOffline() { + assertEquals(PresenceStatus.OFFLINE, FriendStatusResolver.resolve("nobody", nearby, emptyMap()).status) + } + + @Test + fun visibleWithoutAGameIsOnline() { + val s = FriendStatusResolver.resolve("idle", nearby, emptyMap()) + assertEquals(PresenceStatus.ONLINE, s.status) + assertNull(s.target) + } + + @Test + fun hostInGameCanBeWatchedWithTheLiveCount() { + val s = FriendStatusResolver.resolve("host", nearby, mapOf(target to status(7))) + assertEquals(PresenceStatus.IN_GAME, s.status) + assertEquals(target, s.target) + assertEquals(7, s.spectators) + assertFalse(s.full) + } + + @Test + fun guestIsWatchedThroughTheHost() { + val s = FriendStatusResolver.resolve("guest", nearby, mapOf(target to status(3))) + assertEquals(PresenceStatus.IN_GAME, s.status) + assertEquals(target, s.target) + assertEquals(3, s.spectators) + } + + @Test + fun fullGameIsReportedAsFull() { + assertTrue(FriendStatusResolver.resolve("host", nearby, mapOf(target to status(MAX_SPECTATORS))).full) + } + + @Test + fun countIsUnknownUntilTheHostAnswers() { + val s = FriendStatusResolver.resolve("host", nearby, emptyMap()) + assertEquals(PresenceStatus.IN_GAME, s.status) + assertNull(s.spectators) + assertFalse(s.full) + } + + @Test + fun hostSayingTheGameEndedWinsOverAStaleAnnouncement() { + val ended = mapOf(target to status(0, live = false)) + assertEquals(PresenceStatus.ONLINE, FriendStatusResolver.resolve("host", nearby, ended).status) + assertEquals(PresenceStatus.ONLINE, FriendStatusResolver.resolve("guest", nearby, ended).status) + } + + @Test + fun guestWhoseHostIsHiddenIsInGameWithoutWatch() { + val s = FriendStatusResolver.resolve("guest", mapOf("guest" to guest), emptyMap()) + assertEquals(PresenceStatus.IN_GAME, s.status) + assertNull(s.target) + } + + @Test + fun onlyHostsAreProbed() { + assertEquals(setOf(target), FriendStatusResolver.targets(nearby.values)) + } + + @Test + fun advertRoundTripsAndRejectsJunk() { + val state = SpectatorAdvert.State(tag, 40_123) + val attrs = SpectatorAdvert.attributes(state) + assertEquals(state, SpectatorAdvert.parse { attrs[it] ?: "" }) + assertEquals(SpectatorAdvert.State(), SpectatorAdvert.parse { "" }) + assertEquals(SpectatorAdvert.State(), SpectatorAdvert.parse { if (it == "g") "not-a-tag" else "1" }) + assertEquals(SpectatorAdvert.State(tag, 0), SpectatorAdvert.parse { if (it == "g") tag else "99999" }) + assertEquals(emptyMap(), SpectatorAdvert.attributes(SpectatorAdvert.State())) + assertEquals(8, tag.length) + assertEquals("", SpectatorAdvert.tagOf("")) + } +} diff --git a/app/src/test/java/cc/skysparkle/matewave/SpectatorGameTest.kt b/app/src/test/java/cc/skysparkle/matewave/SpectatorGameTest.kt new file mode 100644 index 0000000..d38aed9 --- /dev/null +++ b/app/src/test/java/cc/skysparkle/matewave/SpectatorGameTest.kt @@ -0,0 +1,149 @@ +package cc.skysparkle.matewave + +import cc.skysparkle.matewave.engine.GameStatus +import cc.skysparkle.matewave.engine.PieceColor +import cc.skysparkle.matewave.engine.PieceType +import cc.skysparkle.matewave.spectate.SpectatorClock +import cc.skysparkle.matewave.spectate.SpectatorDiff +import cc.skysparkle.matewave.spectate.SpectatorGame +import cc.skysparkle.matewave.spectate.SpectatorGame.Applied +import cc.skysparkle.matewave.spectate.SpectatorMessage +import cc.skysparkle.matewave.spectate.SpectatorOutcome +import cc.skysparkle.matewave.spectate.SpectatorPlayer +import cc.skysparkle.matewave.spectate.SpectatorResult +import cc.skysparkle.matewave.spectate.SpectatorResults +import cc.skysparkle.matewave.spectate.SpectatorSnapshot +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class SpectatorGameTest { + private fun snapshot(moves: List, gameId: String = "g1", result: SpectatorResult? = null) = SpectatorSnapshot( + gameId = gameId, + white = SpectatorPlayer("u1", "Alice", 1500), + black = SpectatorPlayer("u2", "Bob", 1400), + movesUci = moves, + initialSeconds = 180, + incrementSeconds = 2, + clock = SpectatorClock(170_000, 175_000, if (moves.size % 2 == 0) PieceColor.WHITE else PieceColor.BLACK), + result = result + ) + + private fun move(ply: Int, uci: String, gameId: String = "g1") = SpectatorMessage.MovePlayed(gameId, ply, uci, null) + + @Test + fun loadReplaysTheMoveListWithTurnAndLastMove() { + val game = SpectatorGame() + assertTrue(game.load(snapshot(listOf("e2e4", "e7e5", "e1e2")))) + val view = game.view!! + assertEquals(listOf("e4", "e5", "Ke2"), view.moveSans) + assertEquals(PieceColor.BLACK, view.board.sideToMove) + assertEquals("e1e2", view.lastMove!!.toUci()) + assertEquals(3, view.ply) + assertEquals(180, view.initialSeconds) + } + + @Test + fun illegalHistoryIsRefused() { + assertFalse(SpectatorGame().load(snapshot(listOf("e2e5")))) + assertFalse(SpectatorGame().load(snapshot(listOf("zz99")))) + } + + @Test + fun liveMovesFollowOnAndDuplicatesAreIgnored() { + val game = SpectatorGame() + game.load(snapshot(listOf("d2d4"))) + assertEquals(Applied.APPLIED, game.onMove(move(2, "d7d5"))) + assertEquals(Applied.IGNORED, game.onMove(move(2, "d7d5"))) + assertEquals(Applied.IGNORED, game.onMove(move(1, "d2d4"))) + assertEquals(listOf("d4", "d5"), game.view!!.moveSans) + } + + @Test + fun gapsIllegalMovesAndForeignGamesAskForResync() { + val game = SpectatorGame() + game.load(snapshot(listOf("d2d4"))) + assertEquals(Applied.NEEDS_RESYNC, game.onMove(move(3, "c2c4"))) + assertEquals(Applied.NEEDS_RESYNC, game.onMove(move(2, "d4d5"))) + assertEquals(Applied.NEEDS_RESYNC, game.onMove(move(2, "d7d5", gameId = "other"))) + assertEquals(Applied.NEEDS_RESYNC, SpectatorGame().onMove(move(1, "e2e4"))) + assertEquals(1, game.view!!.ply) + } + + @Test + fun promotionIsKept() { + val game = SpectatorGame() + val moves = listOf("h2h4", "g7g5", "h4g5", "h7h6", "g5h6", "g8f6", "h6h7", "f6g8") + assertTrue(game.load(snapshot(moves))) + assertEquals(Applied.APPLIED, game.onMove(move(9, "h7g8n"))) + assertEquals(PieceType.KNIGHT, game.view!!.lastMove!!.promotion) + assertEquals("hxg8=N", game.view!!.moveSans.last()) + } + + @Test + fun gameOverStopsTheClockAndLaterMovesAreIgnored() { + val game = SpectatorGame() + game.load(snapshot(listOf("f2f3", "e7e5", "g2g4", "d8h4"))) + val result = SpectatorResult(SpectatorOutcome.CHECKMATE, PieceColor.BLACK) + assertEquals(Applied.APPLIED, game.onGameOver(SpectatorMessage.GameOver("g1", result, null))) + assertEquals(result, game.view!!.result) + assertNull(game.view!!.clock!!.running) + assertEquals(Applied.IGNORED, game.onMove(move(5, "a2a3"))) + game.onClock(SpectatorClock(1, 1, PieceColor.WHITE)) + assertNull(game.view!!.clock!!.running) + } + + @Test + fun diffTurnsNewMovesIntoLiveMessagesWithTheLatestClock() { + val before = snapshot(listOf("e2e4")) + val after = snapshot(listOf("e2e4", "e7e5", "g1f3")) + val events = SpectatorDiff.between(before, after) + assertEquals(2, events.size) + val first = events[0] as SpectatorMessage.MovePlayed + val second = events[1] as SpectatorMessage.MovePlayed + assertEquals(2 to "e7e5", first.ply to first.uci) + assertNull(first.clock) + assertEquals(3 to "g1f3", second.ply to second.uci) + assertEquals(after.clock, second.clock) + } + + @Test + fun diffReportsTheEndOnceAndRestartsOnANewGame() { + val playing = snapshot(listOf("e2e4")) + val over = playing.copy(result = SpectatorResult(SpectatorOutcome.RESIGNATION, PieceColor.WHITE)) + assertEquals(listOf(SpectatorMessage.GameOver("g1", over.result!!, over.clock)), SpectatorDiff.between(playing, over)) + assertEquals(emptyList(), SpectatorDiff.between(over, over)) + val rematch = snapshot(emptyList(), gameId = "g2") + assertEquals(listOf(SpectatorMessage.NewGame(rematch)), SpectatorDiff.between(over, rematch)) + assertEquals(emptyList(), SpectatorDiff.between(null, rematch)) + // Clock ticks alone are carried by pings, not extra messages. + assertEquals(emptyList(), SpectatorDiff.between(playing, playing.copy(clock = SpectatorClock(1, 2, null)))) + } + + @Test + fun diffFallsBackToAFullSnapshotWhenHistoryChanges() { + val a = snapshot(listOf("e2e4", "e7e5")) + val b = snapshot(listOf("d2d4")) + assertEquals(listOf(SpectatorMessage.NewGame(b)), SpectatorDiff.between(a, b)) + } + + @Test + fun resultsMapEveryWayAGameCanEnd() { + fun of(status: GameStatus, timedOut: PieceColor? = null, resigned: PieceColor? = null, left: Boolean = false) = + SpectatorResults.of(status, PieceColor.WHITE, timedOut, resigned, left) + assertNull(of(GameStatus.ONGOING)) + assertEquals(SpectatorResult(SpectatorOutcome.CHECKMATE, PieceColor.BLACK), of(GameStatus.CHECKMATE)) + assertEquals(SpectatorResult(SpectatorOutcome.TIMEOUT, PieceColor.WHITE), of(GameStatus.TIMEOUT, timedOut = PieceColor.BLACK)) + assertEquals(SpectatorResult(SpectatorOutcome.RESIGNATION, PieceColor.BLACK), of(GameStatus.RESIGNATION, resigned = PieceColor.WHITE)) + assertEquals(SpectatorResult(SpectatorOutcome.LEFT, PieceColor.WHITE), of(GameStatus.RESIGNATION, resigned = PieceColor.BLACK, left = true)) + assertEquals(SpectatorResult(SpectatorOutcome.STALEMATE, null), of(GameStatus.STALEMATE)) + assertEquals(SpectatorResult(SpectatorOutcome.FIFTY_MOVES, null), of(GameStatus.DRAW_50_MOVES)) + assertEquals(SpectatorResult(SpectatorOutcome.REPETITION, null), of(GameStatus.DRAW_REPETITION)) + assertEquals(SpectatorResult(SpectatorOutcome.INSUFFICIENT_MATERIAL, null), of(GameStatus.DRAW_MATERIAL)) + assertEquals(SpectatorResult(SpectatorOutcome.TIMEOUT_DRAW, null), of(GameStatus.TIMEOUT_DRAW)) + assertEquals(SpectatorResult(SpectatorOutcome.AGREEMENT, null), of(GameStatus.DRAW_AGREEMENT)) + assertEquals(SpectatorResult(SpectatorOutcome.LEFT, PieceColor.BLACK), SpectatorResults.leftBy(PieceColor.WHITE)) + } +} diff --git a/app/src/test/java/cc/skysparkle/matewave/SpectatorHubTest.kt b/app/src/test/java/cc/skysparkle/matewave/SpectatorHubTest.kt new file mode 100644 index 0000000..1a50bc9 --- /dev/null +++ b/app/src/test/java/cc/skysparkle/matewave/SpectatorHubTest.kt @@ -0,0 +1,460 @@ +package cc.skysparkle.matewave + +import cc.skysparkle.matewave.engine.PieceColor +import cc.skysparkle.matewave.spectate.MAX_SPECTATORS +import cc.skysparkle.matewave.spectate.RejectReason +import cc.skysparkle.matewave.spectate.SpectatorBroadcaster +import cc.skysparkle.matewave.spectate.SpectatorClient +import cc.skysparkle.matewave.spectate.SpectatorClient.Event +import cc.skysparkle.matewave.spectate.SpectatorClient.Failure +import cc.skysparkle.matewave.spectate.SpectatorClock +import cc.skysparkle.matewave.spectate.SpectatorGame +import cc.skysparkle.matewave.spectate.SpectatorHub +import cc.skysparkle.matewave.spectate.SpectatorMessage +import cc.skysparkle.matewave.spectate.SpectatorOutcome +import cc.skysparkle.matewave.spectate.SpectatorPlayer +import cc.skysparkle.matewave.spectate.SpectatorProbe +import cc.skysparkle.matewave.spectate.SpectatorProtocol +import cc.skysparkle.matewave.spectate.SpectatorResults +import cc.skysparkle.matewave.spectate.SpectatorSnapshot +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +import org.junit.Test +import java.io.BufferedReader +import java.io.Closeable +import java.io.IOException +import java.io.InputStreamReader +import java.net.InetAddress +import java.net.ServerSocket +import java.net.Socket +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.CountDownLatch +import java.util.concurrent.LinkedBlockingQueue +import java.util.concurrent.TimeUnit + +class SpectatorHubTest { + private val loopback: InetAddress = InetAddress.getLoopbackAddress() + private val hubTiming = SpectatorHub.Timing(helloTimeoutMs = 1_000, pingIntervalMs = 150, silenceTimeoutMs = 900) + private val clientTiming = SpectatorClient.Timing(connectTimeoutMs = 2_000, silenceTimeoutMs = 900) + + private val hubs = CopyOnWriteArrayList() + private val clients = CopyOnWriteArrayList() + private val closeables = CopyOnWriteArrayList() + + @After + fun tearDown() { + clients.forEach { it.stop() } + hubs.forEach { it.close() } + closeables.forEach { runCatching { it.close() } } + } + + private fun snapshot( + moves: List = emptyList(), + clock: SpectatorClock? = SpectatorClock(300_000, 300_000, PieceColor.WHITE), + gameId: String = "g1" + ) = SpectatorSnapshot( + gameId = gameId, + white = SpectatorPlayer("u1", "Alice", 1500), + black = SpectatorPlayer("u2", "Bob", 1400), + movesUci = moves, + initialSeconds = 300, + incrementSeconds = 0, + clock = clock + ) + + private fun hub(initial: SpectatorSnapshot? = snapshot()): SpectatorHub { + val hub = SpectatorHub(timing = hubTiming) + hubs += hub + hub.start(loopback) + if (initial != null) hub.publish(initial) + return hub + } + + private class Recorder { + val events = LinkedBlockingQueue() + + fun next(timeoutMs: Long = 3_000): Event = + events.poll(timeoutMs, TimeUnit.MILLISECONDS) ?: throw AssertionError("No event within $timeoutMs ms") + + /** Skips pings and counts until an event matching [predicate]. */ + fun awaitEvent(timeoutMs: Long = 3_000, predicate: (Event) -> Boolean): Event { + val deadline = System.currentTimeMillis() + timeoutMs + while (true) { + val left = deadline - System.currentTimeMillis() + if (left <= 0) throw AssertionError("Expected event did not arrive") + val event = events.poll(left, TimeUnit.MILLISECONDS) ?: continue + if (predicate(event)) return event + } + } + + fun awaitMessage(timeoutMs: Long = 3_000, predicate: (SpectatorMessage) -> Boolean): SpectatorMessage = + (awaitEvent(timeoutMs) { it is Event.Received && predicate(it.message) } as Event.Received).message + } + + private fun watch( + port: Int, + recorder: Recorder = Recorder(), + version: Int = SpectatorProtocol.VERSION, + minVersion: Int = SpectatorProtocol.MIN_COMPATIBLE_VERSION + ): Pair { + val client = SpectatorClient("127.0.0.1", port, { recorder.events.add(it) }, clientTiming, version, minVersion) + clients += client + client.start() + return client to recorder + } + + private fun awaitCount(hub: SpectatorHub, expected: Int, timeoutMs: Long = 3_000) { + val deadline = System.currentTimeMillis() + timeoutMs + while (hub.count.value != expected) { + if (System.currentTimeMillis() > deadline) fail("Spectator count ${hub.count.value}, expected $expected") + Thread.sleep(10) + } + } + + private fun joined(recorder: Recorder): SpectatorMessage.Welcome { + val event = recorder.next() + assertTrue("Expected to join, got $event", event is Event.Joined) + return (event as Event.Joined).welcome + } + + @Test + fun twentySpectatorsJoinAndTheTwentyFirstIsRefused() { + val hub = hub() + val watchers = List(MAX_SPECTATORS) { watch(hub.port).second } + watchers.forEach { joined(it) } + awaitCount(hub, MAX_SPECTATORS) + + val (_, late) = watch(hub.port) + assertEquals(Event.JoinFailed(Failure.FULL), late.next()) + assertEquals(MAX_SPECTATORS, hub.count.value) + + // Everyone already watching still gets the game. + hub.publish(snapshot(listOf("e2e4")), listOf(SpectatorMessage.MovePlayed("g1", 1, "e2e4", null))) + watchers.forEach { recorder -> + val move = recorder.awaitMessage { it is SpectatorMessage.MovePlayed } as SpectatorMessage.MovePlayed + assertEquals("e2e4", move.uci) + } + } + + @Test + fun simultaneousJoinsNeverExceedTheLimit() { + val hub = hub() + val start = CountDownLatch(1) + val recorders = List(MAX_SPECTATORS + 10) { Recorder() } + val threads = recorders.map { r -> Thread { start.await(); watch(hub.port, r) }.apply { start() } } + start.countDown() + threads.forEach { it.join() } + + val outcomes = recorders.map { it.next(5_000) } + assertEquals(MAX_SPECTATORS, outcomes.count { it is Event.Joined }) + assertEquals(10, outcomes.count { it == Event.JoinFailed(Failure.FULL) }) + assertEquals(MAX_SPECTATORS, hub.count.value) + } + + @Test + fun joiningMidGameGetsFullStateThenFollowsLive() { + val hub = hub() + val broadcaster = SpectatorBroadcaster(hub) + val opening = listOf("e2e4", "e7e5", "g1f3") + broadcaster.update(snapshot()) + broadcaster.update(snapshot(opening, SpectatorClock(290_000, 295_000, PieceColor.BLACK))) + + val (_, recorder) = watch(hub.port) + val welcome = joined(recorder) + assertEquals(1, welcome.count) + assertEquals(opening, welcome.game.movesUci) + assertEquals("Alice", welcome.game.white.name) + assertEquals(300, welcome.game.initialSeconds) + val clock = welcome.game.clock!! + assertEquals(PieceColor.BLACK, clock.running) + assertEquals(290_000, clock.whiteMs) + assertTrue(clock.blackMs in 290_000..295_000) + + val game = SpectatorGame() + assertTrue(game.load(welcome.game)) + assertEquals(PieceColor.BLACK, game.view!!.board.sideToMove) + assertEquals(listOf("e4", "e5", "Nf3"), game.view!!.moveSans) + + broadcaster.update(snapshot(opening + "b8c6", SpectatorClock(290_000, 293_000, PieceColor.WHITE))) + val move = recorder.awaitMessage { it is SpectatorMessage.MovePlayed } as SpectatorMessage.MovePlayed + assertEquals(4, move.ply) + assertEquals(SpectatorGame.Applied.APPLIED, game.onMove(move)) + assertEquals(PieceColor.WHITE, game.view!!.board.sideToMove) + assertEquals("Nc6", game.view!!.moveSans.last()) + } + + @Test + fun hostLeavingMidGameShowsTheResultThenSaysGoodbye() { + val hub = hub() + val broadcaster = SpectatorBroadcaster(hub) + val playing = snapshot(listOf("e2e4")) + broadcaster.update(playing) + val (_, recorder) = watch(hub.port) + joined(recorder) + + broadcaster.close(playing.copy(result = SpectatorResults.leftBy(PieceColor.WHITE))) + val end = recorder.awaitMessage { it is SpectatorMessage.GameOver } as SpectatorMessage.GameOver + assertEquals(SpectatorOutcome.LEFT, end.result.outcome) + assertEquals(PieceColor.BLACK, end.result.winner) + assertEquals(Event.Disconnected(hostClosed = true), recorder.awaitEvent { it is Event.Disconnected }) + } + + @Test + fun hostDroppingOffIsSeenAsConnectionLost() { + val hub = hub() + val link = FlakyLink(hub.port) + val (_, recorder) = watch(link.port) + joined(recorder) + + link.cut() + assertEquals(Event.Disconnected(hostClosed = false), recorder.awaitEvent { it is Event.Disconnected }) + } + + @Test + fun wifiSwitchingOffIsDetectedOnBothSides() { + val hub = hub() + val link = FlakyLink(hub.port) + val (_, cutOff) = watch(link.port) + val (_, direct) = watch(hub.port) + joined(cutOff) + joined(direct) + awaitCount(hub, 2) + + // No more packets either way, but no connection reset: what a dead Wi-Fi link looks like. + link.silent = true + + assertEquals(Event.Disconnected(hostClosed = false), cutOff.awaitEvent { it is Event.Disconnected }) + awaitCount(hub, 1) + // The remaining spectator's counter follows. + assertNotNull(direct.awaitMessage { it is SpectatorMessage.Count && it.count == 1 }) + + // The spectator who still has a connection keeps watching. + hub.publish(snapshot(listOf("d2d4")), listOf(SpectatorMessage.MovePlayed("g1", 1, "d2d4", null))) + assertNotNull(direct.awaitMessage { it is SpectatorMessage.MovePlayed }) + } + + @Test + fun spectatorsLeavingFreeTheirSlotsWhileOthersKeepWatching() { + val hub = hub() + val watchers = List(MAX_SPECTATORS) { watch(hub.port) } + watchers.forEach { joined(it.second) } + awaitCount(hub, MAX_SPECTATORS) + + watchers.take(5).forEach { it.first.stop() } + awaitCount(hub, MAX_SPECTATORS - 5) + + val (_, newcomer) = watch(hub.port) + assertEquals(MAX_SPECTATORS - 4, joined(newcomer).count) + + hub.publish(snapshot(listOf("c2c4")), listOf(SpectatorMessage.MovePlayed("g1", 1, "c2c4", null))) + (watchers.drop(5).map { it.second } + newcomer).forEach { + assertNotNull(it.awaitMessage { m -> m is SpectatorMessage.MovePlayed }) + } + } + + @Test + fun stalledSpectatorsNeverSlowDownTheHost() { + val hub = hub() + val link = FlakyLink(hub.port) + repeat(5) { joined(watch(link.port).second) } + link.silent = true + + val started = System.nanoTime() + repeat(2_000) { i -> + hub.publish(snapshot(), listOf(SpectatorMessage.Count(i, MAX_SPECTATORS))) + } + val elapsedMs = (System.nanoTime() - started) / 1_000_000 + assertTrue("publish took $elapsedMs ms", elapsedMs < 1_000) + } + + @Test + fun outdatedSpectatorIsToldToUpdate() { + val hub = hub() + val (_, recorder) = watch(hub.port, version = 0, minVersion = 0) + assertEquals(Event.JoinFailed(Failure.UPDATE_THIS_APP), recorder.next()) + assertEquals(0, hub.count.value) + } + + @Test + fun outdatedHostIsReported() { + val hub = hub() + val newer = SpectatorProtocol.VERSION + 1 + val (_, recorder) = watch(hub.port, version = newer, minVersion = newer) + assertEquals(Event.JoinFailed(Failure.UPDATE_HOST_APP), recorder.next()) + } + + @Test + fun rawOldClientGetsAClearRejectInsteadOfACrash() { + val hub = hub() + Socket(loopback, hub.port).use { s -> + s.soTimeout = 2_000 + s.getOutputStream().write("{\"type\":\"hello\",\"sv\":0}\n".toByteArray()) + val reply = BufferedReader(InputStreamReader(s.getInputStream())).readLine() + val reject = SpectatorProtocol.decode(reply)!!.message as SpectatorMessage.Reject + assertEquals(RejectReason.UPDATE_REQUIRED, reject.reason) + assertEquals(SpectatorProtocol.MIN_COMPATIBLE_VERSION, reject.minVersion) + } + } + + @Test + fun garbageAndOversizedInputCloseOnlyThatConnection() { + val hub = hub() + val (_, watcher) = watch(hub.port) + joined(watcher) + + for (payload in listOf("hello?\n", "x".repeat(SpectatorProtocol.MAX_CLIENT_LINE_CHARS + 10) + "\n")) { + Socket(loopback, hub.port).use { s -> + s.soTimeout = 2_000 + s.getOutputStream().write(payload.toByteArray()) + // Closed with unread input the host may answer with a reset instead of a clean close. + val read = try { s.getInputStream().read() } catch (e: IOException) { -1 } + assertEquals(-1, read) + } + } + assertEquals(1, hub.count.value) + hub.publish(snapshot(listOf("e2e4")), listOf(SpectatorMessage.MovePlayed("g1", 1, "e2e4", null))) + assertNotNull(watcher.awaitMessage { it is SpectatorMessage.MovePlayed }) + } + + @Test + fun silentConnectionThatNeverSaysHelloIsClosed() { + val hub = hub() + Socket(loopback, hub.port).use { s -> + s.soTimeout = 3_000 + assertEquals(-1, s.getInputStream().read()) + } + assertEquals(0, hub.count.value) + } + + @Test + fun noGameYetIsRefused() { + val hub = hub(initial = null) + val (_, recorder) = watch(hub.port) + assertEquals(Event.JoinFailed(Failure.NO_GAME), recorder.next()) + } + + @Test + fun statusProbeReportsLiveCountWithoutTakingASlot() { + val hub = hub() + repeat(3) { joined(watch(hub.port).second) } + awaitCount(hub, 3) + val status = SpectatorProbe.query("127.0.0.1", hub.port)!! + assertTrue(status.inGame) + assertEquals(3, status.count) + assertEquals(MAX_SPECTATORS, status.max) + assertEquals(3, hub.count.value) + + hub.publish(snapshot().copy(result = SpectatorResults.interrupted)) + assertFalse(SpectatorProbe.query("127.0.0.1", hub.port)!!.inGame) + } + + @Test + fun probeOfAClosedHostIsNull() { + val hub = hub() + val port = hub.port + hub.close() + assertEquals(null, SpectatorProbe.query("127.0.0.1", port, timeoutMs = 500)) + } + + @Test + fun resyncSendsAFreshSnapshot() { + val hub = hub(snapshot(listOf("e2e4", "c7c5"))) + val (client, recorder) = watch(hub.port) + joined(recorder) + client.requestResync() + val fresh = recorder.awaitMessage { it is SpectatorMessage.NewGame } as SpectatorMessage.NewGame + assertEquals(listOf("e2e4", "c7c5"), fresh.game.movesUci) + } + + @Test + fun rematchReachesSpectatorsAsANewGame() { + val hub = hub() + val broadcaster = SpectatorBroadcaster(hub) + val first = snapshot(listOf("f2f3", "e7e5", "g2g4", "d8h4")) + broadcaster.update(first) + val (_, recorder) = watch(hub.port) + joined(recorder) + broadcaster.update(first.copy(result = SpectatorResults.of( + cc.skysparkle.matewave.engine.GameStatus.CHECKMATE, PieceColor.WHITE, null, null, false + ))) + val end = recorder.awaitMessage { it is SpectatorMessage.GameOver } as SpectatorMessage.GameOver + assertEquals(PieceColor.BLACK, end.result.winner) + + broadcaster.update(snapshot(gameId = "g2")) + val next = recorder.awaitMessage { it is SpectatorMessage.NewGame } as SpectatorMessage.NewGame + assertEquals("g2", next.game.gameId) + } + + @Test + fun clocksKeepRunningBetweenHostUpdates() { + val hub = hub(snapshot(clock = SpectatorClock(60_000, 60_000, PieceColor.WHITE))) + Thread.sleep(400) + val (_, recorder) = watch(hub.port) + val clock = joined(recorder).game.clock!! + assertTrue("white ${clock.whiteMs}", clock.whiteMs in 50_000..59_700) + assertEquals(60_000, clock.blackMs) + val ping = recorder.awaitMessage { it is SpectatorMessage.Ping } as SpectatorMessage.Ping + assertTrue(ping.clock!!.whiteMs <= clock.whiteMs) + } + + @Test + fun closingTheHubEndsEveryoneAndRefusesNewcomers() { + val hub = hub() + val recorders = List(3) { watch(hub.port).second } + recorders.forEach { joined(it) } + val port = hub.port + hub.close() + recorders.forEach { assertEquals(Event.Disconnected(hostClosed = true), it.awaitEvent { e -> e is Event.Disconnected }) } + assertEquals(0, hub.count.value) + val (_, late) = watch(port) + assertEquals(Event.JoinFailed(Failure.UNREACHABLE), late.next()) + } + + /** A TCP relay that can go silent (dead Wi-Fi) or drop every connection (host gone). */ + private inner class FlakyLink(target: Int) : Closeable { + private val server = ServerSocket(0, 50, loopback) + private val sockets = CopyOnWriteArrayList() + @Volatile var silent = false + val port: Int get() = server.localPort + + init { + closeables += this + Thread { + while (!server.isClosed) { + val inbound = try { server.accept() } catch (e: IOException) { break } + val outbound = Socket(loopback, target) + sockets += inbound + sockets += outbound + pump(inbound, outbound) + pump(outbound, inbound) + } + }.apply { isDaemon = true }.start() + } + + private fun pump(from: Socket, to: Socket) = Thread { + val buffer = ByteArray(8_192) + try { + while (true) { + val n = from.getInputStream().read(buffer) + if (n < 0) break + if (!silent) to.getOutputStream().write(buffer, 0, n) + } + } catch (_: IOException) { + } finally { + runCatching { from.close() } + runCatching { to.close() } + } + }.apply { isDaemon = true }.start() + + fun cut() = sockets.forEach { runCatching { it.close() } } + + override fun close() { + runCatching { server.close() } + cut() + } + } +} diff --git a/app/src/test/java/cc/skysparkle/matewave/SpectatorProtocolTest.kt b/app/src/test/java/cc/skysparkle/matewave/SpectatorProtocolTest.kt new file mode 100644 index 0000000..b234362 --- /dev/null +++ b/app/src/test/java/cc/skysparkle/matewave/SpectatorProtocolTest.kt @@ -0,0 +1,114 @@ +package cc.skysparkle.matewave + +import cc.skysparkle.matewave.engine.PieceColor +import cc.skysparkle.matewave.spectate.MAX_SPECTATORS +import cc.skysparkle.matewave.spectate.RejectReason +import cc.skysparkle.matewave.spectate.SpectatorClock +import cc.skysparkle.matewave.spectate.SpectatorMessage +import cc.skysparkle.matewave.spectate.SpectatorOutcome +import cc.skysparkle.matewave.spectate.SpectatorPlayer +import cc.skysparkle.matewave.spectate.SpectatorProtocol +import cc.skysparkle.matewave.spectate.SpectatorResult +import cc.skysparkle.matewave.spectate.SpectatorSnapshot +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class SpectatorProtocolTest { + private val clock = SpectatorClock(295_000, 300_000, PieceColor.BLACK) + private val snapshot = SpectatorSnapshot( + gameId = "g1", + white = SpectatorPlayer("u1", "Владимир", 1350), + black = SpectatorPlayer("u2", "Bob", 1200), + movesUci = listOf("e2e4", "e7e5", "g1f3"), + initialSeconds = 300, + incrementSeconds = 2, + clock = clock + ) + + private fun roundTrip(message: SpectatorMessage) { + val envelope = SpectatorProtocol.decode(SpectatorProtocol.encode(message)) + assertNotNull(envelope) + assertEquals(SpectatorProtocol.VERSION, envelope!!.version) + assertEquals(message, envelope.message) + } + + @Test fun hello() = roundTrip(SpectatorMessage.Hello(1)) + @Test fun query() = roundTrip(SpectatorMessage.StatusQuery) + @Test fun pong() = roundTrip(SpectatorMessage.Pong) + @Test fun resync() = roundTrip(SpectatorMessage.Resync) + @Test fun leave() = roundTrip(SpectatorMessage.Leave) + @Test fun welcome() = roundTrip(SpectatorMessage.Welcome(7, MAX_SPECTATORS, snapshot)) + @Test fun status() = roundTrip(SpectatorMessage.Status(true, 7, MAX_SPECTATORS, 1)) + @Test fun reject() = roundTrip(SpectatorMessage.Reject(RejectReason.FULL, 1)) + @Test fun move() = roundTrip(SpectatorMessage.MovePlayed("g1", 4, "b8c6", clock)) + @Test fun moveWithoutClock() = roundTrip(SpectatorMessage.MovePlayed("g1", 4, "e7e8q", null)) + @Test fun count() = roundTrip(SpectatorMessage.Count(3, MAX_SPECTATORS)) + @Test fun ping() = roundTrip(SpectatorMessage.Ping(clock)) + @Test fun closing() = roundTrip(SpectatorMessage.Closing) + @Test fun newGame() = roundTrip(SpectatorMessage.NewGame(snapshot.copy(movesUci = emptyList(), clock = null))) + + @Test + fun gameOverKeepsWinnerAndDraws() { + roundTrip(SpectatorMessage.GameOver("g1", SpectatorResult(SpectatorOutcome.CHECKMATE, PieceColor.WHITE), clock.copy(running = null))) + roundTrip(SpectatorMessage.GameOver("g1", SpectatorResult(SpectatorOutcome.AGREEMENT, null), null)) + roundTrip(SpectatorMessage.GameOver("g1", SpectatorResult(SpectatorOutcome.INTERRUPTED, null), null)) + } + + @Test + fun everyMessageCarriesTheSenderVersion() { + val line = SpectatorProtocol.encode(SpectatorMessage.Pong, version = 7) + assertEquals(7, SpectatorProtocol.decode(line)!!.version) + } + + @Test + fun unknownTypeFromANewerVersionIsSkippedNotFatal() { + val envelope = SpectatorProtocol.decode("""{"type":"emote","sv":9,"what":"wave"}""") + assertNotNull(envelope) + assertEquals(9, envelope!!.version) + assertNull(envelope.message) + } + + @Test + fun unknownOutcomeAndRejectReasonDegradeGracefully() { + val end = SpectatorProtocol.decode("""{"type":"end","sv":2,"gid":"g1","result":{"o":"abandoned"}}""")!!.message + assertEquals(SpectatorOutcome.UNKNOWN, (end as SpectatorMessage.GameOver).result.outcome) + val reject = SpectatorProtocol.decode("""{"type":"reject","sv":2,"reason":"banned","min":2}""")!!.message + assertEquals(RejectReason.OTHER, (reject as SpectatorMessage.Reject).reason) + } + + @Test + fun malformedInputNeverThrows() { + assertNull(SpectatorProtocol.decode("not json")) + assertNull(SpectatorProtocol.decode("{}")) + assertNull(SpectatorProtocol.decode("")) + // Known type with missing fields: skipped like an unknown one. + assertNull(SpectatorProtocol.decode("""{"type":"move","sv":1}""")!!.message) + assertNull(SpectatorProtocol.decode("""{"type":"welcome","sv":1,"n":1}""")!!.message) + } + + @Test + fun oldHelloWithoutMinimumStillParses() { + val hello = SpectatorProtocol.decode("""{"type":"hello","sv":1}""")!!.message + assertEquals(SpectatorMessage.Hello(1), hello) + } + + @Test + fun clockAdvancesOnlyForTheRunningSide() { + val later = clock.advancedBy(1_500) + assertEquals(295_000, later.whiteMs) + assertEquals(298_500, later.blackMs) + assertEquals(0, SpectatorClock(1_000, 5_000, PieceColor.WHITE).advancedBy(9_000).whiteMs) + assertEquals(clock.copy(running = null), clock.copy(running = null).advancedBy(5_000)) + } + + @Test + fun hugeMoveListIsRejected() { + val moves = (1..2_001).joinToString(",") { "\"e2e4\"" } + val line = """{"type":"game","sv":1,"game":{"gid":"g","wp":{},"bp":{},"moves":[$moves]}}""" + assertNull(SpectatorProtocol.decode(line)!!.message) + assertTrue(SpectatorProtocol.MAX_CLIENT_LINE_CHARS < SpectatorProtocol.MAX_HOST_LINE_CHARS) + } +}