@sema-agent/core
Version:
Stateless, task-oriented AI agent core
98 lines (97 loc) • 2.55 kB
JavaScript
export class PushQueue {
buffer = [];
waiters = [];
closed = false;
held = [];
push(value) {
if (this.closed) {
return false;
}
if (this.held.length > 0) {
this.held.push({ value });
return true;
}
this.deliver(value);
return true;
}
reserve() {
if (this.closed)
return undefined;
const place = { values: [], open: true };
this.held.push({ place });
return {
put: (values) => {
if (!place.open)
return;
place.values.push(...values);
this.release();
},
fill: (values) => {
if (!place.open)
return;
place.values.push(...values);
place.open = false;
this.release();
},
};
}
close() {
this.closed = true;
this.endIfDone();
}
freePlaces() {
for (const h of this.held)
if ("place" in h)
h.place.open = false;
this.release();
}
release() {
while (this.held.length > 0) {
const head = this.held[0];
if ("value" in head) {
this.held.shift();
this.deliver(head.value);
continue;
}
for (const v of head.place.values.splice(0))
this.deliver(v);
if (head.place.open)
break;
this.held.shift();
}
this.endIfDone();
}
deliver(value) {
const waiter = this.waiters.shift();
if (waiter) {
waiter({ value, done: false });
}
else {
this.buffer.push(value);
}
}
endIfDone() {
if (!this.closed || this.held.length > 0)
return;
while (this.waiters.length > 0) {
this.waiters.shift()({ value: undefined, done: true });
}
}
async *[Symbol.asyncIterator]() {
for (;;) {
if (this.buffer.length > 0) {
yield this.buffer.shift();
}
else if (this.closed && this.held.length === 0) {
return;
}
else {
const r = await new Promise((resolve) => this.waiters.push(resolve));
if (r.done) {
return;
}
yield r.value;
}
}
}
}