mail-s3-admin/cron-sync.ts

59 lines
1.9 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 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);
}
})();