From c28fe49a7a303ef0440ccffd830e4949a1f2381f Mon Sep 17 00:00:00 2001 From: Joel Kronqvist Date: Tue, 18 Oct 2022 21:41:31 +0300 Subject: Enhanced robustness in retrieving the example input and in the init (at reboot) script. The server errored out if the database was empty and there came a request, as it didn't check for empty arrays in dbparse.js in the function getRandomIndex. Fixed by adding handling & recursion limit. Added in init.sh a check to see if logging in to MySQL is possible to prevent errors at startup. --- dbparse.js | 10 +++++++--- init.sh | 8 ++++++++ server.js | 2 ++ 3 files changed, 17 insertions(+), 3 deletions(-) diff --git a/dbparse.js b/dbparse.js index 29b9cb7..eddfdc8 100644 --- a/dbparse.js +++ b/dbparse.js @@ -173,10 +173,14 @@ function randInt(start, stop) return start + Math.floor(Math.random() * (stop - start)); } -async function getRandomIndex(day, DB) +async function getRandomIndex(day, DB, depth=0) { + if (depth > 10) + return null; + let indexes = await DB.execute("SELECT course, teacher, class FROM shifts WHERE day = ? ORDER BY RAND() LIMIT 1", [day]); - indexes = Object.values(indexes[0]); + + indexes = Object.values(indexes[0] || [null, null, null]); /// ERROR HERE!!! let start = randInt(0, indexes.length); for (let test = 0; test < 3; test++) { @@ -185,7 +189,7 @@ async function getRandomIndex(day, DB) return indexes[i]; } console.log("Warning: row without class/teacher/course in database!"); - return getRandomIndex(day, DB); + return getRandomIndex(day, DB, depth + 1); } diff --git a/init.sh b/init.sh index 55be6ee..2fc915d 100755 --- a/init.sh +++ b/init.sh @@ -13,6 +13,14 @@ echo "# Connected to internet!" echo "" +echo "# Testing DB availability" +while ! echo 'exit' | mysql; do + sleep 5 +done +echo "# Database seems to be available (ignore error messages above)" + +echo "" + cd "$BASE_DIR/LYLLRuoka" echo "# node server.js:" node server.js diff --git a/server.js b/server.js index fcfa1ea..c180b71 100644 --- a/server.js +++ b/server.js @@ -252,6 +252,8 @@ async function buildMain(args) // get the example input res["example-input"] = await DBPARSE.randomIndex(day, SQLDB); + if (res["example-input"] === null) + res["example-input"] = ""; // get the day let weekdays = ["ma", "ti", "ke", "to", "pe", "la", "su"]; -- cgit v1.2.3