Files
ohif-viewer/platform/core/src/utils/Queue.js
T
Emanuel Fiuza de OliveiraandJames Petts 29d4955980 Feat #1130 [WIP] Adding support for downloading and zipping files (#1501)
* Feat #1130 Adding support for downloading and zipping files

@ This is a combination of 12 commits.
 - Feat #1130 Initial Commit
 - Feat #1130 Adding support for hierachical lists
 - Feat #1130 [WIP] Adding support for downloading and zipping files
 - Feat #1130 Adding support for hierarchical folder structure study, series, instances on generated zip file
 - Feat #1130 Adding unit tests and addressing code review feedbacks
 - Feat #1130 POC (adding module to support on progress handling)
 - Feat #1130 Improving logic from progress tracking utils
 - Feat #1130 Renaming module with progress tracking utils
 - Feat #1130 Beta version of Progress Tracking utils
 - Feat #1130 Adding unit tests for Progress Tracking Utils
 - Feat #1130 Documenting public methods from progress tracking utils module
 - Feat #1130 Adding support for download and zip progress reporting

* Feat #1130 Addressing code review feedback

* Feat #1130 Preventing multiple downloads from executing at once

* Feat #1130 Improving error message for concurrent downloads

* Remove downloadAndZipSeriesOnViewports

Co-authored-by: James Petts <jamesapetts@gmail.com>
2020-04-15 18:57:57 +02:00

67 lines
1.6 KiB
JavaScript

export default class Queue {
constructor(limit) {
this.limit = limit;
this.size = 0;
this.awaiting = null;
}
/**
* Creates a new "proxy" function associated with the current execution queue
* instance. When the returned function is invoked, the queue limit is checked
* to make sure the limit of scheduled tasks is repected (throwing an
* exception when the limit has been reached and before calling the original
* function). The original function is only invoked after all the previously
* scheduled tasks have finished executing (their returned promises have
* resolved/rejected);
*
* @param {function} task The function whose execution will be associated
* with the current Queue instance;
* @returns {function} The "proxy" function bound to the current Queue
* instance;
*/
bind(task) {
return bind(this, task);
}
bindSafe(task, onError) {
const boundTask = bind(this, task);
return async function safeTask(...args) {
try {
return await boundTask(...args);
} catch (e) {
onError(e);
}
};
}
}
/**
* Utils
*/
function bind(queue, task) {
const cleaner = clean.bind(null, queue);
return async function boundTask(...args) {
if (queue.size >= queue.limit) {
throw new Error('Queue limit reached');
}
const promise = chain(queue.awaiting, task, args);
queue.awaiting = promise.then(cleaner, cleaner);
queue.size++;
return promise;
};
}
function clean(queue) {
if (queue.size > 0 && --queue.size === 0) {
queue.awaiting = null;
}
}
async function chain(prev, task, args) {
await prev;
return task(...args);
}