Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: MemoryFifo return null when empty and timeout 0 #5753

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 16 additions & 6 deletions yarn-project/foundation/src/fifo/memory_fifo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,17 @@ export class MemoryFifo<T> {
}

/**
* Returns next item within the queue, or blocks until and item has been put into the queue.
* If given a timeout, the promise will reject if no item is received after `timeout` seconds.
* Returns next item within the queue, or blocks until an item has been put into the queue.
*
* If given a timeout, the promise will reject if no item is received after `timeoutSec` seconds.
* If the timeout is undefined (default), this call will block until an item is available or the queue is closed.
* If the timeout is 0 and there are no items available then the queue will immediately reject with a TimeoutError.
*
* If the queue is flushing, `null` is returned.
* @param timeout - The timeout in seconds.
* @param timeoutSec - The timeout in seconds.
* @returns A result promise.
*/
public get(timeout?: number): Promise<T | null> {
public get(timeoutSec?: number): Promise<T | null> {
if (this.items.length) {
return Promise.resolve(this.items.shift()!);
}
Expand All @@ -39,18 +43,24 @@ export class MemoryFifo<T> {
return Promise.resolve(null);
}

// if the caller doesn't want to wait for an item to be available
// immediately reject with a Timeout error
if (timeoutSec === 0) {
return Promise.reject(new TimeoutError('Timeout getting item from queue.'));
}

return new Promise<T | null>((resolve, reject) => {
this.waiting.push(resolve);

if (timeout) {
if (timeoutSec) {
setTimeout(() => {
const index = this.waiting.findIndex(r => r === resolve);
if (index > -1) {
this.waiting.splice(index, 1);
const err = new TimeoutError('Timeout getting item from queue.');
reject(err);
}
}, timeout * 1000);
}, timeoutSec * 1000);
}
});
}
Expand Down
Loading