fix(queue): wait for actual worker drain before disconnecting (CL22)

This commit is contained in:
Boki 2026-10-28 14:47:20 -04:00
parent ec582bd5e8
commit 1aa35d2db3
7 changed files with 177 additions and 29 deletions

View file

@ -23,6 +23,7 @@ export class Queue {
private bullQueue: BullQueue;
private workers: Worker[] = [];
private queueEvents?: QueueEvents;
private closePromise: Promise<void> | null = null;
private queueName: string;
private redisConfig: RedisConfig;
private readonly logger: Logger;
@ -269,27 +270,19 @@ export class Queue {
/**
* Close the queue (cleanup resources)
*/
/**
* Close the queue (cleanup resources)
*/
async close(): Promise<void> {
close(): Promise<void> {
// Retain the actual drain promise. The application owns any deadline that
// forces process exit; a queue must not report completion with active jobs.
return (this.closePromise ??= Promise.resolve().then(() => this.performClose()));
}
private async performClose(): Promise<void> {
try {
// Close workers first with timeout
// Stop taking jobs and wait for every active worker before its transports.
if (this.workers.length > 0) {
const workerClosePromises = this.workers.map(async (worker, idx) => {
try {
const closePromise = worker.close();
const timeoutPromise = new Promise<void>(resolve => {
setTimeout(() => {
this.logger.warn('Worker close timeout, forcing closure', {
queueName: this.queueName,
workerId: idx,
});
resolve();
}, 2000); // 2 second timeout per worker
});
await Promise.race([closePromise, timeoutPromise]);
await worker.close();
} catch (error) {
this.logger.warn('Error closing worker', {
queueName: this.queueName,