@nage-api/observability 1.0.0-beta.2
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 +202 -0
- package/README.md +141 -0
- package/dist/health.controller.d.ts +61 -0
- package/dist/health.controller.js +141 -0
- package/dist/health.d.ts +43 -0
- package/dist/health.js +102 -0
- package/dist/http.interceptor.d.ts +41 -0
- package/dist/http.interceptor.js +107 -0
- package/dist/index.d.ts +18 -0
- package/dist/index.js +42 -0
- package/dist/metrics.d.ts +63 -0
- package/dist/metrics.js +168 -0
- package/dist/observability.module.d.ts +33 -0
- package/dist/observability.module.js +93 -0
- package/dist/ports.d.ts +73 -0
- package/dist/ports.js +18 -0
- package/dist/tokens.d.ts +19 -0
- package/dist/tokens.js +19 -0
- package/dist/tracing.d.ts +41 -0
- package/dist/tracing.js +103 -0
- package/package.json +62 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
# @nage-api/observability
|
|
2
|
+
|
|
3
|
+
Logging, tracing, metrics and health (PLAN.md §18, §21, §25 P1).
|
|
4
|
+
|
|
5
|
+
Ports with no-op defaults. The framework's own instrumentation — a span per
|
|
6
|
+
request, a counter per response — costs nothing when nobody is collecting,
|
|
7
|
+
which is the normal case in development and in tests. An application that wants
|
|
8
|
+
OpenTelemetry or a hosted metrics backend binds an adapter, and no caller
|
|
9
|
+
changes.
|
|
10
|
+
|
|
11
|
+
| Concern | Port | Default | Enabled by |
|
|
12
|
+
| ------- | ------------- | ------------------- | ------------------------------- |
|
|
13
|
+
| Logging | `LoggerPort` | `JsonLogger` (core) | always |
|
|
14
|
+
| Tracing | `TracerPort` | `NoopTracer` | `observability.tracing.enabled` |
|
|
15
|
+
| Metrics | `MetricsPort` | `NoopMetrics` | `observability.metrics.enabled` |
|
|
16
|
+
| Health | — | `HealthRegistry` | always |
|
|
17
|
+
|
|
18
|
+
## Health
|
|
19
|
+
|
|
20
|
+
`/health/live` never touches a dependency. If a database outage made liveness
|
|
21
|
+
fail, the orchestrator would restart every pod and turn a degraded system into
|
|
22
|
+
an outage.
|
|
23
|
+
|
|
24
|
+
`/health/ready` does check, concurrently, each probe under its own timeout —
|
|
25
|
+
because a dependency that hangs must be reported down in bounded time rather
|
|
26
|
+
than holding the probe open until the orchestrator gives up.
|
|
27
|
+
|
|
28
|
+
It also answers `503 draining` the moment a shutdown signal arrives, before any
|
|
29
|
+
probe runs: dependency state was never the only reason to stop taking traffic, and
|
|
30
|
+
a draining instance is about to close the connection it is being offered. The flag
|
|
31
|
+
comes from `NAGE_LIFECYCLE`, published by `NageCoreModule` and flipped by
|
|
32
|
+
`installShutdown`; `/health/live` ignores it deliberately, because failing liveness
|
|
33
|
+
during a drain gets the process killed before it can finish.
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
import { Module } from '@nestjs/common';
|
|
37
|
+
import { NageObservabilityModule, healthCheck } from '@nage-api/observability';
|
|
38
|
+
|
|
39
|
+
// Whatever the application already holds: a Sequelize instance, an ioredis
|
|
40
|
+
// client. A probe is any function that resolves when the dependency answers.
|
|
41
|
+
declare const repository: { ping(): Promise<unknown> };
|
|
42
|
+
declare const redis: { ping(): Promise<unknown> };
|
|
43
|
+
|
|
44
|
+
@Module({
|
|
45
|
+
imports: [
|
|
46
|
+
NageObservabilityModule.forRoot({
|
|
47
|
+
checks: [
|
|
48
|
+
healthCheck('database', () => repository.ping()),
|
|
49
|
+
healthCheck('cache', () => redis.ping(), { critical: false }),
|
|
50
|
+
],
|
|
51
|
+
}),
|
|
52
|
+
],
|
|
53
|
+
})
|
|
54
|
+
export class AppModule {}
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
`critical: false` degrades the report instead of failing it. Pulling a node out
|
|
58
|
+
of the load balancer because Redis blinked makes the outage worse. Readiness
|
|
59
|
+
answers 503 only when something critical is down.
|
|
60
|
+
|
|
61
|
+
Failure detail is **withheld by default**: a probe endpoint is unauthenticated,
|
|
62
|
+
and a connection string in an error message is a disclosure.
|
|
63
|
+
`exposeHealthDetail: true` opts in.
|
|
64
|
+
|
|
65
|
+
## Metrics
|
|
66
|
+
|
|
67
|
+
An in-process registry with Prometheus text exposition, served from `/metrics`
|
|
68
|
+
when metrics are enabled. Counters, gauges and histograms; nothing else.
|
|
69
|
+
|
|
70
|
+
The thing it takes seriously is **cardinality**. A label whose value comes from
|
|
71
|
+
a request path or a user id creates a new time series per value, and a metrics
|
|
72
|
+
endpoint that grows without bound eventually takes the scraper down with it. So
|
|
73
|
+
the HTTP interceptor labels by route **template** (`/orders/:id`, never
|
|
74
|
+
`/orders/1`), and the registry caps series per metric name and exposes
|
|
75
|
+
`nage_metrics_dropped_total` rather than growing silently or dropping silently.
|
|
76
|
+
|
|
77
|
+
Built-in series: `nage_http_requests_total{method,route,status}`,
|
|
78
|
+
`nage_http_request_duration_ms{method,route}`, `nage_http_requests_in_flight`.
|
|
79
|
+
In-flight is decremented on the error path too, so a failing endpoint does not
|
|
80
|
+
show a permanent backlog.
|
|
81
|
+
|
|
82
|
+
## Tracing
|
|
83
|
+
|
|
84
|
+
`NAGE_TRACER` is what application code injects; it resolves to whatever the
|
|
85
|
+
deployment bound, or to `NoopTracer`, and the call site does not change.
|
|
86
|
+
|
|
87
|
+
```ts
|
|
88
|
+
import { Inject, Injectable } from '@nestjs/common';
|
|
89
|
+
import { NAGE_TRACER, type TracerPort } from '@nage-api/observability';
|
|
90
|
+
|
|
91
|
+
interface Order {
|
|
92
|
+
readonly id: string;
|
|
93
|
+
readonly total: number;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
declare const gateway: { charge(order: Order): Promise<{ reference: string }> };
|
|
97
|
+
|
|
98
|
+
@Injectable()
|
|
99
|
+
export class PaymentService {
|
|
100
|
+
constructor(@Inject(NAGE_TRACER) private readonly tracer: TracerPort) {}
|
|
101
|
+
|
|
102
|
+
async charge(order: Order): Promise<{ reference: string }> {
|
|
103
|
+
return this.tracer.trace(
|
|
104
|
+
'charge-card',
|
|
105
|
+
async (span) => {
|
|
106
|
+
span.setAttribute('order.id', order.id);
|
|
107
|
+
return gateway.charge(order);
|
|
108
|
+
},
|
|
109
|
+
{ kind: 'client' },
|
|
110
|
+
);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
The span ends in a `finally`, so a thrown error still closes it — an unclosed
|
|
116
|
+
span reads as an operation that never returned. `RecordingTracer` is the same
|
|
117
|
+
interface backed by memory, so a test can assert on spans without a collector.
|
|
118
|
+
|
|
119
|
+
The span per request comes from the same HTTP interceptor that records the
|
|
120
|
+
metrics, so that interceptor is registered as soon as **either** metrics or
|
|
121
|
+
tracing is enabled. A deployment that turns tracing on and leaves metrics off
|
|
122
|
+
still gets its request spans.
|
|
123
|
+
|
|
124
|
+
Two details: the correlation id from the request context is attached
|
|
125
|
+
automatically, which is what ties a span to the log lines and the response
|
|
126
|
+
envelope for the same request; and string attributes go through the same
|
|
127
|
+
redaction that guards log lines, because attributes reach a collector the team
|
|
128
|
+
may not control.
|
|
129
|
+
|
|
130
|
+
## Not yet implemented
|
|
131
|
+
|
|
132
|
+
- The OpenTelemetry adapter itself. `TracerPort` is the seam; the exporter,
|
|
133
|
+
sampler and propagation headers are not written.
|
|
134
|
+
- pino as a `LoggerPort` implementation (§8 names it); `JsonLogger` in
|
|
135
|
+
`@nage-api/core` covers structured output today.
|
|
136
|
+
- Sentry. `ObservabilityConfig.sentry` is declared and unread.
|
|
137
|
+
- Metric-name collision detection: registering the same name as two different
|
|
138
|
+
types produces two series rather than an error.
|
|
139
|
+
- Binding your own `metrics` sink while `metrics.enabled` is true still mounts
|
|
140
|
+
`/metrics` from the built-in registry, which then renders empty: the
|
|
141
|
+
framework's series go to the bound sink, and only that sink has them.
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `/health/live`, `/health/ready` and `/metrics` (PLAN.md §21).
|
|
3
|
+
*
|
|
4
|
+
* All three are `@Public()`, exempt from throttling — an orchestrator polls
|
|
5
|
+
* them every few seconds — and unwrapped, because probes and scrapers expect an
|
|
6
|
+
* exact body rather than a response envelope.
|
|
7
|
+
*
|
|
8
|
+
* Liveness never touches a dependency. If a database outage made liveness fail,
|
|
9
|
+
* the orchestrator would restart every pod, turning a degraded system into an
|
|
10
|
+
* outage.
|
|
11
|
+
*
|
|
12
|
+
* Readiness returns per-check **status** to anyone, but the failure detail only
|
|
13
|
+
* when the deployment opts in: a probe response is an unauthenticated endpoint,
|
|
14
|
+
* and a connection string in an error message is a disclosure.
|
|
15
|
+
*
|
|
16
|
+
* Readiness also fails the moment a shutdown signal arrives, before any check
|
|
17
|
+
* runs. Dependency state is not the only reason to stop taking traffic: a process
|
|
18
|
+
* that is draining will close the connection it is being offered, and endpoint
|
|
19
|
+
* removal is asynchronous, so the honest answer during a drain is 503.
|
|
20
|
+
*/
|
|
21
|
+
import { type LifecycleState } from '@nage-api/core';
|
|
22
|
+
import { HealthRegistry } from './health.js';
|
|
23
|
+
import { MetricsRegistry } from './metrics.js';
|
|
24
|
+
interface ResponseLike {
|
|
25
|
+
status(code: number): {
|
|
26
|
+
send(body: string): void;
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
export interface PublicHealthCheck {
|
|
30
|
+
readonly name: string;
|
|
31
|
+
readonly status: string;
|
|
32
|
+
readonly durationMs: number;
|
|
33
|
+
readonly detail?: string;
|
|
34
|
+
}
|
|
35
|
+
export interface PublicHealthReport {
|
|
36
|
+
readonly status: string;
|
|
37
|
+
readonly checks: readonly PublicHealthCheck[];
|
|
38
|
+
}
|
|
39
|
+
export declare class HealthController {
|
|
40
|
+
#private;
|
|
41
|
+
/**
|
|
42
|
+
* Constructor injection by token rather than a plain options object: Nest
|
|
43
|
+
* instantiates controllers itself, so a `useValue` provider for a controller
|
|
44
|
+
* class is quietly ignored.
|
|
45
|
+
*/
|
|
46
|
+
constructor(health: HealthRegistry, exposeDetail: boolean, lifecycle?: LifecycleState);
|
|
47
|
+
live(): {
|
|
48
|
+
status: 'ok';
|
|
49
|
+
};
|
|
50
|
+
ready(response: {
|
|
51
|
+
statusCode?: number;
|
|
52
|
+
}): Promise<PublicHealthReport>;
|
|
53
|
+
}
|
|
54
|
+
/** Separate controller so `/metrics` can be mounted, or not, on its own. */
|
|
55
|
+
export declare class MetricsController {
|
|
56
|
+
#private;
|
|
57
|
+
constructor(metrics: MetricsRegistry);
|
|
58
|
+
scrape(_response: ResponseLike): string;
|
|
59
|
+
}
|
|
60
|
+
export {};
|
|
61
|
+
//# sourceMappingURL=health.controller.d.ts.map
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* `/health/live`, `/health/ready` and `/metrics` (PLAN.md §21).
|
|
4
|
+
*
|
|
5
|
+
* All three are `@Public()`, exempt from throttling — an orchestrator polls
|
|
6
|
+
* them every few seconds — and unwrapped, because probes and scrapers expect an
|
|
7
|
+
* exact body rather than a response envelope.
|
|
8
|
+
*
|
|
9
|
+
* Liveness never touches a dependency. If a database outage made liveness fail,
|
|
10
|
+
* the orchestrator would restart every pod, turning a degraded system into an
|
|
11
|
+
* outage.
|
|
12
|
+
*
|
|
13
|
+
* Readiness returns per-check **status** to anyone, but the failure detail only
|
|
14
|
+
* when the deployment opts in: a probe response is an unauthenticated endpoint,
|
|
15
|
+
* and a connection string in an error message is a disclosure.
|
|
16
|
+
*
|
|
17
|
+
* Readiness also fails the moment a shutdown signal arrives, before any check
|
|
18
|
+
* runs. Dependency state is not the only reason to stop taking traffic: a process
|
|
19
|
+
* that is draining will close the connection it is being offered, and endpoint
|
|
20
|
+
* removal is asynchronous, so the honest answer during a drain is 503.
|
|
21
|
+
*/
|
|
22
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
23
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
24
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
25
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
26
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
27
|
+
};
|
|
28
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
29
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
30
|
+
};
|
|
31
|
+
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
32
|
+
return function (target, key) { decorator(target, key, paramIndex); }
|
|
33
|
+
};
|
|
34
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
35
|
+
exports.MetricsController = exports.HealthController = void 0;
|
|
36
|
+
const common_1 = require("@nestjs/common");
|
|
37
|
+
const core_1 = require("@nage-api/core");
|
|
38
|
+
const health_js_1 = require("./health.js");
|
|
39
|
+
const metrics_js_1 = require("./metrics.js");
|
|
40
|
+
const tokens_js_1 = require("./tokens.js");
|
|
41
|
+
let HealthController = class HealthController {
|
|
42
|
+
#health;
|
|
43
|
+
#exposeDetail;
|
|
44
|
+
#lifecycle;
|
|
45
|
+
/**
|
|
46
|
+
* Constructor injection by token rather than a plain options object: Nest
|
|
47
|
+
* instantiates controllers itself, so a `useValue` provider for a controller
|
|
48
|
+
* class is quietly ignored.
|
|
49
|
+
*/
|
|
50
|
+
constructor(health, exposeDetail, lifecycle) {
|
|
51
|
+
this.#health = health;
|
|
52
|
+
this.#exposeDetail = exposeDetail;
|
|
53
|
+
this.#lifecycle = lifecycle;
|
|
54
|
+
}
|
|
55
|
+
live() {
|
|
56
|
+
// No dependency checks, deliberately — and no lifecycle check either. A
|
|
57
|
+
// draining process is healthy; failing liveness while it drains asks the
|
|
58
|
+
// orchestrator to kill the process that is trying to finish its work.
|
|
59
|
+
return { status: 'ok' };
|
|
60
|
+
}
|
|
61
|
+
async ready(response) {
|
|
62
|
+
// Checked before the probes, and instead of them: the verdict cannot change,
|
|
63
|
+
// and a draining process should not be spending its drain budget on a
|
|
64
|
+
// `SELECT 1`.
|
|
65
|
+
if (this.#lifecycle?.draining === true) {
|
|
66
|
+
response.statusCode = common_1.HttpStatus.SERVICE_UNAVAILABLE;
|
|
67
|
+
return { status: 'draining', checks: [] };
|
|
68
|
+
}
|
|
69
|
+
const report = await this.#health.check();
|
|
70
|
+
// 503 when a critical dependency is down, so a load balancer stops sending
|
|
71
|
+
// traffic. `degraded` still serves: the application works, just less well.
|
|
72
|
+
if (report.status === 'down')
|
|
73
|
+
response.statusCode = common_1.HttpStatus.SERVICE_UNAVAILABLE;
|
|
74
|
+
return {
|
|
75
|
+
status: report.status,
|
|
76
|
+
checks: report.checks.map((check) => ({
|
|
77
|
+
name: check.name,
|
|
78
|
+
status: check.status,
|
|
79
|
+
durationMs: check.durationMs,
|
|
80
|
+
...(this.#exposeDetail && check.detail !== undefined ? { detail: check.detail } : {}),
|
|
81
|
+
})),
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
exports.HealthController = HealthController;
|
|
86
|
+
__decorate([
|
|
87
|
+
(0, common_1.Get)('live'),
|
|
88
|
+
(0, core_1.Public)(),
|
|
89
|
+
(0, core_1.SkipRateLimit)(),
|
|
90
|
+
(0, core_1.NoEnvelope)(),
|
|
91
|
+
__metadata("design:type", Function),
|
|
92
|
+
__metadata("design:paramtypes", []),
|
|
93
|
+
__metadata("design:returntype", Object)
|
|
94
|
+
], HealthController.prototype, "live", null);
|
|
95
|
+
__decorate([
|
|
96
|
+
(0, common_1.Get)('ready'),
|
|
97
|
+
(0, core_1.Public)(),
|
|
98
|
+
(0, core_1.SkipRateLimit)(),
|
|
99
|
+
(0, core_1.NoEnvelope)(),
|
|
100
|
+
(0, common_1.HttpCode)(common_1.HttpStatus.OK),
|
|
101
|
+
__param(0, (0, common_1.Res)({ passthrough: true })),
|
|
102
|
+
__metadata("design:type", Function),
|
|
103
|
+
__metadata("design:paramtypes", [Object]),
|
|
104
|
+
__metadata("design:returntype", Promise)
|
|
105
|
+
], HealthController.prototype, "ready", null);
|
|
106
|
+
exports.HealthController = HealthController = __decorate([
|
|
107
|
+
(0, common_1.Controller)('health'),
|
|
108
|
+
__param(0, (0, common_1.Inject)(tokens_js_1.NAGE_HEALTH)),
|
|
109
|
+
__param(1, (0, common_1.Inject)(tokens_js_1.NAGE_HEALTH_EXPOSE_DETAIL)),
|
|
110
|
+
__param(2, (0, common_1.Optional)()),
|
|
111
|
+
__param(2, (0, common_1.Inject)(core_1.NAGE_LIFECYCLE)),
|
|
112
|
+
__metadata("design:paramtypes", [health_js_1.HealthRegistry, Boolean, Function])
|
|
113
|
+
], HealthController);
|
|
114
|
+
/** Separate controller so `/metrics` can be mounted, or not, on its own. */
|
|
115
|
+
let MetricsController = class MetricsController {
|
|
116
|
+
#metrics;
|
|
117
|
+
constructor(metrics) {
|
|
118
|
+
this.#metrics = metrics;
|
|
119
|
+
}
|
|
120
|
+
scrape(_response) {
|
|
121
|
+
return this.#metrics.render();
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
exports.MetricsController = MetricsController;
|
|
125
|
+
__decorate([
|
|
126
|
+
(0, common_1.Get)('metrics'),
|
|
127
|
+
(0, core_1.Public)(),
|
|
128
|
+
(0, core_1.SkipRateLimit)(),
|
|
129
|
+
(0, core_1.NoEnvelope)(),
|
|
130
|
+
(0, common_1.Header)('content-type', 'text/plain; version=0.0.4; charset=utf-8'),
|
|
131
|
+
__param(0, (0, common_1.Res)({ passthrough: true })),
|
|
132
|
+
__metadata("design:type", Function),
|
|
133
|
+
__metadata("design:paramtypes", [Object]),
|
|
134
|
+
__metadata("design:returntype", String)
|
|
135
|
+
], MetricsController.prototype, "scrape", null);
|
|
136
|
+
exports.MetricsController = MetricsController = __decorate([
|
|
137
|
+
(0, common_1.Controller)(),
|
|
138
|
+
__param(0, (0, common_1.Inject)(tokens_js_1.NAGE_METRICS_REGISTRY)),
|
|
139
|
+
__metadata("design:paramtypes", [metrics_js_1.MetricsRegistry])
|
|
140
|
+
], MetricsController);
|
|
141
|
+
//# sourceMappingURL=health.controller.js.map
|
package/dist/health.d.ts
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Readiness and liveness (PLAN.md §21).
|
|
3
|
+
*
|
|
4
|
+
* Liveness answers "is this process wedged?" — it must not touch a dependency,
|
|
5
|
+
* because a database outage restarting every pod turns a degraded system into
|
|
6
|
+
* an outage. Readiness answers "should traffic come here?" and does check
|
|
7
|
+
* dependencies.
|
|
8
|
+
*
|
|
9
|
+
* Two things the legacy framework got wrong and this fixes:
|
|
10
|
+
*
|
|
11
|
+
* **A slow probe is a failing probe.** Every check runs under a timeout, so a
|
|
12
|
+
* dependency that hangs is reported as down in bounded time rather than holding
|
|
13
|
+
* the probe open until the orchestrator's own timeout fires.
|
|
14
|
+
*
|
|
15
|
+
* **Not every dependency is critical.** A cache being down should degrade the
|
|
16
|
+
* report, not fail it — pulling a node out of the load balancer because Redis
|
|
17
|
+
* blinked makes the outage worse.
|
|
18
|
+
*/
|
|
19
|
+
import type { Clock, HealthCheck, HealthReport } from './ports.js';
|
|
20
|
+
export interface HealthRegistryOptions {
|
|
21
|
+
/** Per-check timeout. A probe that has not answered by then is down. */
|
|
22
|
+
readonly timeoutMs?: number;
|
|
23
|
+
readonly clock?: Clock;
|
|
24
|
+
}
|
|
25
|
+
export declare class HealthRegistry {
|
|
26
|
+
#private;
|
|
27
|
+
constructor(options?: HealthRegistryOptions);
|
|
28
|
+
register(check: HealthCheck): this;
|
|
29
|
+
unregister(name: string): this;
|
|
30
|
+
get names(): readonly string[];
|
|
31
|
+
/**
|
|
32
|
+
* Run every check.
|
|
33
|
+
*
|
|
34
|
+
* Concurrently, because readiness is polled every few seconds and running ten
|
|
35
|
+
* probes in series makes the probe itself the slow dependency.
|
|
36
|
+
*/
|
|
37
|
+
check(): Promise<HealthReport>;
|
|
38
|
+
}
|
|
39
|
+
/** Build a check from any async probe — a `SELECT 1`, a `PING`, a HEAD request. */
|
|
40
|
+
export declare function healthCheck(name: string, probe: () => Promise<unknown>, options?: {
|
|
41
|
+
critical?: boolean;
|
|
42
|
+
}): HealthCheck;
|
|
43
|
+
//# sourceMappingURL=health.d.ts.map
|