import dotenv from 'dotenv'; dotenv.config(); import rDramaSession from './rdrama/session/SessionManager'; import RedisSessionManager from './redis/session/SessionManager'; import { CommentProcessor } from './rdrama/services/CommentProcessor'; // Run every 300,000 milliseconds (5 minutes) by default const workflowInterval = 1000 * 60 * Number(process.env.POLLING_FREQUENCY || 5); async function startApplication() { console.log('Redis Start'); const redisManager = RedisSessionManager.getInstance(); console.log('RDrama Session Start'); const rDramaSessionManager = rDramaSession.getInstance(); if (!process.env.RDRAMA_API_KEY) { throw new Error('RDRAMA_API_KEY is undefined. Please set this environment variable.'); } rDramaSessionManager.setAuthorizationToken(process.env.RDRAMA_API_KEY); // Initialize and start workflow try { await CommentProcessor.processComments(); console.log(`${new Date()} Workflow executed successfully.`); } catch (error) { console.error('An error occurred during workflow execution:', error); } // Schedule future runs setInterval(async () => { try { await CommentProcessor.processComments(); console.log(`${new Date()} Workflow executed successfully.`); } catch (error) { console.error('An error occurred during workflow execution:', error); } }, workflowInterval); // Setup shutdown and error handling setupProcessListeners(redisManager, rDramaSessionManager); } function setupProcessListeners(redisManager: RedisSessionManager, rDramaSessionManager: rDramaSession) { process.on('SIGINT', async () => { console.log('SIGINT received. Shutting down gracefully...'); await shutdownServices(redisManager, rDramaSessionManager); }); process.on('SIGTERM', async () => { console.log('SIGTERM received. Shutting down gracefully...'); await shutdownServices(redisManager, rDramaSessionManager); }); process.on('uncaughtException', async (error) => { console.error('Uncaught Exception:', error); await shutdownServices(redisManager, rDramaSessionManager); process.exit(1); // Exit with error }); process.on('unhandledRejection', async (reason, promise) => { console.error('Unhandled Rejection at:', promise, 'reason:', reason); await shutdownServices(redisManager, rDramaSessionManager); process.exit(1); // Exit with error }); } async function shutdownServices(redisManager: RedisSessionManager, rDramaSessionManager: rDramaSession) { await redisManager.shutdown(); await rDramaSessionManager.shutdown(); console.log('Services shut down successfully.'); process.exit(0); // Exit cleanly } startApplication() .then(() => console.log('Application started successfully.')) .catch((error) => console.error('Application failed to start:', error));