@wrcb/cb-common 1.0.512 → 1.0.515

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -17,4 +17,12 @@ export interface HealthCheckConfig {
17
17
  };
18
18
  }>;
19
19
  }
20
+ /**
21
+ * Política:
22
+ * - /live → liveness: SEM dependências externas, sempre 200 se o processo está up.
23
+ * - /health → readiness/startup: pode retornar 503 se dependências essenciais falharem.
24
+ *
25
+ * Dica: alinhe o STARTUP_GRACE_PERIOD com sua startupProbe.
26
+ * Por padrão, 300_000 ms (5min). Configurável via HEALTH_STARTUP_GRACE_MS.
27
+ */
20
28
  export declare function createHealthRouter(config: HealthCheckConfig): import("express-serve-static-core").Router;
@@ -16,48 +16,56 @@ exports.createHealthRouter = createHealthRouter;
16
16
  // @wrcb/cb-common/server/src/routes/health.ts
17
17
  const express_1 = __importDefault(require("express"));
18
18
  const mongoose_1 = __importDefault(require("mongoose"));
19
+ /**
20
+ * Política:
21
+ * - /live → liveness: SEM dependências externas, sempre 200 se o processo está up.
22
+ * - /health → readiness/startup: pode retornar 503 se dependências essenciais falharem.
23
+ *
24
+ * Dica: alinhe o STARTUP_GRACE_PERIOD com sua startupProbe.
25
+ * Por padrão, 300_000 ms (5min). Configurável via HEALTH_STARTUP_GRACE_MS.
26
+ */
19
27
  function createHealthRouter(config) {
28
+ var _a;
20
29
  const router = express_1.default.Router();
21
30
  const startupTime = Date.now();
22
- const STARTUP_GRACE_PERIOD = 60000;
23
- // Health Check Principal
24
- router.get('/health', (req, res) => {
31
+ const STARTUP_GRACE_PERIOD = Number((_a = process.env.HEALTH_STARTUP_GRACE_MS) !== null && _a !== void 0 ? _a : 300000); // 5 min por padrão
32
+ // Liveness: NÃO consultar NATS/Redis/Mongo. Apenas indica que o processo está de pé.
33
+ router.get('/live', (_req, res) => {
34
+ res.status(200).send('OK');
35
+ });
36
+ // Readiness/Startup (com tolerância durante bootstrap)
37
+ router.get('/health', (_req, res) => {
25
38
  const now = Date.now();
26
39
  const isStartup = now - startupTime < STARTUP_GRACE_PERIOD;
27
- const health = {
28
- status: 'checking',
40
+ const checks = {
41
+ mongodb: checkMongoDB()
42
+ };
43
+ if (config.natsWrapper) {
44
+ checks.nats = checkNATS(config.natsWrapper);
45
+ }
46
+ if (config.workers) {
47
+ checks.workers = checkWorkers(config.workers, isStartup);
48
+ }
49
+ if (config.customChecks) {
50
+ checks.custom = checkCustom(config.customChecks);
51
+ }
52
+ const allHealthy = isStartup
53
+ ? checks.mongodb.status === 'healthy' // durante startup, só exigimos Mongo OK
54
+ : Object.values(checks).every(check => check && typeof check === 'object' && 'status' in check
55
+ ? check.status === 'healthy'
56
+ : true);
57
+ const payload = {
58
+ status: allHealthy ? 'healthy' : 'unhealthy',
29
59
  timestamp: new Date().toISOString(),
30
60
  service: config.serviceName,
31
61
  uptime: process.uptime(),
32
62
  isStartup,
33
- checks: Object.assign(Object.assign(Object.assign({ mongodb: checkMongoDB() }, (config.natsWrapper && { nats: checkNATS(config.natsWrapper) })), (config.workers && {
34
- workers: checkWorkers(config.workers, isStartup)
35
- })), (config.customChecks && {
36
- custom: checkCustom(config.customChecks)
37
- }))
63
+ checks
38
64
  };
39
- // Durante startup, ser mais tolerante
40
- const allHealthy = isStartup
41
- ? health.checks.mongodb.status === 'healthy'
42
- : Object.values(health.checks).every(check => typeof check === 'object' && 'status' in check
43
- ? check.status === 'healthy'
44
- : true);
45
- health.status = allHealthy ? 'healthy' : 'unhealthy';
46
- const statusCode = allHealthy ? 200 : 503;
47
- res.status(statusCode).json(health);
65
+ res.status(allHealthy ? 200 : 503).json(payload);
48
66
  });
49
- // Endpoint simplificado para Kubernetes
50
- router.get('/health', (req, res) => {
51
- const mongoHealthy = mongoose_1.default.connection.readyState === 1;
52
- if (mongoHealthy) {
53
- res.status(200).send('OK');
54
- }
55
- else {
56
- res.status(503).send('NOT READY');
57
- }
58
- });
59
- // Endpoint de métricas
60
- router.get('/metrics', (req, res) => __awaiter(this, void 0, void 0, function* () {
67
+ // Métricas opcionais
68
+ router.get('/metrics', (_req, res) => __awaiter(this, void 0, void 0, function* () {
61
69
  try {
62
70
  const metrics = {
63
71
  timestamp: new Date().toISOString(),
@@ -81,8 +89,9 @@ function createHealthRouter(config) {
81
89
  }));
82
90
  return router;
83
91
  }
84
- // Funções auxiliares
92
+ // Auxiliares
85
93
  function checkMongoDB() {
94
+ var _a;
86
95
  const state = mongoose_1.default.connection.readyState;
87
96
  const states = {
88
97
  0: { status: 'unhealthy', message: 'disconnected' },
@@ -90,14 +99,13 @@ function checkMongoDB() {
90
99
  2: { status: 'unhealthy', message: 'connecting' },
91
100
  3: { status: 'unhealthy', message: 'disconnecting' }
92
101
  };
93
- return (states[state] || {
102
+ return ((_a = states[state]) !== null && _a !== void 0 ? _a : {
94
103
  status: 'unhealthy',
95
104
  message: 'unknown'
96
105
  });
97
106
  }
98
107
  function checkNATS(natsWrapper) {
99
108
  try {
100
- // Verificar se client existe sem tentar acessá-lo se não estiver pronto
101
109
  if (!natsWrapper || typeof natsWrapper.client === 'undefined') {
102
110
  return { status: 'unhealthy', message: 'not_initialized' };
103
111
  }
@@ -105,7 +113,7 @@ function checkNATS(natsWrapper) {
105
113
  ? { status: 'unhealthy', message: 'connection_closed' }
106
114
  : { status: 'healthy', message: 'connected' };
107
115
  }
108
- catch (error) {
116
+ catch (_a) {
109
117
  return { status: 'unhealthy', message: 'not_connected' };
110
118
  }
111
119
  }
@@ -114,14 +122,13 @@ function checkWorkers(workers, isStartup = false) {
114
122
  let allRunning = true;
115
123
  try {
116
124
  workers.forEach(({ name, instance, isRunningProperty = 'isRunning' }) => {
117
- const isRunning = instance[isRunningProperty] === true;
125
+ const isRunning = (instance === null || instance === void 0 ? void 0 : instance[isRunningProperty]) === true;
118
126
  workerStatus[name] = isRunning ? 'running' : 'stopped';
119
127
  if (!isRunning && !isStartup)
120
128
  allRunning = false;
121
129
  });
122
130
  }
123
- catch (error) {
124
- console.error('Error checking workers:', error);
131
+ catch (_a) {
125
132
  if (!isStartup)
126
133
  allRunning = false;
127
134
  }
@@ -141,7 +148,7 @@ function checkCustom(customChecks) {
141
148
  if (result.status !== 'healthy')
142
149
  allHealthy = false;
143
150
  }
144
- catch (error) {
151
+ catch (_a) {
145
152
  results[name] = { status: 'unhealthy', message: 'check_failed' };
146
153
  allHealthy = false;
147
154
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wrcb/cb-common",
3
- "version": "1.0.512",
3
+ "version": "1.0.515",
4
4
  "description": "Common resources between services",
5
5
  "main": "./build/index.js",
6
6
  "types": "./build/index.d.ts",