@wrcb/cb-common 1.0.503 → 1.0.505

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.
@@ -0,0 +1,20 @@
1
+ export interface HealthCheckConfig {
2
+ serviceName: string;
3
+ natsWrapper?: {
4
+ client?: any;
5
+ isClosed: boolean;
6
+ };
7
+ workers?: Array<{
8
+ name: string;
9
+ instance: any;
10
+ isRunningProperty?: string;
11
+ }>;
12
+ customChecks?: Array<{
13
+ name: string;
14
+ checkFunction: () => {
15
+ status: 'healthy' | 'unhealthy';
16
+ message: string;
17
+ };
18
+ }>;
19
+ }
20
+ export declare function createHealthRouter(config: HealthCheckConfig): import("express-serve-static-core").Router;
@@ -0,0 +1,152 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.createHealthRouter = createHealthRouter;
16
+ // @wrcb/cb-common/server/src/routes/health.ts
17
+ const express_1 = __importDefault(require("express"));
18
+ const mongoose_1 = __importDefault(require("mongoose"));
19
+ function createHealthRouter(config) {
20
+ const router = express_1.default.Router();
21
+ const startupTime = Date.now();
22
+ const STARTUP_GRACE_PERIOD = 60000;
23
+ // Health Check Principal
24
+ router.get('/health', (req, res) => {
25
+ const now = Date.now();
26
+ const isStartup = now - startupTime < STARTUP_GRACE_PERIOD;
27
+ const health = {
28
+ status: 'checking',
29
+ timestamp: new Date().toISOString(),
30
+ service: config.serviceName,
31
+ uptime: process.uptime(),
32
+ 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
+ }))
38
+ };
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);
48
+ });
49
+ // Endpoint simplificado para Kubernetes
50
+ router.get('/healthz', (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* () {
61
+ try {
62
+ const metrics = {
63
+ timestamp: new Date().toISOString(),
64
+ uptime: process.uptime(),
65
+ memory: process.memoryUsage(),
66
+ mongodb: {
67
+ readyState: mongoose_1.default.connection.readyState,
68
+ host: mongoose_1.default.connection.host,
69
+ name: mongoose_1.default.connection.name
70
+ },
71
+ env: {
72
+ nodeEnv: process.env.NODE_ENV,
73
+ version: process.version
74
+ }
75
+ };
76
+ res.json(metrics);
77
+ }
78
+ catch (error) {
79
+ res.status(500).json({ error: 'Error collecting metrics' });
80
+ }
81
+ }));
82
+ return router;
83
+ }
84
+ // Funções auxiliares
85
+ function checkMongoDB() {
86
+ const state = mongoose_1.default.connection.readyState;
87
+ const states = {
88
+ 0: { status: 'unhealthy', message: 'disconnected' },
89
+ 1: { status: 'healthy', message: 'connected' },
90
+ 2: { status: 'unhealthy', message: 'connecting' },
91
+ 3: { status: 'unhealthy', message: 'disconnecting' }
92
+ };
93
+ return (states[state] || {
94
+ status: 'unhealthy',
95
+ message: 'unknown'
96
+ });
97
+ }
98
+ function checkNATS(natsWrapper) {
99
+ try {
100
+ if (!natsWrapper.client) {
101
+ return { status: 'unhealthy', message: 'not_initialized' };
102
+ }
103
+ return natsWrapper.isClosed
104
+ ? { status: 'unhealthy', message: 'connection_closed' }
105
+ : { status: 'healthy', message: 'connected' };
106
+ }
107
+ catch (error) {
108
+ return { status: 'unhealthy', message: 'error_checking' };
109
+ }
110
+ }
111
+ function checkWorkers(workers, isStartup = false) {
112
+ const workerStatus = {};
113
+ let allRunning = true;
114
+ try {
115
+ workers.forEach(({ name, instance, isRunningProperty = 'isRunning' }) => {
116
+ const isRunning = instance[isRunningProperty] === true;
117
+ workerStatus[name] = isRunning ? 'running' : 'stopped';
118
+ if (!isRunning && !isStartup)
119
+ allRunning = false;
120
+ });
121
+ }
122
+ catch (error) {
123
+ console.error('Error checking workers:', error);
124
+ if (!isStartup)
125
+ allRunning = false;
126
+ }
127
+ return {
128
+ status: allRunning || isStartup ? 'healthy' : 'unhealthy',
129
+ workers: workerStatus,
130
+ startupMode: isStartup
131
+ };
132
+ }
133
+ function checkCustom(customChecks) {
134
+ const results = {};
135
+ let allHealthy = true;
136
+ customChecks.forEach(({ name, checkFunction }) => {
137
+ try {
138
+ const result = checkFunction();
139
+ results[name] = result;
140
+ if (result.status !== 'healthy')
141
+ allHealthy = false;
142
+ }
143
+ catch (error) {
144
+ results[name] = { status: 'unhealthy', message: 'check_failed' };
145
+ allHealthy = false;
146
+ }
147
+ });
148
+ return {
149
+ status: allHealthy ? 'healthy' : 'unhealthy',
150
+ checks: results
151
+ };
152
+ }
package/build/server.d.ts CHANGED
@@ -25,7 +25,7 @@ export * from './middlewares/requireProvidedBusinessData';
25
25
  export * from './middlewares/requireHybridAuth';
26
26
  export * from './middlewares/standardResponse';
27
27
  export * from './middlewares/uploadMedia';
28
- export * from './routes/getHealth';
28
+ export * from './routes/health';
29
29
  export * from './events/baseListener';
30
30
  export * from './events/basePublisher';
31
31
  export * from './events/callStartedEvent';
package/build/server.js CHANGED
@@ -41,7 +41,7 @@ __exportStar(require("./middlewares/requireProvidedBusinessData"), exports);
41
41
  __exportStar(require("./middlewares/requireHybridAuth"), exports);
42
42
  __exportStar(require("./middlewares/standardResponse"), exports);
43
43
  __exportStar(require("./middlewares/uploadMedia"), exports);
44
- __exportStar(require("./routes/getHealth"), exports);
44
+ __exportStar(require("./routes/health"), exports);
45
45
  __exportStar(require("./events/baseListener"), exports);
46
46
  __exportStar(require("./events/basePublisher"), exports);
47
47
  __exportStar(require("./events/callStartedEvent"), exports);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wrcb/cb-common",
3
- "version": "1.0.503",
3
+ "version": "1.0.505",
4
4
  "description": "Common resources between services",
5
5
  "main": "./build/index.js",
6
6
  "types": "./build/index.d.ts",
@@ -1,2 +0,0 @@
1
- declare const router: import("express-serve-static-core").Router;
2
- export { router as getHealthRouter };
@@ -1,16 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.getHealthRouter = void 0;
7
- const express_1 = __importDefault(require("express"));
8
- const router = express_1.default.Router();
9
- exports.getHealthRouter = router;
10
- router.get('/health', (req, res) => {
11
- res.status(200).json({
12
- status: 'healthy',
13
- service: 'cb-logs',
14
- timestamp: new Date().toISOString()
15
- });
16
- });