import { PlataClusterManager } from '++/libs/cluster' import { HotReload } from '++/libs/hot-reload' export const main = async () => { const cluster = new PlataClusterManager() if (cluster.isPrimary()) { let workers: number | undefined = undefined if (Plata.config._PLATA_API_WORKERS !== undefined) { workers = +Plata.config._PLATA_API_WORKERS || undefined } const clustersPromise: RequireFolderReturn<{ default: Cluster.WorkerConfig }> = require("@@/clusters/*.*") if (process.argv.includes('--hot')) Plata.FastPromise(() => HotReload.setupHotReloadPrimary()) ; const clusters = await clustersPromise if (clusters.errorID !== undefined) { console.log(clusters) process.exit(0) } // start Clusters { const promises: any = [] clusters.forEach(c => { const config = c.exports.default promises.push(cluster._startCluster(config).then(r => { if (r !== null) { console.log(r) process.exit(0) } })) }) await Promise.all(promises) } // Inicia a API await cluster._startCluster({ name: '__PLATA_EXPRESS__', env: Plata.config.ENV ?? 'prod', onStart: async () => {}, workers: workers, }) } else { if (Plata.config._PLATA_WORKER_NAME === '__PLATA_EXPRESS__') { const { getCustomExpress } = await import('++/libs/custom') const { buildExpressRouter, loadRoutesFromProject } = await import('++/libs/router') const { createServer } = await import('node:https') if (process.argv.includes('--hot')) Plata.FastPromise(() => HotReload.setupHotReloadWorker()) ; const projectRoutesPromise = Plata.FastPromise(() => loadRoutesFromProject()) const { app, router, expressImport } = await getCustomExpress() app.disable('x-powered-by') const apiRoots = Plata.config._PLATA_API_ROOT ?? '/api' app.use(expressImport.json({ limit: Plata.config._PLATA_API_JSON_SIZE ?? '100kb', verify(req: any, _res, buf) { req.rawBody = buf }, })) const requiredRoutes = await projectRoutesPromise if (requiredRoutes.errorID !== undefined) { console.log(requiredRoutes) await cluster.send({ action: 'KILL', msg: 'Erro enquanto carregava as rotas' }) return } { const result = await buildExpressRouter(requiredRoutes, router) if (result.errorID !== undefined) { console.log(JSON.stringify(result, null, 4)) await cluster.send({ action: 'KILL', msg: 'Erro enquanto carregava as rotas' }) return } app.use(apiRoots.split(','), result as any) } app.use((err, _req, res, _next) => { return res.status(500).json({ errorID: 'PRAPI0001', error: 'Erro interno inesperado', msg: { message: err.message, stack: err.stack ?? new Error().stack } }) }) app.all('*', (req, res) => { return res.status(404).json({ errorID: 'PRAPI0002', msg: 'Rota não encontrada', error: req.path }) }) const port = process.env.PORT ?? 3050 if (!Plata.config._PLATA_API_SSL_KEY || !Plata.config._PLATA_API_SSL_CERT) { console.log(`Nenhum certificado configurado na env ${process.env.ENV}:`) console.log(`_PLATA_API_SSL_KEY: ${process.env._PLATA_API_SSL_KEY}`) console.log(`_PLATA_API_SSL_CERT: ${process.env._PLATA_API_SSL_CERT}`) app.listen(port, () => { console.log(`Iniciando Worker Express na porta ${port}`) setTimeout(() => process.removeAllListeners('exit'), 500) }) } else { console.log('Iniciando a Plata com ssl usando os arquivos:') console.log(`key: ${process.env._PLATA_API_SSL_KEY}`) console.log(`cert: ${process.env._PLATA_API_SSL_CERT}`) const fs = await import('node:fs/promises') const path = await import('node:path') const [ cert, key ] = await Promise.all([ fs.readFile(path.normalize(path.join( Plata.ProjectDir, Plata.config._PLATA_API_SSL_CERT ))), fs.readFile(path.normalize(path.join( Plata.ProjectDir, Plata.config._PLATA_API_SSL_KEY ))) ]).catch(err => { console.log({ errorID: 'PRAPI0003', msg: 'Erro ao ler o certifica e chave ssl', error: { message: err?.toString(), stack: err?.stack } } satisfies PlataError) process.exit(1) }) const https = createServer({ cert, key, passphrase: process.env._PLATA_API_SSL_PASS }, app) https.listen(port, () => { console.log(`Iniciando Worker Express na porta ${port} com SSL`) setTimeout(() => process.removeAllListeners('exit'), 500) }) } } else { if (Plata.config._PLATA_WORKER_NAME === undefined) { await cluster.send({ action: 'KILL', msg: 'tried to start a Worker without _PLATA_WORKER_NAME' }) return } await cluster._onStartCluster( Plata.config._PLATA_WORKER_NAME, Plata.config._PLATA_WORKER_TYPE, ) } } }