From 6a2ca8a69bf66276bb6d49856666a8c2ffad1a82 Mon Sep 17 00:00:00 2001 From: xuef Date: Tue, 28 Nov 2023 07:18:18 +0000 Subject: [PATCH] Fix an issue that pushing may miss messages. --- .../Controllers/GamesController.cs | 32 ++++++++++++------- 1 file changed, 20 insertions(+), 12 deletions(-) diff --git a/src/Aiursoft.ChessServer/Controllers/GamesController.cs b/src/Aiursoft.ChessServer/Controllers/GamesController.cs index 6309318..aa0a1dd 100644 --- a/src/Aiursoft.ChessServer/Controllers/GamesController.cs +++ b/src/Aiursoft.ChessServer/Controllers/GamesController.cs @@ -53,33 +53,41 @@ public class GamesController : Controller } }); } - + [Route("games/{id}/ws")] public async Task GetWebSocket([FromRoute] int id) { var lastReadId = _counter.GetCurrent; var (channel, blocker) = _database.ListenChannel(id); - + await _pusher.Accept(HttpContext); try { await Task.Factory.StartNew(_pusher.PendingClose); while (_pusher.Connected) { + while (true) + { + var nextMessages = channel + .GetMessagesFrom(lastReadId); + + if (!nextMessages.Any()) + { + break; + } + + var messageToPush = nextMessages.MinBy(t => t.Id); + await _pusher.SendMessage(messageToPush!.Content); + lastReadId = messageToPush.Id; + } await blocker.WaitAsync(); - var nextMessages = channel - .GetMessagesFrom(lastReadId) - .ToList(); - var messageToPush = nextMessages.MinBy(t => t.Id); - await _pusher.SendMessage(messageToPush!.Content); - lastReadId = messageToPush.Id; } } finally { await _pusher.Close(); if (!channel.UnRegister(out blocker)) - { + { throw new InvalidOperationException("Failed to unregister blocker!"); } } @@ -93,7 +101,7 @@ public class GamesController : Controller var game = _database.GetOrAdd(id); return Ok(game.ToAscii()); } - + [Route("games/{id}/html")] public IActionResult GetHtml([FromRoute] int id) { @@ -108,7 +116,7 @@ public class GamesController : Controller } [Route("games/{id}/pgn")] - public IActionResult GetPgn([FromRoute]int id) + public IActionResult GetPgn([FromRoute] int id) { var game = _database.GetOrAdd(id); return Ok(game.ToPgn()); @@ -116,7 +124,7 @@ public class GamesController : Controller [HttpPost] [Route("games/{id}/move/{player}/{move}")] - public IActionResult Move([FromRoute]int id, [FromRoute]string player, [FromRoute]string move) + public IActionResult Move([FromRoute] int id, [FromRoute] string player, [FromRoute] string move) { var game = _database.GetOrAdd(id); try