@a2alite/sdk
Version:
A Modular SDK (Server & Client) for Agent to Agent (A2A) protocol, with easy task lifecycle management
75 lines (74 loc) • 2.48 kB
JavaScript
/**
* In-memory implementation of IQueue<T>
*
* InMemoryQueue provides a simple, non-persistent queue implementation
* with support for blocking dequeue operations. When the queue is empty,
* dequeue operations will block until an item is available or the queue is closed.
*
* @template T - The type of items stored in this queue
*/
class InMemoryQueue {
constructor() {
/** Internal array storing queue items */
this.items = [];
/** Whether the queue has been closed */
this._isClosed = false;
/** Pending promises for blocked dequeue operations */
this.pendingDequeuePromises = [];
}
async dequeue() {
if (this._isClosed) {
return;
}
if (this.items.length === 0) {
// block and add the promise to the pending list to be resolved when an item is enqueued
return new Promise((resolve) => {
this.pendingDequeuePromises.push(resolve);
});
}
// return the first item
return this.items.shift();
}
async enqueue(item) {
this.items.push(item);
// resolve any pending promises
this.resolvePendingPromises();
}
/**
* Resolves pending dequeue promises with available items
* @private
*/
resolvePendingPromises() {
// iterate and resolve any pending promises as long as there are items in the queue
while (this.pendingDequeuePromises.length > 0 && this.items.length > 0) {
const resolvePending = this.pendingDequeuePromises.shift();
resolvePending(this.items.shift());
}
}
async size() {
return this.items.length;
}
async isEmpty() {
return this.items.length === 0;
}
async peek() {
if (this.items.length === 0)
return undefined;
return this.items[0];
}
/**
* Closes the queue and resolves any pending promises with undefined
* Once closed, the queue cannot be used for further operations
*/
async close() {
this.items = [];
// iterate and resolve any pending promises as long as there are items in the queue
while (this.pendingDequeuePromises.length > 0) {
const resolvePending = this.pendingDequeuePromises.shift();
resolvePending(undefined);
}
this.pendingDequeuePromises = [];
this._isClosed = true;
}
}
export { InMemoryQueue };