{"version":3,"file":"taskQueue.mjs","names":[],"sources":["../../src/tools/taskQueue.ts"],"sourcesContent":["import { ONE_SECOND } from '@openobserve/js-core/time'\nimport { requestIdleCallback } from './requestIdleCallback'\n\n/**\n * Maximum delay before starting to execute tasks in the queue. We don't want to wait too long\n * before running tasks, as it might hurt reliability (ex: if the user navigates away, we might lose\n * the opportunity to send some data). We also don't want to run tasks too often, as it might hurt\n * performance.\n */\nconst IDLE_CALLBACK_TIMEOUT = ONE_SECOND\n\n/**\n * Maximum amount of time allocated to running tasks when a timeout (`IDLE_CALLBACK_TIMEOUT`) is\n * reached. We should not run tasks for too long as it will hurt performance, but we should still\n * run some tasks to avoid postponing them forever.\n *\n * Rational: Running tasks for 30ms every second (IDLE_CALLBACK_TIMEOUT) should be acceptable.\n */\nexport const MAX_EXECUTION_TIME_ON_TIMEOUT = 30\n\nexport interface TaskQueue {\n  push(task: Task): void\n  stop(): void\n}\n\ntype Task = () => void\n\nexport function createTaskQueue(): TaskQueue {\n  const pendingTasks: Task[] = []\n\n  function run(deadline: IdleDeadline | null) {\n    let executionTimeRemaining: () => number\n    // `deadline` can be null when `requestIdleCallback` is replaced by a page-injected polyfill\n    // (e.g. `setTimeout(cb, 0)` in some WKWebViews) that invokes the callback with no argument.\n    if (!deadline || deadline.didTimeout) {\n      const start = performance.now()\n      executionTimeRemaining = () => MAX_EXECUTION_TIME_ON_TIMEOUT - (performance.now() - start)\n    } else {\n      executionTimeRemaining = deadline.timeRemaining.bind(deadline)\n    }\n\n    while (executionTimeRemaining() > 0 && pendingTasks.length) {\n      pendingTasks.shift()!()\n    }\n\n    if (pendingTasks.length) {\n      scheduleNextRun()\n    }\n  }\n\n  function scheduleNextRun() {\n    requestIdleCallback(run, { timeout: IDLE_CALLBACK_TIMEOUT })\n  }\n\n  return {\n    push(task) {\n      if (pendingTasks.push(task) === 1) {\n        scheduleNextRun()\n      }\n    },\n    stop() {\n      pendingTasks.length = 0\n    },\n  }\n}\n"],"mappings":";;;;;;;;;AASA,MAAM,wBAAwB;;;;;;;;AAS9B,MAAa,gCAAgC;AAS7C,SAAgB,kBAA6B;CAC3C,MAAM,eAAuB,CAAC;CAE9B,SAAS,IAAI,UAA+B;EAC1C,IAAI;EAGJ,IAAI,CAAC,YAAY,SAAS,YAAY;GACpC,MAAM,QAAQ,YAAY,IAAI;GAC9B,+BAAA,MAAgE,YAAY,IAAI,IAAI;EACtF,OACE,yBAAyB,SAAS,cAAc,KAAK,QAAQ;EAG/D,OAAO,uBAAuB,IAAI,KAAK,aAAa,QAClD,aAAa,MAAM,CAAC,CAAE;EAGxB,IAAI,aAAa,QACf,gBAAgB;CAEpB;CAEA,SAAS,kBAAkB;EACzB,oBAAoB,KAAK,EAAE,SAAS,sBAAsB,CAAC;CAC7D;CAEA,OAAO;EACL,KAAK,MAAM;GACT,IAAI,aAAa,KAAK,IAAI,MAAM,GAC9B,gBAAgB;EAEpB;EACA,OAAO;GACL,aAAa,SAAS;EACxB;CACF;AACF"}