From 5eb5413d10e24dceb96fd86252c4641109b432d7 Mon Sep 17 00:00:00 2001 From: HF Date: Tue, 30 May 2023 19:47:55 +0200 Subject: [PATCH] render in queue --- ppfun-bridge/src/pixelplanet/constants.js | 1 + ppfun-bridge/src/pixelplanet/index.js | 52 +++++++++++++++++++++-- 2 files changed, 49 insertions(+), 4 deletions(-) diff --git a/ppfun-bridge/src/pixelplanet/constants.js b/ppfun-bridge/src/pixelplanet/constants.js index 1191b4e..7a9ba72 100644 --- a/ppfun-bridge/src/pixelplanet/constants.js +++ b/ppfun-bridge/src/pixelplanet/constants.js @@ -4,3 +4,4 @@ export const MAX_SCALE = 40; // 52 in log2 export const TILE_SIZE = 256; export const TILE_ZOOM_LEVEL = 2; export const BACKGROUND_CLR_RGB = [ 196, 196, 196 ]; +export const QUEUE_LIMIT = 3; diff --git a/ppfun-bridge/src/pixelplanet/index.js b/ppfun-bridge/src/pixelplanet/index.js index 85fba56..b567504 100644 --- a/ppfun-bridge/src/pixelplanet/index.js +++ b/ppfun-bridge/src/pixelplanet/index.js @@ -2,6 +2,7 @@ import fetch from 'node-fetch'; import canvases from './canvases.js'; import renderCanvas from './renderCanvas.js'; +import { QUEUE_LIMIT } from './constants.js'; const linkRegExp = /(#[a-z]*,-?[0-9]*,-?[0-9]*(,-?[0-9]+)?)/gi; const linkRegExpFilter = (val, ind) => ((ind % 3) !== 2); @@ -17,8 +18,50 @@ function compArray(arr1, arr2) { return true; } -export async function parseCanvasLinks(text) { +/* + * render canvas snapshots sequentially in a queue, + * don't repeat most recent render + */ +const queue = []; +let rendering = false; +let lastTitle = ''; +async function render() { + if (!queue.length) { + rendering = false; + return; + } + rendering = true; + const [args, resolve, reject] = queue.shift(); + try { + const ret = await renderCanvas(...args); + resolve(ret); + setTimeout(render, 100); + } catch (err) { + reject(err) + } +} + +function renderCanvasQueue(...args) { + if (queue.length >= QUEUE_LIMIT || args[0] === lastTitle) { + return null; + } + return new Promise((resolve, reject) => { + lastTitle = args[0]; + queue.push([args, resolve, reject]); + if (!rendering) { + setImmediate(render); + } + }); +} + +/** + * check if canvas link is in message and return screenshot of the + * current canvas if so + * @param text message text + * @return object with image, name, type, w, h, size + */ +export async function parseCanvasLinks(text) { if (!text || !canvases) { return null; } @@ -50,9 +93,10 @@ export async function parseCanvasLinks(text) { ) { return; } - console.log(`Fetch canvas ${canvas.title} on ${x}/${y} with zoom ${z}`); - - const imageData = await renderCanvas(canvas, x, y, z); + + const title = `${canvas.title}_${x}_${y}_${z}`; + console.log(`Fetch canvas ${title}`); + const imageData = await renderCanvasQueue(title, canvas, x, y, z); return imageData; }