(limit: number = 100)
| 16 | * @param limit max number of promises that can be stored in the buffer |
| 17 | */ |
| 18 | export function makePromiseBuffer<T>(limit: number = 100): PromiseBuffer<T> { |
| 19 | const buffer: Set<PromiseLike<T>> = new Set(); |
| 20 | |
| 21 | function isReady(): boolean { |
| 22 | return buffer.size < limit; |
| 23 | } |
| 24 | |
| 25 | /** |
| 26 | * Remove a promise from the queue. |
| 27 | * |
| 28 | * @param task Can be any PromiseLike<T> |
| 29 | * @returns Removed promise. |
| 30 | */ |
| 31 | function remove(task: PromiseLike<T>): void { |
| 32 | buffer.delete(task); |
| 33 | } |
| 34 | |
| 35 | /** |
| 36 | * Add a promise (representing an in-flight action) to the queue, and set it to remove itself on fulfillment. |
| 37 | * |
| 38 | * @param taskProducer A function producing any PromiseLike<T>; In previous versions this used to be `task: |
| 39 | * PromiseLike<T>`, but under that model, Promises were instantly created on the call-site and their executor |
| 40 | * functions therefore ran immediately. Thus, even if the buffer was full, the action still happened. By |
| 41 | * requiring the promise to be wrapped in a function, we can defer promise creation until after the buffer |
| 42 | * limit check. |
| 43 | * @returns The original promise. |
| 44 | */ |
| 45 | function add(taskProducer: () => PromiseLike<T>): PromiseLike<T> { |
| 46 | if (!isReady()) { |
| 47 | return rejectedSyncPromise(SENTRY_BUFFER_FULL_ERROR); |
| 48 | } |
| 49 | |
| 50 | // start the task and add its promise to the queue |
| 51 | const task = taskProducer(); |
| 52 | buffer.add(task); |
| 53 | void task.then( |
| 54 | () => remove(task), |
| 55 | () => remove(task), |
| 56 | ); |
| 57 | return task; |
| 58 | } |
| 59 | |
| 60 | /** |
| 61 | * Wait for all promises in the queue to resolve or for timeout to expire, whichever comes first. |
| 62 | * |
| 63 | * @param timeout The time, in ms, after which to resolve to `false` if the queue is still non-empty. Passing `0` (or |
| 64 | * not passing anything) will make the promise wait as long as it takes for the queue to drain before resolving to |
| 65 | * `true`. |
| 66 | * @returns A promise which will resolve to `true` if the queue is already empty or drains before the timeout, and |
| 67 | * `false` otherwise |
| 68 | */ |
| 69 | function drain(timeout?: number): PromiseLike<boolean> { |
| 70 | if (!buffer.size) { |
| 71 | return resolvedSyncPromise(true); |
| 72 | } |
| 73 | |
| 74 | // We want to resolve even if one of the promises rejects |
| 75 | const drainPromise = Promise.allSettled(Array.from(buffer)).then(() => true); |
no outgoing calls
no test coverage detected