@3sixty/telemetry-processors 0.0.0-stage → 0.20.0-next.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.
Files changed (35) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +24 -2
  3. package/dist/es/index.js +9 -0
  4. package/dist/es/index.js.map +1 -0
  5. package/dist/es/metricsRouteProcessor.js +320 -0
  6. package/dist/es/metricsRouteProcessor.js.map +1 -0
  7. package/dist/es/models/IMetricsRouteProcessorConfig.js +4 -0
  8. package/dist/es/models/IMetricsRouteProcessorConfig.js.map +1 -0
  9. package/dist/es/models/IMetricsRouteProcessorConstructorOptions.js +2 -0
  10. package/dist/es/models/IMetricsRouteProcessorConstructorOptions.js.map +1 -0
  11. package/dist/es/models/IPendingMetricRecording.js +2 -0
  12. package/dist/es/models/IPendingMetricRecording.js.map +1 -0
  13. package/dist/es/models/restRequestsMetrics.js +12 -0
  14. package/dist/es/models/restRequestsMetrics.js.map +1 -0
  15. package/dist/es/models/telemetryMetricIds.js +13 -0
  16. package/dist/es/models/telemetryMetricIds.js.map +1 -0
  17. package/dist/types/index.d.ts +6 -0
  18. package/dist/types/metricsRouteProcessor.d.ts +65 -0
  19. package/dist/types/models/IMetricsRouteProcessorConfig.d.ts +34 -0
  20. package/dist/types/models/IMetricsRouteProcessorConstructorOptions.d.ts +18 -0
  21. package/dist/types/models/IPendingMetricRecording.d.ts +27 -0
  22. package/dist/types/models/restRequestsMetrics.d.ts +5 -0
  23. package/dist/types/models/telemetryMetricIds.d.ts +13 -0
  24. package/docs/changelog.md +0 -0
  25. package/docs/examples.md +37 -0
  26. package/docs/reference/classes/MetricsRouteProcessor.md +173 -0
  27. package/docs/reference/index.md +20 -0
  28. package/docs/reference/interfaces/IMetricsRouteProcessorConfig.md +68 -0
  29. package/docs/reference/interfaces/IMetricsRouteProcessorConstructorOptions.md +27 -0
  30. package/docs/reference/interfaces/IPendingMetricRecording.md +44 -0
  31. package/docs/reference/type-aliases/TelemetryMetricIds.md +5 -0
  32. package/docs/reference/variables/RestRequestsMetrics.md +5 -0
  33. package/docs/reference/variables/TelemetryMetricIds.md +13 -0
  34. package/locales/en.json +9 -0
  35. package/package.json +39 -5
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2024 IOTA Stiftung.
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,25 @@
1
- # Temporary Holding Version
1
+ # 3Sixty Telemetry Processors
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Route processors for recording telemetry metrics from the web server.
4
+
5
+ ## Installation
6
+
7
+ ```shell
8
+ npm install @3sixty/telemetry-processors
9
+ ```
10
+
11
+ ## Examples
12
+
13
+ Usage of the APIs is shown in the examples [docs/examples.md](docs/examples.md)
14
+
15
+ ## Reference
16
+
17
+ Detailed reference documentation for the API can be found in [docs/reference/index.md](docs/reference/index.md)
18
+
19
+ ## Changelog
20
+
21
+ The changes between each version can be found in [docs/changelog.md](docs/changelog.md)
22
+
23
+ ## Origin
24
+
25
+ This package is derived from the original [iotaledger/twin-telemetry](https://github.com/iotaledger/twin-telemetry/tree/next/packages/telemetry-processors) repository.
@@ -0,0 +1,9 @@
1
+ // Copyright 2026 IOTA Stiftung.
2
+ // SPDX-License-Identifier: Apache-2.0.
3
+ export * from "./metricsRouteProcessor.js";
4
+ export * from "./models/IMetricsRouteProcessorConfig.js";
5
+ export * from "./models/IMetricsRouteProcessorConstructorOptions.js";
6
+ export * from "./models/IPendingMetricRecording.js";
7
+ export * from "./models/restRequestsMetrics.js";
8
+ export * from "./models/telemetryMetricIds.js";
9
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,gCAAgC;AAChC,uCAAuC;AACvC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,0CAA0C,CAAC;AACzD,cAAc,sDAAsD,CAAC;AACrE,cAAc,qCAAqC,CAAC;AACpD,cAAc,iCAAiC,CAAC;AAChD,cAAc,gCAAgC,CAAC","sourcesContent":["// Copyright 2026 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nexport * from \"./metricsRouteProcessor.js\";\nexport * from \"./models/IMetricsRouteProcessorConfig.js\";\nexport * from \"./models/IMetricsRouteProcessorConstructorOptions.js\";\nexport * from \"./models/IPendingMetricRecording.js\";\nexport * from \"./models/restRequestsMetrics.js\";\nexport * from \"./models/telemetryMetricIds.js\";\n"]}
@@ -0,0 +1,320 @@
1
+ import { ContextIdStore } from "@3sixty/context";
2
+ import { BaseError, Coerce, ComponentFactory, Is, JsonHelper, ObjectHelper } from "@3sixty/core";
3
+ import { MetricCounterOperation, MetricHelper } from "@3sixty/telemetry-models";
4
+ import { RestRequestsMetrics } from "./models/restRequestsMetrics.js";
5
+ import { TelemetryMetricIds } from "./models/telemetryMetricIds.js";
6
+ /**
7
+ * Route processor that records HTTP request counts after each request completes.
8
+ * Emits a single counter labelled with the HTTP method, route template, and status class.
9
+ * Raw request URLs are never used as labels to keep cardinality bounded.
10
+ * Recording is queued off the response path, so the reply never waits for telemetry storage.
11
+ */
12
+ export class MetricsRouteProcessor {
13
+ /**
14
+ * Runtime name for the class.
15
+ */
16
+ static CLASS_NAME = "MetricsRouteProcessor";
17
+ /**
18
+ * Default number of request values to retain.
19
+ */
20
+ static DEFAULT_MAX_HISTORY = 10000;
21
+ /**
22
+ * Default path prefixes excluded from metrics recording, the probe and info routes.
23
+ * The root entry is matched in full, so the routes below it are still recorded.
24
+ */
25
+ static DEFAULT_EXCLUDE_PATHS = [
26
+ "/",
27
+ "/favicon.ico",
28
+ "/spec",
29
+ "/livez",
30
+ "/readyz",
31
+ "/info",
32
+ "/health"
33
+ ];
34
+ /**
35
+ * Default number of recordings queued before new ones are dropped.
36
+ */
37
+ static DEFAULT_MAX_PENDING_RECORDINGS = 1000;
38
+ /**
39
+ * Default interval in milliseconds between drains of the queue.
40
+ */
41
+ static DEFAULT_DRAIN_INTERVAL_MS = 1000;
42
+ /**
43
+ * Resolved telemetry component.
44
+ * @internal
45
+ */
46
+ _telemetry;
47
+ /**
48
+ * The component for logging metric recording failures.
49
+ * @internal
50
+ */
51
+ _logging;
52
+ /**
53
+ * Paths excluded from metrics recording.
54
+ * @internal
55
+ */
56
+ _excludePaths;
57
+ /**
58
+ * Maximum number of request values retained; 0 retains everything.
59
+ * @internal
60
+ */
61
+ _maxHistory;
62
+ /**
63
+ * Maximum number of recordings queued off the response path; 0 queues everything.
64
+ * @internal
65
+ */
66
+ _maxPendingRecordings;
67
+ /**
68
+ * Interval in milliseconds between drains of the queue.
69
+ * @internal
70
+ */
71
+ _drainIntervalMs;
72
+ /**
73
+ * Recordings queued but not yet handed to the telemetry component.
74
+ * @internal
75
+ */
76
+ _pending;
77
+ /**
78
+ * The timer which drains the queue.
79
+ * @internal
80
+ */
81
+ _drainTimer;
82
+ /**
83
+ * Is a drain of the queue in progress.
84
+ * @internal
85
+ */
86
+ _isDraining;
87
+ /**
88
+ * Number of recordings dropped since the last one that was recorded.
89
+ * @internal
90
+ */
91
+ _droppedRecordings;
92
+ /**
93
+ * Create a new instance of MetricsRouteProcessor.
94
+ * @param options The options for the processor.
95
+ */
96
+ constructor(options) {
97
+ this._telemetry = ComponentFactory.getIfExists(options?.telemetryComponentType);
98
+ this._logging = ComponentFactory.getIfExists(options?.loggingComponentType);
99
+ this._excludePaths =
100
+ options?.config?.excludePaths ?? MetricsRouteProcessor.DEFAULT_EXCLUDE_PATHS;
101
+ const cfgMaxHistory = Coerce.integer(options?.config?.maxHistory) ?? MetricsRouteProcessor.DEFAULT_MAX_HISTORY;
102
+ this._maxHistory = cfgMaxHistory > 0 ? cfgMaxHistory : 0;
103
+ const cfgMaxPending = Coerce.integer(options?.config?.maxPendingRecordings) ??
104
+ MetricsRouteProcessor.DEFAULT_MAX_PENDING_RECORDINGS;
105
+ this._maxPendingRecordings = cfgMaxPending > 0 ? cfgMaxPending : 0;
106
+ const cfgDrainInterval = Coerce.integer(options?.config?.drainIntervalMs) ??
107
+ MetricsRouteProcessor.DEFAULT_DRAIN_INTERVAL_MS;
108
+ this._drainIntervalMs =
109
+ cfgDrainInterval > 0 ? cfgDrainInterval : MetricsRouteProcessor.DEFAULT_DRAIN_INTERVAL_MS;
110
+ this._pending = [];
111
+ this._isDraining = false;
112
+ this._droppedRecordings = 0;
113
+ }
114
+ /**
115
+ * Returns the class name of the component.
116
+ * @returns The class name of the component.
117
+ */
118
+ className() {
119
+ return MetricsRouteProcessor.CLASS_NAME;
120
+ }
121
+ /**
122
+ * Register all REST request metrics and start the timer which drains the queued recordings.
123
+ * @returns A promise that resolves when all metrics have been registered.
124
+ */
125
+ async start() {
126
+ // Guarded so a second start cannot leave the first interval running.
127
+ if (Is.undefined(this._telemetry) || !Is.undefined(this._drainTimer)) {
128
+ return;
129
+ }
130
+ // A value is recorded for every request, so the history is capped.
131
+ await MetricHelper.createMetrics(this._telemetry, RestRequestsMetrics.map(metric => ({
132
+ ...metric,
133
+ maxHistory: this._maxHistory > 0 ? this._maxHistory : undefined
134
+ })));
135
+ this._drainTimer = globalThis.setInterval(async () => {
136
+ try {
137
+ await this.drainPending();
138
+ }
139
+ catch (err) {
140
+ await this.logDrainFailed(err);
141
+ }
142
+ }, this._drainIntervalMs);
143
+ }
144
+ /**
145
+ * Clear the drain timer and hand over the recordings which are still queued.
146
+ * When a drain is already running it finishes the batch it took, and anything queued after
147
+ * that is left unwritten rather than holding the shutdown open.
148
+ * @returns A promise that resolves when the queued recordings have been handed over.
149
+ */
150
+ async stop() {
151
+ if (!Is.undefined(this._drainTimer)) {
152
+ globalThis.clearInterval(this._drainTimer);
153
+ this._drainTimer = undefined;
154
+ }
155
+ await this.drainPending();
156
+ }
157
+ /**
158
+ * Queue a counter increment after the request completes.
159
+ * @param request The HTTP request.
160
+ * @param response The HTTP response.
161
+ * @param route The matched route definition, if any.
162
+ * @param contextIds The context IDs for the request.
163
+ * @param processorState Shared state for the current request processor chain.
164
+ */
165
+ async post(request, response, route, contextIds, processorState) {
166
+ if (Is.undefined(this._telemetry)) {
167
+ return;
168
+ }
169
+ const routePath = route?.path ?? "unknown";
170
+ // Entries are prefixes, apart from the root which is matched in full.
171
+ if (this._excludePaths.some(p => (p === "/" ? routePath === "/" : routePath.startsWith(p)))) {
172
+ return;
173
+ }
174
+ if (this._maxPendingRecordings > 0 && this._pending.length >= this._maxPendingRecordings) {
175
+ this._droppedRecordings++;
176
+ return;
177
+ }
178
+ // The reply is sent once the post hooks resolve, so the recording is left for the drain
179
+ // timer rather than written here.
180
+ this._pending.push({
181
+ contextIds: ObjectHelper.clone(contextIds),
182
+ method: request.method ?? "unknown",
183
+ route: routePath,
184
+ statusCode: response.statusCode ?? 0,
185
+ statusClass: this.toStatusClass(response.statusCode ?? 0)
186
+ });
187
+ }
188
+ /**
189
+ * Hand the recordings queued so far to the telemetry component, batched by context.
190
+ * @returns A promise that resolves when those recordings have been handed over.
191
+ * @internal
192
+ */
193
+ async drainPending() {
194
+ // One drain at a time, so a telemetry component slower than the request rate is not
195
+ // called concurrently by every tick of the timer.
196
+ if (this._isDraining) {
197
+ return;
198
+ }
199
+ this._isDraining = true;
200
+ try {
201
+ // Only the recordings queued so far are written, so requests arriving during the
202
+ // drain extend the next one rather than this one.
203
+ const recordings = this._pending.splice(0, this._pending.length);
204
+ const dropped = this._droppedRecordings;
205
+ this._droppedRecordings = 0;
206
+ if (dropped > 0) {
207
+ await this.logRecordsDropped(dropped);
208
+ }
209
+ const batches = new Map();
210
+ for (const recording of recordings) {
211
+ // Canonical key, so the same context ids group whatever order their keys are in.
212
+ const key = JsonHelper.canonicalize(recording.contextIds);
213
+ let batch = batches.get(key);
214
+ if (Is.undefined(batch)) {
215
+ batch = { contextIds: recording.contextIds, values: [] };
216
+ batches.set(key, batch);
217
+ }
218
+ batch.values.push({
219
+ id: TelemetryMetricIds.RestRequests,
220
+ value: MetricCounterOperation.Increment,
221
+ customData: {
222
+ method: recording.method,
223
+ route: recording.route,
224
+ statusCode: recording.statusCode,
225
+ statusClass: recording.statusClass
226
+ }
227
+ });
228
+ }
229
+ for (const batch of batches.values()) {
230
+ // One call per context, so a tenant-less batch costs a single tenant query and
231
+ // fan-out instead of one per request. Recorded in the requests' own context, and
232
+ // a batch which fails is logged rather than re-queued, so nothing accumulates
233
+ // while the component is unavailable.
234
+ await ContextIdStore.run(batch.contextIds, async () => MetricHelper.metricValues(this._telemetry, batch.values, async (err) => this.logRecordsFailed(err, batch.values.length)));
235
+ }
236
+ }
237
+ finally {
238
+ this._isDraining = false;
239
+ }
240
+ }
241
+ /**
242
+ * Log that a batch of request metrics could not be recorded.
243
+ * @param err The error the telemetry component raised.
244
+ * @param count The number of metrics in the batch.
245
+ * @returns A promise that resolves when the entry has been logged.
246
+ * @internal
247
+ */
248
+ async logRecordsFailed(err, count) {
249
+ await this._logging?.log({
250
+ level: "warn",
251
+ source: MetricsRouteProcessor.CLASS_NAME,
252
+ ts: Date.now(),
253
+ message: "metricRecordsFailed",
254
+ error: BaseError.fromError(err),
255
+ data: { count }
256
+ });
257
+ }
258
+ /**
259
+ * Log that the queue could not be drained.
260
+ * @param err The error the drain raised.
261
+ * @returns A promise that resolves when the entry has been logged.
262
+ * @internal
263
+ */
264
+ async logDrainFailed(err) {
265
+ await this._logging?.log({
266
+ level: "warn",
267
+ source: MetricsRouteProcessor.CLASS_NAME,
268
+ ts: Date.now(),
269
+ message: "metricDrainFailed",
270
+ error: BaseError.fromError(err)
271
+ });
272
+ }
273
+ /**
274
+ * Log the recordings dropped because the queue was full.
275
+ * @param count The number of recordings dropped.
276
+ * @returns A promise that resolves when the entry has been logged.
277
+ * @internal
278
+ */
279
+ async logRecordsDropped(count) {
280
+ try {
281
+ await this._logging?.log({
282
+ level: "warn",
283
+ source: MetricsRouteProcessor.CLASS_NAME,
284
+ ts: Date.now(),
285
+ message: "metricRecordsDropped",
286
+ data: { count }
287
+ });
288
+ }
289
+ catch {
290
+ // Carried into the next recording rather than lost, and absorbed so a broken logging
291
+ // component cannot reject the drain.
292
+ this._droppedRecordings += count;
293
+ }
294
+ }
295
+ /**
296
+ * Derive the status class label from a numeric HTTP status code.
297
+ * @param statusCode The HTTP status code.
298
+ * @returns The status class label (1xx, 2xx, 3xx, 4xx, 5xx, or unknown).
299
+ * @internal
300
+ */
301
+ toStatusClass(statusCode) {
302
+ if (statusCode >= 500) {
303
+ return "5xx";
304
+ }
305
+ if (statusCode >= 400) {
306
+ return "4xx";
307
+ }
308
+ if (statusCode >= 300) {
309
+ return "3xx";
310
+ }
311
+ if (statusCode >= 200) {
312
+ return "2xx";
313
+ }
314
+ if (statusCode >= 100) {
315
+ return "1xx";
316
+ }
317
+ return "unknown";
318
+ }
319
+ }
320
+ //# sourceMappingURL=metricsRouteProcessor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"metricsRouteProcessor.js","sourceRoot":"","sources":["../../src/metricsRouteProcessor.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,cAAc,EAAoB,MAAM,iBAAiB,CAAC;AACnE,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,gBAAgB,EAAE,EAAE,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAGjG,OAAO,EACN,sBAAsB,EACtB,YAAY,EAGZ,MAAM,0BAA0B,CAAC;AAGlC,OAAO,EAAE,mBAAmB,EAAE,MAAM,iCAAiC,CAAC;AACtE,OAAO,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AAEpE;;;;;GAKG;AACH,MAAM,OAAO,qBAAqB;IACjC;;OAEG;IACI,MAAM,CAAU,UAAU,2BAA2C;IAE5E;;OAEG;IACI,MAAM,CAAU,mBAAmB,GAAW,KAAK,CAAC;IAE3D;;;OAGG;IACI,MAAM,CAAU,qBAAqB,GAAa;QACxD,GAAG;QACH,cAAc;QACd,OAAO;QACP,QAAQ;QACR,SAAS;QACT,OAAO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tIHttpResponse,\n\tIHttpServerRequest\n} from \"@3sixty/api-models\";\nimport { ContextIdStore, type IContextIds } from \"@3sixty/context\";\nimport { BaseError, Coerce, ComponentFactory, Is, JsonHelper, ObjectHelper } from \"@3sixty/core\";\nimport type { ILoggingComponent } from \"@3sixty/logging-models\";\nimport { nameof } from \"@3sixty/nameof\";\nimport {\n\tMetricCounterOperation,\n\tMetricHelper,\n\ttype ITelemetryComponent,\n\ttype ITelemetryMetricValueEntry\n} from \"@3sixty/telemetry-models\";\nimport type { IMetricsRouteProcessorConstructorOptions } from \"./models/IMetricsRouteProcessorConstructorOptions.js\";\nimport type { IPendingMetricRecording } from \"./models/IPendingMetricRecording.js\";\nimport { RestRequestsMetrics } from \"./models/restRequestsMetrics.js\";\nimport { TelemetryMetricIds } from \"./models/telemetryMetricIds.js\";\n\n/**\n * Route processor that records HTTP request counts after each request completes.\n * Emits a single counter labelled with the HTTP method, route template, and status class.\n * Raw request URLs are never used as labels to keep cardinality bounded.\n * Recording is queued off the response path, so the reply never waits for telemetry storage.\n */\nexport class MetricsRouteProcessor implements IBaseRouteProcessor {\n\t/**\n\t * Runtime name for the class.\n\t */\n\tpublic static readonly CLASS_NAME: string = nameof<MetricsRouteProcessor>();\n\n\t/**\n\t * Default number of request values to retain.\n\t */\n\tpublic static readonly DEFAULT_MAX_HISTORY: number = 10000;\n\n\t/**\n\t * Default path prefixes excluded from metrics recording, the probe and info routes.\n\t * The root entry is matched in full, so the routes below it are still recorded.\n\t */\n\tpublic static readonly DEFAULT_EXCLUDE_PATHS: string[] = [\n\t\t\"/\",\n\t\t\"/favicon.ico\",\n\t\t\"/spec\",\n\t\t\"/livez\",\n\t\t\"/readyz\",\n\t\t\"/info\",\n\t\t\"/health\"\n\t];\n\n\t/**\n\t * Default number of recordings queued before new ones are dropped.\n\t */\n\tpublic static readonly DEFAULT_MAX_PENDING_RECORDINGS: number = 1000;\n\n\t/**\n\t * Default interval in milliseconds between drains of the queue.\n\t */\n\tpublic static readonly DEFAULT_DRAIN_INTERVAL_MS: number = 1000;\n\n\t/**\n\t * Resolved telemetry component.\n\t * @internal\n\t */\n\tprivate readonly _telemetry?: ITelemetryComponent;\n\n\t/**\n\t * The component for logging metric recording failures.\n\t * @internal\n\t */\n\tprivate readonly _logging?: ILoggingComponent;\n\n\t/**\n\t * Paths excluded from metrics recording.\n\t * @internal\n\t */\n\tprivate readonly _excludePaths: string[];\n\n\t/**\n\t * Maximum number of request values retained; 0 retains everything.\n\t * @internal\n\t */\n\tprivate readonly _maxHistory: number;\n\n\t/**\n\t * Maximum number of recordings queued off the response path; 0 queues everything.\n\t * @internal\n\t */\n\tprivate readonly _maxPendingRecordings: number;\n\n\t/**\n\t * Interval in milliseconds between drains of the queue.\n\t * @internal\n\t */\n\tprivate readonly _drainIntervalMs: number;\n\n\t/**\n\t * Recordings queued but not yet handed to the telemetry component.\n\t * @internal\n\t */\n\tprivate readonly _pending: IPendingMetricRecording[];\n\n\t/**\n\t * The timer which drains the queue.\n\t * @internal\n\t */\n\tprivate _drainTimer?: ReturnType<typeof setInterval>;\n\n\t/**\n\t * Is a drain of the queue in progress.\n\t * @internal\n\t */\n\tprivate _isDraining: boolean;\n\n\t/**\n\t * Number of recordings dropped since the last one that was recorded.\n\t * @internal\n\t */\n\tprivate _droppedRecordings: number;\n\n\t/**\n\t * Create a new instance of MetricsRouteProcessor.\n\t * @param options The options for the processor.\n\t */\n\tconstructor(options?: IMetricsRouteProcessorConstructorOptions) {\n\t\tthis._telemetry = ComponentFactory.getIfExists<ITelemetryComponent>(\n\t\t\toptions?.telemetryComponentType\n\t\t);\n\t\tthis._logging = ComponentFactory.getIfExists<ILoggingComponent>(options?.loggingComponentType);\n\t\tthis._excludePaths =\n\t\t\toptions?.config?.excludePaths ?? MetricsRouteProcessor.DEFAULT_EXCLUDE_PATHS;\n\n\t\tconst cfgMaxHistory =\n\t\t\tCoerce.integer(options?.config?.maxHistory) ?? MetricsRouteProcessor.DEFAULT_MAX_HISTORY;\n\t\tthis._maxHistory = cfgMaxHistory > 0 ? cfgMaxHistory : 0;\n\n\t\tconst cfgMaxPending =\n\t\t\tCoerce.integer(options?.config?.maxPendingRecordings) ??\n\t\t\tMetricsRouteProcessor.DEFAULT_MAX_PENDING_RECORDINGS;\n\t\tthis._maxPendingRecordings = cfgMaxPending > 0 ? cfgMaxPending : 0;\n\n\t\tconst cfgDrainInterval =\n\t\t\tCoerce.integer(options?.config?.drainIntervalMs) ??\n\t\t\tMetricsRouteProcessor.DEFAULT_DRAIN_INTERVAL_MS;\n\t\tthis._drainIntervalMs =\n\t\t\tcfgDrainInterval > 0 ? cfgDrainInterval : MetricsRouteProcessor.DEFAULT_DRAIN_INTERVAL_MS;\n\n\t\tthis._pending = [];\n\t\tthis._isDraining = false;\n\t\tthis._droppedRecordings = 0;\n\t}\n\n\t/**\n\t * Returns the class name of the component.\n\t * @returns The class name of the component.\n\t */\n\tpublic className(): string {\n\t\treturn MetricsRouteProcessor.CLASS_NAME;\n\t}\n\n\t/**\n\t * Register all REST request metrics and start the timer which drains the queued recordings.\n\t * @returns A promise that resolves when all metrics have been registered.\n\t */\n\tpublic async start(): Promise<void> {\n\t\t// Guarded so a second start cannot leave the first interval running.\n\t\tif (Is.undefined(this._telemetry) || !Is.undefined(this._drainTimer)) {\n\t\t\treturn;\n\t\t}\n\n\t\t// A value is recorded for every request, so the history is capped.\n\t\tawait MetricHelper.createMetrics(\n\t\t\tthis._telemetry,\n\t\t\tRestRequestsMetrics.map(metric => ({\n\t\t\t\t...metric,\n\t\t\t\tmaxHistory: this._maxHistory > 0 ? this._maxHistory : undefined\n\t\t\t}))\n\t\t);\n\n\t\tthis._drainTimer = globalThis.setInterval(async () => {\n\t\t\ttry {\n\t\t\t\tawait this.drainPending();\n\t\t\t} catch (err) {\n\t\t\t\tawait this.logDrainFailed(err);\n\t\t\t}\n\t\t}, this._drainIntervalMs);\n\t}\n\n\t/**\n\t * Clear the drain timer and hand over the recordings which are still queued.\n\t * When a drain is already running it finishes the batch it took, and anything queued after\n\t * that is left unwritten rather than holding the shutdown open.\n\t * @returns A promise that resolves when the queued recordings have been handed over.\n\t */\n\tpublic async stop(): Promise<void> {\n\t\tif (!Is.undefined(this._drainTimer)) {\n\t\t\tglobalThis.clearInterval(this._drainTimer);\n\t\t\tthis._drainTimer = undefined;\n\t\t}\n\n\t\tawait this.drainPending();\n\t}\n\n\t/**\n\t * Queue a counter increment after the request completes.\n\t * @param request The HTTP request.\n\t * @param response The HTTP response.\n\t * @param route The matched route definition, if any.\n\t * @param contextIds The context IDs for the request.\n\t * @param processorState Shared state for the current request processor chain.\n\t */\n\tpublic async post(\n\t\trequest: IHttpServerRequest,\n\t\tresponse: IHttpResponse,\n\t\troute: IBaseRoute | undefined,\n\t\tcontextIds: IContextIds,\n\t\tprocessorState: { [id: string]: unknown }\n\t): Promise<void> {\n\t\tif (Is.undefined(this._telemetry)) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst routePath = route?.path ?? \"unknown\";\n\n\t\t// Entries are prefixes, apart from the root which is matched in full.\n\t\tif (this._excludePaths.some(p => (p === \"/\" ? routePath === \"/\" : routePath.startsWith(p)))) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (this._maxPendingRecordings > 0 && this._pending.length >= this._maxPendingRecordings) {\n\t\t\tthis._droppedRecordings++;\n\t\t\treturn;\n\t\t}\n\n\t\t// The reply is sent once the post hooks resolve, so the recording is left for the drain\n\t\t// timer rather than written here.\n\t\tthis._pending.push({\n\t\t\tcontextIds: ObjectHelper.clone(contextIds),\n\t\t\tmethod: request.method ?? \"unknown\",\n\t\t\troute: routePath,\n\t\t\tstatusCode: response.statusCode ?? 0,\n\t\t\tstatusClass: this.toStatusClass(response.statusCode ?? 0)\n\t\t});\n\t}\n\n\t/**\n\t * Hand the recordings queued so far to the telemetry component, batched by context.\n\t * @returns A promise that resolves when those recordings have been handed over.\n\t * @internal\n\t */\n\tprivate async drainPending(): Promise<void> {\n\t\t// One drain at a time, so a telemetry component slower than the request rate is not\n\t\t// called concurrently by every tick of the timer.\n\t\tif (this._isDraining) {\n\t\t\treturn;\n\t\t}\n\t\tthis._isDraining = true;\n\n\t\ttry {\n\t\t\t// Only the recordings queued so far are written, so requests arriving during the\n\t\t\t// drain extend the next one rather than this one.\n\t\t\tconst recordings = this._pending.splice(0, this._pending.length);\n\n\t\t\tconst dropped = this._droppedRecordings;\n\t\t\tthis._droppedRecordings = 0;\n\t\t\tif (dropped > 0) {\n\t\t\t\tawait this.logRecordsDropped(dropped);\n\t\t\t}\n\n\t\t\tconst batches = new Map<\n\t\t\t\tstring,\n\t\t\t\t{ contextIds: IContextIds; values: ITelemetryMetricValueEntry[] }\n\t\t\t>();\n\t\t\tfor (const recording of recordings) {\n\t\t\t\t// Canonical key, so the same context ids group whatever order their keys are in.\n\t\t\t\tconst key = JsonHelper.canonicalize(recording.contextIds);\n\t\t\t\tlet batch = batches.get(key);\n\t\t\t\tif (Is.undefined(batch)) {\n\t\t\t\t\tbatch = { contextIds: recording.contextIds, values: [] };\n\t\t\t\t\tbatches.set(key, batch);\n\t\t\t\t}\n\t\t\t\tbatch.values.push({\n\t\t\t\t\tid: TelemetryMetricIds.RestRequests,\n\t\t\t\t\tvalue: MetricCounterOperation.Increment,\n\t\t\t\t\tcustomData: {\n\t\t\t\t\t\tmethod: recording.method,\n\t\t\t\t\t\troute: recording.route,\n\t\t\t\t\t\tstatusCode: recording.statusCode,\n\t\t\t\t\t\tstatusClass: recording.statusClass\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tfor (const batch of batches.values()) {\n\t\t\t\t// One call per context, so a tenant-less batch costs a single tenant query and\n\t\t\t\t// fan-out instead of one per request. Recorded in the requests' own context, and\n\t\t\t\t// a batch which fails is logged rather than re-queued, so nothing accumulates\n\t\t\t\t// while the component is unavailable.\n\t\t\t\tawait ContextIdStore.run(batch.contextIds, async () =>\n\t\t\t\t\tMetricHelper.metricValues(this._telemetry, batch.values, async err =>\n\t\t\t\t\t\tthis.logRecordsFailed(err, batch.values.length)\n\t\t\t\t\t)\n\t\t\t\t);\n\t\t\t}\n\t\t} finally {\n\t\t\tthis._isDraining = false;\n\t\t}\n\t}\n\n\t/**\n\t * Log that a batch of request metrics could not be recorded.\n\t * @param err The error the telemetry component raised.\n\t * @param count The number of metrics in the batch.\n\t * @returns A promise that resolves when the entry has been logged.\n\t * @internal\n\t */\n\tprivate async logRecordsFailed(err: unknown, count: number): Promise<void> {\n\t\tawait this._logging?.log({\n\t\t\tlevel: \"warn\",\n\t\t\tsource: MetricsRouteProcessor.CLASS_NAME,\n\t\t\tts: Date.now(),\n\t\t\tmessage: \"metricRecordsFailed\",\n\t\t\terror: BaseError.fromError(err),\n\t\t\tdata: { count }\n\t\t});\n\t}\n\n\t/**\n\t * Log that the queue could not be drained.\n\t * @param err The error the drain raised.\n\t * @returns A promise that resolves when the entry has been logged.\n\t * @internal\n\t */\n\tprivate async logDrainFailed(err: unknown): Promise<void> {\n\t\tawait this._logging?.log({\n\t\t\tlevel: \"warn\",\n\t\t\tsource: MetricsRouteProcessor.CLASS_NAME,\n\t\t\tts: Date.now(),\n\t\t\tmessage: \"metricDrainFailed\",\n\t\t\terror: BaseError.fromError(err)\n\t\t});\n\t}\n\n\t/**\n\t * Log the recordings dropped because the queue was full.\n\t * @param count The number of recordings dropped.\n\t * @returns A promise that resolves when the entry has been logged.\n\t * @internal\n\t */\n\tprivate async logRecordsDropped(count: number): Promise<void> {\n\t\ttry {\n\t\t\tawait this._logging?.log({\n\t\t\t\tlevel: \"warn\",\n\t\t\t\tsource: MetricsRouteProcessor.CLASS_NAME,\n\t\t\t\tts: Date.now(),\n\t\t\t\tmessage: \"metricRecordsDropped\",\n\t\t\t\tdata: { count }\n\t\t\t});\n\t\t} catch {\n\t\t\t// Carried into the next recording rather than lost, and absorbed so a broken logging\n\t\t\t// component cannot reject the drain.\n\t\t\tthis._droppedRecordings += count;\n\t\t}\n\t}\n\n\t/**\n\t * Derive the status class label from a numeric HTTP status code.\n\t * @param statusCode The HTTP status code.\n\t * @returns The status class label (1xx, 2xx, 3xx, 4xx, 5xx, or unknown).\n\t * @internal\n\t */\n\tprivate toStatusClass(statusCode: number): string {\n\t\tif (statusCode >= 500) {\n\t\t\treturn \"5xx\";\n\t\t}\n\t\tif (statusCode >= 400) {\n\t\t\treturn \"4xx\";\n\t\t}\n\t\tif (statusCode >= 300) {\n\t\t\treturn \"3xx\";\n\t\t}\n\t\tif (statusCode >= 200) {\n\t\t\treturn \"2xx\";\n\t\t}\n\t\tif (statusCode >= 100) {\n\t\t\treturn \"1xx\";\n\t\t}\n\t\treturn \"unknown\";\n\t}\n}\n"]}
@@ -0,0 +1,4 @@
1
+ // Copyright 2026 IOTA Stiftung.
2
+ // SPDX-License-Identifier: Apache-2.0.
3
+ export {};
4
+ //# sourceMappingURL=IMetricsRouteProcessorConfig.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"IMetricsRouteProcessorConfig.js","sourceRoot":"","sources":["../../../src/models/IMetricsRouteProcessorConfig.ts"],"names":[],"mappings":"AAAA,gCAAgC;AAChC,uCAAuC","sourcesContent":["// Copyright 2026 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\n\n/**\n * Configuration for the MetricsRouteProcessor.\n */\nexport interface IMetricsRouteProcessorConfig {\n\t/**\n\t * URL path prefixes that should not be recorded as metrics, with the root path \"/\" matched in\n\t * full so the routes below it are still recorded.\n\t * Useful for suppressing noise from health-check or metrics-scrape endpoints. Supplying this\n\t * replaces the defaults rather than adding to them, so include the probe paths to keep them\n\t * excluded, or an empty array to record every route.\n\t * @default [\"/\", \"/favicon.ico\", \"/spec\", \"/livez\", \"/readyz\", \"/info\", \"/health\"].\n\t */\n\texcludePaths?: string[];\n\n\t/**\n\t * Maximum number of request values to retain. A value is recorded for every request that\n\t * is not excluded, so without a cap the history grows for as long as the node serves\n\t * traffic; values &lt;= 0 retain everything.\n\t * @default 10000.\n\t */\n\tmaxHistory?: number;\n\n\t/**\n\t * Maximum number of recordings queued off the response path before new ones are dropped.\n\t * Recording never blocks the response, so without a cap a telemetry component slower than the\n\t * request rate would queue values without bound; values &lt;= 0 queue everything.\n\t * @default 1000.\n\t */\n\tmaxPendingRecordings?: number;\n\n\t/**\n\t * Interval in milliseconds between drains of the queued recordings; values &lt;= 0 use the\n\t * default.\n\t * @default 1000.\n\t */\n\tdrainIntervalMs?: number;\n}\n"]}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=IMetricsRouteProcessorConstructorOptions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"IMetricsRouteProcessorConstructorOptions.js","sourceRoot":"","sources":["../../../src/models/IMetricsRouteProcessorConstructorOptions.ts"],"names":[],"mappings":"","sourcesContent":["// Copyright 2026 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nimport type { IMetricsRouteProcessorConfig } from \"./IMetricsRouteProcessorConfig.js\";\n\n/**\n * Constructor options for the MetricsRouteProcessor.\n */\nexport interface IMetricsRouteProcessorConstructorOptions {\n\t/**\n\t * The component type to use for the telemetry component.\n\t */\n\ttelemetryComponentType?: string;\n\n\t/**\n\t * The component type to use for logging metric recording failures.\n\t */\n\tloggingComponentType?: string;\n\n\t/**\n\t * Optional processor configuration.\n\t */\n\tconfig?: IMetricsRouteProcessorConfig;\n}\n"]}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=IPendingMetricRecording.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"IPendingMetricRecording.js","sourceRoot":"","sources":["../../../src/models/IPendingMetricRecording.ts"],"names":[],"mappings":"","sourcesContent":["// Copyright 2026 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nimport type { IContextIds } from \"@3sixty/context\";\n\n/**\n * A request metric queued by the metrics route processor, waiting to be handed to the\n * telemetry component.\n */\nexport interface IPendingMetricRecording {\n\t/**\n\t * The context IDs of the request, used to record the metric in that request's context.\n\t */\n\tcontextIds: IContextIds;\n\n\t/**\n\t * The HTTP method of the request.\n\t */\n\tmethod: string;\n\n\t/**\n\t * The route template path of the request.\n\t */\n\troute: string;\n\n\t/**\n\t * The HTTP status code of the response.\n\t */\n\tstatusCode: number;\n\n\t/**\n\t * The status class of the response.\n\t */\n\tstatusClass: string;\n}\n"]}
@@ -0,0 +1,12 @@
1
+ // Copyright 2026 IOTA Stiftung.
2
+ // SPDX-License-Identifier: Apache-2.0.
3
+ import { MetricType } from "@3sixty/telemetry-models";
4
+ import { TelemetryMetricIds } from "./telemetryMetricIds.js";
5
+ /**
6
+ * Metrics registered by the metrics route processor.
7
+ */
8
+ // eslint-disable-next-line @typescript-eslint/naming-convention
9
+ export const RestRequestsMetrics = [
10
+ { id: TelemetryMetricIds.RestRequests, label: "REST requests", type: MetricType.Counter }
11
+ ];
12
+ //# sourceMappingURL=restRequestsMetrics.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"restRequestsMetrics.js","sourceRoot":"","sources":["../../../src/models/restRequestsMetrics.ts"],"names":[],"mappings":"AAAA,gCAAgC;AAChC,uCAAuC;AACvC,OAAO,EAAE,UAAU,EAAyB,MAAM,0BAA0B,CAAC;AAC7E,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAE7D;;GAEG;AACH,gEAAgE;AAChE,MAAM,CAAC,MAAM,mBAAmB,GAAuB;IACtD,EAAE,EAAE,EAAE,kBAAkB,CAAC,YAAY,EAAE,KAAK,EAAE,eAAe,EAAE,IAAI,EAAE,UAAU,CAAC,OAAO,EAAE;CACzF,CAAC","sourcesContent":["// Copyright 2026 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nimport { MetricType, type ITelemetryMetric } from \"@3sixty/telemetry-models\";\nimport { TelemetryMetricIds } from \"./telemetryMetricIds.js\";\n\n/**\n * Metrics registered by the metrics route processor.\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport const RestRequestsMetrics: ITelemetryMetric[] = [\n\t{ id: TelemetryMetricIds.RestRequests, label: \"REST requests\", type: MetricType.Counter }\n];\n"]}