From bd2300303b60419c24d7d583b9d7c4bf40399c95 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matt=C3=A9o=20Delabre?= Date: Sun, 29 Nov 2020 21:28:56 +0100 Subject: [PATCH] Add progress information during exploration --- lib/explore.mjs | 5 ++++- routes/mazes.mjs | 29 ++++++++++++++++++++--------- 2 files changed, 24 insertions(+), 10 deletions(-) diff --git a/lib/explore.mjs b/lib/explore.mjs index 927d6b3..62bbfb5 100644 --- a/lib/explore.mjs +++ b/lib/explore.mjs @@ -10,9 +10,10 @@ const GRAPH_LINK = ' "%s" -> "%s"'; * * @async * @param string videoId Source video identifier. + * @param function onUpdate Callback run every time a new video is explored. * @return Array. Nodes and set of neighbors of each node. */ -export const exploreVideos = async videoId => +export const exploreVideos = async (videoId, onUpdate) => { // Store metadata about each visited video const videosNodes = Object.create(null); @@ -46,6 +47,8 @@ export const exploreVideos = async videoId => queue.push(nextId); } } + + onUpdate(Object.keys(videosNodes).length, queue.length); } return [videosNodes, nextVideos]; diff --git a/routes/mazes.mjs b/routes/mazes.mjs index b4d5185..9637c3d 100644 --- a/routes/mazes.mjs +++ b/routes/mazes.mjs @@ -5,6 +5,7 @@ import { toSVG } from '../lib/graphviz.mjs'; const router = express.Router(); export default router; +const statusDone = Symbol('DONE'); const statusPending = Symbol('PENDING'); const statusError = Symbol('ERROR'); const cache = Object.create(null); @@ -45,37 +46,47 @@ router.get('/:videoId', async (req, res) => { if (videoId in cache) { - if (cache[videoId] === statusPending) + if (cache[videoId][0] === statusPending) { res.header('Refresh', '5'); - res.send('Exploration in progress… Please wait.'); + res.send(`Exploration in progress, please wait.
+${cache[videoId][1]}…`); } - else if (cache[videoId] === statusError) + else if (cache[videoId][0] === statusError) { res.status(500).send('Error'); } else { - res.send(cache[videoId]); + res.send(cache[videoId][1]); } } else { - cache[videoId] = statusPending; + cache[videoId] = [statusPending, 'Starting exploration']; res.header('Refresh', '1'); - res.send('Exploration in progress… Please wait.'); + res.send('Exploration in progress, please wait.'); try { - const graph = await exploreVideos(req.params.videoId); + const graph = await exploreVideos(req.params.videoId, (done, rem) => + { + cache[videoId] = [ + statusPending, + `${done} videos explored, ${rem} pending` + ]; + }); + + cache[videoId] = [statusPending, 'Converting graph to SVG']; const graphviz = toGraphviz(...graph); const svg = await toSVG(graphviz); - cache[videoId] = svg; + + cache[videoId] = [statusDone, svg]; } catch (err) { console.error(err); - cache[videoId] = statusError; + cache[videoId] = [statusError]; } } });