Skip to content
Open
Show file tree
Hide file tree
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
32 changes: 31 additions & 1 deletion src/batch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,11 @@ export class BatchFlight<K, V> {
validateNonNegativeDuration('timeoutMs', this.timeoutMs);
}

/** Returns the number of unique keys currently queued for the next batch flush. */
get pendingCount(): number {
return this.pending.size;
}

/** Queues `key` for the next batch flush and resolves with its individual value. */
load(key: K): Promise<V> {
try {
Expand Down Expand Up @@ -179,7 +184,8 @@ export class BatchFlight<K, V> {
}, this.maxWindowMs);
}

private flush(): void {
/** Triggers an immediate flush of currently pending keys (no-op if empty). */
flush(): void {
if (this.pending.size === 0) {
return;
}
Expand All @@ -196,6 +202,30 @@ export class BatchFlight<K, V> {
void this.executeBatch(entries, keys);
}

/**
* Cancels any active flush timer and rejects all currently pending waiters
* with `reason`, returning the number of cleared entries.
*/
clear(reason?: unknown): number {
Comment on lines +205 to +209

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 API references omit new helpers

The public API references in README.md and llms.txt still list only load() and loadMany(). Add pendingCount, flush(), and clear() there. Explain that they only affect queued keys, that flush() does not wait for completion, and that clear() returns a unique-key count. These details matter for the shutdown use case this change adds.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/batch.ts
Line: 205-209

Comment:
**API references omit new helpers**

The public API references in `README.md` and `llms.txt` still list only `load()` and `loadMany()`. Add `pendingCount`, `flush()`, and `clear()` there. Explain that they only affect queued keys, that `flush()` does not wait for completion, and that `clear()` returns a unique-key count. These details matter for the shutdown use case this change adds.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

if (this.flushTimer !== undefined) {
clearTimeout(this.flushTimer);
this.flushTimer = undefined;
}

const count = this.pending.size;
if (count === 0) {
return 0;
}

const entries = Array.from(this.pending.values());
this.pending.clear();
const rejection = reason !== undefined ? reason : new Error('BatchFlight cleared');
for (const entry of entries) {
entry.reject(rejection);
}
return count;
}

private async executeBatch(
entries: readonly PendingKey<K, V>[],
keys: readonly K[],
Expand Down
50 changes: 50 additions & 0 deletions test/batch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,56 @@ describe('BatchFlight', () => {

await expect(pending).resolves.toBe('val:1');
});

it('tracks pendingCount and flushes immediately with flush()', async () => {
const batches: number[][] = [];
const batch = new BatchFlight<number, string>(
async (keys) => {
batches.push([...keys]);
return keys.map((k) => `val:${k}`);
},
{ maxWindowMs: 5_000 },
);

expect(batch.pendingCount).toBe(0);
batch.flush(); // no-op when empty
expect(batches).toEqual([]);

const p1 = batch.load(1);
const p2 = batch.load(2);
const p2Dup = batch.load(2);
expect(batch.pendingCount).toBe(2);

batch.flush();
expect(batch.pendingCount).toBe(0);
await expect(Promise.all([p1, p2, p2Dup])).resolves.toEqual(['val:1', 'val:2', 'val:2']);
expect(batches).toEqual([[1, 2]]);
});

it('clear() cancels active timer, rejects pending waiters, and returns cleared count', async () => {
let called = false;
const batch = new BatchFlight<number, string>(
async (keys) => {
called = true;
return keys.map((k) => `val:${k}`);
},
{ maxWindowMs: 5_000 },
Comment on lines +349 to +356

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Timer cleanup goes unchecked

The new clear() test never checks that its timer was removed. Both promise assertions finish before the 5-second window ends. called stays false even if the timer later fires because the queue is already empty.

Use fake timers and assert that no timer remains after clear(). Cover the same cleanup after public flush(). Otherwise, a change that leaves Node.js running unnecessarily would pass these tests.

Prompt To Fix With AI
This is a comment left during a code review.
Path: test/batch.test.ts
Line: 349-356

Comment:
**Timer cleanup goes unchecked**

The new `clear()` test never checks that its timer was removed. Both promise assertions finish before the 5-second window ends. `called` stays false even if the timer later fires because the queue is already empty.

Use fake timers and assert that no timer remains after `clear()`. Cover the same cleanup after public `flush()`. Otherwise, a change that leaves Node.js running unnecessarily would pass these tests.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

);

expect(batch.clear()).toBe(0);

const p1 = batch.load(1);
const p2 = batch.load(2);
expect(batch.pendingCount).toBe(2);

const reason = new Error('shutting down');
expect(batch.clear(reason)).toBe(2);
expect(batch.pendingCount).toBe(0);

await expect(p1).rejects.toBe(reason);
await expect(p2).rejects.toBe(reason);
expect(called).toBe(false);
});
});

// =========================================================================
Expand Down