diff --git a/cron-sync.ts b/cron-sync.ts new file mode 100644 index 0000000..319d371 --- /dev/null +++ b/cron-sync.ts @@ -0,0 +1,59 @@ +// cron-sync.ts +import cron from 'node-cron'; +import { fileURLToPath } from 'node:url'; +import path from 'node:path'; +import dotenv from 'dotenv'; +import http from 'node:http'; +import https from 'node:https'; +import { syncAllDomains } from './app/lib/sync'; // .ts/.js-Endung NICHT nötig mit NodeNext + +// __dirname in ESM/TS: +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); + +// .env robust laden – relativ zum Script-Verzeichnis +dotenv.config({ path: path.join(__dirname, '.env') }); + +// Keep-Alive für HTTP(S) +http.globalAgent.keepAlive = true; +https.globalAgent.keepAlive = true; + +// Debug-Logging +console.log('DATABASE_URL:', process.env.DATABASE_URL); +console.log('AWS_REGION:', process.env.AWS_REGION); +console.log('AWS_ACCESS_KEY_ID:', process.env.AWS_ACCESS_KEY_ID ? 'Set' : 'Not set'); +console.log('AWS_SECRET_ACCESS_KEY:', process.env.AWS_SECRET_ACCESS_KEY ? 'Set' : 'Not set'); + +// Timeout-Wrapper (10 Min Default) +async function runSyncWithTimeout(timeoutMs = 600_000) { + return Promise.race([ + syncAllDomains(), + new Promise((_, reject) => setTimeout(() => reject(new Error('Sync timeout exceeded')), timeoutMs)), + ]); +} + +console.log('Starting Cron Job for S3 Sync...'); + +// Cron: jede volle Stunde +cron.schedule('*/5 * * * *', async () => { + const ts = new Date().toISOString(); + console.log(`[${ts}] Running scheduled sync...`); + try { + await runSyncWithTimeout(); + console.log('✅ Sync completed successfully.'); + } catch (err) { + console.error('❌ Sync error:', err); + } +}); + +// Optional: initial direkt synchronisieren +(async () => { + const ts = new Date().toISOString(); + console.log(`[${ts}] Initial sync run on startup...`); + try { + await runSyncWithTimeout(); + console.log('✅ Initial sync completed successfully.'); + } catch (err) { + console.error('❌ Initial sync error:', err); + } +})(); \ No newline at end of file