fix(queue): preserve pending payloads during shutdown (CL22)
This commit is contained in:
parent
5400dba47e
commit
3fc0a272d8
6 changed files with 266 additions and 87 deletions
|
|
@ -31,7 +31,7 @@ export class QueueManager {
|
|||
private rateLimiter?: QueueRateLimiter;
|
||||
private redisConnection: ReturnType<typeof getRedisConnection>;
|
||||
private ioredisConnection?: Redis;
|
||||
private isShuttingDown = false;
|
||||
private lifecycle: 'running' | 'draining' | 'closed' = 'running';
|
||||
private shutdownPromise: Promise<void> | null = null;
|
||||
private config: QueueManagerConfig;
|
||||
private readonly logger: Logger;
|
||||
|
|
@ -95,6 +95,7 @@ export class QueueManager {
|
|||
* If serviceName is configured, automatically handles namespacing
|
||||
*/
|
||||
getQueue(queueName: string, options: QueueOptions = {}): Queue {
|
||||
this.assertConnectionsOpen();
|
||||
let fullQueueName = queueName;
|
||||
let isOwnQueue = true;
|
||||
|
||||
|
|
@ -135,6 +136,9 @@ export class QueueManager {
|
|||
return existingQueue;
|
||||
}
|
||||
}
|
||||
if (this.lifecycle !== 'running') {
|
||||
throw new Error('QueueManager is shutting down; new queues cannot be created');
|
||||
}
|
||||
|
||||
// Create new queue with merged options
|
||||
const mergedOptions = {
|
||||
|
|
@ -167,12 +171,9 @@ export class QueueManager {
|
|||
// Store the queue
|
||||
this.queues.set(queueName, queue);
|
||||
|
||||
// Automatically initialize batch cache for the queue
|
||||
this.initializeBatchCacheSync(queueName);
|
||||
|
||||
// Rate limit rules are now added via addRateLimitRules after handlers are initialized
|
||||
|
||||
this.logger.info('Queue created with batch cache', {
|
||||
this.logger.info('Queue created', {
|
||||
queueName,
|
||||
originalQueueName: options.handlerRegistry ? 'has-handler-registry' : 'no-handler-registry',
|
||||
workers: workers,
|
||||
|
|
@ -204,6 +205,7 @@ export class QueueManager {
|
|||
* Get or create a cache for a queue
|
||||
*/
|
||||
getCache(queueName: string): CacheProvider {
|
||||
this.assertConnectionsOpen();
|
||||
if (!this.caches.has(queueName)) {
|
||||
const cacheProvider = createCache({
|
||||
redisConfig: this.config.redis,
|
||||
|
|
@ -241,16 +243,6 @@ export class QueueManager {
|
|||
this.logger.info('Cache initialized for queue', { queueName });
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize batch cache synchronously (for automatic initialization)
|
||||
* The cache will be ready for use, but we don't wait for Redis connection
|
||||
*/
|
||||
private initializeBatchCacheSync(queueName: string): void {
|
||||
// Just create the cache - it will connect automatically when first used
|
||||
this.getCache(queueName);
|
||||
this.logger.trace('Batch cache initialized synchronously for queue', { queueName });
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the queues map (for subclasses)
|
||||
*/
|
||||
|
|
@ -455,89 +447,82 @@ export class QueueManager {
|
|||
/**
|
||||
* Shutdown all queues and workers (thread-safe)
|
||||
*/
|
||||
async shutdown(): Promise<void> {
|
||||
// If already shutting down, return the existing promise
|
||||
if (this.shutdownPromise) {
|
||||
return this.shutdownPromise;
|
||||
shutdown(): Promise<void> {
|
||||
if (!this.shutdownPromise) {
|
||||
this.lifecycle = 'draining';
|
||||
this.logger.info('Shutting down QueueManager...');
|
||||
// Store the promise before invoking owned transports, including cleanup
|
||||
// callbacks that can request shutdown again.
|
||||
this.shutdownPromise = Promise.resolve().then(() => this.performShutdown());
|
||||
}
|
||||
|
||||
if (this.isShuttingDown) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.isShuttingDown = true;
|
||||
this.logger.info('Shutting down QueueManager...');
|
||||
|
||||
// Create shutdown promise
|
||||
this.shutdownPromise = this.performShutdown();
|
||||
return this.shutdownPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform the actual shutdown
|
||||
*/
|
||||
private async performShutdown(): Promise<void> {
|
||||
private assertConnectionsOpen(): void {
|
||||
if (this.lifecycle === 'closed') {
|
||||
throw new Error('QueueManager is closed');
|
||||
}
|
||||
}
|
||||
|
||||
private async closeQueue(queue: Pick<Queue, 'close'>): Promise<void> {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
try {
|
||||
// Close all queues (this now includes workers since they're managed by Queue class)
|
||||
const queueShutdownPromises = Array.from(this.queues.values()).map(async queue => {
|
||||
await Promise.race([
|
||||
queue.close(),
|
||||
new Promise<never>((_, reject) => {
|
||||
timer = setTimeout(() => reject(new Error('Queue close timeout')), 5000);
|
||||
}),
|
||||
]);
|
||||
} catch (error) {
|
||||
this.logger.warn('Error closing queue', { error });
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
private async performShutdown(): Promise<void> {
|
||||
// Active workers may still read batch payloads or publish child jobs while
|
||||
// their queues drain. Close those connections only after queue close settles.
|
||||
await Promise.all([...this.queues.values()].map(queue => this.closeQueue(queue)));
|
||||
this.lifecycle = 'closed';
|
||||
await Promise.all([...this.producerQueues.values()].map(queue => this.closeQueue(queue)));
|
||||
await Promise.all(
|
||||
[...this.caches.values()].map(async cache => {
|
||||
try {
|
||||
// Add timeout to queue.close() to prevent hanging
|
||||
const closePromise = queue.close();
|
||||
const timeoutPromise = new Promise<never>(
|
||||
(_, reject) => setTimeout(() => reject(new Error('Queue close timeout')), 5000) // 5 second timeout per queue
|
||||
);
|
||||
|
||||
await Promise.race([closePromise, timeoutPromise]);
|
||||
} catch (error) {
|
||||
this.logger.warn('Error closing queue', { error: (error as Error).message });
|
||||
}
|
||||
});
|
||||
|
||||
await Promise.all(queueShutdownPromises);
|
||||
|
||||
// Close all caches
|
||||
const cacheShutdownPromises = Array.from(this.caches.values()).map(async cache => {
|
||||
try {
|
||||
// Clear cache before shutdown
|
||||
await cache.clear();
|
||||
} catch (error) {
|
||||
this.logger.warn('Error clearing cache', { error: (error as Error).message });
|
||||
} finally {
|
||||
// Batch payloads belong to queued work, not to this process. Completion
|
||||
// cleanup and TTL own deletion, even when another process uses this namespace.
|
||||
await cache.disconnect?.();
|
||||
}
|
||||
});
|
||||
|
||||
await Promise.all(cacheShutdownPromises);
|
||||
|
||||
// Close ioredis connection
|
||||
if (this.ioredisConnection) {
|
||||
try {
|
||||
await this.ioredisConnection.quit();
|
||||
this.logger.debug('IoRedis connection closed');
|
||||
} catch (error) {
|
||||
this.logger.warn('Error closing ioredis connection', { error: (error as Error).message });
|
||||
this.logger.warn('Error disconnecting batch cache', { error });
|
||||
}
|
||||
})
|
||||
);
|
||||
if (this.ioredisConnection) {
|
||||
try {
|
||||
await this.ioredisConnection.quit();
|
||||
} catch (error) {
|
||||
this.logger.warn('Error closing ioredis connection', { error });
|
||||
try {
|
||||
this.ioredisConnection.disconnect();
|
||||
} catch (disconnectError) {
|
||||
this.logger.warn('Error disconnecting ioredis connection', { error: disconnectError });
|
||||
}
|
||||
}
|
||||
|
||||
// Clear collections
|
||||
this.queues.clear();
|
||||
this.caches.clear();
|
||||
|
||||
this.logger.info('QueueManager shutdown complete');
|
||||
} catch (error) {
|
||||
this.logger.error('Error during shutdown', { error: (error as Error).message });
|
||||
throw error;
|
||||
} finally {
|
||||
// Reset shutdown state
|
||||
this.shutdownPromise = null;
|
||||
this.isShuttingDown = false;
|
||||
}
|
||||
this.queues.clear();
|
||||
this.producerQueues.clear();
|
||||
this.caches.clear();
|
||||
this.ioredisConnection = undefined;
|
||||
this.logger.info('QueueManager shutdown complete');
|
||||
}
|
||||
|
||||
/**
|
||||
* Start workers for all queues (used when delayWorkerStart is enabled)
|
||||
*/
|
||||
startAllWorkers(): void {
|
||||
if (this.lifecycle !== 'running') {
|
||||
throw new Error('QueueManager is shutting down; workers cannot be started');
|
||||
}
|
||||
let workersStarted = 0;
|
||||
const queues = this.queues;
|
||||
|
||||
|
|
@ -699,6 +684,7 @@ export class QueueManager {
|
|||
* Get a producer queue for sending to other services
|
||||
*/
|
||||
private getProducerQueue(queueName: string): BullQueue {
|
||||
this.assertConnectionsOpen();
|
||||
if (!this.producerQueues.has(queueName)) {
|
||||
const queue = new BullQueue(queueName, {
|
||||
connection: this.redisConnection,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue