From 137193c3e908483ae1199aea7dbdee365b9e2e8f Mon Sep 17 00:00:00 2001 From: Tomi Turtiainen <10324676+tomi@users.noreply.github.com> Date: Wed, 27 Nov 2024 10:36:37 +0200 Subject: [PATCH] fix(core): Increase task runner offer validity and introduce randomness (no-changelog) (#11907) --- packages/@n8n/task-runner/src/task-runner.ts | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/packages/@n8n/task-runner/src/task-runner.ts b/packages/@n8n/task-runner/src/task-runner.ts index 8af8aeeb08..1486af280d 100644 --- a/packages/@n8n/task-runner/src/task-runner.ts +++ b/packages/@n8n/task-runner/src/task-runner.ts @@ -1,4 +1,4 @@ -import { ApplicationError, ensureError } from 'n8n-workflow'; +import { ApplicationError, ensureError, randomInt } from 'n8n-workflow'; import { nanoid } from 'nanoid'; import { EventEmitter } from 'node:events'; import { type MessageEvent, WebSocket } from 'ws'; @@ -42,8 +42,11 @@ export interface RPCCallObject { [name: string]: ((...args: unknown[]) => Promise) | RPCCallObject; } -const VALID_TIME_MS = 1000; -const VALID_EXTRA_MS = 100; +const OFFER_VALID_TIME_MS = 5000; +const OFFER_VALID_EXTRA_MS = 100; + +/** Converts milliseconds to nanoseconds */ +const msToNs = (ms: number) => BigInt(ms * 1_000_000); export interface TaskRunnerOpts extends BaseRunnerConfig { taskType: string; @@ -167,16 +170,20 @@ export abstract class TaskRunner extends EventEmitter { (Object.values(this.openOffers).length + Object.values(this.runningTasks).length); for (let i = 0; i < offersToSend; i++) { + // Add a bit of randomness so that not all offers expire at the same time + const validForInMs = OFFER_VALID_TIME_MS + randomInt(500); + // Add a little extra time to account for latency + const validUntil = process.hrtime.bigint() + msToNs(validForInMs + OFFER_VALID_EXTRA_MS); const offer: TaskOffer = { offerId: nanoid(), - validUntil: process.hrtime.bigint() + BigInt((VALID_TIME_MS + VALID_EXTRA_MS) * 1_000_000), // Adding a little extra time to account for latency + validUntil, }; this.openOffers.set(offer.offerId, offer); this.send({ type: 'runner:taskoffer', taskType: this.taskType, offerId: offer.offerId, - validFor: VALID_TIME_MS, + validFor: validForInMs, }); } }