|
| 1 | +/** |
| 2 | + * Internal Scheduler for Self-Hosted Environments |
| 3 | + * |
| 4 | + * This module provides a built-in scheduler that periodically polls the |
| 5 | + * /api/schedules/execute endpoint to trigger scheduled workflows. |
| 6 | + * This is necessary for self-hosted environments that don't have access |
| 7 | + * to external cron services like Vercel Cron Jobs. |
| 8 | + * |
| 9 | + * Enable by setting ENABLE_INTERNAL_SCHEDULER=true in your environment. |
| 10 | + */ |
| 11 | + |
| 12 | +import { env } from '@/lib/core/config/env' |
| 13 | +import { createLogger } from '@/lib/logs/console/logger' |
| 14 | + |
| 15 | +const logger = createLogger('InternalScheduler') |
| 16 | + |
| 17 | +const DEFAULT_POLL_INTERVAL_MS = 60000 // 1 minute |
| 18 | + |
| 19 | +let schedulerInterval: ReturnType<typeof setInterval> | null = null |
| 20 | +let isRunning = false |
| 21 | + |
| 22 | +/** |
| 23 | + * Execute the schedule poll |
| 24 | + */ |
| 25 | +async function pollSchedules(): Promise<void> { |
| 26 | + if (isRunning) { |
| 27 | + logger.debug('Previous poll still running, skipping this cycle') |
| 28 | + return |
| 29 | + } |
| 30 | + |
| 31 | + isRunning = true |
| 32 | + |
| 33 | + try { |
| 34 | + const appUrl = env.NEXT_PUBLIC_APP_URL || env.BETTER_AUTH_URL || 'http://localhost:3000' |
| 35 | + const cronSecret = env.CRON_SECRET |
| 36 | + |
| 37 | + if (!cronSecret) { |
| 38 | + logger.warn('CRON_SECRET not configured, internal scheduler cannot authenticate') |
| 39 | + return |
| 40 | + } |
| 41 | + |
| 42 | + const response = await fetch(`${appUrl}/api/schedules/execute`, { |
| 43 | + method: 'GET', |
| 44 | + headers: { |
| 45 | + Authorization: `Bearer ${cronSecret}`, |
| 46 | + 'User-Agent': 'sim-studio-internal-scheduler/1.0', |
| 47 | + }, |
| 48 | + }) |
| 49 | + |
| 50 | + if (!response.ok) { |
| 51 | + const errorText = await response.text() |
| 52 | + logger.error('Schedule poll failed', { |
| 53 | + status: response.status, |
| 54 | + error: errorText, |
| 55 | + }) |
| 56 | + return |
| 57 | + } |
| 58 | + |
| 59 | + const result = await response.json() |
| 60 | + if (result.executedCount > 0) { |
| 61 | + logger.info(`Triggered ${result.executedCount} scheduled workflow(s)`) |
| 62 | + } |
| 63 | + } catch (error) { |
| 64 | + logger.error('Error during schedule poll', error) |
| 65 | + } finally { |
| 66 | + isRunning = false |
| 67 | + } |
| 68 | +} |
| 69 | + |
| 70 | +/** |
| 71 | + * Start the internal scheduler |
| 72 | + */ |
| 73 | +export function startInternalScheduler(): void { |
| 74 | + if (schedulerInterval) { |
| 75 | + logger.warn('Internal scheduler already running') |
| 76 | + return |
| 77 | + } |
| 78 | + |
| 79 | + const pollInterval = Number(env.INTERNAL_SCHEDULER_INTERVAL_MS) || DEFAULT_POLL_INTERVAL_MS |
| 80 | + |
| 81 | + logger.info(`Starting internal scheduler with poll interval: ${pollInterval}ms`) |
| 82 | + |
| 83 | + // Run immediately on start |
| 84 | + void pollSchedules() |
| 85 | + |
| 86 | + // Then run at regular intervals |
| 87 | + schedulerInterval = setInterval(() => { |
| 88 | + void pollSchedules() |
| 89 | + }, pollInterval) |
| 90 | +} |
| 91 | + |
| 92 | +/** |
| 93 | + * Stop the internal scheduler |
| 94 | + */ |
| 95 | +export function stopInternalScheduler(): void { |
| 96 | + if (schedulerInterval) { |
| 97 | + clearInterval(schedulerInterval) |
| 98 | + schedulerInterval = null |
| 99 | + logger.info('Internal scheduler stopped') |
| 100 | + } |
| 101 | +} |
| 102 | + |
| 103 | +/** |
| 104 | + * Check if the internal scheduler should be enabled |
| 105 | + */ |
| 106 | +export function shouldEnableInternalScheduler(): boolean { |
| 107 | + return env.ENABLE_INTERNAL_SCHEDULER === 'true' |
| 108 | +} |
| 109 | + |
| 110 | +/** |
| 111 | + * Initialize the internal scheduler if enabled |
| 112 | + */ |
| 113 | +export function initializeInternalScheduler(): void { |
| 114 | + if (!shouldEnableInternalScheduler()) { |
| 115 | + logger.debug('Internal scheduler disabled (set ENABLE_INTERNAL_SCHEDULER=true to enable)') |
| 116 | + return |
| 117 | + } |
| 118 | + |
| 119 | + if (!env.CRON_SECRET) { |
| 120 | + logger.warn('Cannot start internal scheduler: CRON_SECRET is not configured') |
| 121 | + return |
| 122 | + } |
| 123 | + |
| 124 | + startInternalScheduler() |
| 125 | + |
| 126 | + // Graceful shutdown handlers |
| 127 | + process.on('SIGTERM', () => { |
| 128 | + stopInternalScheduler() |
| 129 | + }) |
| 130 | + |
| 131 | + process.on('SIGINT', () => { |
| 132 | + stopInternalScheduler() |
| 133 | + }) |
| 134 | +} |
0 commit comments