import { Queue, RedisOptions } from 'bullmq'; /** * Job status types matching BullMQ states */ type JobStatus = "active" | "waiting" | "waiting-children" | "prioritized" | "completed" | "failed" | "delayed" | "paused" | "unknown"; /** * Configuration options for Workbench */ interface WorkbenchOptions { /** BullMQ Queue instances to display */ queues?: Queue[]; /** Redis connection for auto-discovery of queues */ redis?: string | RedisOptions; /** Basic auth credentials */ auth?: { username: string; password: string; }; /** Dashboard title */ title?: string; /** Logo URL */ logo?: string; /** Override base path detection */ basePath?: string; /** Disable actions (retry, remove, promote) */ readonly?: boolean; /** Fields from job.data to extract as filterable tags (e.g., ['teamId', 'userId']) */ tags?: string[]; /** * BullMQ key prefix used during queue auto-discovery from `redis`. Ignored * when `queues` is set explicitly. Defaults to `"bull"`. */ prefix?: string; /** * Maximum number of queues to keep when auto-discovering from `redis`. * Prevents connection storms on very large Redis deployments. Defaults to * 100. Ignored when `queues` is set explicitly. */ maxQueues?: number; /** Self-hosted alerting configuration */ alerts?: AlertsOptions; } /** Supported alert trigger types */ type AlertTrigger = "job_failed" | "job_stalled" | "retries_exhausted" | "failed_backlog" | "no_workers_with_backlog"; type AlertSeverity = "critical" | "warning" | "info"; type AlertContactPointPreset = "slack" | "webhook" | "discord"; /** Where notifications are sent (Slack/Discord incoming webhook or generic webhook) */ interface AlertContactPoint { id: string; name: string; preset: AlertContactPointPreset; /** Webhook URL — stored server-side; API responses mask this value */ url: string; enabled: boolean; displayName?: string; iconUrl?: string; /** Extra headers for generic webhook preset */ headers?: Record; createdAt: number; updatedAt: number; } /** Rule that maps a trigger to one or more contact points */ interface AlertRule { id: string; name: string; enabled: boolean; trigger: AlertTrigger; severity: AlertSeverity; /** Empty or omitted = all queues */ queues?: string[]; /** Optional job name filter for event triggers */ jobNames?: string[]; /** Threshold for backlog-style triggers (failed count or waiting count) */ threshold?: number; contactPointIds: string[]; cooldownMs?: number; createdAt: number; updatedAt: number; } /** Pluggable persistence for alert contact points and rules */ interface AlertStore { getContactPoints(): Promise; getContactPoint(id: string): Promise; createContactPoint(input: Omit): Promise; updateContactPoint(id: string, input: Partial>): Promise; deleteContactPoint(id: string): Promise; getRules(): Promise; getRule(id: string): Promise; createRule(input: Omit): Promise; updateRule(id: string, input: Partial>): Promise; deleteRule(id: string): Promise; close?(): Promise; } type AlertPersistence = "redis" | "memory" | "custom"; interface AlertsOptions { /** Set to `false` to disable alerting entirely. Default: on. */ enabled?: boolean; /** Seed data imported into Redis on first run when the store is empty */ contactPoints?: AlertContactPoint[]; /** Seed data imported into Redis on first run when the store is empty */ rules?: AlertRule[]; /** Override the config store entirely */ store?: AlertStore; /** Where to persist dashboard-managed config. Default: `"redis"` when a connection exists */ persistence?: "redis" | "memory"; /** Redis key prefix for stored config. Default: Workbench `prefix` or `"bull"` */ storagePrefix?: string; defaults?: { cooldownMs?: number; sendResolved?: boolean; }; /** Public dashboard URL included in notification links */ dashboardUrl?: string; } /** Normalized alert event for delivery and activity log */ interface AlertEvent { id: string; ruleId: string; ruleName: string; trigger: AlertTrigger; severity: AlertSeverity; status: "firing" | "resolved"; fingerprint: string; queue?: string; jobId?: string; jobName?: string; message: string; failedReason?: string; attemptsMade?: number; counts?: { failed?: number; backlog?: number; workers?: number | null; }; firedAt: number; resolvedAt?: number; } /** Contact point as returned by the API (URL masked) */ type AlertContactPointPublic = Omit & { urlMasked: string; }; interface AlertDeliveryRecord { contactPointId: string; contactPointName: string; success: boolean; error?: string; at: number; } /** Runtime status exposed to the dashboard */ interface AlertRuntimeStatus { enabled: boolean; persistence: AlertPersistence; listenerCount: number; listeners: Array<{ queue: string; connected: boolean; }>; healthCheckIntervalMs: number; lastHealthCheckAt?: number; recentEvents: AlertEvent[]; lastDeliveries: AlertDeliveryRecord[]; defaults: { cooldownMs: number; sendResolved: boolean; }; } /** * Queue information for API responses */ interface QueueInfo { name: string; counts: { waiting: number; active: number; completed: number; failed: number; delayed: number; prioritized: number; "waiting-children": number; paused: number; }; isPaused: boolean; /** Active workers for this queue; null when Redis CLIENT LIST is unavailable */ workerCount?: number | null; } /** * Worker information from BullMQ */ interface WorkerInfo { id: string; name: string; addr: string; age: number; idle: number; started: number; queueName: string; } /** * Extracted tag key-value pairs from job data */ type JobTags = Record; /** * Job information for API responses */ interface JobInfo { id: string; name: string; data: unknown; opts: { attempts?: number; delay?: number; priority?: number; }; progress: number | object; attemptsMade: number; processedOn?: number; finishedOn?: number; timestamp: number; failedReason?: string; stacktrace?: string[]; returnvalue?: unknown; status: JobStatus; duration?: number; /** Extracted tag values from job.data based on configured tag fields */ tags?: JobTags; /** Parent job info if this job is part of a flow */ parent?: { id: string; queueName: string; }; } /** * BullMQ job.log() entries for a single job */ interface JobLogsResponse { logs: string[]; count: number; } /** * Overview stats for dashboard */ interface OverviewStats { totalJobs: number; activeJobs: number; failedJobs: number; completedToday: number; avgDuration: number; queues: QueueInfo[]; } /** * Paginated response wrapper */ interface PaginatedResponse { data: T[]; total: number; cursor?: string; hasMore: boolean; } /** * Search result item */ interface SearchResult { queue: string; job: JobInfo; } /** * Run item - job execution with queue context */ interface RunInfo extends JobInfo { queueName: string; } /** * Lightweight run info for list view - only fields needed for table display * Excludes large fields like full job.data, opts, progress, etc. */ interface RunInfoList { id: string; name: string; status: JobStatus; queueName: string; tags?: JobTags; processedOn?: number; timestamp: number; duration?: number; failedReason?: string; } /** * Scheduler info for repeatable jobs */ interface SchedulerInfo { /** Job scheduler key (the id passed to upsertJobScheduler); used by "Run now". */ key: string; name: string; queueName: string; pattern?: string; every?: number; next?: number; endDate?: number; tz?: string; } /** * Delayed job info */ interface DelayedJobInfo { id: string; name: string; queueName: string; delay: number; processAt: number; data: unknown; } /** * Test job request */ interface TestJobRequest { queueName: string; jobName: string; data: unknown; opts?: { delay?: number; priority?: number; attempts?: number; }; } /** * Sort direction */ type SortDirection = "asc" | "desc"; /** * Sort options for API requests */ interface SortOptions { field: string; direction: SortDirection; } /** * Valid sort fields for runs/jobs */ type RunSortField = "timestamp" | "name" | "status" | "duration" | "queueName"; /** * Valid sort fields for repeatable schedulers */ type RepeatableSortField = "name" | "queueName" | "pattern" | "next" | "tz"; /** * Valid sort fields for delayed schedulers */ type DelayedSortField = "name" | "queueName" | "processAt" | "delay"; /** * Hourly bucket for metrics aggregation */ interface HourlyBucket { /** Unix timestamp (start of hour) */ hour: number; /** Number of completed jobs */ completed: number; /** Number of failed jobs */ failed: number; /** Average processing duration in ms */ avgDuration: number; /** Average queue wait time in ms */ avgWaitTime: number; } /** * Metrics for a single queue */ interface QueueMetrics { queueName: string; buckets: HourlyBucket[]; summary: { totalCompleted: number; totalFailed: number; /** Error rate as 0-1 */ errorRate: number; /** Average processing duration in ms */ avgDuration: number; /** Average queue wait time in ms */ avgWaitTime: number; /** Average throughput per hour */ throughputPerHour: number; }; } /** * Slowest job entry */ interface SlowestJob { name: string; queueName: string; duration: number; jobId: string; } /** * Most failing job type entry */ interface FailingJobType { name: string; queueName: string; jobId: string; failCount: number; totalCount: number; errorRate: number; } /** * Complete metrics response */ interface MetricsResponse { /** Metrics per queue */ queues: QueueMetrics[]; /** Aggregated metrics across all queues */ aggregate: Omit & { queueName: "all"; }; /** Top 10 slowest jobs */ slowestJobs: SlowestJob[]; /** Top 10 most failing job types */ mostFailingTypes: FailingJobType[]; /** Timestamp when metrics were computed */ computedAt: number; } /** * A node in a flow tree representing a job and its children */ interface FlowNode { job: JobInfo; queueName: string; children?: FlowNode[]; } /** * Flow summary for list view */ interface FlowSummary { /** Root job ID */ id: string; /** Root job name */ name: string; /** Queue containing root job */ queueName: string; /** Root job status */ status: JobStatus; /** Total number of jobs in flow */ totalJobs: number; /** Number of completed jobs */ completedJobs: number; /** Number of failed jobs */ failedJobs: number; /** When flow was created */ timestamp: number; /** Duration if completed */ duration?: number; } /** * Request to create a test flow */ interface CreateFlowRequest { name: string; queueName: string; data?: unknown; children: CreateFlowChildRequest[]; } /** * Child job in a flow creation request */ interface CreateFlowChildRequest { name: string; queueName: string; data?: unknown; children?: CreateFlowChildRequest[]; } /** * Activity bucket for timeline */ interface ActivityBucket { /** Unix timestamp (start of bucket) */ time: number; /** Number of completed jobs */ completed: number; /** Number of failed jobs */ failed: number; } /** * Activity stats response for the 7-day timeline */ interface ActivityStatsResponse { /** Activity buckets (4-hour intervals over 7 days) */ buckets: ActivityBucket[]; /** Start time of the first bucket */ startTime: number; /** End time (now) */ endTime: number; /** Size of each bucket in ms */ bucketSize: number; /** Total completed in period */ totalCompleted: number; /** Total failed in period */ totalFailed: number; /** Timestamp when stats were computed */ computedAt: number; } /** * Manages queue operations for the Workbench dashboard */ declare class QueueManager { private queues; private tagFields; private flowProducer; private cache; private readonly CACHE_TTL; constructor(queues: Queue[], tagFields?: string[]); /** * Get cached value or compute and cache */ private cached; /** * Execute a promise with a timeout */ private withTimeout; /** * Get jobs by time range using Redis sorted sets (ZRANGEBYSCORE) * This is more efficient than fetching all jobs and filtering in memory */ private getJobsByTimeRange; /** * Cache for job state lookups to avoid repeated Redis calls */ private jobStateCache; /** * Cache for job counts to avoid repeated Redis calls * Short TTL since counts change frequently but are expensive to fetch */ private countCache; /** * Get job counts with caching */ private getCachedJobCounts; /** * Invalidate caches related to a job or queue */ private invalidateJobCache; /** * Clear cache (useful after mutations) */ clearCache(prefix?: string): void; /** * Get quick job counts across all queues (lightweight, for smart polling) * Returns total counts per status - cached and very fast */ getQuickCounts(): Promise<{ waiting: number; active: number; completed: number; failed: number; delayed: number; prioritized: number; "waiting-children": number; total: number; timestamp: number; }>; /** * Get configured tag field names */ getTagFields(): string[]; /** * Get just queue names (very fast, no Redis calls) * Used for sidebar initial render */ getQueueNames(): string[]; /** * Get a queue by name */ getQueue(name: string): Queue | undefined; /** * Internal map of queue instances (for alerting and advanced integrations) */ getQueueMap(): Map; /** * Get information for all queues (cached) */ getQueues(): Promise; /** * Get overview statistics (cached) */ getOverview(): Promise; /** * Pause a queue - stops processing new jobs */ pauseQueue(queueName: string): Promise; /** * Resume a paused queue */ resumeQueue(queueName: string): Promise; /** * Check if a queue is paused */ isQueuePaused(queueName: string): Promise; /** * Get metrics for the last 24 hours (cached - expensive operation) */ getMetrics(): Promise; /** * Get activity stats for the last 7 days (cached) * Returns 4-hour buckets for the activity timeline */ getActivityStats(): Promise; /** * Get jobs for a specific queue with pagination and sorting */ getJobs(queueName: string, status?: JobStatus, limit?: number, start?: number, sort?: SortOptions): Promise>; /** * Get a single job by ID */ getJob(queueName: string, jobId: string): Promise; /** * Get worker logs written via job.log() */ getJobLogs(queueName: string, jobId: string, start?: number, end?: number, asc?: boolean): Promise; /** * Retry a failed job */ retryJob(queueName: string, jobId: string): Promise; /** * Remove a job */ removeJob(queueName: string, jobId: string): Promise; /** * Promote a delayed job to waiting */ promoteJob(queueName: string, jobId: string): Promise; /** * Parse search query for field:value filters * Returns { filters: { field: value }, text: remainingText } */ private parseSearchQuery; /** * Check if a raw job matches all provided filters (before conversion) * This is more efficient than converting to JobInfo first */ private jobMatchesAllFilters; /** * Check if a job matches the given tag filters */ private jobMatchesFilters; /** * Search jobs across all queues * Supports field:value syntax (e.g., "teamId:abc-123 invoice") * Optimized with parallel processing, early exits, and count checks */ search(query: string, limit?: number): Promise; /** * Clean jobs from a queue */ cleanJobs(queueName: string, status: "completed" | "failed", grace?: number): Promise; /** * FAST PATH: Get latest runs without filters * Optimized for the common case of viewing newest jobs (timestamp desc, no filters) * - Single getJobs call per queue (not per status type) * - No count checks needed * - Minimal Redis round-trips */ private getLatestRuns; /** * Get all runs (jobs) across all queues with sorting and filtering * Uses fast path for common case (no filters, timestamp desc) */ getAllRuns(limit?: number, start?: number, sort?: SortOptions, filters?: { status?: JobStatus; tags?: Record; text?: string; timeRange?: { start: number; end: number; }; }): Promise>; /** * Get all schedulers (repeatable and delayed jobs) with sorting */ getSchedulers(repeatableSort?: SortOptions, delayedSort?: SortOptions): Promise<{ repeatable: SchedulerInfo[]; delayed: DelayedJobInfo[]; }>; /** * Enqueue a new job (for testing) */ enqueueJob(request: TestJobRequest): Promise<{ id: string; }>; /** * Trigger an immediate, one-off run of a repeatable job scheduler. * * Enqueues a clone of the scheduler's job (name + data + opts) so the run * behaves like a scheduled execution, but as a standalone job. The repeat * schedule is left untouched, and scheduling internals are stripped so it * runs now and never collides with the deterministic ids of scheduled * iterations. * * `schedulerKey` is the scheduler's `key` from {@link getSchedulers} (the id * passed to upsertJobScheduler). We resolve it via getJobSchedulers rather * than the singular getJobScheduler, which mis-parses some keys. * * Data/opts source: modern schedulers (upsertJobScheduler) carry a `template`. * Legacy repeatables — `queue.add(name, data, { repeat })` — store NO template, * so we fall back to the next pending iteration (a delayed job tagged with this * scheduler's key), which carries the real payload and options. */ runSchedulerNow(queueName: string, schedulerKey: string): Promise<{ id: string; } | null>; /** * Extract tag values from job data based on configured tag fields */ private extractTags; /** * Get unique values for a specific tag field across all jobs */ getTagValues(field: string, limit?: number): Promise<{ value: string; count: number; }[]>; /** * Get sortable value from JobInfo/RunInfo */ private getSortValue; /** * Get sortable value from RunInfoList (lightweight version) */ private getSortValueForList; /** * Get sortable value from SchedulerInfo */ private getSchedulerSortValue; /** * Get sortable value from DelayedJobInfo */ private getDelayedSortValue; /** * Convert a BullMQ Job to JobInfo or RunInfoList * @param job - The BullMQ job to convert * @param fields - "list" for lightweight list view, "full" for complete job details * @param knownState - Optional: skip getState() call if state is already known from fetch */ private jobToInfo; /** * Retry multiple jobs across queues * Processed in parallel for better performance */ bulkRetry(jobs: { queueName: string; jobId: string; }[]): Promise<{ success: number; failed: number; }>; /** * Delete multiple jobs across queues * Processed in parallel for better performance */ bulkDelete(jobs: { queueName: string; jobId: string; }[]): Promise<{ success: number; failed: number; }>; /** * Promote multiple delayed jobs across queues (move to waiting) * Processed in parallel for better performance */ bulkPromote(jobs: { queueName: string; jobId: string; }[]): Promise<{ success: number; failed: number; }>; /** * Get all flows (jobs that have children or are part of a flow) - cached * Optimized to focus on waiting-children type first and early exit */ getFlows(limit?: number): Promise; /** * Get a single flow tree by root job ID */ getFlow(queueName: string, jobId: string): Promise; /** * Create a new flow */ createFlow(request: CreateFlowRequest): Promise<{ id: string; }>; /** * Build a FlowJob from CreateFlowRequest or CreateFlowChildRequest */ private buildFlowJob; /** * Convert BullMQ flow tree to our FlowNode structure */ private convertFlowTree; /** * Count statistics for a flow tree */ private countFlowStats; } declare class AlertManager { private readonly store; private readonly persistence; private readonly options; private readonly queueManager; private readonly getQueues; private queueEvents; private listenerStatus; private healthTimer; private lastHealthCheckAt?; private recentEvents; private lastDeliveries; private cooldowns; private activeHealthAlerts; private started; private closed; constructor(queueManager: QueueManager, getQueues: () => Map, options: AlertsOptions, store?: AlertStore, persistence?: "redis" | "memory" | "custom"); get enabled(): boolean; getStore(): AlertStore; /** Start QueueEvents listeners and health-check loop */ start(): Promise; close(): Promise; private closeListeners; getStatus(): Promise; /** Send a test notification through a contact point */ sendTest(contactPointId: string): Promise; /** Preview what a rule would look like without sending */ previewRule(rule: AlertRule): AlertEvent; private handleQueueEvent; private runHealthChecks; private resolveHealthAlert; private fireRule; private deliver; private buildFingerprint; private buildMessage; private matchesQueue; private matchesJobName; private pushEvent; private pushDelivery; } /** * Internal metadata produced by {@link WorkbenchCore.fromOptions} when queues * are auto-discovered from a Redis connection. */ interface DiscoveryMeta { /** Total number of queues found on the connection (before capping). */ total: number; /** True if the result was capped at `maxQueues`. */ capped: boolean; /** The cap that was applied. */ cap: number; } /** * Core Workbench class that manages the dashboard */ declare class WorkbenchCore { readonly options: Required> & WorkbenchOptions; readonly queueManager: QueueManager; readonly discovery: DiscoveryMeta | null; readonly alertManager: AlertManager | null; readonly alertsPersistence: "redis" | "memory" | "custom" | null; constructor(options: WorkbenchOptions | Queue[], discovery?: DiscoveryMeta | null); /** * Async factory: build a `WorkbenchCore` from `WorkbenchOptions`, performing * BullMQ queue auto-discovery via `SCAN :*:meta` when `queues` is * not provided. * * - When `queues` is set explicitly, behaves like `new WorkbenchCore(opts)`. * - When only `redis` is set, scans the connection for queues, caps at * `maxQueues` (default 100) to avoid connection storms with very large * deployments, and constructs the core with the resulting list. * - When no queues are discovered, the core is constructed with an empty * queue map so the dashboard can render an "empty" state instead of * erroring out. */ static fromOptions(opts: WorkbenchOptions): Promise; /** * Get the queue manager instance */ getQueueManager(): QueueManager; /** * Check if authentication is required */ requiresAuth(): boolean; /** * Validate authentication credentials */ validateAuth(username: string, password: string): boolean; /** * Get dashboard configuration for the UI */ getConfig(): { title: string; logo: string | undefined; readonly: boolean; queues: string[]; tags: string[]; discovery: DiscoveryMeta | null; alertsEnabled: boolean; alertsPersistence: "redis" | "memory" | "custom" | null; }; } export { type ActivityBucket as A, type RunSortField as B, type CreateFlowChildRequest as C, type DelayedJobInfo as D, type SearchResult as E, type FailingJobType as F, type SlowestJob as G, type HourlyBucket as H, type SortDirection as I, type JobInfo as J, type SortOptions as K, type WorkbenchOptions as L, type MetricsResponse as M, type WorkerInfo as N, type OverviewStats as O, type PaginatedResponse as P, type QueueInfo as Q, type RepeatableSortField as R, type SchedulerInfo as S, type TestJobRequest as T, WorkbenchCore as W, type ActivityStatsResponse as a, type AlertContactPoint as b, type AlertContactPointPreset as c, type AlertContactPointPublic as d, type AlertDeliveryRecord as e, type AlertEvent as f, AlertManager as g, type AlertPersistence as h, type AlertRule as i, type AlertRuntimeStatus as j, type AlertSeverity as k, type AlertStore as l, type AlertTrigger as m, type AlertsOptions as n, type CreateFlowRequest as o, type DelayedSortField as p, type DiscoveryMeta as q, type FlowNode as r, type FlowSummary as s, type JobLogsResponse as t, type JobStatus as u, type JobTags as v, QueueManager as w, type QueueMetrics as x, type RunInfo as y, type RunInfoList as z };