From 1fd89f6ef109f2bb84267e0b40af51a90b804479 Mon Sep 17 00:00:00 2001 From: Vladyslav Karpenko Date: Tue, 19 Dec 2023 20:03:12 +0200 Subject: [PATCH] Worker task execution timeout (global) The setting server.workers.timeout in application configuration is required but allows zero value to switch off the limit. Closes: https://github.com/metarhia/impress/issues/1950 Co-authored-by: Timur Shemsedinov PR-URL: https://github.com/metarhia/impress/pull/1951 --- CHANGELOG.md | 1 + lib/worker.js | 15 +++++++++++++-- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 613c9868..88a02c9b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ ## [Unreleased][unreleased] - Fixed API endpoints local queue settings applying +- Worker task execution global timeout implementation - Reimplement global timeouts.request usage during a Procedure invocation ## [3.0.13][] - 2023-10-22 diff --git a/lib/worker.js b/lib/worker.js index 82801b6e..4c8f113a 100644 --- a/lib/worker.js +++ b/lib/worker.js @@ -50,15 +50,26 @@ const handlers = { invoke: async ({ exclusive, data, port }) => { const { method, args } = data; - const { sandbox } = application; + const { sandbox, config } = application; const handler = metarhia.metautil.namespaceByPath(sandbox, method); if (!handler) { const error = new Error('Handler not found'); return void port.postMessage({ name: 'error', error }); } const msg = { name: 'invoke', status: 'done' }; + const { timeout } = config.server.workers; try { - const result = await handler(args); + let result; + if (timeout) { + const ac = new AbortController(); + result = await Promise.race([ + metarhia.metautil.timeout(timeout, ac.signal), + handler(args), + ]); + ac.abort(); + } else { + result = await handler(args); + } port.postMessage({ ...msg, data: result }); } catch (error) { port.postMessage({ name: 'error', error });