This repository was archived by the owner on May 14, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
87 lines (68 loc) · 2.25 KB
/
main.js
File metadata and controls
87 lines (68 loc) · 2.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import dotenv from 'dotenv';
import Fastify from 'fastify';
import registerEndpoints from './endpoints/index.js';
import { parseDebugOptions } from './functions/helpers.js';
import { createLogger } from './functions/log.js';
import { getBearerToken } from './functions/token.js';
import registerCors from './plugins/cors.js';
import registerStatsFile from './plugins/statsFile.js';
async function main() {
dotenv.config();
const mau_id = process.env.MAU_ID;
const pwd = process.env.MAU_PWD;
const mfa_secret = process.env.MFA_SECRET;
if (!mau_id || !pwd) throw new Error('Missing MAU_ID or MAU_PWD in .env');
const debugOpts = parseDebugOptions();
// CREATE LOGGER
const log = createLogger(debugOpts);
log.info('Debug options:', debugOpts);
const app = Fastify({
logger: false,
});
await app.register(registerCors);
await app.register(registerStatsFile);
log.info('stats exists:', Boolean(app.stats));
// Attach shared objects so routes can use them
app.decorate('logx', log);
app.decorate('debugOpts', debugOpts);
const port = Number(process.env.PORT ?? 3000);
const host = process.env.HOST ?? '127.0.0.1';
app.decorate('isReady', false);
await app.register(registerEndpoints);
// readiness gate
app.addHook('onRequest', async (req, reply) => {
if (req.url.startsWith('/health')) return;
if (req.method === 'OPTIONS') return;
if (!app.isReady) {
return reply.code(503).send({
ok: false,
ready: false,
reason: 'starting_up',
});
}
});
// count usage (after route is known)
app.addHook('onResponse', async (req, reply) => {
if (req.url.startsWith('/health')) return;
if (req.method === 'OPTIONS') return;
const route = (req.routeOptions && req.routeOptions.url) || req.url.split('?')[0];
app.stats.inc({ route, method: req.method });
});
await app.listen({ port, host });
log.info(`Fastify listening on http://${host}:${port}`);
// Prime token AFTER listen (async)
(async () => {
try {
await getBearerToken({ log, debugOpts });
log.info('Bearer token primed.');
app.isReady = true;
} catch (e) {
log.error('Token prime failed at boot:', e?.message ?? e);
// keep isReady=false -> endpoints will return 503 (except /health)
}
})();
}
main().catch((e) => {
console.error(e);
process.exit(1);
});