More defensively save games when closing
authorRaphaël Jakse <raphael.jakse@univ-grenoble-alpes.fr>
Sun, 5 Apr 2020 20:00:07 +0000 (22:00 +0200)
committerRaphaël Jakse <raphael.jakse@univ-grenoble-alpes.fr>
Sun, 5 Apr 2020 20:00:07 +0000 (22:00 +0200)
trivabble-server.js

index 530495f5bae972e0d725f0fd6df446fef887f740..24f6b5fae914bdb9214988e438f94fb024fdb40b 100644 (file)
@@ -115,16 +115,14 @@ let saveTimeout = null;
 let running = true;
 const server = http.createServer(handleRequest);
 
-function saveGames(exit) {
+function saveGames(callback) {
     fs.writeFile("games.backup.json", JSON.stringify(games), function (err) {
         if (err) {
             console.error("ERROR: Cannot save games!");
-        } else if (exit) {
-            console.log("Games saved.");
         }
 
-        if (exit) {
-            server.close();
+        if (typeof callback === "function") {
+            return callback(err);
         }
     });
 
@@ -153,26 +151,34 @@ function writeResponse(responseAndIsES, data, terminate) {
 }
 
 function stop() {
-    running = false;
-    console.log("Closing connections and saving the game state...");
+    console.log("Saving games a first time");
+    if (saveTimeout) {
+        clearTimeout(saveTimeout);
+        saveTimeout = null;
+    }
 
-    let listeningPlayerCount = 0;
-    let gamesCount = 0;
+    saveGames(function () {
+        running = false;
+        console.log("Closing connections and saving the game state...");
 
-    for (const gameID of Object.keys(games)) {
-        const game = games[gameID];
-        for (const listeningPlayer of game.listeningPlayers) {
-            writeResponse(listeningPlayer, '{"stopping": 2000}', true);
-        }
+        let listeningPlayerCount = 0;
+        let gamesCount = 0;
+
+        for (const gameID of Object.keys(games)) {
+            const game = games[gameID];
+            for (const listeningPlayer of game.listeningPlayers) {
+                writeResponse(listeningPlayer, '{"stopping": 2000}', true);
+            }
 
-        if (game.listeningPlayers.length) {
-            listeningPlayerCount += game.listeningPlayers.length;
-            gamesCount++;
+            if (game.listeningPlayers.length) {
+                listeningPlayerCount += game.listeningPlayers.length;
+                gamesCount++;
+            }
         }
-    }
 
-    console.log("Stopped", gamesCount, "games and", listeningPlayerCount, "player connections.");
-    saveGames(true);
+        console.log("Stopped", gamesCount, "games and", listeningPlayerCount, "player connections.");
+        server.close(saveGames);
+    });
 }
 
 function stopKeepAlive(responseAndIsES) {