'use strict'; const activityIngestQueue = require('./activityIngestQueue'); let epoch = null; async function beginGlobalActivityScan(db) { if (!epoch || !epoch.active) { const created = { active: true, baselineDone: 0, enumerationsInProgress: 0, initPromise: null, }; epoch = created; created.initPromise = activityIngestQueue .getActivityIngestQueueCounts(db) .then(counts => { created.baselineDone = Number(counts.done || 0); }) .catch(err => { if (epoch === created) created.active = false; throw err; }); } const current = epoch; current.enumerationsInProgress++; try { await current.initPromise; } catch (err) { current.enumerationsInProgress = Math.max( 0, current.enumerationsInProgress - 1 ); throw err; } } function finishGlobalActivityScan() { if (epoch) { epoch.enumerationsInProgress = Math.max( 0, epoch.enumerationsInProgress - 1 ); } } async function getGlobalActivityScanStatus(db) { const counts = await activityIngestQueue.getActivityIngestQueueCounts(db); const pending = Number(counts.pending || 0); const processing = Number(counts.processing || 0); const done = Number(counts.done || 0); const errors = Number(counts.error || 0); const remaining = pending + processing; const totalCurrent = pending + processing + done + errors; let current; let total; let percent; let baselineDone = done; if (epoch && epoch.active) { baselineDone = epoch.baselineDone; total = Math.max(0, totalCurrent - baselineDone); current = Math.max(0, (done - baselineDone) + errors); percent = total <= 0 ? 100 : Math.max(0, Math.min(100, Math.round(current / total * 100))); // Chiude il ciclo quando tutte le scansioni hanno terminato // l'accodamento e non restano job pending o processing. if (epoch.enumerationsInProgress === 0 && remaining === 0) { epoch.active = false; } } else { total = totalCurrent; current = totalCurrent; percent = 100; } return { pending, processing, done, errors, remaining, current, total, percent, baselineDone, }; } module.exports = { beginGlobalActivityScan, finishGlobalActivityScan, getGlobalActivityScanStatus, };