T-7: M0.3a — Harden dev Mongo safety: env-safety throws on unsafe data-pipeline QA reads, scheduled jobs default off, read-only bypass tests

This commit is contained in:
Studio 2026-11-27 01:47:31 -05:00
parent 7cf940afce
commit abbab4b5a8
10 changed files with 644 additions and 18 deletions

View file

@ -6,9 +6,13 @@ import type { HandlerRegistry } from '@stock-bot/handler-registry';
import { defined } from '@stock-bot/invariants';
import { getLogger } from '@stock-bot/logger';
import type { LoggerLike as Logger } from '@stock-bot/logger';
import { Queue, type QueueWorkerConfig } from './queue';
import {
Queue,
removeScheduledJobsFromBullQueue,
type QueueWorkerConfig,
} from './queue';
import { QueueRateLimiter } from './rate-limiter';
import { getFullQueueName, parseQueueName } from './service-utils';
import { getFullQueueName, normalizeServiceName, parseQueueName } from './service-utils';
import type {
GlobalStats,
JobData,
@ -558,6 +562,72 @@ export class QueueManager {
});
}
/**
* Reconcile and remove persisted repeatable/scheduled jobs for the specified
* handler queues owned by this service without starting workers.
* Manual jobs and other services' queues are preserved.
*/
async removeScheduledJobsForQueues(queueNames: string[]): Promise<number> {
this.assertConnectionsOpen();
let totalRemoved = 0;
const seenFullNames = new Set<string>();
const normalizedService = this.serviceName
? normalizeServiceName(this.serviceName)
: undefined;
for (const rawQueueName of queueNames) {
let fullQueueName = rawQueueName;
let isOwnQueue = true;
if (this.serviceName) {
const parsed = parseQueueName(rawQueueName);
if (parsed) {
fullQueueName = rawQueueName;
isOwnQueue =
parsed.service === this.serviceName || parsed.service === normalizedService;
} else {
fullQueueName = getFullQueueName(this.serviceName, rawQueueName);
isOwnQueue = true;
}
}
if (!isOwnQueue || seenFullNames.has(fullQueueName)) {
continue;
}
seenFullNames.add(fullQueueName);
const existingQueue = this.queues.get(fullQueueName);
if (existingQueue) {
totalRemoved += await existingQueue.removeAllScheduledJobs();
continue;
}
// Open a workerless BullQueue handle to clear persisted repeat schedules
// before any worker can consume stale repeat jobs.
const tempQueue = new BullQueue(fullQueueName, {
connection: { ...this.redisConnection, maxRetriesPerRequest: 1, enableOfflineQueue: false },
});
try {
totalRemoved += await removeScheduledJobsFromBullQueue(tempQueue);
} finally {
await tempQueue.close().catch(error => {
this.logger.warn('Error closing temporary reconciliation queue', {
queueName: fullQueueName,
error,
});
});
}
}
this.logger.info('Reconciled disabled scheduled jobs for service queues', {
service: this.serviceName || 'default',
queueCount: seenFullNames.size,
removedCount: totalRemoved,
});
return totalRemoved;
}
/**
* Wait for all queues to be ready
*/

View file

@ -6,6 +6,53 @@ import type { QueueManager } from './queue-manager';
import type { ExtendedJobOptions, JobData, JobOptions, QueueStats, RedisConfig } from './types';
import { getRedisConnection } from './utils';
export type SchedulableBullQueue = Pick<
BullQueue,
'getRepeatableJobs' | 'removeRepeatableByKey' | 'getJobs'
> &
Partial<Pick<BullQueue, 'getJobSchedulers' | 'removeJobScheduler'>>;
/**
* Remove all persisted repeatable/scheduled jobs and any pending repeat-spawned
* job instances from a BullMQ queue while preserving manual (non-repeating) jobs.
*/
export async function removeScheduledJobsFromBullQueue(
bullQueue: SchedulableBullQueue
): Promise<number> {
const removedKeys = new Set<string>();
const repeatableJobs = await bullQueue.getRepeatableJobs();
for (const job of repeatableJobs) {
if (job.key) {
await bullQueue.removeRepeatableByKey(job.key);
removedKeys.add(job.key);
}
}
if (
typeof bullQueue.getJobSchedulers === 'function' &&
typeof bullQueue.removeJobScheduler === 'function'
) {
const schedulers = await bullQueue.getJobSchedulers();
for (const scheduler of schedulers) {
if (scheduler.key && !removedKeys.has(scheduler.key)) {
await bullQueue.removeJobScheduler(scheduler.key);
removedKeys.add(scheduler.key);
}
}
}
const pendingJobs = await bullQueue.getJobs(['waiting', 'delayed']);
for (const job of pendingJobs) {
const repeatKey = job?.repeatJobKey ?? job?.opts?.repeatJobKey;
if (repeatKey) {
await job.remove();
}
}
return removedKeys.size;
}
export interface QueueWorkerConfig {
workers?: number;
concurrency?: number;
@ -167,6 +214,19 @@ export class Queue {
return await this.bullQueue.add(name, data, scheduledOptions);
}
/**
* Remove all persisted repeatable/scheduled jobs and any pending repeat-spawned
* occurrences from this queue while preserving manual jobs.
*/
async removeAllScheduledJobs(): Promise<number> {
const removedCount = await removeScheduledJobsFromBullQueue(this.bullQueue);
this.logger.info('Removed scheduled jobs from queue', {
queueName: this.queueName,
removedCount,
});
return removedCount;
}
/**
* Get queue statistics
*/

View file

@ -1,5 +1,5 @@
import { describe, expect, it, mock } from 'bun:test';
import { Queue } from '../src/queue';
import { Queue, removeScheduledJobsFromBullQueue } from '../src/queue';
import type { QueueWorkerConfig, RedisConfig } from '../src/types';
describe('Queue Class', () => {
@ -122,4 +122,53 @@ describe('Queue Class', () => {
expect(queue.getWorkerCount()).toBe(0);
});
});
describe('scheduled job reconciliation', () => {
it('removes repeatable jobs, job schedulers, and pending repeat instances while preserving manual jobs', async () => {
const removedRepeatKeys: string[] = [];
const removedSchedulerKeys: string[] = [];
const removedJobIds: string[] = [];
const fakeBullQueue = {
getRepeatableJobs: mock(async () => [
{ key: '{data-ingestion_eod}:crawl', name: 'crawl' },
]),
removeRepeatableByKey: mock(async (key: string) => {
removedRepeatKeys.push(key);
return true;
}),
getJobSchedulers: mock(async () => [
{ key: '{data-ingestion_eod}:crawl', name: 'crawl' },
{ key: '{data-ingestion_eod}:intraday', name: 'intraday' },
]),
removeJobScheduler: mock(async (key: string) => {
removedSchedulerKeys.push(key);
return true;
}),
getJobs: mock(async () => [
{
id: 'repeat-job-1',
repeatJobKey: '{data-ingestion_eod}:crawl',
remove: mock(async () => {
removedJobIds.push('repeat-job-1');
}),
},
{
id: 'manual-eod-job-1',
opts: {},
remove: mock(async () => {
removedJobIds.push('manual-eod-job-1');
}),
},
]),
};
const removedCount = await removeScheduledJobsFromBullQueue(fakeBullQueue as any);
expect(removedCount).toBe(2);
expect(removedRepeatKeys).toEqual(['{data-ingestion_eod}:crawl']);
expect(removedSchedulerKeys).toEqual(['{data-ingestion_eod}:intraday']);
expect(removedJobIds).toEqual(['repeat-job-1']);
});
});
});