@mh.js/health-monitor 1.0.0
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.
- package/LICENSE +21 -0
- package/README.md +237 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +18 -0
- package/dist/monitor.d.ts +15 -0
- package/dist/monitor.js +104 -0
- package/dist/types.d.ts +20 -0
- package/dist/types.js +2 -0
- package/package.json +37 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 mh.js
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
# Health Monitor
|
|
2
|
+
|
|
3
|
+
A lightweight health check and event loop monitoring library for Node.js applications.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- **Event Loop Lag Detection**: Monitors if the event loop is blocked to detect system load.
|
|
8
|
+
- **Custom Health Indicators**: Check the status of various components like databases, Redis, external APIs, etc.
|
|
9
|
+
- **Timeout Handling**: Prevents unresponsive states by setting timeouts for each health check.
|
|
10
|
+
- **Stale State Detection**: Automatically switches to 'down' state if the health check loop stops or is delayed.
|
|
11
|
+
- **TypeScript Support**: Includes type definitions for safe use in TypeScript projects.
|
|
12
|
+
|
|
13
|
+
## Installation
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
npm install @mh.js/health-monitor
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Usage
|
|
20
|
+
|
|
21
|
+
### Basic Configuration
|
|
22
|
+
|
|
23
|
+
```typescript
|
|
24
|
+
import { HealthMonitor } from "health-monitor";
|
|
25
|
+
|
|
26
|
+
// Create monitor instance
|
|
27
|
+
const monitor = new HealthMonitor({
|
|
28
|
+
interval: 3000, // Check interval (default: 3000ms)
|
|
29
|
+
timeout: 1000, // Timeout (default: 1000ms)
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
// Start monitoring
|
|
33
|
+
monitor.start();
|
|
34
|
+
|
|
35
|
+
// Get status (e.g., Express route handler)
|
|
36
|
+
app.get("/health", (req, res) => {
|
|
37
|
+
const status = monitor.getStatus();
|
|
38
|
+
res.status(status.status === "ok" ? 200 : 503).json(status);
|
|
39
|
+
});
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
### Register Custom Indicators
|
|
43
|
+
|
|
44
|
+
```typescript
|
|
45
|
+
// Database check example
|
|
46
|
+
monitor.register({
|
|
47
|
+
name: "database",
|
|
48
|
+
check: async () => {
|
|
49
|
+
// Perform actual DB ping logic
|
|
50
|
+
await db.ping();
|
|
51
|
+
},
|
|
52
|
+
timeout: 500, // Individual timeout setting
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
// Redis check example
|
|
56
|
+
monitor.register({
|
|
57
|
+
name: "redis",
|
|
58
|
+
check: async () => {
|
|
59
|
+
// Perform actual Redis ping logic
|
|
60
|
+
await redis.ping();
|
|
61
|
+
},
|
|
62
|
+
timeout: 500,
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
// External API check example
|
|
66
|
+
monitor.register({
|
|
67
|
+
name: "external-api",
|
|
68
|
+
check: async () => {
|
|
69
|
+
const response = await fetch("https://api.example.com/health");
|
|
70
|
+
if (!response.ok) throw new Error("API Unreachable");
|
|
71
|
+
},
|
|
72
|
+
});
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
## API
|
|
76
|
+
|
|
77
|
+
### `new HealthMonitor(config?)`
|
|
78
|
+
|
|
79
|
+
- `config.interval`: Health check interval (ms). Default 3000.
|
|
80
|
+
- `config.timeout`: Default timeout for each indicator (ms). Default 1000.
|
|
81
|
+
|
|
82
|
+
### `monitor.register(indicator)`
|
|
83
|
+
|
|
84
|
+
Registers a new health indicator. Supports method chaining.
|
|
85
|
+
|
|
86
|
+
- `indicator.name`: Component name (identifier).
|
|
87
|
+
- `indicator.check`: Async function to check status. Considered 'down' if Promise rejects.
|
|
88
|
+
- `indicator.timeout`: (Optional) Timeout for this indicator (ms).
|
|
89
|
+
|
|
90
|
+
### `monitor.start()`
|
|
91
|
+
|
|
92
|
+
Starts periodic health checks.
|
|
93
|
+
|
|
94
|
+
### `monitor.stop()`
|
|
95
|
+
|
|
96
|
+
Stops health checks.
|
|
97
|
+
|
|
98
|
+
### `monitor.getStatus()`
|
|
99
|
+
|
|
100
|
+
Returns the current health status.
|
|
101
|
+
|
|
102
|
+
#### Return Type (`HealthStatus`)
|
|
103
|
+
|
|
104
|
+
```typescript
|
|
105
|
+
interface HealthStatus {
|
|
106
|
+
status: "ok" | "down";
|
|
107
|
+
lag: number; // Event loop lag (ms)
|
|
108
|
+
details: {
|
|
109
|
+
[name: string]: {
|
|
110
|
+
status: "up" | "down";
|
|
111
|
+
latency?: number; // Response time (ms)
|
|
112
|
+
error?: string; // Error message
|
|
113
|
+
};
|
|
114
|
+
};
|
|
115
|
+
timestamp: number; // Last check timestamp
|
|
116
|
+
}
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
---
|
|
120
|
+
|
|
121
|
+
# Health Monitor (Korean)
|
|
122
|
+
|
|
123
|
+
Node.js 애플리케이션을 위한 경량 헬스 체크 및 이벤트 루프 모니터링 라이브러리입니다.
|
|
124
|
+
|
|
125
|
+
## 기능
|
|
126
|
+
|
|
127
|
+
- **이벤트 루프 지연(Lag) 감지**: 이벤트 루프가 차단되었는지 모니터링하여 시스템 부하를 감지합니다.
|
|
128
|
+
- **커스텀 헬스 인디케이터**: 데이터베이스, Redis, 외부 API 등 다양한 구성 요소의 상태를 체크할 수 있습니다.
|
|
129
|
+
- **타임아웃 처리**: 각 헬스 체크에 대한 타임아웃을 설정하여 응답 없는 상태를 방지합니다.
|
|
130
|
+
- **Stale 상태 감지**: 헬스 체크 루프가 멈추거나 지연될 경우 자동으로 'down' 상태로 전환합니다.
|
|
131
|
+
- **TypeScript 지원**: 타입 정의가 포함되어 있어 TypeScript 프로젝트에서 안전하게 사용할 수 있습니다.
|
|
132
|
+
|
|
133
|
+
## 설치
|
|
134
|
+
|
|
135
|
+
```bash
|
|
136
|
+
npm install @mh.js/health-monitor
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
## 사용법
|
|
140
|
+
|
|
141
|
+
### 기본 설정
|
|
142
|
+
|
|
143
|
+
```typescript
|
|
144
|
+
import { HealthMonitor } from "health-monitor";
|
|
145
|
+
|
|
146
|
+
// 모니터 인스턴스 생성
|
|
147
|
+
const monitor = new HealthMonitor({
|
|
148
|
+
interval: 3000, // 체크 주기 (기본값: 3000ms)
|
|
149
|
+
timeout: 1000, // 타임아웃 (기본값: 1000ms)
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
// 모니터링 시작
|
|
153
|
+
monitor.start();
|
|
154
|
+
|
|
155
|
+
// 상태 조회 (예: Express 라우트 핸들러)
|
|
156
|
+
app.get("/health", (req, res) => {
|
|
157
|
+
const status = monitor.getStatus();
|
|
158
|
+
res.status(status.status === "ok" ? 200 : 503).json(status);
|
|
159
|
+
});
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
### 커스텀 인디케이터 등록
|
|
163
|
+
|
|
164
|
+
```typescript
|
|
165
|
+
// 데이터베이스 체크 예시
|
|
166
|
+
monitor.register({
|
|
167
|
+
name: "database",
|
|
168
|
+
check: async () => {
|
|
169
|
+
// 실제 DB 핑(ping) 로직 수행
|
|
170
|
+
await db.ping();
|
|
171
|
+
},
|
|
172
|
+
timeout: 500, // 개별 타임아웃 설정 가능
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
// redis 체크 예시
|
|
176
|
+
monitor.register({
|
|
177
|
+
name: "redis",
|
|
178
|
+
check: async () => {
|
|
179
|
+
// 실제 Redis 핑(ping) 로직 수행
|
|
180
|
+
await redis.ping();
|
|
181
|
+
},
|
|
182
|
+
timeout: 500,
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
// 외부 API 체크 예시
|
|
186
|
+
monitor.register({
|
|
187
|
+
name: "external-api",
|
|
188
|
+
check: async () => {
|
|
189
|
+
const response = await fetch("https://api.example.com/health");
|
|
190
|
+
if (!response.ok) throw new Error("API Unreachable");
|
|
191
|
+
},
|
|
192
|
+
});
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
## API
|
|
196
|
+
|
|
197
|
+
### `new HealthMonitor(config?)`
|
|
198
|
+
|
|
199
|
+
- `config.interval`: 헬스 체크 주기 (ms). 기본값 3000.
|
|
200
|
+
- `config.timeout`: 각 인디케이터의 기본 타임아웃 (ms). 기본값 1000.
|
|
201
|
+
|
|
202
|
+
### `monitor.register(indicator)`
|
|
203
|
+
|
|
204
|
+
새로운 헬스 인디케이터를 등록합니다. 메서드 체이닝을 지원합니다.
|
|
205
|
+
|
|
206
|
+
- `indicator.name`: 컴포넌트 이름 (식별자).
|
|
207
|
+
- `indicator.check`: 상태를 체크하는 비동기 함수. Promise가 reject되면 'down'으로 간주합니다.
|
|
208
|
+
- `indicator.timeout`: (선택) 해당 인디케이터의 타임아웃 (ms).
|
|
209
|
+
|
|
210
|
+
### `monitor.start()`
|
|
211
|
+
|
|
212
|
+
주기적인 헬스 체크를 시작합니다.
|
|
213
|
+
|
|
214
|
+
### `monitor.stop()`
|
|
215
|
+
|
|
216
|
+
헬스 체크를 중지합니다.
|
|
217
|
+
|
|
218
|
+
### `monitor.getStatus()`
|
|
219
|
+
|
|
220
|
+
현재 헬스 상태를 반환합니다.
|
|
221
|
+
|
|
222
|
+
#### 반환 타입 (`HealthStatus`)
|
|
223
|
+
|
|
224
|
+
```typescript
|
|
225
|
+
interface HealthStatus {
|
|
226
|
+
status: "ok" | "down";
|
|
227
|
+
lag: number; // 이벤트 루프 지연 시간 (ms)
|
|
228
|
+
details: {
|
|
229
|
+
[name: string]: {
|
|
230
|
+
status: "up" | "down";
|
|
231
|
+
latency?: number; // 응답 시간 (ms)
|
|
232
|
+
error?: string; // 에러 메시지
|
|
233
|
+
};
|
|
234
|
+
};
|
|
235
|
+
timestamp: number; // 마지막 체크 시간
|
|
236
|
+
}
|
|
237
|
+
```
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
+
};
|
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
__exportStar(require("./types"), exports);
|
|
18
|
+
__exportStar(require("./monitor"), exports);
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { HealthIndicator, HealthStatus, MonitorConfig } from './types';
|
|
2
|
+
export declare class HealthMonitor {
|
|
3
|
+
private indicators;
|
|
4
|
+
private intervalId;
|
|
5
|
+
private isCheckInProgress;
|
|
6
|
+
private config;
|
|
7
|
+
private latestStatus;
|
|
8
|
+
constructor(config?: MonitorConfig);
|
|
9
|
+
register(indicator: HealthIndicator): this;
|
|
10
|
+
start(): void;
|
|
11
|
+
stop(): void;
|
|
12
|
+
getStatus(): HealthStatus;
|
|
13
|
+
private checkEventLoopLag;
|
|
14
|
+
private check;
|
|
15
|
+
}
|
package/dist/monitor.js
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.HealthMonitor = void 0;
|
|
4
|
+
const perf_hooks_1 = require("perf_hooks");
|
|
5
|
+
class HealthMonitor {
|
|
6
|
+
constructor(config) {
|
|
7
|
+
var _a, _b;
|
|
8
|
+
this.indicators = [];
|
|
9
|
+
this.intervalId = null;
|
|
10
|
+
this.isCheckInProgress = false;
|
|
11
|
+
this.latestStatus = {
|
|
12
|
+
status: 'ok',
|
|
13
|
+
lag: 0,
|
|
14
|
+
details: {},
|
|
15
|
+
timestamp: Date.now(),
|
|
16
|
+
};
|
|
17
|
+
this.config = {
|
|
18
|
+
interval: (_a = config === null || config === void 0 ? void 0 : config.interval) !== null && _a !== void 0 ? _a : 3000,
|
|
19
|
+
timeout: (_b = config === null || config === void 0 ? void 0 : config.timeout) !== null && _b !== void 0 ? _b : 1000,
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
register(indicator) {
|
|
23
|
+
this.indicators.push(indicator);
|
|
24
|
+
return this;
|
|
25
|
+
}
|
|
26
|
+
start() {
|
|
27
|
+
if (this.intervalId)
|
|
28
|
+
return;
|
|
29
|
+
this.check();
|
|
30
|
+
this.intervalId = setInterval(() => this.check(), this.config.interval);
|
|
31
|
+
this.intervalId.unref();
|
|
32
|
+
}
|
|
33
|
+
stop() {
|
|
34
|
+
if (this.intervalId) {
|
|
35
|
+
clearInterval(this.intervalId);
|
|
36
|
+
this.intervalId = null;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
getStatus() {
|
|
40
|
+
const now = Date.now();
|
|
41
|
+
const isStale = (now - this.latestStatus.timestamp) > (this.config.interval * 3);
|
|
42
|
+
if (isStale) {
|
|
43
|
+
return {
|
|
44
|
+
status: 'down',
|
|
45
|
+
lag: 0,
|
|
46
|
+
details: {
|
|
47
|
+
system: {
|
|
48
|
+
status: 'down',
|
|
49
|
+
error: 'Health check loop is stalled (Event loop might be blocked)',
|
|
50
|
+
}
|
|
51
|
+
},
|
|
52
|
+
timestamp: now,
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
return this.latestStatus;
|
|
56
|
+
}
|
|
57
|
+
async checkEventLoopLag() {
|
|
58
|
+
const start = perf_hooks_1.performance.now();
|
|
59
|
+
return new Promise(resolve => setImmediate(() => resolve(perf_hooks_1.performance.now() - start)));
|
|
60
|
+
}
|
|
61
|
+
async check() {
|
|
62
|
+
if (this.isCheckInProgress)
|
|
63
|
+
return;
|
|
64
|
+
this.isCheckInProgress = true;
|
|
65
|
+
try {
|
|
66
|
+
const details = {};
|
|
67
|
+
let isAllUp = true;
|
|
68
|
+
const lag = await this.checkEventLoopLag();
|
|
69
|
+
const checkPromises = this.indicators.map(async (ind) => {
|
|
70
|
+
var _a;
|
|
71
|
+
const startTime = Date.now();
|
|
72
|
+
const timeoutMs = (_a = ind.timeout) !== null && _a !== void 0 ? _a : this.config.timeout;
|
|
73
|
+
try {
|
|
74
|
+
await Promise.race([
|
|
75
|
+
ind.check(),
|
|
76
|
+
new Promise((_, reject) => setTimeout(() => reject(new Error(`Timeout of ${timeoutMs}ms exceeded`)), timeoutMs))
|
|
77
|
+
]);
|
|
78
|
+
details[ind.name] = { status: 'up', latency: Date.now() - startTime };
|
|
79
|
+
}
|
|
80
|
+
catch (error) {
|
|
81
|
+
isAllUp = false;
|
|
82
|
+
details[ind.name] = {
|
|
83
|
+
status: 'down',
|
|
84
|
+
error: error.message || 'Unknown Error'
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
});
|
|
88
|
+
await Promise.allSettled(checkPromises);
|
|
89
|
+
this.latestStatus = {
|
|
90
|
+
status: isAllUp ? 'ok' : 'down',
|
|
91
|
+
lag,
|
|
92
|
+
details,
|
|
93
|
+
timestamp: Date.now(),
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
catch (error) {
|
|
97
|
+
console.error('HealthMonitor unexpected error:', error);
|
|
98
|
+
}
|
|
99
|
+
finally {
|
|
100
|
+
this.isCheckInProgress = false;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
exports.HealthMonitor = HealthMonitor;
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export interface HealthIndicator {
|
|
2
|
+
name: string;
|
|
3
|
+
check: () => Promise<any>;
|
|
4
|
+
timeout?: number;
|
|
5
|
+
}
|
|
6
|
+
export interface ComponentDetail {
|
|
7
|
+
status: 'up' | 'down';
|
|
8
|
+
latency?: number;
|
|
9
|
+
error?: string;
|
|
10
|
+
}
|
|
11
|
+
export interface HealthStatus {
|
|
12
|
+
status: 'ok' | 'down';
|
|
13
|
+
lag: number;
|
|
14
|
+
details: Record<string, ComponentDetail>;
|
|
15
|
+
timestamp: number;
|
|
16
|
+
}
|
|
17
|
+
export interface MonitorConfig {
|
|
18
|
+
interval?: number;
|
|
19
|
+
timeout?: number;
|
|
20
|
+
}
|
package/dist/types.js
ADDED
package/package.json
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@mh.js/health-monitor",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Lightweight health check and event loop monitoring detection library for Node.js. Supports custom indicators and TypeScript.",
|
|
5
|
+
"main": "dist/index.js",
|
|
6
|
+
"types": "dist/index.d.ts",
|
|
7
|
+
"files": [
|
|
8
|
+
"dist"
|
|
9
|
+
],
|
|
10
|
+
"publishConfig": {
|
|
11
|
+
"access": "public"
|
|
12
|
+
},
|
|
13
|
+
"scripts": {
|
|
14
|
+
"build": "tsc",
|
|
15
|
+
"prepublishOnly": "npm run build",
|
|
16
|
+
"test": "echo \"Error: no test specified\" && exit 1"
|
|
17
|
+
},
|
|
18
|
+
"keywords": [
|
|
19
|
+
"health-check",
|
|
20
|
+
"health-monitor",
|
|
21
|
+
"event-loop",
|
|
22
|
+
"event-loop-lag",
|
|
23
|
+
"lag-detection",
|
|
24
|
+
"monitoring",
|
|
25
|
+
"heartbeat",
|
|
26
|
+
"typescript",
|
|
27
|
+
"performance",
|
|
28
|
+
"nodejs"
|
|
29
|
+
],
|
|
30
|
+
"author": "mh.js",
|
|
31
|
+
"license": "MIT",
|
|
32
|
+
"type": "commonjs",
|
|
33
|
+
"devDependencies": {
|
|
34
|
+
"@types/node": "^25.0.9",
|
|
35
|
+
"typescript": "^5.9.3"
|
|
36
|
+
}
|
|
37
|
+
}
|