UNPKG

acelga-bus

Version:

An extensible typescript message bus with support for middlewares

77 lines 3.1 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); class AllParallelScheduler { schedule(events, maxConcurrency) { if (!Number.isFinite(maxConcurrency) || !maxConcurrency || maxConcurrency <= 0 || events.length <= maxConcurrency) { return { plan: events.map(event => { return { payloads: [event], preserveOrder: false, }; }), rebuildOrder: create1to1Mapper(), }; } const plan = new Array(maxConcurrency).fill(0).map(() => []); const indexMapping = new Array(maxConcurrency).fill(0).map(() => []); events.forEach((event, index) => { const pipelineIndex = index - maxConcurrency * Math.floor(index / maxConcurrency); plan[pipelineIndex].push(event); indexMapping[pipelineIndex].push(index); }); const clonedPlan = plan.map(pipeline => { return { preserveOrder: false, payloads: pipeline.slice(0), }; }); return { plan: clonedPlan, rebuildOrder: createMapper(indexMapping, plan), }; } } exports.default = AllParallelScheduler; function create1to1Mapper() { return (results) => { return results.map((result) => { if (!Array.isArray(result) || result.length !== 1) { throw new ResultsStructureNotMatchingOriginalExecutionPlan(); } return result[0]; }); }; } function createMapper(indexMapping, plan) { return (results) => { const originalOrder = []; if (plan.length !== results.length) { throw new ResultsStructureNotMatchingOriginalExecutionPlan(); } plan.forEach((pipeline, pipelineIndex) => { const isResultPipelineArray = Array.isArray(results[pipelineIndex]); const isResultSameLength = results[pipelineIndex].length === pipeline.length; if (!isResultPipelineArray || !isResultSameLength) { throw new ResultsStructureNotMatchingOriginalExecutionPlan(); } pipeline.forEach((item, itemIndex) => { const originalIndex = indexMapping[pipelineIndex][itemIndex]; const resultValue = results[pipelineIndex][itemIndex]; originalOrder[originalIndex] = resultValue; }); }); return originalOrder; }; } class ResultsStructureNotMatchingOriginalExecutionPlan extends Error { constructor() { super(); this.message = 'The results provided to decode from the scheduled execution plan doesn\'t match the original scheduled structure. Are you sure you are not deleting items or that you are passing the correct variable?'; } } exports.ResultsStructureNotMatchingOriginalExecutionPlan = ResultsStructureNotMatchingOriginalExecutionPlan; //# sourceMappingURL=allParallelScheduler.js.map