@neon-pixels/health 0.0.0 → 0.4.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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Neon Pixels Studio
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,55 @@
1
+ # @neon-pixels/health
2
+
3
+ The logic behind a public health endpoint: probe a dependency with a timeout, cache the answer briefly, share one probe between concurrent callers, and answer with a body that reveals nothing. The route, its auth exemption, its rate limit, and any extra response fields stay in your app.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ pnpm add @neon-pixels/health
9
+ ```
10
+
11
+ No runtime dependencies and no database driver: the probe is any function that returns a promise.
12
+
13
+ ## Usage
14
+
15
+ ```ts
16
+ import {
17
+ createHealthCheck,
18
+ HEALTH_RESPONSE_HEADERS,
19
+ } from "@neon-pixels/health";
20
+
21
+ const health = createHealthCheck({
22
+ probe: () => database.execute(sql`select 1`),
23
+ onFailure: (reason) => reportError(reason),
24
+ });
25
+
26
+ // In your route handler:
27
+ const { statusCode, body } = await health.check();
28
+ setResponseStatus(event, statusCode);
29
+ setHeaders(event, HEALTH_RESPONSE_HEADERS);
30
+ return body;
31
+ ```
32
+
33
+ `check()` never rejects. It resolves to `{ statusCode: 200, body: { status: "ok" } }` or `{ statusCode: 503, body: { status: "unavailable" } }`. A probe that throws, rejects, or times out is unavailable.
34
+
35
+ ## Options
36
+
37
+ | Option | Default | Meaning |
38
+ | ------------ | ------- | ---------------------------------------------------------------------- |
39
+ | `probe` | none | Required. Any `() => Promise<unknown>`. |
40
+ | `timeoutMs` | `3000` | Probe timeout. A timed-out probe is not cancelled, only abandoned. |
41
+ | `cacheTtlMs` | `5000` | How long a result, healthy or not, is reused. |
42
+ | `onFailure` | none | Called with the reason when the result goes from healthy to unhealthy. |
43
+
44
+ Concurrent callers share one in-flight probe. `onFailure` fires once per outage (the first check counts as coming from healthy), and an error it throws is swallowed.
45
+
46
+ ## Testing
47
+
48
+ `reset()` clears the cache and the in-flight probe. A probe that was already running when you reset cannot write its result afterwards.
49
+
50
+ ## Exports
51
+
52
+ - `createHealthCheck(options)` returns `{ check, reset }`.
53
+ - `HEALTH_RESPONSE_HEADERS` is `{ "Cache-Control": "no-store" }`.
54
+ - `HealthProbeTimeoutError`, the reason passed to `onFailure` on a timeout.
55
+ - Types: `HealthCheck`, `HealthCheckOptions`, `HealthProbe`, `HealthResult`.
@@ -0,0 +1,34 @@
1
+ export declare const DEFAULT_PROBE_TIMEOUT_MS = 3000;
2
+ export declare const DEFAULT_CACHE_TTL_MS = 5000;
3
+ export declare const HEALTH_RESPONSE_HEADERS: Readonly<Record<string, string>>;
4
+ export type HealthProbe = () => Promise<unknown>;
5
+ export type HealthResult = {
6
+ readonly statusCode: 200;
7
+ readonly body: {
8
+ readonly status: "ok";
9
+ };
10
+ } | {
11
+ readonly statusCode: 503;
12
+ readonly body: {
13
+ readonly status: "unavailable";
14
+ };
15
+ };
16
+ export type HealthCheckOptions = {
17
+ /** Any function returning a promise; a rejection or timeout is unhealthy. */
18
+ probe: HealthProbe;
19
+ /** Probe timeout in milliseconds. Defaults to 3000. */
20
+ timeoutMs?: number;
21
+ /** How long a result is reused in milliseconds. Defaults to 5000. */
22
+ cacheTtlMs?: number;
23
+ /** Called with the failure reason when the result goes from healthy to unhealthy. */
24
+ onFailure?: (reason: unknown) => void | Promise<void>;
25
+ };
26
+ export type HealthCheck = {
27
+ check: () => Promise<HealthResult>;
28
+ /** Clears the cache and in-flight state. Intended for tests. */
29
+ reset: () => void;
30
+ };
31
+ export declare class HealthProbeTimeoutError extends Error {
32
+ constructor(timeoutMs: number);
33
+ }
34
+ export declare function createHealthCheck(options: HealthCheckOptions): HealthCheck;
package/dist/index.js ADDED
@@ -0,0 +1,93 @@
1
+ // src/index.ts
2
+ const DEFAULT_PROBE_TIMEOUT_MS = 3e3;
3
+ const DEFAULT_CACHE_TTL_MS = 5e3;
4
+ const HEALTH_RESPONSE_HEADERS = Object.freeze({ "Cache-Control": "no-store" });
5
+ const OK_RESULT = Object.freeze({
6
+ statusCode: 200,
7
+ body: Object.freeze({ status: "ok" })
8
+ });
9
+ const UNAVAILABLE_RESULT = Object.freeze({
10
+ statusCode: 503,
11
+ body: Object.freeze({ status: "unavailable" })
12
+ });
13
+ var HealthProbeTimeoutError = class extends Error {
14
+ constructor(timeoutMs) {
15
+ super(`health probe timed out after ${timeoutMs}ms`);
16
+ this.name = "HealthProbeTimeoutError";
17
+ }
18
+ };
19
+ async function withTimeout(run, timeoutMs) {
20
+ let timer;
21
+ const timeout = new Promise((_resolve, reject) => {
22
+ timer = setTimeout(() => reject(new HealthProbeTimeoutError(timeoutMs)), timeoutMs);
23
+ });
24
+ try {
25
+ await Promise.race([(async () => run())(), timeout]);
26
+ } finally {
27
+ clearTimeout(timer);
28
+ }
29
+ }
30
+ async function runProbe(probe, timeoutMs) {
31
+ try {
32
+ await withTimeout(probe, timeoutMs);
33
+ return { healthy: true };
34
+ } catch (reason) {
35
+ return {
36
+ healthy: false,
37
+ reason
38
+ };
39
+ }
40
+ }
41
+ function ignoreRejection() {}
42
+ function notifyFailure(onFailure, reason) {
43
+ try {
44
+ Promise.resolve(onFailure?.(reason)).catch(ignoreRejection);
45
+ } catch {}
46
+ }
47
+ function createHealthCheck(options) {
48
+ const { probe, timeoutMs = DEFAULT_PROBE_TIMEOUT_MS, cacheTtlMs = DEFAULT_CACHE_TTL_MS, onFailure } = options;
49
+ let cached = null;
50
+ let inFlight = null;
51
+ let wasHealthy = true;
52
+ let generation = 0;
53
+ function record(outcome) {
54
+ const result = outcome.healthy ? OK_RESULT : UNAVAILABLE_RESULT;
55
+ cached = {
56
+ result,
57
+ checkedAt: Date.now()
58
+ };
59
+ const wasHealthyBefore = wasHealthy;
60
+ wasHealthy = outcome.healthy;
61
+ if (!outcome.healthy && wasHealthyBefore) notifyFailure(onFailure, outcome.reason);
62
+ return result;
63
+ }
64
+ async function probeAndRecord() {
65
+ const startedGeneration = generation;
66
+ const outcome = await runProbe(probe, timeoutMs);
67
+ if (startedGeneration !== generation) return outcome.healthy ? OK_RESULT : UNAVAILABLE_RESULT;
68
+ return record(outcome);
69
+ }
70
+ function startProbe() {
71
+ const pending = probeAndRecord();
72
+ inFlight = pending;
73
+ pending.finally(() => {
74
+ if (inFlight === pending) inFlight = null;
75
+ });
76
+ return pending;
77
+ }
78
+ async function check() {
79
+ if (cached && Date.now() - cached.checkedAt < cacheTtlMs) return cached.result;
80
+ return inFlight ?? startProbe();
81
+ }
82
+ function reset() {
83
+ cached = null;
84
+ inFlight = null;
85
+ wasHealthy = true;
86
+ generation += 1;
87
+ }
88
+ return {
89
+ check,
90
+ reset
91
+ };
92
+ }
93
+ export { DEFAULT_CACHE_TTL_MS, DEFAULT_PROBE_TIMEOUT_MS, HEALTH_RESPONSE_HEADERS, HealthProbeTimeoutError, createHealthCheck };
package/package.json CHANGED
@@ -1 +1,32 @@
1
- {"name":"@neon-pixels/health","version":"0.0.0","description":"Placeholder. The first real release follows.","license":"MIT","repository":{"type":"git","url":"git+https://github.com/neonpixels-studio/packages.git"}}
1
+ {
2
+ "name": "@neon-pixels/health",
3
+ "version": "0.4.0",
4
+ "description": "Health endpoint logic: a timed, cached, single-flight probe that never rejects, with a minimal public response.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/neonpixels-studio/packages.git",
10
+ "directory": "packages/health"
11
+ },
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/index.d.ts",
15
+ "default": "./dist/index.js"
16
+ },
17
+ "./package.json": "./package.json"
18
+ },
19
+ "files": [
20
+ "dist"
21
+ ],
22
+ "publishConfig": {
23
+ "access": "public"
24
+ },
25
+ "engines": {
26
+ "node": "^22.17.0 || ^24.0.0 || >=26.0.0"
27
+ },
28
+ "scripts": {
29
+ "build": "tsdown",
30
+ "typecheck": "tsc --noEmit -p tsconfig.json"
31
+ }
32
+ }