import Fastify from 'fastify' import cookie from '@fastify/cookie' import cors from '@fastify/cors' import { initDb } from './db.js' import { connect as connectMqtt } from './lib/mqtt.js' import { startEngine } from './lib/engine.js' import { deviceRoutes } from './routes/devices.js' import { scheduleRoutes } from './routes/schedules.js' import { settingsRoutes } from './routes/settings.js' const app = Fastify({ logger: true, trustProxy: true }) const startedAt = Date.now() await app.register(cookie) await app.register(cors, { origin: process.env.CORS_ORIGIN || false, credentials: true, }) app.get('/health', async () => ({ status: 'healthy', version: process.env.BUILD_VERSION || String(startedAt) })) await app.register(deviceRoutes) await app.register(scheduleRoutes) await app.register(settingsRoutes) try { await initDb() // The broker may be unreachable at boot — connect() handles that with its own // backoff and never blocks startup. connectMqtt().catch(err => app.log.warn(`MQTT connect failed at startup: ${err.message}`)) startEngine() await app.listen({ port: 3001, host: '0.0.0.0' }) } catch (err) { app.log.error(err) process.exit(1) }