@catbee/utils 2.0.4 → 2.1.1
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/README.md +1 -0
- package/cache/index.cjs +36 -16
- package/cache/index.d.ts +6 -2
- package/cache/index.mjs +36 -16
- package/context-store/index.cjs +97 -76
- package/context-store/index.d.ts +74 -57
- package/context-store/index.mjs +97 -77
- package/healthz-server/index.cjs +356 -0
- package/healthz-server/index.d.ts +291 -0
- package/healthz-server/index.mjs +352 -0
- package/index.cjs +7 -0
- package/index.d.ts +1 -0
- package/index.mjs +1 -0
- package/logger/index.cjs +174 -76
- package/logger/index.d.ts +29 -18
- package/logger/index.mjs +174 -77
- package/package.json +12 -7
- package/server/index.cjs +216 -74
- package/server/index.d.ts +72 -14
- package/server/index.mjs +215 -74
|
@@ -0,0 +1,352 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* The MIT License
|
|
3
|
+
*
|
|
4
|
+
* Copyright (c) 2026 Catbee Technologies. https://catbee.in/license
|
|
5
|
+
*
|
|
6
|
+
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
7
|
+
* of this software and associated documentation files (the "Software"), to deal
|
|
8
|
+
* in the Software without restriction, including without limitation the rights
|
|
9
|
+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
10
|
+
* copies of the Software, and to permit persons to whom the Software is
|
|
11
|
+
* furnished to do so, subject to the following conditions:
|
|
12
|
+
*
|
|
13
|
+
* The above copyright notice and this permission notice shall be included in all
|
|
14
|
+
* copies or substantial portions of the Software.
|
|
15
|
+
*
|
|
16
|
+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
17
|
+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
21
|
+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
22
|
+
* SOFTWARE.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
import { createServer } from 'http';
|
|
26
|
+
import { Env } from '@catbee/utils/env';
|
|
27
|
+
|
|
28
|
+
var __defProp = Object.defineProperty;
|
|
29
|
+
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
30
|
+
function getDefaultHealthzConfig() {
|
|
31
|
+
return {
|
|
32
|
+
host: Env.get("HEALTHZ_HOST", "") || Env.get("SERVER_HEALTHZ_HOST", "") || Env.get("SERVER_HOST", "") || Env.get("HOST", "0.0.0.0"),
|
|
33
|
+
port: Env.getPort("HEALTHZ_PORT", Env.getPort("SERVER_HEALTHZ_PORT", 8282)),
|
|
34
|
+
healthzPath: Env.get("HEALTHZ_PATH", "") || Env.get("SERVER_HEALTHZ_PATH", "") || Env.get("SERVER_HEALTH_CHECK_PATH", "/healthz"),
|
|
35
|
+
readyzPath: Env.get("HEALTHZ_READYZ_PATH", "") || Env.get("SERVER_READYZ_PATH", "/readyz"),
|
|
36
|
+
startupzPath: Env.get("HEALTHZ_STARTUPZ_PATH", "") || Env.get("SERVER_STARTUPZ_PATH", "/startupz"),
|
|
37
|
+
detailed: Env.getBoolean("HEALTHZ_DETAILED", Env.getBoolean("SERVER_HEALTH_CHECK_DETAILED_OUTPUT", true)),
|
|
38
|
+
checks: [],
|
|
39
|
+
checkTimeoutMs: Env.getDuration("HEALTHZ_CHECK_TIMEOUT_MS", 5e3),
|
|
40
|
+
shutdownDelayMs: Env.getDuration("HEALTHZ_SHUTDOWN_DELAY_MS", 5e3)
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
__name(getDefaultHealthzConfig, "getDefaultHealthzConfig");
|
|
44
|
+
function resolveConfig(userConfig) {
|
|
45
|
+
const defaults = getDefaultHealthzConfig();
|
|
46
|
+
if (!userConfig) return {
|
|
47
|
+
...defaults
|
|
48
|
+
};
|
|
49
|
+
const cleaned = Object.fromEntries(Object.entries(userConfig).filter(([, v]) => v !== void 0));
|
|
50
|
+
return {
|
|
51
|
+
...defaults,
|
|
52
|
+
...cleaned
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
__name(resolveConfig, "resolveConfig");
|
|
56
|
+
|
|
57
|
+
// src/healthz-server/healthz-server.ts
|
|
58
|
+
var SINGLETON_KEY = Symbol.for("CatbeeHealthzServer");
|
|
59
|
+
var _global = globalThis;
|
|
60
|
+
var HealthzServer = class _HealthzServer {
|
|
61
|
+
static {
|
|
62
|
+
__name(this, "HealthzServer");
|
|
63
|
+
}
|
|
64
|
+
server;
|
|
65
|
+
config;
|
|
66
|
+
startedAt = Date.now();
|
|
67
|
+
/** Whether the health server has successfully started listening (for `/startupz`) */
|
|
68
|
+
started = false;
|
|
69
|
+
/** Whether the service is ready to receive traffic (for `/readyz`) */
|
|
70
|
+
ready = false;
|
|
71
|
+
shuttingDown = false;
|
|
72
|
+
onSigterm = /* @__PURE__ */ __name(() => this.initiateShutdown(), "onSigterm");
|
|
73
|
+
onSigint = /* @__PURE__ */ __name(() => this.initiateShutdown(), "onSigint");
|
|
74
|
+
constructor(config) {
|
|
75
|
+
this.config = config;
|
|
76
|
+
this.server = createServer((req, res) => this.handleRequest(req, res));
|
|
77
|
+
process.once("SIGTERM", this.onSigterm);
|
|
78
|
+
process.once("SIGINT", this.onSigint);
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Boot the health-check server.
|
|
82
|
+
* Returns `null` if a server is already running in this process.
|
|
83
|
+
*/
|
|
84
|
+
static async start(opts) {
|
|
85
|
+
if (_global[SINGLETON_KEY]) return null;
|
|
86
|
+
const config = resolveConfig(opts);
|
|
87
|
+
const instance = new _HealthzServer(config);
|
|
88
|
+
_global[SINGLETON_KEY] = instance;
|
|
89
|
+
return new Promise((resolve, reject) => {
|
|
90
|
+
const onError = /* @__PURE__ */ __name((err) => {
|
|
91
|
+
instance.cleanup();
|
|
92
|
+
delete _global[SINGLETON_KEY];
|
|
93
|
+
reject(err);
|
|
94
|
+
}, "onError");
|
|
95
|
+
instance.server.once("error", onError);
|
|
96
|
+
instance.server.listen({
|
|
97
|
+
host: config.host,
|
|
98
|
+
port: config.port
|
|
99
|
+
}, () => {
|
|
100
|
+
instance.server.off("error", onError);
|
|
101
|
+
instance.started = true;
|
|
102
|
+
const addr = instance.server.address();
|
|
103
|
+
if (!addr || typeof addr === "string") {
|
|
104
|
+
instance.cleanup();
|
|
105
|
+
delete _global[SINGLETON_KEY];
|
|
106
|
+
reject(new Error("Failed to resolve health server address"));
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
resolve({
|
|
110
|
+
address: addr.address,
|
|
111
|
+
family: addr.family,
|
|
112
|
+
port: addr.port
|
|
113
|
+
});
|
|
114
|
+
});
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
/** Whether the health-check server is currently running and started. */
|
|
118
|
+
static isStarted() {
|
|
119
|
+
return _global[SINGLETON_KEY]?.started ?? false;
|
|
120
|
+
}
|
|
121
|
+
/** Mark the service as ready / not-ready for traffic. */
|
|
122
|
+
static setReady(ready) {
|
|
123
|
+
const instance = _global[SINGLETON_KEY];
|
|
124
|
+
if (!instance) return;
|
|
125
|
+
instance.ready = ready;
|
|
126
|
+
}
|
|
127
|
+
/** Whether the service is currently marked as ready. */
|
|
128
|
+
static isReady() {
|
|
129
|
+
return _global[SINGLETON_KEY]?.ready ?? false;
|
|
130
|
+
}
|
|
131
|
+
/** Gracefully stop the health-check server. */
|
|
132
|
+
static async stop() {
|
|
133
|
+
const instance = _global[SINGLETON_KEY];
|
|
134
|
+
if (!instance) return;
|
|
135
|
+
instance.cleanup();
|
|
136
|
+
return new Promise((resolve) => {
|
|
137
|
+
if (typeof instance.server.closeIdleConnections === "function") {
|
|
138
|
+
instance.server.closeIdleConnections();
|
|
139
|
+
}
|
|
140
|
+
instance.server.close(() => {
|
|
141
|
+
delete _global[SINGLETON_KEY];
|
|
142
|
+
resolve();
|
|
143
|
+
});
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
static getInstance() {
|
|
147
|
+
return _global[SINGLETON_KEY];
|
|
148
|
+
}
|
|
149
|
+
async handleRequest(req, res) {
|
|
150
|
+
const isHead = req.method === "HEAD";
|
|
151
|
+
if (req.method !== "GET" && !isHead) {
|
|
152
|
+
this.sendJson(res, 405, {
|
|
153
|
+
error: "Method Not Allowed"
|
|
154
|
+
}, isHead);
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
const url = req.url ?? "/";
|
|
158
|
+
try {
|
|
159
|
+
if (url === this.config.healthzPath) {
|
|
160
|
+
await this.handleLiveness(res, isHead);
|
|
161
|
+
} else if (url === this.config.readyzPath) {
|
|
162
|
+
await this.handleReadiness(res, isHead);
|
|
163
|
+
} else if (url === this.config.startupzPath) {
|
|
164
|
+
this.handleStartup(res, isHead);
|
|
165
|
+
} else {
|
|
166
|
+
this.sendJson(res, 404, {
|
|
167
|
+
error: "Not Found"
|
|
168
|
+
}, isHead);
|
|
169
|
+
}
|
|
170
|
+
} catch (err) {
|
|
171
|
+
const message = err instanceof Error ? err.message : "Internal Server Error";
|
|
172
|
+
this.sendJson(res, 500, {
|
|
173
|
+
error: message
|
|
174
|
+
}, isHead);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
/** `/healthz` — Liveness probe */
|
|
178
|
+
async handleLiveness(res, isHead = false) {
|
|
179
|
+
const results = await this.runChecks(this.config.checks);
|
|
180
|
+
if (this.config.onHealthCheck) {
|
|
181
|
+
const start = Date.now();
|
|
182
|
+
try {
|
|
183
|
+
const ok = await this.executeCheck(this.config.onHealthCheck, this.config.checkTimeoutMs);
|
|
184
|
+
results.push({
|
|
185
|
+
name: "custom",
|
|
186
|
+
ok: !!ok,
|
|
187
|
+
durationMs: Date.now() - start,
|
|
188
|
+
...!ok ? {
|
|
189
|
+
error: "Health check returned false"
|
|
190
|
+
} : {}
|
|
191
|
+
});
|
|
192
|
+
} catch (err) {
|
|
193
|
+
const message = err instanceof Error ? err.message : "Unknown error";
|
|
194
|
+
results.push({
|
|
195
|
+
name: "custom",
|
|
196
|
+
ok: false,
|
|
197
|
+
durationMs: Date.now() - start,
|
|
198
|
+
error: message
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
const allOk = results.every((r) => r.ok);
|
|
203
|
+
const status = allOk ? "ok" : "unhealthy";
|
|
204
|
+
const httpStatus = allOk ? 200 : 503;
|
|
205
|
+
this.sendProbe(res, httpStatus, status, results, isHead);
|
|
206
|
+
}
|
|
207
|
+
/** `/readyz` — Readiness probe */
|
|
208
|
+
async handleReadiness(res, isHead = false) {
|
|
209
|
+
if (this.shuttingDown || !this.ready) {
|
|
210
|
+
const status2 = "unhealthy";
|
|
211
|
+
this.sendProbe(res, 503, status2, [
|
|
212
|
+
{
|
|
213
|
+
name: "readiness",
|
|
214
|
+
ok: false,
|
|
215
|
+
durationMs: 0,
|
|
216
|
+
error: this.shuttingDown ? "Shutting down" : "Not ready"
|
|
217
|
+
}
|
|
218
|
+
], isHead);
|
|
219
|
+
return;
|
|
220
|
+
}
|
|
221
|
+
const checksToRun = this.config.readinessChecks ?? this.config.checks;
|
|
222
|
+
const results = await this.runChecks(checksToRun);
|
|
223
|
+
if (this.config.onReadinessCheck) {
|
|
224
|
+
const start = Date.now();
|
|
225
|
+
try {
|
|
226
|
+
const ready = await this.executeCheck(this.config.onReadinessCheck, this.config.checkTimeoutMs);
|
|
227
|
+
results.push({
|
|
228
|
+
name: "custom-readiness",
|
|
229
|
+
ok: !!ready,
|
|
230
|
+
durationMs: Date.now() - start,
|
|
231
|
+
...!ready ? {
|
|
232
|
+
error: "Readiness check returned false"
|
|
233
|
+
} : {}
|
|
234
|
+
});
|
|
235
|
+
} catch (err) {
|
|
236
|
+
const message = err instanceof Error ? err.message : "Unknown error";
|
|
237
|
+
results.push({
|
|
238
|
+
name: "custom-readiness",
|
|
239
|
+
ok: false,
|
|
240
|
+
durationMs: Date.now() - start,
|
|
241
|
+
error: message
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
const allOk = results.every((r) => r.ok);
|
|
246
|
+
const status = allOk ? "ok" : "unhealthy";
|
|
247
|
+
const httpStatus = allOk ? 200 : 503;
|
|
248
|
+
this.sendProbe(res, httpStatus, status, results, isHead);
|
|
249
|
+
}
|
|
250
|
+
/** `/startupz` — Startup probe */
|
|
251
|
+
handleStartup(res, isHead = false) {
|
|
252
|
+
if (this.started) {
|
|
253
|
+
this.sendProbe(res, 200, "ok", [], isHead);
|
|
254
|
+
} else {
|
|
255
|
+
this.sendProbe(res, 503, "unhealthy", [
|
|
256
|
+
{
|
|
257
|
+
name: "startup",
|
|
258
|
+
ok: false,
|
|
259
|
+
durationMs: 0,
|
|
260
|
+
error: "Service has not started yet"
|
|
261
|
+
}
|
|
262
|
+
], isHead);
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
async runChecks(checks) {
|
|
266
|
+
if (checks.length === 0) return [];
|
|
267
|
+
return Promise.all(checks.map(async ({ name, check }) => {
|
|
268
|
+
const start = Date.now();
|
|
269
|
+
try {
|
|
270
|
+
const result = await this.executeCheck(check, this.config.checkTimeoutMs);
|
|
271
|
+
return {
|
|
272
|
+
name,
|
|
273
|
+
ok: !!result,
|
|
274
|
+
durationMs: Date.now() - start
|
|
275
|
+
};
|
|
276
|
+
} catch (err) {
|
|
277
|
+
const message = err instanceof Error ? err.message : "Unknown error";
|
|
278
|
+
return {
|
|
279
|
+
name,
|
|
280
|
+
ok: false,
|
|
281
|
+
durationMs: Date.now() - start,
|
|
282
|
+
error: message
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
}));
|
|
286
|
+
}
|
|
287
|
+
sendProbe(res, httpStatus, status, checks, isHead = false) {
|
|
288
|
+
const body = {
|
|
289
|
+
status,
|
|
290
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
291
|
+
uptimeSeconds: Math.floor((Date.now() - this.startedAt) / 1e3)
|
|
292
|
+
};
|
|
293
|
+
if (this.config.detailed && checks.length > 0) {
|
|
294
|
+
body.checks = checks;
|
|
295
|
+
}
|
|
296
|
+
this.sendJson(res, httpStatus, body, isHead);
|
|
297
|
+
}
|
|
298
|
+
sendJson(res, status, body, isHead = false) {
|
|
299
|
+
const payload = JSON.stringify(body);
|
|
300
|
+
res.writeHead(status, {
|
|
301
|
+
"Content-Type": "application/json; charset=utf-8",
|
|
302
|
+
"Content-Length": Buffer.byteLength(payload),
|
|
303
|
+
"Cache-Control": "no-cache, no-store, must-revalidate",
|
|
304
|
+
"X-Content-Type-Options": "nosniff"
|
|
305
|
+
});
|
|
306
|
+
if (isHead) {
|
|
307
|
+
res.end();
|
|
308
|
+
} else {
|
|
309
|
+
res.end(payload);
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
async executeCheck(fn, ms) {
|
|
313
|
+
const controller = new AbortController();
|
|
314
|
+
let timer;
|
|
315
|
+
const timeoutPromise = new Promise((_, reject) => {
|
|
316
|
+
timer = setTimeout(() => {
|
|
317
|
+
const error = new Error(`Check timed out after ${ms}ms`);
|
|
318
|
+
controller.abort(error);
|
|
319
|
+
reject(error);
|
|
320
|
+
}, ms);
|
|
321
|
+
});
|
|
322
|
+
try {
|
|
323
|
+
const checkPromise = Promise.resolve().then(() => fn(controller.signal));
|
|
324
|
+
checkPromise.catch(() => {
|
|
325
|
+
});
|
|
326
|
+
return await Promise.race([
|
|
327
|
+
checkPromise,
|
|
328
|
+
timeoutPromise
|
|
329
|
+
]);
|
|
330
|
+
} finally {
|
|
331
|
+
if (timer) clearTimeout(timer);
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
async initiateShutdown() {
|
|
335
|
+
if (this.shuttingDown) return;
|
|
336
|
+
this.shuttingDown = true;
|
|
337
|
+
this.ready = false;
|
|
338
|
+
if (this.config.shutdownDelayMs > 0) {
|
|
339
|
+
await new Promise((r) => setTimeout(r, this.config.shutdownDelayMs));
|
|
340
|
+
}
|
|
341
|
+
await _HealthzServer.stop();
|
|
342
|
+
}
|
|
343
|
+
cleanup() {
|
|
344
|
+
process.off("SIGTERM", this.onSigterm);
|
|
345
|
+
process.off("SIGINT", this.onSigint);
|
|
346
|
+
this.ready = false;
|
|
347
|
+
this.started = false;
|
|
348
|
+
this.shuttingDown = false;
|
|
349
|
+
}
|
|
350
|
+
};
|
|
351
|
+
|
|
352
|
+
export { HealthzServer, getDefaultHealthzConfig, resolveConfig };
|
package/index.cjs
CHANGED
|
@@ -39,6 +39,7 @@ var env = require("./env/index.cjs");
|
|
|
39
39
|
var error = require("./error/index.cjs");
|
|
40
40
|
var exception = require("./exception/index.cjs");
|
|
41
41
|
var fs = require("./fs/index.cjs");
|
|
42
|
+
var healthzServer = require("./healthz-server/index.cjs");
|
|
42
43
|
var httpStatusCodes = require("./http-status-codes/index.cjs");
|
|
43
44
|
var id = require("./id/index.cjs");
|
|
44
45
|
var logger = require("./logger/index.cjs");
|
|
@@ -145,6 +146,12 @@ Object.keys(fs).forEach(function (k) {
|
|
|
145
146
|
get: function () { return fs[k]; }
|
|
146
147
|
});
|
|
147
148
|
});
|
|
149
|
+
Object.keys(healthzServer).forEach(function (k) {
|
|
150
|
+
if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
|
|
151
|
+
enumerable: true,
|
|
152
|
+
get: function () { return healthzServer[k]; }
|
|
153
|
+
});
|
|
154
|
+
});
|
|
148
155
|
Object.keys(httpStatusCodes).forEach(function (k) {
|
|
149
156
|
if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
|
|
150
157
|
enumerable: true,
|
package/index.d.ts
CHANGED
package/index.mjs
CHANGED
|
@@ -37,6 +37,7 @@ export * from "./env/index.mjs";
|
|
|
37
37
|
export * from "./error/index.mjs";
|
|
38
38
|
export * from "./exception/index.mjs";
|
|
39
39
|
export * from "./fs/index.mjs";
|
|
40
|
+
export * from "./healthz-server/index.mjs";
|
|
40
41
|
export * from "./http-status-codes/index.mjs";
|
|
41
42
|
export * from "./id/index.mjs";
|
|
42
43
|
export * from "./logger/index.mjs";
|