import fastifyStatic from '@fastify/static'; import Fastify, { type FastifyInstance } from 'fastify'; import { type ServerConfig, loadConfig } from './config.js'; import { channelRoutes } from './routes/channel.js'; import { healthRoutes } from './routes/health.js'; import { createQueueRoutes } from './routes/queue.js'; /** * Construit et configure l'instance Fastify de l'application : fichiers * statiques du client, et routes applicatives. * * @param config - Configuration runtime résolue depuis l'environnement. * @returns L'instance Fastify prête à être démarrée. */ async function buildServer(config: ServerConfig): Promise { const app = Fastify({ logger: true }); try { await app.register(fastifyStatic, { root: config.clientDistPath, index: ['index.html'], }); await app.register(healthRoutes); await app.register(channelRoutes); await app.register(createQueueRoutes(config)); } catch (error) { app.log.error({ err: error }, "Échec de l'enregistrement des plugins Fastify"); throw error; } return app; } /** * Installe les gestionnaires d'arrêt propre du serveur (SIGINT/SIGTERM). * * @param app - Instance Fastify à fermer proprement à l'arrêt. */ function installShutdownHandlers(app: FastifyInstance): void { const shutdown = async (signal: string): Promise => { app.log.info(`Signal ${signal} reçu, arrêt du serveur...`); try { await app.close(); process.exit(0); } catch (error) { app.log.error({ err: error }, "Échec de l'arrêt propre du serveur"); process.exit(1); } }; for (const signal of ['SIGINT', 'SIGTERM'] as const) { process.on(signal, () => { shutdown(signal).catch((error: unknown) => { console.error(`Échec du gestionnaire ${signal}`, error); process.exit(1); }); }); } } /** * Point d'entrée du serveur : construit l'application, la démarre, et * installe les gestionnaires d'arrêt propre. */ async function main(): Promise { const config = loadConfig(); const app = await buildServer(config); try { await app.listen({ port: config.port, host: config.host }); app.log.info(`Serveur démarré sur http://${config.host}:${config.port}`); } catch (error) { app.log.error({ err: error }, 'Échec du démarrage du serveur'); process.exit(1); } installShutdownHandlers(app); } main().catch((error: unknown) => { console.error('Erreur fatale au démarrage', error); process.exit(1); });