refactor: pre-M0 cleanup, core library hardening, and isolated dev/QA Docker stack
- Remove ~44k LOC of dead code, legacy v1 TS simulator/strategy stack, event-bus, analytics FastAPI prototype, legacy calculation archives, and unused deps (data-ingestion provider API handlers untouched) - Extract @stock-bot/di/http-security and isolate @stock-bot/browser to data-ingestion via ServiceContainerBuilder.withRegistrations() - Harden @stock-bot/mongodb read-only proxies, flatten @stock-bot/postgres with unified master+research migrations, and fix @stock-bot/config EnvLoader, ServiceApplication worker lifecycle, NamespacedCache.clear(), and BatchProcessor error propagation - Flatten workspace root (remove apps/stock/package.json) and collapse orchestrator re-export shims - Pin all Docker image versions, add shm_size/nofile/RAM caps and docker-compose.quant.yml, fix 05-add-visible-column.sql view recreation, and decouple dev/QA Compose project names for side-by-side execution - Update PLATFORM-PLAN, DATA-CONTRACTS (bars_1m PARTITION BY MONTH, Rust bulk ETL, DuckDB limits), MILESTONES, and servers docs
This commit is contained in:
parent
ce9e2df67c
commit
4cd6038063
432 changed files with 1247 additions and 44469 deletions
|
|
@ -346,6 +346,7 @@ async function addJobsInChunks(
|
|||
chunkSize: chunk.length,
|
||||
error,
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,257 +0,0 @@
|
|||
import { Queue, type Job } from 'bullmq';
|
||||
import type { DLQConfig, RedisConfig } from './types';
|
||||
import { getRedisConnection } from './utils';
|
||||
|
||||
// Logger interface for type safety
|
||||
interface Logger {
|
||||
info(message: string, meta?: Record<string, unknown>): void;
|
||||
error(message: string, meta?: Record<string, unknown>): void;
|
||||
warn(message: string, meta?: Record<string, unknown>): void;
|
||||
debug(message: string, meta?: Record<string, unknown>): void;
|
||||
}
|
||||
|
||||
export class DeadLetterQueueHandler {
|
||||
private dlq: Queue;
|
||||
private config: Required<DLQConfig>;
|
||||
private failureCount = new Map<string, number>();
|
||||
private readonly logger: Logger;
|
||||
|
||||
constructor(
|
||||
private mainQueue: Queue,
|
||||
connection: RedisConfig,
|
||||
config: DLQConfig = {},
|
||||
logger?: Logger
|
||||
) {
|
||||
this.logger = logger || console;
|
||||
this.config = {
|
||||
maxRetries: config.maxRetries ?? 3,
|
||||
retryDelay: config.retryDelay ?? 60000, // 1 minute
|
||||
alertThreshold: config.alertThreshold ?? 100,
|
||||
cleanupAge: config.cleanupAge ?? 168, // 7 days
|
||||
};
|
||||
|
||||
// Create DLQ with same name but -dlq suffix
|
||||
const dlqName = `${mainQueue.name}-dlq`;
|
||||
this.dlq = new Queue(dlqName, { connection: getRedisConnection(connection) });
|
||||
}
|
||||
|
||||
/**
|
||||
* Process a failed job - either retry or move to DLQ
|
||||
*/
|
||||
async handleFailedJob(job: Job, error: Error): Promise<void> {
|
||||
const jobKey = `${job.name}:${job.id}`;
|
||||
const currentFailures = (this.failureCount.get(jobKey) || 0) + 1;
|
||||
this.failureCount.set(jobKey, currentFailures);
|
||||
|
||||
this.logger.warn('Job failed', {
|
||||
jobId: job.id,
|
||||
jobName: job.name,
|
||||
attempt: job.attemptsMade,
|
||||
maxAttempts: job.opts.attempts,
|
||||
error: error.message,
|
||||
failureCount: currentFailures,
|
||||
});
|
||||
|
||||
// Check if job should be moved to DLQ
|
||||
if (job.attemptsMade >= (job.opts.attempts || this.config.maxRetries)) {
|
||||
await this.moveToDeadLetterQueue(job, error);
|
||||
this.failureCount.delete(jobKey);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Move job to dead letter queue
|
||||
*/
|
||||
private async moveToDeadLetterQueue(job: Job, error: Error): Promise<void> {
|
||||
try {
|
||||
const dlqData = {
|
||||
originalJob: {
|
||||
id: job.id,
|
||||
name: job.name,
|
||||
data: job.data,
|
||||
opts: job.opts,
|
||||
attemptsMade: job.attemptsMade,
|
||||
failedReason: job.failedReason,
|
||||
processedOn: job.processedOn,
|
||||
timestamp: job.timestamp,
|
||||
},
|
||||
error: {
|
||||
message: error.message,
|
||||
stack: error.stack,
|
||||
name: error.name,
|
||||
},
|
||||
movedToDLQAt: new Date().toISOString(),
|
||||
};
|
||||
|
||||
await this.dlq.add('failed-job', dlqData, {
|
||||
removeOnComplete: 100,
|
||||
removeOnFail: 100,
|
||||
});
|
||||
|
||||
this.logger.error('Job moved to DLQ', {
|
||||
jobId: job.id,
|
||||
jobName: job.name,
|
||||
error: error.message,
|
||||
});
|
||||
|
||||
// Check if we need to alert
|
||||
await this.checkAlertThreshold();
|
||||
} catch (dlqError) {
|
||||
this.logger.error('Failed to move job to DLQ', {
|
||||
jobId: job.id,
|
||||
error: dlqError,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Retry jobs from DLQ
|
||||
*/
|
||||
async retryDLQJobs(limit = 10): Promise<number> {
|
||||
const jobs = await this.dlq.getCompleted(0, limit);
|
||||
let retriedCount = 0;
|
||||
|
||||
for (const dlqJob of jobs) {
|
||||
try {
|
||||
const { originalJob } = dlqJob.data;
|
||||
|
||||
// Re-add to main queue with delay
|
||||
await this.mainQueue.add(originalJob.name, originalJob.data, {
|
||||
...originalJob.opts,
|
||||
delay: this.config.retryDelay,
|
||||
attempts: this.config.maxRetries,
|
||||
});
|
||||
|
||||
// Remove from DLQ
|
||||
await dlqJob.remove();
|
||||
retriedCount++;
|
||||
|
||||
this.logger.info('Job retried from DLQ', {
|
||||
originalJobId: originalJob.id,
|
||||
jobName: originalJob.name,
|
||||
});
|
||||
} catch (error) {
|
||||
this.logger.error('Failed to retry DLQ job', {
|
||||
dlqJobId: dlqJob.id,
|
||||
error,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return retriedCount;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get DLQ statistics
|
||||
*/
|
||||
async getStats(): Promise<{
|
||||
total: number;
|
||||
recent: number;
|
||||
byJobName: Record<string, number>;
|
||||
oldestJob: Date | null;
|
||||
}> {
|
||||
const [completed, failed, waiting] = await Promise.all([
|
||||
this.dlq.getCompleted(),
|
||||
this.dlq.getFailed(),
|
||||
this.dlq.getWaiting(),
|
||||
]);
|
||||
|
||||
const allJobs = [...completed, ...failed, ...waiting];
|
||||
const byJobName: Record<string, number> = {};
|
||||
let oldestTimestamp: number | null = null;
|
||||
|
||||
for (const job of allJobs) {
|
||||
const jobName = job.data.originalJob?.name || 'unknown';
|
||||
byJobName[jobName] = (byJobName[jobName] || 0) + 1;
|
||||
|
||||
if (!oldestTimestamp || job.timestamp < oldestTimestamp) {
|
||||
oldestTimestamp = job.timestamp;
|
||||
}
|
||||
}
|
||||
|
||||
// Count recent jobs (last 24 hours)
|
||||
const oneDayAgo = Date.now() - 24 * 60 * 60 * 1000;
|
||||
const recent = allJobs.filter(job => job.timestamp > oneDayAgo).length;
|
||||
|
||||
return {
|
||||
total: allJobs.length,
|
||||
recent,
|
||||
byJobName,
|
||||
oldestJob: oldestTimestamp ? new Date(oldestTimestamp) : null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Clean up old DLQ entries
|
||||
*/
|
||||
async cleanup(): Promise<number> {
|
||||
const ageInMs = this.config.cleanupAge * 60 * 60 * 1000;
|
||||
const cutoffTime = Date.now() - ageInMs;
|
||||
|
||||
const jobs = await this.dlq.getCompleted();
|
||||
let removedCount = 0;
|
||||
|
||||
for (const job of jobs) {
|
||||
if (job.timestamp < cutoffTime) {
|
||||
await job.remove();
|
||||
removedCount++;
|
||||
}
|
||||
}
|
||||
|
||||
this.logger.info('DLQ cleanup completed', {
|
||||
removedCount,
|
||||
cleanupAge: `${this.config.cleanupAge} hours`,
|
||||
});
|
||||
|
||||
return removedCount;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if alert threshold is exceeded
|
||||
*/
|
||||
private async checkAlertThreshold(): Promise<void> {
|
||||
const stats = await this.getStats();
|
||||
|
||||
if (stats.total >= this.config.alertThreshold) {
|
||||
this.logger.error('DLQ alert threshold exceeded', {
|
||||
threshold: this.config.alertThreshold,
|
||||
currentCount: stats.total,
|
||||
byJobName: stats.byJobName,
|
||||
});
|
||||
// In a real implementation, this would trigger alerts
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get failed jobs for inspection
|
||||
*/
|
||||
async inspectFailedJobs(limit = 10): Promise<
|
||||
Array<{
|
||||
id: string;
|
||||
name: string;
|
||||
data: unknown;
|
||||
error: unknown;
|
||||
failedAt: string;
|
||||
attempts: number;
|
||||
}>
|
||||
> {
|
||||
const jobs = await this.dlq.getCompleted(0, limit);
|
||||
|
||||
return jobs.map(job => ({
|
||||
id: job.data.originalJob.id,
|
||||
name: job.data.originalJob.name,
|
||||
data: job.data.originalJob.data,
|
||||
error: job.data.error,
|
||||
failedAt: job.data.movedToDLQAt,
|
||||
attempts: job.data.originalJob.attemptsMade,
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Shutdown DLQ handler
|
||||
*/
|
||||
async shutdown(): Promise<void> {
|
||||
await this.dlq.close();
|
||||
this.failureCount.clear();
|
||||
}
|
||||
}
|
||||
|
|
@ -1,67 +1,32 @@
|
|||
// Core exports
|
||||
export { Queue } from './queue';
|
||||
export { QueueManager } from './queue-manager';
|
||||
export { ServiceCache, createServiceCache } from './service-cache';
|
||||
// Service utilities
|
||||
export {
|
||||
normalizeServiceName,
|
||||
generateCachePrefix,
|
||||
getFullQueueName,
|
||||
parseQueueName,
|
||||
} from './service-utils';
|
||||
|
||||
// Batch processing
|
||||
export { processBatchJob, processItems } from './batch-processor';
|
||||
|
||||
// DLQ handling
|
||||
export { DeadLetterQueueHandler } from './dlq-handler';
|
||||
|
||||
// Metrics
|
||||
export { QueueMetricsCollector } from './queue-metrics';
|
||||
|
||||
// Rate limiting
|
||||
export { QueueRateLimiter } from './rate-limiter';
|
||||
|
||||
// Types
|
||||
export type {
|
||||
// Core types
|
||||
JobData,
|
||||
JobOptions,
|
||||
QueueOptions,
|
||||
GlobalStats,
|
||||
|
||||
// Batch processing types
|
||||
BatchResult,
|
||||
ProcessOptions,
|
||||
BatchJobData,
|
||||
|
||||
// Handler types
|
||||
JobHandler,
|
||||
TypedJobHandler,
|
||||
HandlerConfig,
|
||||
HandlerConfigWithSchedule,
|
||||
HandlerInitializer,
|
||||
QueueStats,
|
||||
QueueWorkerConfig,
|
||||
|
||||
// Configuration types
|
||||
RedisConfig,
|
||||
QueueConfig,
|
||||
QueueManagerConfig,
|
||||
|
||||
// Rate limiting types
|
||||
RateLimitConfig,
|
||||
RateLimitRule,
|
||||
|
||||
// DLQ types
|
||||
DLQConfig,
|
||||
DLQJobInfo,
|
||||
|
||||
// Scheduled job types
|
||||
ScheduledJob,
|
||||
ScheduleConfig,
|
||||
|
||||
// Smart Queue types
|
||||
SmartQueueConfig,
|
||||
QueueRoute,
|
||||
} from './types';
|
||||
|
|
|
|||
|
|
@ -1,318 +0,0 @@
|
|||
import { Queue, QueueEvents } from 'bullmq';
|
||||
|
||||
// import { getLogger } from '@stock-bot/logger';
|
||||
|
||||
// const logger = getLogger('queue-metrics');
|
||||
|
||||
interface QueueMetrics {
|
||||
// Job counts
|
||||
waiting: number;
|
||||
active: number;
|
||||
completed: number;
|
||||
failed: number;
|
||||
delayed: number;
|
||||
paused?: number;
|
||||
|
||||
// Performance metrics
|
||||
processingTime: {
|
||||
avg: number;
|
||||
min: number;
|
||||
max: number;
|
||||
p95: number;
|
||||
p99: number;
|
||||
};
|
||||
|
||||
// Throughput
|
||||
throughput: {
|
||||
completedPerMinute: number;
|
||||
failedPerMinute: number;
|
||||
totalPerMinute: number;
|
||||
};
|
||||
|
||||
// Job age
|
||||
oldestWaitingJob: Date | null;
|
||||
|
||||
// Health
|
||||
isHealthy: boolean;
|
||||
healthIssues: string[];
|
||||
}
|
||||
|
||||
export class QueueMetricsCollector {
|
||||
private processingTimes: number[] = [];
|
||||
private completedTimestamps: number[] = [];
|
||||
private failedTimestamps: number[] = [];
|
||||
private jobStartTimes = new Map<string, number>();
|
||||
private readonly maxSamples = 1000;
|
||||
private readonly metricsInterval = 60000; // 1 minute
|
||||
|
||||
constructor(
|
||||
private queue: Queue,
|
||||
private queueEvents: QueueEvents
|
||||
) {
|
||||
this.setupEventListeners();
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup event listeners for metrics collection
|
||||
*/
|
||||
private setupEventListeners(): void {
|
||||
this.queueEvents.on('completed', () => {
|
||||
// Record completion
|
||||
this.completedTimestamps.push(Date.now());
|
||||
this.cleanupOldTimestamps();
|
||||
});
|
||||
|
||||
this.queueEvents.on('failed', () => {
|
||||
// Record failure
|
||||
this.failedTimestamps.push(Date.now());
|
||||
this.cleanupOldTimestamps();
|
||||
});
|
||||
|
||||
// Track processing times
|
||||
this.queueEvents.on('active', ({ jobId }) => {
|
||||
this.jobStartTimes.set(jobId, Date.now());
|
||||
});
|
||||
|
||||
this.queueEvents.on('completed', ({ jobId }) => {
|
||||
const startTime = this.jobStartTimes.get(jobId);
|
||||
if (startTime) {
|
||||
const processingTime = Date.now() - startTime;
|
||||
this.recordProcessingTime(processingTime);
|
||||
this.jobStartTimes.delete(jobId);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Record processing time
|
||||
*/
|
||||
private recordProcessingTime(time: number): void {
|
||||
this.processingTimes.push(time);
|
||||
|
||||
// Keep only recent samples
|
||||
if (this.processingTimes.length > this.maxSamples) {
|
||||
this.processingTimes = this.processingTimes.slice(-this.maxSamples);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clean up old timestamps
|
||||
*/
|
||||
private cleanupOldTimestamps(): void {
|
||||
const cutoff = Date.now() - this.metricsInterval;
|
||||
|
||||
this.completedTimestamps = this.completedTimestamps.filter(ts => ts > cutoff);
|
||||
this.failedTimestamps = this.failedTimestamps.filter(ts => ts > cutoff);
|
||||
}
|
||||
|
||||
/**
|
||||
* Collect current metrics
|
||||
*/
|
||||
async collect(): Promise<QueueMetrics> {
|
||||
// Get job counts
|
||||
const [waiting, active, completed, failed, delayed] = await Promise.all([
|
||||
this.queue.getWaitingCount(),
|
||||
this.queue.getActiveCount(),
|
||||
this.queue.getCompletedCount(),
|
||||
this.queue.getFailedCount(),
|
||||
this.queue.getDelayedCount(),
|
||||
]);
|
||||
|
||||
// BullMQ doesn't have getPausedCount, check if queue is paused
|
||||
const paused = (await this.queue.isPaused()) ? waiting : 0;
|
||||
|
||||
// Calculate processing time metrics
|
||||
const processingTime = this.calculateProcessingTimeMetrics();
|
||||
|
||||
// Calculate throughput
|
||||
const throughput = this.calculateThroughput();
|
||||
|
||||
// Get oldest waiting job
|
||||
const oldestWaitingJob = await this.getOldestWaitingJob();
|
||||
|
||||
// Check health
|
||||
const { isHealthy, healthIssues } = this.checkHealth({
|
||||
waiting,
|
||||
active,
|
||||
failed,
|
||||
processingTime,
|
||||
});
|
||||
|
||||
return {
|
||||
waiting,
|
||||
active,
|
||||
completed,
|
||||
failed,
|
||||
delayed,
|
||||
paused,
|
||||
processingTime,
|
||||
throughput,
|
||||
oldestWaitingJob,
|
||||
isHealthy,
|
||||
healthIssues,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate processing time metrics
|
||||
*/
|
||||
private calculateProcessingTimeMetrics(): QueueMetrics['processingTime'] {
|
||||
if (this.processingTimes.length === 0) {
|
||||
return { avg: 0, min: 0, max: 0, p95: 0, p99: 0 };
|
||||
}
|
||||
|
||||
const sorted = [...this.processingTimes].sort((a, b) => a - b);
|
||||
const sum = sorted.reduce((acc, val) => acc + val, 0);
|
||||
|
||||
return {
|
||||
avg: sorted.length > 0 ? Math.round(sum / sorted.length) : 0,
|
||||
min: sorted[0] || 0,
|
||||
max: sorted[sorted.length - 1] || 0,
|
||||
p95: sorted[Math.floor(sorted.length * 0.95)] || 0,
|
||||
p99: sorted[Math.floor(sorted.length * 0.99)] || 0,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate throughput metrics
|
||||
*/
|
||||
private calculateThroughput(): QueueMetrics['throughput'] {
|
||||
const now = Date.now();
|
||||
const oneMinuteAgo = now - 60000;
|
||||
|
||||
const completedPerMinute = this.completedTimestamps.filter(ts => ts > oneMinuteAgo).length;
|
||||
const failedPerMinute = this.failedTimestamps.filter(ts => ts > oneMinuteAgo).length;
|
||||
|
||||
return {
|
||||
completedPerMinute,
|
||||
failedPerMinute,
|
||||
totalPerMinute: completedPerMinute + failedPerMinute,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get oldest waiting job
|
||||
*/
|
||||
private async getOldestWaitingJob(): Promise<Date | null> {
|
||||
const waitingJobs = await this.queue.getWaiting(0, 1);
|
||||
|
||||
if (waitingJobs.length > 0) {
|
||||
return new Date(waitingJobs[0].timestamp);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check queue health
|
||||
*/
|
||||
private checkHealth(metrics: {
|
||||
waiting: number;
|
||||
active: number;
|
||||
failed: number;
|
||||
processingTime: QueueMetrics['processingTime'];
|
||||
}): { isHealthy: boolean; healthIssues: string[] } {
|
||||
const issues: string[] = [];
|
||||
|
||||
// Check for high failure rate
|
||||
const failureRate = metrics.failed / (metrics.failed + this.completedTimestamps.length);
|
||||
if (failureRate > 0.1) {
|
||||
issues.push(`High failure rate: ${(failureRate * 100).toFixed(1)}%`);
|
||||
}
|
||||
|
||||
// Check for queue backlog
|
||||
if (metrics.waiting > 1000) {
|
||||
issues.push(`Large queue backlog: ${metrics.waiting} jobs waiting`);
|
||||
}
|
||||
|
||||
// Check for slow processing
|
||||
if (metrics.processingTime.avg > 30000) {
|
||||
// 30 seconds
|
||||
issues.push(
|
||||
`Slow average processing time: ${(metrics.processingTime.avg / 1000).toFixed(1)}s`
|
||||
);
|
||||
}
|
||||
|
||||
// Check for stalled active jobs
|
||||
if (metrics.active > 100) {
|
||||
issues.push(`High number of active jobs: ${metrics.active}`);
|
||||
}
|
||||
|
||||
return {
|
||||
isHealthy: issues.length === 0,
|
||||
healthIssues: issues,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get formatted metrics report
|
||||
*/
|
||||
async getReport(): Promise<string> {
|
||||
const metrics = await this.collect();
|
||||
|
||||
return `
|
||||
Queue Metrics Report
|
||||
===================
|
||||
Status: ${metrics.isHealthy ? '✅ Healthy' : '⚠️ Issues Detected'}
|
||||
|
||||
Job Counts:
|
||||
- Waiting: ${metrics.waiting}
|
||||
- Active: ${metrics.active}
|
||||
- Completed: ${metrics.completed}
|
||||
- Failed: ${metrics.failed}
|
||||
- Delayed: ${metrics.delayed}
|
||||
- Paused: ${metrics.paused}
|
||||
|
||||
Performance:
|
||||
- Avg Processing Time: ${(metrics.processingTime.avg / 1000).toFixed(2)}s
|
||||
- Min/Max: ${(metrics.processingTime.min / 1000).toFixed(2)}s / ${(metrics.processingTime.max / 1000).toFixed(2)}s
|
||||
- P95/P99: ${(metrics.processingTime.p95 / 1000).toFixed(2)}s / ${(metrics.processingTime.p99 / 1000).toFixed(2)}s
|
||||
|
||||
Throughput:
|
||||
- Completed/min: ${metrics.throughput.completedPerMinute}
|
||||
- Failed/min: ${metrics.throughput.failedPerMinute}
|
||||
- Total/min: ${metrics.throughput.totalPerMinute}
|
||||
|
||||
${metrics.oldestWaitingJob ? `Oldest Waiting Job: ${metrics.oldestWaitingJob.toISOString()}` : 'No waiting jobs'}
|
||||
|
||||
${metrics.healthIssues.length > 0 ? `\nHealth Issues:\n${metrics.healthIssues.map(issue => `- ${issue}`).join('\n')}` : ''}
|
||||
`.trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* Export metrics in Prometheus format
|
||||
*/
|
||||
async getPrometheusMetrics(): Promise<string> {
|
||||
const metrics = await this.collect();
|
||||
const queueName = this.queue.name;
|
||||
|
||||
return `
|
||||
# HELP queue_jobs_total Total number of jobs by status
|
||||
# TYPE queue_jobs_total gauge
|
||||
queue_jobs_total{queue="${queueName}",status="waiting"} ${metrics.waiting}
|
||||
queue_jobs_total{queue="${queueName}",status="active"} ${metrics.active}
|
||||
queue_jobs_total{queue="${queueName}",status="completed"} ${metrics.completed}
|
||||
queue_jobs_total{queue="${queueName}",status="failed"} ${metrics.failed}
|
||||
queue_jobs_total{queue="${queueName}",status="delayed"} ${metrics.delayed}
|
||||
queue_jobs_total{queue="${queueName}",status="paused"} ${metrics.paused}
|
||||
|
||||
# HELP queue_processing_time_seconds Job processing time in seconds
|
||||
# TYPE queue_processing_time_seconds summary
|
||||
queue_processing_time_seconds{queue="${queueName}",quantile="0.5"} ${(metrics.processingTime.avg / 1000).toFixed(3)}
|
||||
queue_processing_time_seconds{queue="${queueName}",quantile="0.95"} ${(metrics.processingTime.p95 / 1000).toFixed(3)}
|
||||
queue_processing_time_seconds{queue="${queueName}",quantile="0.99"} ${(metrics.processingTime.p99 / 1000).toFixed(3)}
|
||||
queue_processing_time_seconds_sum{queue="${queueName}"} ${((metrics.processingTime.avg * this.processingTimes.length) / 1000).toFixed(3)}
|
||||
queue_processing_time_seconds_count{queue="${queueName}"} ${this.processingTimes.length}
|
||||
|
||||
# HELP queue_throughput_per_minute Jobs processed per minute
|
||||
# TYPE queue_throughput_per_minute gauge
|
||||
queue_throughput_per_minute{queue="${queueName}",status="completed"} ${metrics.throughput.completedPerMinute}
|
||||
queue_throughput_per_minute{queue="${queueName}",status="failed"} ${metrics.throughput.failedPerMinute}
|
||||
queue_throughput_per_minute{queue="${queueName}",status="total"} ${metrics.throughput.totalPerMinute}
|
||||
|
||||
# HELP queue_health Queue health status
|
||||
# TYPE queue_health gauge
|
||||
queue_health{queue="${queueName}"} ${metrics.isHealthy ? 1 : 0}
|
||||
`.trim();
|
||||
}
|
||||
}
|
||||
|
|
@ -84,16 +84,6 @@ export interface GlobalStats {
|
|||
uptime: number;
|
||||
}
|
||||
|
||||
// Legacy type for backward compatibility
|
||||
export interface QueueConfig extends QueueManagerConfig {
|
||||
queueName?: string;
|
||||
workers?: number;
|
||||
concurrency?: number;
|
||||
handlers?: HandlerInitializer[];
|
||||
dlqConfig?: DLQConfig;
|
||||
enableMetrics?: boolean;
|
||||
}
|
||||
|
||||
// Extended batch job data for queue implementation
|
||||
export interface BatchJobData {
|
||||
payloadKey: string;
|
||||
|
|
@ -103,10 +93,6 @@ export interface BatchJobData {
|
|||
totalDelayHours: number; // Total time to distribute all batches
|
||||
}
|
||||
|
||||
export interface HandlerInitializer {
|
||||
(): void | Promise<void>;
|
||||
}
|
||||
|
||||
// Rate limiting types
|
||||
export type RateLimitWindow = import('@stock-bot/types').RateLimitWindow;
|
||||
|
||||
|
|
@ -120,40 +106,6 @@ export interface RateLimitRule {
|
|||
config: RateLimitConfig;
|
||||
}
|
||||
|
||||
// DLQ types
|
||||
export interface DLQConfig {
|
||||
maxRetries?: number;
|
||||
retryDelay?: number;
|
||||
alertThreshold?: number;
|
||||
cleanupAge?: number;
|
||||
}
|
||||
|
||||
export interface DLQJobInfo {
|
||||
id: string;
|
||||
name: string;
|
||||
failedReason: string;
|
||||
attemptsMade: number;
|
||||
timestamp: number;
|
||||
data: unknown;
|
||||
}
|
||||
|
||||
export interface ScheduleConfig {
|
||||
pattern: string;
|
||||
jobName: string;
|
||||
data?: unknown;
|
||||
options?: ExtendedJobOptions;
|
||||
}
|
||||
|
||||
// Smart Queue Types
|
||||
export interface SmartQueueConfig extends QueueManagerConfig {
|
||||
/** Name of the current service */
|
||||
serviceName: string;
|
||||
/** Whether to auto-discover handlers from registry */
|
||||
autoDiscoverHandlers?: boolean;
|
||||
/** Custom service registry (defaults to built-in) */
|
||||
serviceRegistry?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface QueueRoute {
|
||||
/** Full queue name (now just the handler name, e.g., 'ceo') */
|
||||
fullName: string;
|
||||
|
|
|
|||
|
|
@ -120,15 +120,17 @@ describe('Batch Processor', () => {
|
|||
throw new Error('Failed to add jobs');
|
||||
});
|
||||
|
||||
// processBatchJob should still complete even if addBulk fails
|
||||
const _result = await processBatchJob(
|
||||
batchData,
|
||||
'test-queue',
|
||||
mockQueueManager as unknown as QueueManager
|
||||
);
|
||||
// processBatchJob rethrows chunk errors and retains the cached payload for retry
|
||||
await expect(
|
||||
processBatchJob(
|
||||
batchData,
|
||||
'test-queue',
|
||||
mockQueueManager as unknown as QueueManager
|
||||
)
|
||||
).rejects.toThrow('Failed to add jobs');
|
||||
|
||||
expect(mockQueue.addBulk).toHaveBeenCalled();
|
||||
// The error is logged in addJobsInChunks, not in processBatchJob
|
||||
expect(mockCache.del).not.toHaveBeenCalled();
|
||||
expect(mockLogger.error).toHaveBeenCalledWith('Failed to add job chunk', expect.any(Object));
|
||||
});
|
||||
|
||||
|
|
@ -273,15 +275,15 @@ describe('Batch Processor', () => {
|
|||
throw new Error('Process error');
|
||||
});
|
||||
|
||||
// processItems catches errors and continues, so it won't reject
|
||||
const result = await processItems(
|
||||
items,
|
||||
'test-queue',
|
||||
options,
|
||||
mockQueueManager as unknown as QueueManager
|
||||
);
|
||||
await expect(
|
||||
processItems(
|
||||
items,
|
||||
'test-queue',
|
||||
options,
|
||||
mockQueueManager as unknown as QueueManager
|
||||
)
|
||||
).rejects.toThrow('Process error');
|
||||
|
||||
expect(result.jobsCreated).toBe(0);
|
||||
expect(mockQueue.addBulk).toHaveBeenCalled();
|
||||
expect(mockLogger.error).toHaveBeenCalledWith('Failed to add job chunk', expect.any(Object));
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,278 +0,0 @@
|
|||
import type { Job, Queue } from 'bullmq';
|
||||
import { beforeEach, describe, expect, it, mock } from 'bun:test';
|
||||
import { DeadLetterQueueHandler } from '../src/dlq-handler';
|
||||
import type { RedisConfig } from '../src/types';
|
||||
|
||||
describe('DeadLetterQueueHandler', () => {
|
||||
// Mock the DLQ Queue that will be created
|
||||
const mockDLQQueue = {
|
||||
name: 'test-queue-dlq',
|
||||
add: mock(() => Promise.resolve({})),
|
||||
getCompleted: mock(() => Promise.resolve([])),
|
||||
getFailed: mock(() => Promise.resolve([])),
|
||||
getWaiting: mock(() => Promise.resolve([])),
|
||||
close: mock(() => Promise.resolve()),
|
||||
} as unknown as Queue;
|
||||
const mockLogger = {
|
||||
info: mock(() => {}),
|
||||
error: mock(() => {}),
|
||||
warn: mock(() => {}),
|
||||
debug: mock(() => {}),
|
||||
trace: mock(() => {}),
|
||||
};
|
||||
|
||||
const mockQueue = {
|
||||
name: 'test-queue',
|
||||
add: mock(() => Promise.resolve({})),
|
||||
getCompleted: mock(() => Promise.resolve([])),
|
||||
getFailed: mock(() => Promise.resolve([])),
|
||||
getWaiting: mock(() => Promise.resolve([])),
|
||||
} as unknown as Queue;
|
||||
|
||||
const mockRedisConfig: RedisConfig = {
|
||||
host: 'localhost',
|
||||
port: 6379,
|
||||
};
|
||||
|
||||
let dlqHandler: DeadLetterQueueHandler;
|
||||
|
||||
beforeEach(() => {
|
||||
// Reset DLQ queue mocks
|
||||
mockDLQQueue.add = mock(() => Promise.resolve({}));
|
||||
mockDLQQueue.getCompleted = mock(() => Promise.resolve([]));
|
||||
mockDLQQueue.getFailed = mock(() => Promise.resolve([]));
|
||||
mockDLQQueue.getWaiting = mock(() => Promise.resolve([]));
|
||||
mockDLQQueue.close = mock(() => Promise.resolve());
|
||||
|
||||
// Create handler with mocked DLQ queue
|
||||
dlqHandler = new DeadLetterQueueHandler(mockQueue, mockRedisConfig, {}, mockLogger);
|
||||
// Override the dlq property to use our mock
|
||||
(dlqHandler as any).dlq = mockDLQQueue;
|
||||
|
||||
// Reset mocks
|
||||
mockLogger.info = mock(() => {});
|
||||
mockLogger.error = mock(() => {});
|
||||
mockLogger.warn = mock(() => {});
|
||||
});
|
||||
|
||||
describe('handleFailedJob', () => {
|
||||
it('should log failed job details', async () => {
|
||||
const mockJob = {
|
||||
id: 'job-123',
|
||||
name: 'test-job',
|
||||
queueName: 'test-queue',
|
||||
data: {
|
||||
handler: 'testHandler',
|
||||
operation: 'testOp',
|
||||
payload: { test: true },
|
||||
},
|
||||
attemptsMade: 3,
|
||||
opts: { attempts: 3 },
|
||||
failedReason: 'Test error',
|
||||
finishedOn: Date.now(),
|
||||
processedOn: Date.now() - 5000,
|
||||
timestamp: Date.now() - 10000,
|
||||
} as Job;
|
||||
|
||||
const error = new Error('Job processing failed');
|
||||
|
||||
await dlqHandler.handleFailedJob(mockJob, error);
|
||||
|
||||
expect(mockLogger.error).toHaveBeenCalledWith(
|
||||
'Job moved to DLQ',
|
||||
expect.objectContaining({
|
||||
jobId: 'job-123',
|
||||
jobName: 'test-job',
|
||||
error: 'Job processing failed',
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('should handle jobs without data gracefully', async () => {
|
||||
const mockJob = {
|
||||
id: 'job-123',
|
||||
name: 'test-job',
|
||||
queueName: 'test-queue',
|
||||
data: null,
|
||||
attemptsMade: 3,
|
||||
opts: { attempts: 3 },
|
||||
timestamp: Date.now() - 10000,
|
||||
processedOn: Date.now() - 5000,
|
||||
} as any;
|
||||
|
||||
const error = new Error('No data');
|
||||
|
||||
await dlqHandler.handleFailedJob(mockJob, error);
|
||||
|
||||
expect(mockLogger.error).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should check alert threshold', async () => {
|
||||
const mockJob = {
|
||||
id: 'job-123',
|
||||
name: 'critical-job',
|
||||
queueName: 'critical-queue',
|
||||
data: { handler: 'critical', operation: 'process' },
|
||||
attemptsMade: 3,
|
||||
opts: { attempts: 3 },
|
||||
} as Job;
|
||||
|
||||
const error = new Error('Critical failure');
|
||||
|
||||
await dlqHandler.handleFailedJob(mockJob, error);
|
||||
|
||||
expect(mockLogger.warn).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('getStats', () => {
|
||||
it('should return DLQ statistics', async () => {
|
||||
const mockJobs = [
|
||||
{
|
||||
id: 'job-1',
|
||||
data: { originalJob: { name: 'process' } },
|
||||
timestamp: Date.now(),
|
||||
},
|
||||
{
|
||||
id: 'job-2',
|
||||
data: { originalJob: { name: 'process' } },
|
||||
timestamp: Date.now() - 100000,
|
||||
},
|
||||
{
|
||||
id: 'job-3',
|
||||
data: { originalJob: { name: 'validate' } },
|
||||
timestamp: Date.now() - 200000,
|
||||
},
|
||||
];
|
||||
|
||||
mockDLQQueue.getCompleted = mock(() => Promise.resolve(mockJobs));
|
||||
mockDLQQueue.getFailed = mock(() => Promise.resolve([]));
|
||||
mockDLQQueue.getWaiting = mock(() => Promise.resolve([]));
|
||||
|
||||
const stats = await dlqHandler.getStats();
|
||||
|
||||
expect(stats.total).toBe(3);
|
||||
expect(stats.byJobName['process']).toBe(2);
|
||||
expect(stats.byJobName['validate']).toBe(1);
|
||||
expect(stats.oldestJob).toBeDefined();
|
||||
});
|
||||
|
||||
it('should handle empty DLQ', async () => {
|
||||
const stats = await dlqHandler.getStats();
|
||||
|
||||
expect(stats.total).toBe(0);
|
||||
expect(stats.byJobName).toEqual({});
|
||||
expect(stats.oldestJob).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('retryDLQJobs', () => {
|
||||
it('should retry jobs from DLQ', async () => {
|
||||
const mockDLQJobs = [
|
||||
{
|
||||
id: 'dlq-1',
|
||||
data: {
|
||||
originalJob: {
|
||||
id: 'orig-1',
|
||||
name: 'retry-job',
|
||||
data: { test: true },
|
||||
opts: {},
|
||||
},
|
||||
},
|
||||
remove: mock(() => Promise.resolve()),
|
||||
},
|
||||
];
|
||||
|
||||
(dlqHandler as any).dlq = {
|
||||
getCompleted: mock(() => Promise.resolve(mockDLQJobs)),
|
||||
};
|
||||
|
||||
const retriedCount = await dlqHandler.retryDLQJobs(1);
|
||||
|
||||
expect(retriedCount).toBe(1);
|
||||
expect(mockQueue.add).toHaveBeenCalledWith(
|
||||
'retry-job',
|
||||
{ test: true },
|
||||
expect.objectContaining({ delay: expect.any(Number) })
|
||||
);
|
||||
expect(mockDLQJobs[0].remove).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('cleanup', () => {
|
||||
it('should clean up old DLQ entries', async () => {
|
||||
const oldJob = {
|
||||
id: 'old-1',
|
||||
timestamp: Date.now() - 8 * 24 * 60 * 60 * 1000, // 8 days old
|
||||
remove: mock(() => Promise.resolve()),
|
||||
};
|
||||
|
||||
const newJob = {
|
||||
id: 'new-1',
|
||||
timestamp: Date.now() - 1 * 24 * 60 * 60 * 1000, // 1 day old
|
||||
remove: mock(() => Promise.resolve()),
|
||||
};
|
||||
|
||||
(dlqHandler as any).dlq = {
|
||||
getCompleted: mock(() => Promise.resolve([oldJob, newJob])),
|
||||
};
|
||||
|
||||
const removedCount = await dlqHandler.cleanup();
|
||||
|
||||
expect(removedCount).toBe(1);
|
||||
expect(oldJob.remove).toHaveBeenCalled();
|
||||
expect(newJob.remove).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('inspectFailedJobs', () => {
|
||||
it('should return formatted failed jobs', async () => {
|
||||
const mockDLQJobs = [
|
||||
{
|
||||
data: {
|
||||
originalJob: {
|
||||
id: 'orig-1',
|
||||
name: 'test-job',
|
||||
data: { test: true },
|
||||
attemptsMade: 3,
|
||||
},
|
||||
error: {
|
||||
message: 'Test error',
|
||||
stack: 'Error stack',
|
||||
},
|
||||
movedToDLQAt: '2024-01-01T00:00:00Z',
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
(dlqHandler as any).dlq = {
|
||||
getCompleted: mock(() => Promise.resolve(mockDLQJobs)),
|
||||
};
|
||||
|
||||
const inspected = await dlqHandler.inspectFailedJobs(10);
|
||||
|
||||
expect(inspected).toHaveLength(1);
|
||||
expect(inspected[0]).toEqual({
|
||||
id: 'orig-1',
|
||||
name: 'test-job',
|
||||
data: { test: true },
|
||||
error: { message: 'Test error', stack: 'Error stack' },
|
||||
failedAt: '2024-01-01T00:00:00Z',
|
||||
attempts: 3,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('shutdown', () => {
|
||||
it('should close DLQ and clear state', async () => {
|
||||
const mockClose = mock(() => Promise.resolve());
|
||||
(dlqHandler as any).dlq = {
|
||||
close: mockClose,
|
||||
};
|
||||
|
||||
await dlqHandler.shutdown();
|
||||
|
||||
expect(mockClose).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -1,233 +0,0 @@
|
|||
import type { Job, Queue, QueueEvents } from 'bullmq';
|
||||
import { beforeEach, describe, expect, it, mock, type Mock } from 'bun:test';
|
||||
import { QueueMetricsCollector } from '../src/queue-metrics';
|
||||
|
||||
describe('QueueMetricsCollector', () => {
|
||||
let metrics: QueueMetricsCollector;
|
||||
let mockQueue: {
|
||||
name: string;
|
||||
getWaitingCount: Mock<() => Promise<number>>;
|
||||
getActiveCount: Mock<() => Promise<number>>;
|
||||
getCompletedCount: Mock<() => Promise<number>>;
|
||||
getFailedCount: Mock<() => Promise<number>>;
|
||||
getDelayedCount: Mock<() => Promise<number>>;
|
||||
isPaused: Mock<() => Promise<boolean>>;
|
||||
getWaiting: Mock<() => Promise<Job[]>>;
|
||||
};
|
||||
let mockQueueEvents: {
|
||||
on: Mock<(event: string, handler: Function) => void>;
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
mockQueue = {
|
||||
name: 'test-queue',
|
||||
getWaitingCount: mock(() => Promise.resolve(0)),
|
||||
getActiveCount: mock(() => Promise.resolve(0)),
|
||||
getCompletedCount: mock(() => Promise.resolve(0)),
|
||||
getFailedCount: mock(() => Promise.resolve(0)),
|
||||
getDelayedCount: mock(() => Promise.resolve(0)),
|
||||
isPaused: mock(() => Promise.resolve(false)),
|
||||
getWaiting: mock(() => Promise.resolve([])),
|
||||
};
|
||||
|
||||
mockQueueEvents = {
|
||||
on: mock(() => {}),
|
||||
};
|
||||
|
||||
metrics = new QueueMetricsCollector(
|
||||
mockQueue as unknown as Queue,
|
||||
mockQueueEvents as unknown as QueueEvents
|
||||
);
|
||||
});
|
||||
|
||||
describe('collect metrics', () => {
|
||||
it('should collect current metrics', async () => {
|
||||
mockQueue.getWaitingCount.mockImplementation(() => Promise.resolve(5));
|
||||
mockQueue.getActiveCount.mockImplementation(() => Promise.resolve(2));
|
||||
mockQueue.getCompletedCount.mockImplementation(() => Promise.resolve(100));
|
||||
mockQueue.getFailedCount.mockImplementation(() => Promise.resolve(3));
|
||||
mockQueue.getDelayedCount.mockImplementation(() => Promise.resolve(1));
|
||||
|
||||
// Add some completed timestamps to avoid 100% failure rate
|
||||
const completedHandler = mockQueueEvents.on.mock.calls.find(
|
||||
call => call[0] === 'completed'
|
||||
)?.[1];
|
||||
if (completedHandler) {
|
||||
for (let i = 0; i < 50; i++) {
|
||||
completedHandler();
|
||||
}
|
||||
}
|
||||
|
||||
const result = await metrics.collect();
|
||||
|
||||
expect(result.waiting).toBe(5);
|
||||
expect(result.active).toBe(2);
|
||||
expect(result.completed).toBe(100);
|
||||
expect(result.failed).toBe(3);
|
||||
expect(result.delayed).toBe(1);
|
||||
expect(result.isHealthy).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect health issues', async () => {
|
||||
mockQueue.getWaitingCount.mockImplementation(() => Promise.resolve(2000)); // High backlog
|
||||
mockQueue.getActiveCount.mockImplementation(() => Promise.resolve(150)); // High active
|
||||
mockQueue.getFailedCount.mockImplementation(() => Promise.resolve(50));
|
||||
|
||||
const result = await metrics.collect();
|
||||
|
||||
expect(result.isHealthy).toBe(false);
|
||||
expect(result.healthIssues.length).toBeGreaterThan(0);
|
||||
expect(result.healthIssues.some(issue => issue.includes('queue backlog'))).toBe(true);
|
||||
expect(result.healthIssues.some(issue => issue.includes('active jobs'))).toBe(true);
|
||||
});
|
||||
|
||||
it('should handle paused queue', async () => {
|
||||
mockQueue.getWaitingCount.mockImplementation(() => Promise.resolve(10));
|
||||
mockQueue.isPaused.mockImplementation(() => Promise.resolve(true));
|
||||
|
||||
const result = await metrics.collect();
|
||||
|
||||
expect(result.paused).toBe(10);
|
||||
});
|
||||
});
|
||||
|
||||
describe('processing time metrics', () => {
|
||||
it('should calculate processing time metrics', async () => {
|
||||
// Access private property for testing
|
||||
const metricsWithPrivate = metrics as QueueMetricsCollector & {
|
||||
processingTimes: number[];
|
||||
};
|
||||
metricsWithPrivate.processingTimes = [1000, 2000, 3000, 4000, 5000];
|
||||
|
||||
const result = await metrics.collect();
|
||||
|
||||
expect(result.processingTime.avg).toBe(3000);
|
||||
expect(result.processingTime.min).toBe(1000);
|
||||
expect(result.processingTime.max).toBe(5000);
|
||||
expect(result.processingTime.p95).toBe(5000);
|
||||
});
|
||||
|
||||
it('should handle no processing times', async () => {
|
||||
const result = await metrics.collect();
|
||||
|
||||
expect(result.processingTime.avg).toBe(0);
|
||||
expect(result.processingTime.min).toBe(0);
|
||||
expect(result.processingTime.max).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('throughput metrics', () => {
|
||||
it('should calculate throughput', async () => {
|
||||
// Access private properties for testing
|
||||
const metricsWithPrivate = metrics as QueueMetricsCollector & {
|
||||
completedTimestamps: number[];
|
||||
failedTimestamps: number[];
|
||||
};
|
||||
|
||||
const now = Date.now();
|
||||
metricsWithPrivate.completedTimestamps = [
|
||||
now - 30000, // 30 seconds ago
|
||||
now - 20000,
|
||||
now - 10000,
|
||||
];
|
||||
metricsWithPrivate.failedTimestamps = [now - 25000, now - 5000];
|
||||
|
||||
const result = await metrics.collect();
|
||||
|
||||
expect(result.throughput.completedPerMinute).toBe(3);
|
||||
expect(result.throughput.failedPerMinute).toBe(2);
|
||||
expect(result.throughput.totalPerMinute).toBe(5);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getReport', () => {
|
||||
it('should generate formatted report', async () => {
|
||||
mockQueue.getWaitingCount.mockImplementation(() => Promise.resolve(5));
|
||||
mockQueue.getActiveCount.mockImplementation(() => Promise.resolve(2));
|
||||
mockQueue.getCompletedCount.mockImplementation(() => Promise.resolve(100));
|
||||
mockQueue.getFailedCount.mockImplementation(() => Promise.resolve(3));
|
||||
|
||||
// Add some completed timestamps to make it healthy
|
||||
const completedHandler = mockQueueEvents.on.mock.calls.find(
|
||||
call => call[0] === 'completed'
|
||||
)?.[1];
|
||||
if (completedHandler) {
|
||||
for (let i = 0; i < 50; i++) {
|
||||
completedHandler();
|
||||
}
|
||||
}
|
||||
|
||||
const report = await metrics.getReport();
|
||||
|
||||
expect(report).toContain('Queue Metrics Report');
|
||||
expect(report).toContain('✅ Healthy');
|
||||
expect(report).toContain('Waiting: 5');
|
||||
expect(report).toContain('Active: 2');
|
||||
expect(report).toContain('Completed: 100');
|
||||
expect(report).toContain('Failed: 3');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getPrometheusMetrics', () => {
|
||||
it('should generate Prometheus formatted metrics', async () => {
|
||||
mockQueue.getWaitingCount.mockImplementation(() => Promise.resolve(5));
|
||||
mockQueue.getActiveCount.mockImplementation(() => Promise.resolve(2));
|
||||
mockQueue.getCompletedCount.mockImplementation(() => Promise.resolve(100));
|
||||
mockQueue.getFailedCount.mockImplementation(() => Promise.resolve(3));
|
||||
|
||||
const prometheusMetrics = await metrics.getPrometheusMetrics();
|
||||
|
||||
expect(prometheusMetrics).toContain('# HELP queue_jobs_total');
|
||||
expect(prometheusMetrics).toContain(
|
||||
'queue_jobs_total{queue="test-queue",status="waiting"} 5'
|
||||
);
|
||||
expect(prometheusMetrics).toContain('queue_jobs_total{queue="test-queue",status="active"} 2');
|
||||
expect(prometheusMetrics).toContain(
|
||||
'queue_jobs_total{queue="test-queue",status="completed"} 100'
|
||||
);
|
||||
expect(prometheusMetrics).toContain('# HELP queue_processing_time_seconds');
|
||||
expect(prometheusMetrics).toContain('# HELP queue_throughput_per_minute');
|
||||
expect(prometheusMetrics).toContain('# HELP queue_health');
|
||||
});
|
||||
});
|
||||
|
||||
describe('event listeners', () => {
|
||||
it('should setup event listeners on construction', () => {
|
||||
const newMockQueueEvents = {
|
||||
on: mock<(event: string, handler: Function) => void>(() => {}),
|
||||
};
|
||||
|
||||
new QueueMetricsCollector(
|
||||
mockQueue as unknown as Queue,
|
||||
newMockQueueEvents as unknown as QueueEvents
|
||||
);
|
||||
|
||||
expect(newMockQueueEvents.on).toHaveBeenCalledWith('completed', expect.any(Function));
|
||||
expect(newMockQueueEvents.on).toHaveBeenCalledWith('failed', expect.any(Function));
|
||||
expect(newMockQueueEvents.on).toHaveBeenCalledWith('active', expect.any(Function));
|
||||
});
|
||||
});
|
||||
|
||||
describe('oldest waiting job', () => {
|
||||
it('should get oldest waiting job date', async () => {
|
||||
const oldJob = {
|
||||
timestamp: Date.now() - 60000, // 1 minute ago
|
||||
} as Job;
|
||||
|
||||
mockQueue.getWaiting.mockImplementation(() => Promise.resolve([oldJob]));
|
||||
|
||||
const result = await metrics.collect();
|
||||
|
||||
expect(result.oldestWaitingJob).toBeDefined();
|
||||
expect(result.oldestWaitingJob).toBeInstanceOf(Date);
|
||||
});
|
||||
|
||||
it('should return null when no waiting jobs', async () => {
|
||||
mockQueue.getWaiting.mockImplementation(() => Promise.resolve([]));
|
||||
|
||||
const result = await metrics.collect();
|
||||
|
||||
expect(result.oldestWaitingJob).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue