@opengeni/observability 0.2.1 → 0.3.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 +190 -0
- package/dist/index.d.ts +40 -3
- package/dist/index.js +163 -103
- package/dist/index.js.map +1 -1
- package/package.json +7 -6
- package/src/index.ts +193 -108
package/LICENSE
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
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
|
+
Copyright 2026 Cloudgeni-ai
|
|
179
|
+
|
|
180
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
181
|
+
you may not use this file except in compliance with the License.
|
|
182
|
+
You may obtain a copy of the License at
|
|
183
|
+
|
|
184
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
185
|
+
|
|
186
|
+
Unless required by applicable law or agreed to in writing, software
|
|
187
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
188
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
189
|
+
See the License for the specific language governing permissions and
|
|
190
|
+
limitations under the License.
|
package/dist/index.d.ts
CHANGED
|
@@ -3,6 +3,7 @@ type Attributes = Record<string, AttributeValue>;
|
|
|
3
3
|
type ObservabilitySettings = {
|
|
4
4
|
serviceName: string;
|
|
5
5
|
environment: string;
|
|
6
|
+
deploymentRevision?: string | undefined;
|
|
6
7
|
observabilityStructuredLogs: boolean;
|
|
7
8
|
observabilityMetricsEnabled: boolean;
|
|
8
9
|
observabilityOtlpEndpoint?: string | undefined;
|
|
@@ -21,15 +22,21 @@ type Span = {
|
|
|
21
22
|
error?: unknown;
|
|
22
23
|
}) => void;
|
|
23
24
|
};
|
|
25
|
+
type MetricLabels = Record<string, AttributeValue>;
|
|
24
26
|
declare function createObservability(settings: ObservabilitySettings, options: ObservabilityOptions): Observability;
|
|
25
27
|
declare class Observability {
|
|
26
28
|
private readonly settings;
|
|
27
29
|
private readonly options;
|
|
28
|
-
private readonly
|
|
30
|
+
private readonly registry;
|
|
31
|
+
private readonly counters;
|
|
32
|
+
private readonly gauges;
|
|
33
|
+
private readonly histograms;
|
|
34
|
+
private readonly registrations;
|
|
29
35
|
private readonly now;
|
|
30
36
|
private readonly exporter;
|
|
31
37
|
private readonly resourceAttributes;
|
|
32
38
|
constructor(settings: ObservabilitySettings, options: ObservabilityOptions);
|
|
39
|
+
debug(message: string, attributes?: Attributes): void;
|
|
33
40
|
info(message: string, attributes?: Attributes): void;
|
|
34
41
|
warn(message: string, attributes?: Attributes): void;
|
|
35
42
|
error(message: string, attributes?: Attributes): void;
|
|
@@ -46,7 +53,37 @@ declare class Observability {
|
|
|
46
53
|
status: string;
|
|
47
54
|
durationSeconds: number;
|
|
48
55
|
}): void;
|
|
49
|
-
|
|
56
|
+
incrementCounter(input: {
|
|
57
|
+
name: string;
|
|
58
|
+
help?: string;
|
|
59
|
+
labels?: MetricLabels;
|
|
60
|
+
amount?: number;
|
|
61
|
+
}): void;
|
|
62
|
+
setGauge(input: {
|
|
63
|
+
name: string;
|
|
64
|
+
help?: string;
|
|
65
|
+
labels?: MetricLabels;
|
|
66
|
+
value: number;
|
|
67
|
+
}): void;
|
|
68
|
+
incrementGauge(input: {
|
|
69
|
+
name: string;
|
|
70
|
+
help?: string;
|
|
71
|
+
labels?: MetricLabels;
|
|
72
|
+
amount?: number;
|
|
73
|
+
}): void;
|
|
74
|
+
observeHistogram(input: {
|
|
75
|
+
name: string;
|
|
76
|
+
help?: string;
|
|
77
|
+
labels?: MetricLabels;
|
|
78
|
+
value: number;
|
|
79
|
+
buckets?: number[];
|
|
80
|
+
}): void;
|
|
81
|
+
prometheusMetrics(): Promise<string>;
|
|
82
|
+
private counter;
|
|
83
|
+
private gauge;
|
|
84
|
+
private histogram;
|
|
85
|
+
private register;
|
|
86
|
+
private assertRegistration;
|
|
50
87
|
private exportSpan;
|
|
51
88
|
}
|
|
52
89
|
type StartupDependencyRetryEvent = {
|
|
@@ -59,4 +96,4 @@ type StartupDependencyRetryEvent = {
|
|
|
59
96
|
declare function logStartupDependencyRetry(observability: Observability, event: StartupDependencyRetryEvent): void;
|
|
60
97
|
declare function parseHeaders(value: string): Record<string, string>;
|
|
61
98
|
|
|
62
|
-
export { type AttributeValue, type Attributes, Observability, type ObservabilityOptions, type ObservabilitySettings, type Span, type StartupDependencyRetryEvent, createObservability, logStartupDependencyRetry, parseHeaders };
|
|
99
|
+
export { type AttributeValue, type Attributes, type MetricLabels, Observability, type ObservabilityOptions, type ObservabilitySettings, type Span, type StartupDependencyRetryEvent, createObservability, logStartupDependencyRetry, parseHeaders };
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,13 @@
|
|
|
1
1
|
// src/index.ts
|
|
2
|
-
|
|
2
|
+
import {
|
|
3
|
+
collectDefaultMetrics,
|
|
4
|
+
Counter,
|
|
5
|
+
Gauge,
|
|
6
|
+
Histogram,
|
|
7
|
+
Registry
|
|
8
|
+
} from "prom-client";
|
|
9
|
+
var httpHistogramBuckets = [5e-3, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10];
|
|
10
|
+
var durationHistogramBuckets = [0.01, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60, 120, 300, 900, 1800, 3600];
|
|
3
11
|
function createObservability(settings, options) {
|
|
4
12
|
return new Observability(settings, options);
|
|
5
13
|
}
|
|
@@ -14,13 +22,37 @@ var Observability = class {
|
|
|
14
22
|
"deployment.environment": settings.environment,
|
|
15
23
|
"opengeni.component": options.component
|
|
16
24
|
};
|
|
25
|
+
this.registry.setDefaultLabels({
|
|
26
|
+
service: settings.serviceName,
|
|
27
|
+
environment: settings.environment,
|
|
28
|
+
component: options.component
|
|
29
|
+
});
|
|
30
|
+
if (settings.observabilityMetricsEnabled) {
|
|
31
|
+
collectDefaultMetrics({ register: this.registry, prefix: "opengeni_" });
|
|
32
|
+
this.setGauge({
|
|
33
|
+
name: "opengeni_build_info",
|
|
34
|
+
help: "OpenGeni build information.",
|
|
35
|
+
labels: {
|
|
36
|
+
version: buildVersion(),
|
|
37
|
+
revision: settings.deploymentRevision ?? "dev"
|
|
38
|
+
},
|
|
39
|
+
value: 1
|
|
40
|
+
});
|
|
41
|
+
}
|
|
17
42
|
}
|
|
18
43
|
settings;
|
|
19
44
|
options;
|
|
20
|
-
|
|
45
|
+
registry = new Registry();
|
|
46
|
+
counters = /* @__PURE__ */ new Map();
|
|
47
|
+
gauges = /* @__PURE__ */ new Map();
|
|
48
|
+
histograms = /* @__PURE__ */ new Map();
|
|
49
|
+
registrations = /* @__PURE__ */ new Map();
|
|
21
50
|
now;
|
|
22
51
|
exporter;
|
|
23
52
|
resourceAttributes;
|
|
53
|
+
debug(message, attributes = {}) {
|
|
54
|
+
this.log("debug", message, attributes);
|
|
55
|
+
}
|
|
24
56
|
info(message, attributes = {}) {
|
|
25
57
|
this.log("info", message, attributes);
|
|
26
58
|
}
|
|
@@ -91,43 +123,137 @@ var Observability = class {
|
|
|
91
123
|
};
|
|
92
124
|
}
|
|
93
125
|
recordHttpRequest(input) {
|
|
126
|
+
this.incrementCounter({
|
|
127
|
+
name: "opengeni_http_requests_total",
|
|
128
|
+
help: "Total HTTP requests handled by OpenGeni.",
|
|
129
|
+
labels: {
|
|
130
|
+
method: input.method,
|
|
131
|
+
route: input.route,
|
|
132
|
+
status: String(input.status),
|
|
133
|
+
component: this.options.component
|
|
134
|
+
}
|
|
135
|
+
});
|
|
136
|
+
this.observeHistogram({
|
|
137
|
+
name: "opengeni_http_request_duration_seconds",
|
|
138
|
+
help: "HTTP request duration in seconds.",
|
|
139
|
+
buckets: httpHistogramBuckets,
|
|
140
|
+
value: input.durationSeconds,
|
|
141
|
+
labels: {
|
|
142
|
+
method: input.method,
|
|
143
|
+
route: input.route,
|
|
144
|
+
component: this.options.component
|
|
145
|
+
}
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
recordWorkerActivity(input) {
|
|
149
|
+
this.incrementCounter({
|
|
150
|
+
name: "opengeni_worker_activity_runs_total",
|
|
151
|
+
help: "Total worker activity executions.",
|
|
152
|
+
labels: {
|
|
153
|
+
activity: input.activity,
|
|
154
|
+
status: input.status,
|
|
155
|
+
component: this.options.component
|
|
156
|
+
}
|
|
157
|
+
});
|
|
158
|
+
this.observeHistogram({
|
|
159
|
+
name: "opengeni_worker_activity_duration_seconds",
|
|
160
|
+
help: "Worker activity duration in seconds.",
|
|
161
|
+
buckets: durationHistogramBuckets,
|
|
162
|
+
value: input.durationSeconds,
|
|
163
|
+
labels: {
|
|
164
|
+
activity: input.activity,
|
|
165
|
+
component: this.options.component
|
|
166
|
+
}
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
incrementCounter(input) {
|
|
94
170
|
if (!this.settings.observabilityMetricsEnabled) {
|
|
95
171
|
return;
|
|
96
172
|
}
|
|
97
|
-
const labels =
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
status: String(input.status),
|
|
101
|
-
component: this.options.component
|
|
102
|
-
};
|
|
103
|
-
this.metrics.increment("opengeni_http_requests_total", labels);
|
|
104
|
-
this.metrics.observe("opengeni_http_request_duration_seconds", histogramBuckets, input.durationSeconds, {
|
|
105
|
-
method: input.method,
|
|
106
|
-
route: input.route,
|
|
107
|
-
component: this.options.component
|
|
108
|
-
});
|
|
173
|
+
const labels = normalizeLabels(input.labels);
|
|
174
|
+
const counter = this.counter(input.name, input.help ?? `${input.name} counter.`, Object.keys(labels));
|
|
175
|
+
counter.inc(labels, input.amount ?? 1);
|
|
109
176
|
}
|
|
110
|
-
|
|
177
|
+
setGauge(input) {
|
|
111
178
|
if (!this.settings.observabilityMetricsEnabled) {
|
|
112
179
|
return;
|
|
113
180
|
}
|
|
114
|
-
const labels =
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
component: this.options.component
|
|
118
|
-
};
|
|
119
|
-
this.metrics.increment("opengeni_worker_activity_runs_total", labels);
|
|
120
|
-
this.metrics.observe("opengeni_worker_activity_duration_seconds", histogramBuckets, input.durationSeconds, {
|
|
121
|
-
activity: input.activity,
|
|
122
|
-
component: this.options.component
|
|
123
|
-
});
|
|
181
|
+
const labels = normalizeLabels(input.labels);
|
|
182
|
+
const gauge = this.gauge(input.name, input.help ?? `${input.name} gauge.`, Object.keys(labels));
|
|
183
|
+
gauge.set(labels, input.value);
|
|
124
184
|
}
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
});
|
|
185
|
+
incrementGauge(input) {
|
|
186
|
+
if (!this.settings.observabilityMetricsEnabled) {
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
const labels = normalizeLabels(input.labels);
|
|
190
|
+
const gauge = this.gauge(input.name, input.help ?? `${input.name} gauge.`, Object.keys(labels));
|
|
191
|
+
gauge.inc(labels, input.amount ?? 1);
|
|
192
|
+
}
|
|
193
|
+
observeHistogram(input) {
|
|
194
|
+
if (!this.settings.observabilityMetricsEnabled) {
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
const labels = normalizeLabels(input.labels);
|
|
198
|
+
const histogram = this.histogram(
|
|
199
|
+
input.name,
|
|
200
|
+
input.help ?? `${input.name} histogram.`,
|
|
201
|
+
Object.keys(labels),
|
|
202
|
+
input.buckets ?? durationHistogramBuckets
|
|
203
|
+
);
|
|
204
|
+
histogram.observe(labels, input.value);
|
|
205
|
+
}
|
|
206
|
+
async prometheusMetrics() {
|
|
207
|
+
if (!this.settings.observabilityMetricsEnabled) {
|
|
208
|
+
return "";
|
|
209
|
+
}
|
|
210
|
+
return await this.registry.metrics();
|
|
211
|
+
}
|
|
212
|
+
counter(name, help, labelNames) {
|
|
213
|
+
const existing = this.counters.get(name);
|
|
214
|
+
if (existing) {
|
|
215
|
+
this.assertRegistration(name, "counter", labelNames);
|
|
216
|
+
return existing;
|
|
217
|
+
}
|
|
218
|
+
this.register(name, "counter", labelNames);
|
|
219
|
+
const metric = new Counter({ name, help, labelNames, registers: [this.registry] });
|
|
220
|
+
this.counters.set(name, metric);
|
|
221
|
+
return metric;
|
|
222
|
+
}
|
|
223
|
+
gauge(name, help, labelNames) {
|
|
224
|
+
const existing = this.gauges.get(name);
|
|
225
|
+
if (existing) {
|
|
226
|
+
this.assertRegistration(name, "gauge", labelNames);
|
|
227
|
+
return existing;
|
|
228
|
+
}
|
|
229
|
+
this.register(name, "gauge", labelNames);
|
|
230
|
+
const metric = new Gauge({ name, help, labelNames, registers: [this.registry] });
|
|
231
|
+
this.gauges.set(name, metric);
|
|
232
|
+
return metric;
|
|
233
|
+
}
|
|
234
|
+
histogram(name, help, labelNames, buckets) {
|
|
235
|
+
const existing = this.histograms.get(name);
|
|
236
|
+
if (existing) {
|
|
237
|
+
this.assertRegistration(name, "histogram", labelNames);
|
|
238
|
+
return existing;
|
|
239
|
+
}
|
|
240
|
+
this.register(name, "histogram", labelNames);
|
|
241
|
+
const metric = new Histogram({ name, help, labelNames, buckets, registers: [this.registry] });
|
|
242
|
+
this.histograms.set(name, metric);
|
|
243
|
+
return metric;
|
|
244
|
+
}
|
|
245
|
+
register(name, kind, labelNames) {
|
|
246
|
+
const sorted = [...labelNames].sort();
|
|
247
|
+
this.registrations.set(name, { kind, labelNames: sorted });
|
|
248
|
+
}
|
|
249
|
+
assertRegistration(name, kind, labelNames) {
|
|
250
|
+
const registration = this.registrations.get(name);
|
|
251
|
+
const sorted = [...labelNames].sort();
|
|
252
|
+
if (!registration || registration.kind !== kind || registration.labelNames.length !== sorted.length || registration.labelNames.some((label, index) => label !== sorted[index])) {
|
|
253
|
+
throw new Error(
|
|
254
|
+
`Metric ${name} was already registered as ${registration?.kind ?? "unknown"} with labels [${registration?.labelNames.join(",") ?? ""}], not ${kind} [${sorted.join(",")}]`
|
|
255
|
+
);
|
|
256
|
+
}
|
|
131
257
|
}
|
|
132
258
|
exportSpan(span) {
|
|
133
259
|
if (!this.settings.observabilityOtlpEndpoint) {
|
|
@@ -172,79 +298,13 @@ function logStartupDependencyRetry(observability, event) {
|
|
|
172
298
|
error: message
|
|
173
299
|
});
|
|
174
300
|
}
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
const key = metricKey(name, labels);
|
|
180
|
-
this.counters.set(key, (this.counters.get(key) ?? 0) + amount);
|
|
181
|
-
}
|
|
182
|
-
observe(name, buckets, value, labels) {
|
|
183
|
-
const key = metricKey(name, labels);
|
|
184
|
-
const histogram = this.histograms.get(key) ?? {
|
|
185
|
-
buckets,
|
|
186
|
-
counts: buckets.map(() => 0),
|
|
187
|
-
sum: 0,
|
|
188
|
-
count: 0,
|
|
189
|
-
labels
|
|
190
|
-
};
|
|
191
|
-
histogram.sum += value;
|
|
192
|
-
histogram.count += 1;
|
|
193
|
-
for (let index = 0; index < buckets.length; index += 1) {
|
|
194
|
-
if (value <= buckets[index]) {
|
|
195
|
-
histogram.counts[index] = (histogram.counts[index] ?? 0) + 1;
|
|
196
|
-
}
|
|
197
|
-
}
|
|
198
|
-
this.histograms.set(key, histogram);
|
|
199
|
-
}
|
|
200
|
-
toPrometheus(resourceLabels) {
|
|
201
|
-
const lines = [
|
|
202
|
-
"# HELP opengeni_http_requests_total Total HTTP requests handled by the OpenGeni API.",
|
|
203
|
-
"# TYPE opengeni_http_requests_total counter"
|
|
204
|
-
];
|
|
205
|
-
for (const [key, value] of this.counters) {
|
|
206
|
-
const { name, labels } = parseMetricKey(key);
|
|
207
|
-
if (name.endsWith("_total")) {
|
|
208
|
-
lines.push(`${name}${formatLabels({ ...resourceLabels, ...labels })} ${value}`);
|
|
209
|
-
}
|
|
210
|
-
}
|
|
211
|
-
lines.push(
|
|
212
|
-
"# HELP opengeni_http_request_duration_seconds HTTP request duration in seconds.",
|
|
213
|
-
"# TYPE opengeni_http_request_duration_seconds histogram",
|
|
214
|
-
"# HELP opengeni_worker_activity_runs_total Total worker activity executions.",
|
|
215
|
-
"# TYPE opengeni_worker_activity_runs_total counter",
|
|
216
|
-
"# HELP opengeni_worker_activity_duration_seconds Worker activity duration in seconds.",
|
|
217
|
-
"# TYPE opengeni_worker_activity_duration_seconds histogram"
|
|
218
|
-
);
|
|
219
|
-
for (const [key, histogram] of this.histograms) {
|
|
220
|
-
const { name, labels } = parseMetricKey(key);
|
|
221
|
-
const baseLabels = { ...resourceLabels, ...labels };
|
|
222
|
-
for (let index = 0; index < histogram.buckets.length; index += 1) {
|
|
223
|
-
lines.push(`${name}_bucket${formatLabels({ ...baseLabels, le: String(histogram.buckets[index]) })} ${histogram.counts[index]}`);
|
|
224
|
-
}
|
|
225
|
-
lines.push(`${name}_bucket${formatLabels({ ...baseLabels, le: "+Inf" })} ${histogram.count}`);
|
|
226
|
-
lines.push(`${name}_sum${formatLabels(baseLabels)} ${histogram.sum}`);
|
|
227
|
-
lines.push(`${name}_count${formatLabels(baseLabels)} ${histogram.count}`);
|
|
228
|
-
}
|
|
229
|
-
return `${lines.join("\n")}
|
|
230
|
-
`;
|
|
231
|
-
}
|
|
232
|
-
};
|
|
233
|
-
function metricKey(name, labels) {
|
|
234
|
-
return JSON.stringify({ name, labels: Object.fromEntries(Object.entries(labels).sort(([a], [b]) => a.localeCompare(b))) });
|
|
235
|
-
}
|
|
236
|
-
function parseMetricKey(key) {
|
|
237
|
-
return JSON.parse(key);
|
|
238
|
-
}
|
|
239
|
-
function formatLabels(labels) {
|
|
240
|
-
const entries = Object.entries(labels).filter(([, value]) => value.length > 0);
|
|
241
|
-
if (entries.length === 0) {
|
|
242
|
-
return "";
|
|
243
|
-
}
|
|
244
|
-
return `{${entries.map(([key, value]) => `${key}="${escapeMetricLabel(value)}"`).join(",")}}`;
|
|
301
|
+
function normalizeLabels(labels = {}) {
|
|
302
|
+
return Object.fromEntries(
|
|
303
|
+
Object.entries(labels).filter(([, value]) => value !== void 0 && value !== null).map(([key, value]) => [key, String(value)]).sort((left, right) => left[0].localeCompare(right[0]))
|
|
304
|
+
);
|
|
245
305
|
}
|
|
246
|
-
function
|
|
247
|
-
return
|
|
306
|
+
function buildVersion() {
|
|
307
|
+
return process.env.OPENGENI_VERSION ?? process.env.npm_package_version ?? "dev";
|
|
248
308
|
}
|
|
249
309
|
function cleanAttributes(attributes) {
|
|
250
310
|
return Object.fromEntries(Object.entries(attributes).filter(([, value]) => value !== void 0));
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["export type AttributeValue = string | number | boolean | null | undefined;\nexport type Attributes = Record<string, AttributeValue>;\n\nexport type ObservabilitySettings = {\n serviceName: string;\n environment: string;\n observabilityStructuredLogs: boolean;\n observabilityMetricsEnabled: boolean;\n observabilityOtlpEndpoint?: string | undefined;\n observabilityOtlpHeaders: string;\n};\n\nexport type ObservabilityOptions = {\n component: string;\n now?: () => number;\n exporter?: (url: string, body: unknown, headers: Record<string, string>) => Promise<void>;\n};\n\nexport type Span = {\n traceId: string;\n spanId: string;\n end: (input?: { attributes?: Attributes; error?: unknown }) => void;\n};\n\nconst histogramBuckets = [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10];\n\nexport function createObservability(settings: ObservabilitySettings, options: ObservabilityOptions): Observability {\n return new Observability(settings, options);\n}\n\nexport class Observability {\n private readonly metrics = new MetricsRegistry();\n private readonly now: () => number;\n private readonly exporter: (url: string, body: unknown, headers: Record<string, string>) => Promise<void>;\n private readonly resourceAttributes: Attributes;\n\n constructor(private readonly settings: ObservabilitySettings, private readonly options: ObservabilityOptions) {\n this.now = options.now ?? Date.now;\n this.exporter = options.exporter ?? defaultExporter;\n this.resourceAttributes = {\n \"service.name\": settings.serviceName,\n \"deployment.environment\": settings.environment,\n \"opengeni.component\": options.component,\n };\n }\n\n info(message: string, attributes: Attributes = {}): void {\n this.log(\"info\", message, attributes);\n }\n\n warn(message: string, attributes: Attributes = {}): void {\n this.log(\"warn\", message, attributes);\n }\n\n error(message: string, attributes: Attributes = {}): void {\n this.log(\"error\", message, attributes);\n }\n\n log(level: \"debug\" | \"info\" | \"warn\" | \"error\", message: string, attributes: Attributes = {}): void {\n if (!this.settings.observabilityStructuredLogs) {\n const line = attributes.error ? `${message}: ${String(attributes.error)}` : message;\n if (level === \"warn\") {\n console.warn(line);\n } else if (level === \"error\") {\n console.error(line);\n } else {\n console.log(line);\n }\n return;\n }\n const record = {\n timestamp: new Date(this.now()).toISOString(),\n level,\n message,\n service: this.settings.serviceName,\n environment: this.settings.environment,\n component: this.options.component,\n ...cleanAttributes(attributes),\n };\n const serialized = JSON.stringify(record);\n if (level === \"warn\") {\n console.warn(serialized);\n } else if (level === \"error\") {\n console.error(serialized);\n } else {\n console.log(serialized);\n }\n }\n\n startSpan(name: string, attributes: Attributes = {}): Span {\n const traceId = randomHex(16);\n const spanId = randomHex(8);\n const startMs = this.now();\n let ended = false;\n return {\n traceId,\n spanId,\n end: (input = {}) => {\n if (ended) {\n return;\n }\n ended = true;\n const errorAttributes = input.error ? errorToAttributes(input.error) : {};\n this.exportSpan({\n traceId,\n spanId,\n name,\n startMs,\n endMs: this.now(),\n attributes: {\n ...attributes,\n ...input.attributes,\n ...errorAttributes,\n },\n error: input.error,\n });\n },\n };\n }\n\n recordHttpRequest(input: { method: string; route: string; status: number; durationSeconds: number }): void {\n if (!this.settings.observabilityMetricsEnabled) {\n return;\n }\n const labels = {\n method: input.method,\n route: input.route,\n status: String(input.status),\n component: this.options.component,\n };\n this.metrics.increment(\"opengeni_http_requests_total\", labels);\n this.metrics.observe(\"opengeni_http_request_duration_seconds\", histogramBuckets, input.durationSeconds, {\n method: input.method,\n route: input.route,\n component: this.options.component,\n });\n }\n\n recordWorkerActivity(input: { activity: string; status: string; durationSeconds: number }): void {\n if (!this.settings.observabilityMetricsEnabled) {\n return;\n }\n const labels = {\n activity: input.activity,\n status: input.status,\n component: this.options.component,\n };\n this.metrics.increment(\"opengeni_worker_activity_runs_total\", labels);\n this.metrics.observe(\"opengeni_worker_activity_duration_seconds\", histogramBuckets, input.durationSeconds, {\n activity: input.activity,\n component: this.options.component,\n });\n }\n\n prometheusMetrics(): string {\n return this.metrics.toPrometheus({\n service: this.settings.serviceName,\n environment: this.settings.environment,\n component: this.options.component,\n });\n }\n\n private exportSpan(span: {\n traceId: string;\n spanId: string;\n name: string;\n startMs: number;\n endMs: number;\n attributes: Attributes;\n error?: unknown;\n }): void {\n if (!this.settings.observabilityOtlpEndpoint) {\n return;\n }\n const endpoint = `${this.settings.observabilityOtlpEndpoint.replace(/\\/$/, \"\")}/v1/traces`;\n const body = {\n resourceSpans: [{\n resource: {\n attributes: otlpAttributes(this.resourceAttributes),\n },\n scopeSpans: [{\n scope: {\n name: \"@opengeni/observability\",\n version: \"0.1.0\",\n },\n spans: [{\n traceId: span.traceId,\n spanId: span.spanId,\n name: span.name,\n kind: 1,\n startTimeUnixNano: millisToNanos(span.startMs),\n endTimeUnixNano: millisToNanos(span.endMs),\n attributes: otlpAttributes(span.attributes),\n status: span.error ? { code: 2, message: errorMessage(span.error) } : { code: 1 },\n }],\n }],\n }],\n };\n void this.exporter(endpoint, body, parseHeaders(this.settings.observabilityOtlpHeaders)).catch((error) => {\n this.warn(\"OTLP span export failed\", { error: errorMessage(error), endpoint });\n });\n }\n}\n\nexport type StartupDependencyRetryEvent = {\n label: string;\n attempt: number;\n attempts: number;\n delayMs: number;\n error: unknown;\n};\n\nexport function logStartupDependencyRetry(observability: Observability, event: StartupDependencyRetryEvent): void {\n const message = event.error instanceof Error ? event.error.message : String(event.error);\n observability.warn(\"Startup dependency connection failed; retrying\", {\n dependency: event.label,\n attempt: event.attempt,\n attempts: event.attempts,\n delayMs: event.delayMs,\n error: message,\n });\n}\n\nclass MetricsRegistry {\n private readonly counters = new Map<string, number>();\n private readonly histograms = new Map<string, { buckets: number[]; counts: number[]; sum: number; count: number; labels: Record<string, string> }>();\n\n increment(name: string, labels: Record<string, string>, amount = 1): void {\n const key = metricKey(name, labels);\n this.counters.set(key, (this.counters.get(key) ?? 0) + amount);\n }\n\n observe(name: string, buckets: number[], value: number, labels: Record<string, string>): void {\n const key = metricKey(name, labels);\n const histogram = this.histograms.get(key) ?? {\n buckets,\n counts: buckets.map(() => 0),\n sum: 0,\n count: 0,\n labels,\n };\n histogram.sum += value;\n histogram.count += 1;\n for (let index = 0; index < buckets.length; index += 1) {\n if (value <= buckets[index]!) {\n histogram.counts[index] = (histogram.counts[index] ?? 0) + 1;\n }\n }\n this.histograms.set(key, histogram);\n }\n\n toPrometheus(resourceLabels: Record<string, string>): string {\n const lines = [\n \"# HELP opengeni_http_requests_total Total HTTP requests handled by the OpenGeni API.\",\n \"# TYPE opengeni_http_requests_total counter\",\n ];\n for (const [key, value] of this.counters) {\n const { name, labels } = parseMetricKey(key);\n if (name.endsWith(\"_total\")) {\n lines.push(`${name}${formatLabels({ ...resourceLabels, ...labels })} ${value}`);\n }\n }\n lines.push(\n \"# HELP opengeni_http_request_duration_seconds HTTP request duration in seconds.\",\n \"# TYPE opengeni_http_request_duration_seconds histogram\",\n \"# HELP opengeni_worker_activity_runs_total Total worker activity executions.\",\n \"# TYPE opengeni_worker_activity_runs_total counter\",\n \"# HELP opengeni_worker_activity_duration_seconds Worker activity duration in seconds.\",\n \"# TYPE opengeni_worker_activity_duration_seconds histogram\",\n );\n for (const [key, histogram] of this.histograms) {\n const { name, labels } = parseMetricKey(key);\n const baseLabels = { ...resourceLabels, ...labels };\n for (let index = 0; index < histogram.buckets.length; index += 1) {\n lines.push(`${name}_bucket${formatLabels({ ...baseLabels, le: String(histogram.buckets[index]) })} ${histogram.counts[index]}`);\n }\n lines.push(`${name}_bucket${formatLabels({ ...baseLabels, le: \"+Inf\" })} ${histogram.count}`);\n lines.push(`${name}_sum${formatLabels(baseLabels)} ${histogram.sum}`);\n lines.push(`${name}_count${formatLabels(baseLabels)} ${histogram.count}`);\n }\n return `${lines.join(\"\\n\")}\\n`;\n }\n}\n\nfunction metricKey(name: string, labels: Record<string, string>): string {\n return JSON.stringify({ name, labels: Object.fromEntries(Object.entries(labels).sort(([a], [b]) => a.localeCompare(b))) });\n}\n\nfunction parseMetricKey(key: string): { name: string; labels: Record<string, string> } {\n return JSON.parse(key) as { name: string; labels: Record<string, string> };\n}\n\nfunction formatLabels(labels: Record<string, string>): string {\n const entries = Object.entries(labels).filter(([, value]) => value.length > 0);\n if (entries.length === 0) {\n return \"\";\n }\n return `{${entries.map(([key, value]) => `${key}=\"${escapeMetricLabel(value)}\"`).join(\",\")}}`;\n}\n\nfunction escapeMetricLabel(value: string): string {\n return value.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, \"\\\\\\\"\").replace(/\\n/g, \"\\\\n\");\n}\n\nfunction cleanAttributes(attributes: Attributes): Record<string, string | number | boolean | null> {\n return Object.fromEntries(Object.entries(attributes).filter(([, value]) => value !== undefined)) as Record<string, string | number | boolean | null>;\n}\n\nfunction errorToAttributes(error: unknown): Attributes {\n return {\n \"error.type\": error instanceof Error ? error.name : \"Error\",\n \"error.message\": errorMessage(error),\n };\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction otlpAttributes(attributes: Attributes): Array<{ key: string; value: Record<string, string | number | boolean> }> {\n return Object.entries(cleanAttributes(attributes)).map(([key, value]) => ({\n key,\n value: otlpValue(value),\n }));\n}\n\nfunction otlpValue(value: string | number | boolean | null): Record<string, string | number | boolean> {\n if (typeof value === \"number\") {\n return Number.isInteger(value) ? { intValue: value } : { doubleValue: value };\n }\n if (typeof value === \"boolean\") {\n return { boolValue: value };\n }\n return { stringValue: value === null ? \"\" : value };\n}\n\nfunction millisToNanos(ms: number): string {\n return String(BigInt(Math.round(ms)) * 1_000_000n);\n}\n\nfunction randomHex(bytes: number): string {\n const values = crypto.getRandomValues(new Uint8Array(bytes));\n return Array.from(values, (value) => value.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nexport function parseHeaders(value: string): Record<string, string> {\n if (!value.trim()) {\n return {};\n }\n const entries: Array<[string, string]> = value.split(\",\").map((pair): [string, string] => {\n const separator = pair.indexOf(\"=\");\n if (separator === -1) {\n return [pair.trim(), \"\"];\n }\n return [pair.slice(0, separator).trim(), pair.slice(separator + 1).trim()];\n }).filter(([key]) => key.length > 0);\n return Object.fromEntries(entries);\n}\n\nasync function defaultExporter(url: string, body: unknown, headers: Record<string, string>): Promise<void> {\n const response = await fetch(url, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n ...headers,\n },\n body: JSON.stringify(body),\n });\n if (!response.ok) {\n throw new Error(`OTLP endpoint returned HTTP ${response.status}`);\n }\n}\n"],"mappings":";AAwBA,IAAM,mBAAmB,CAAC,MAAO,MAAM,OAAO,MAAM,KAAK,MAAM,KAAK,GAAG,KAAK,GAAG,EAAE;AAE1E,SAAS,oBAAoB,UAAiC,SAA8C;AACjH,SAAO,IAAI,cAAc,UAAU,OAAO;AAC5C;AA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AC3B,CAAC;AACD,MAAI,CAAC,SAAS,IAAI;AAChB,UAAM,IAAI,MAAM,+BAA+B,SAAS,MAAM,EAAE;AAAA,EAClE;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import {\n collectDefaultMetrics,\n Counter,\n Gauge,\n Histogram,\n Registry,\n} from \"prom-client\";\n\nexport type AttributeValue = string | number | boolean | null | undefined;\nexport type Attributes = Record<string, AttributeValue>;\n\nexport type ObservabilitySettings = {\n serviceName: string;\n environment: string;\n deploymentRevision?: string | undefined;\n observabilityStructuredLogs: boolean;\n observabilityMetricsEnabled: boolean;\n observabilityOtlpEndpoint?: string | undefined;\n observabilityOtlpHeaders: string;\n};\n\nexport type ObservabilityOptions = {\n component: string;\n now?: () => number;\n exporter?: (url: string, body: unknown, headers: Record<string, string>) => Promise<void>;\n};\n\nexport type Span = {\n traceId: string;\n spanId: string;\n end: (input?: { attributes?: Attributes; error?: unknown }) => void;\n};\n\nexport type MetricLabels = Record<string, AttributeValue>;\n\nconst httpHistogramBuckets = [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10];\nconst durationHistogramBuckets = [0.01, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60, 120, 300, 900, 1800, 3600];\n\nexport function createObservability(settings: ObservabilitySettings, options: ObservabilityOptions): Observability {\n return new Observability(settings, options);\n}\n\ntype MetricRegistration = {\n kind: \"counter\" | \"gauge\" | \"histogram\";\n labelNames: string[];\n};\n\nexport class Observability {\n private readonly registry = new Registry();\n private readonly counters = new Map<string, Counter<string>>();\n private readonly gauges = new Map<string, Gauge<string>>();\n private readonly histograms = new Map<string, Histogram<string>>();\n private readonly registrations = new Map<string, MetricRegistration>();\n private readonly now: () => number;\n private readonly exporter: (url: string, body: unknown, headers: Record<string, string>) => Promise<void>;\n private readonly resourceAttributes: Attributes;\n\n constructor(private readonly settings: ObservabilitySettings, private readonly options: ObservabilityOptions) {\n this.now = options.now ?? Date.now;\n this.exporter = options.exporter ?? defaultExporter;\n this.resourceAttributes = {\n \"service.name\": settings.serviceName,\n \"deployment.environment\": settings.environment,\n \"opengeni.component\": options.component,\n };\n this.registry.setDefaultLabels({\n service: settings.serviceName,\n environment: settings.environment,\n component: options.component,\n });\n if (settings.observabilityMetricsEnabled) {\n collectDefaultMetrics({ register: this.registry, prefix: \"opengeni_\" });\n this.setGauge({\n name: \"opengeni_build_info\",\n help: \"OpenGeni build information.\",\n labels: {\n version: buildVersion(),\n revision: settings.deploymentRevision ?? \"dev\",\n },\n value: 1,\n });\n }\n }\n\n debug(message: string, attributes: Attributes = {}): void {\n this.log(\"debug\", message, attributes);\n }\n\n info(message: string, attributes: Attributes = {}): void {\n this.log(\"info\", message, attributes);\n }\n\n warn(message: string, attributes: Attributes = {}): void {\n this.log(\"warn\", message, attributes);\n }\n\n error(message: string, attributes: Attributes = {}): void {\n this.log(\"error\", message, attributes);\n }\n\n log(level: \"debug\" | \"info\" | \"warn\" | \"error\", message: string, attributes: Attributes = {}): void {\n if (!this.settings.observabilityStructuredLogs) {\n const line = attributes.error ? `${message}: ${String(attributes.error)}` : message;\n if (level === \"warn\") {\n console.warn(line);\n } else if (level === \"error\") {\n console.error(line);\n } else {\n console.log(line);\n }\n return;\n }\n const record = {\n timestamp: new Date(this.now()).toISOString(),\n level,\n message,\n service: this.settings.serviceName,\n environment: this.settings.environment,\n component: this.options.component,\n ...cleanAttributes(attributes),\n };\n const serialized = JSON.stringify(record);\n if (level === \"warn\") {\n console.warn(serialized);\n } else if (level === \"error\") {\n console.error(serialized);\n } else {\n console.log(serialized);\n }\n }\n\n startSpan(name: string, attributes: Attributes = {}): Span {\n const traceId = randomHex(16);\n const spanId = randomHex(8);\n const startMs = this.now();\n let ended = false;\n return {\n traceId,\n spanId,\n end: (input = {}) => {\n if (ended) {\n return;\n }\n ended = true;\n const errorAttributes = input.error ? errorToAttributes(input.error) : {};\n this.exportSpan({\n traceId,\n spanId,\n name,\n startMs,\n endMs: this.now(),\n attributes: {\n ...attributes,\n ...input.attributes,\n ...errorAttributes,\n },\n error: input.error,\n });\n },\n };\n }\n\n recordHttpRequest(input: { method: string; route: string; status: number; durationSeconds: number }): void {\n this.incrementCounter({\n name: \"opengeni_http_requests_total\",\n help: \"Total HTTP requests handled by OpenGeni.\",\n labels: {\n method: input.method,\n route: input.route,\n status: String(input.status),\n component: this.options.component,\n },\n });\n this.observeHistogram({\n name: \"opengeni_http_request_duration_seconds\",\n help: \"HTTP request duration in seconds.\",\n buckets: httpHistogramBuckets,\n value: input.durationSeconds,\n labels: {\n method: input.method,\n route: input.route,\n component: this.options.component,\n },\n });\n }\n\n recordWorkerActivity(input: { activity: string; status: string; durationSeconds: number }): void {\n this.incrementCounter({\n name: \"opengeni_worker_activity_runs_total\",\n help: \"Total worker activity executions.\",\n labels: {\n activity: input.activity,\n status: input.status,\n component: this.options.component,\n },\n });\n this.observeHistogram({\n name: \"opengeni_worker_activity_duration_seconds\",\n help: \"Worker activity duration in seconds.\",\n buckets: durationHistogramBuckets,\n value: input.durationSeconds,\n labels: {\n activity: input.activity,\n component: this.options.component,\n },\n });\n }\n\n incrementCounter(input: { name: string; help?: string; labels?: MetricLabels; amount?: number }): void {\n if (!this.settings.observabilityMetricsEnabled) {\n return;\n }\n const labels = normalizeLabels(input.labels);\n const counter = this.counter(input.name, input.help ?? `${input.name} counter.`, Object.keys(labels));\n counter.inc(labels as never, input.amount ?? 1);\n }\n\n setGauge(input: { name: string; help?: string; labels?: MetricLabels; value: number }): void {\n if (!this.settings.observabilityMetricsEnabled) {\n return;\n }\n const labels = normalizeLabels(input.labels);\n const gauge = this.gauge(input.name, input.help ?? `${input.name} gauge.`, Object.keys(labels));\n gauge.set(labels as never, input.value);\n }\n\n incrementGauge(input: { name: string; help?: string; labels?: MetricLabels; amount?: number }): void {\n if (!this.settings.observabilityMetricsEnabled) {\n return;\n }\n const labels = normalizeLabels(input.labels);\n const gauge = this.gauge(input.name, input.help ?? `${input.name} gauge.`, Object.keys(labels));\n gauge.inc(labels as never, input.amount ?? 1);\n }\n\n observeHistogram(input: { name: string; help?: string; labels?: MetricLabels; value: number; buckets?: number[] }): void {\n if (!this.settings.observabilityMetricsEnabled) {\n return;\n }\n const labels = normalizeLabels(input.labels);\n const histogram = this.histogram(\n input.name,\n input.help ?? `${input.name} histogram.`,\n Object.keys(labels),\n input.buckets ?? durationHistogramBuckets,\n );\n histogram.observe(labels as never, input.value);\n }\n\n async prometheusMetrics(): Promise<string> {\n if (!this.settings.observabilityMetricsEnabled) {\n return \"\";\n }\n return await this.registry.metrics();\n }\n\n private counter(name: string, help: string, labelNames: string[]): Counter<string> {\n const existing = this.counters.get(name);\n if (existing) {\n this.assertRegistration(name, \"counter\", labelNames);\n return existing;\n }\n this.register(name, \"counter\", labelNames);\n const metric = new Counter({ name, help, labelNames, registers: [this.registry] });\n this.counters.set(name, metric);\n return metric;\n }\n\n private gauge(name: string, help: string, labelNames: string[]): Gauge<string> {\n const existing = this.gauges.get(name);\n if (existing) {\n this.assertRegistration(name, \"gauge\", labelNames);\n return existing;\n }\n this.register(name, \"gauge\", labelNames);\n const metric = new Gauge({ name, help, labelNames, registers: [this.registry] });\n this.gauges.set(name, metric);\n return metric;\n }\n\n private histogram(name: string, help: string, labelNames: string[], buckets: number[]): Histogram<string> {\n const existing = this.histograms.get(name);\n if (existing) {\n this.assertRegistration(name, \"histogram\", labelNames);\n return existing;\n }\n this.register(name, \"histogram\", labelNames);\n const metric = new Histogram({ name, help, labelNames, buckets, registers: [this.registry] });\n this.histograms.set(name, metric);\n return metric;\n }\n\n private register(name: string, kind: MetricRegistration[\"kind\"], labelNames: string[]): void {\n const sorted = [...labelNames].sort();\n this.registrations.set(name, { kind, labelNames: sorted });\n }\n\n private assertRegistration(name: string, kind: MetricRegistration[\"kind\"], labelNames: string[]): void {\n const registration = this.registrations.get(name);\n const sorted = [...labelNames].sort();\n if (\n !registration\n || registration.kind !== kind\n || registration.labelNames.length !== sorted.length\n || registration.labelNames.some((label, index) => label !== sorted[index])\n ) {\n throw new Error(\n `Metric ${name} was already registered as ${registration?.kind ?? \"unknown\"} `\n + `with labels [${registration?.labelNames.join(\",\") ?? \"\"}], not ${kind} [${sorted.join(\",\")}]`,\n );\n }\n }\n\n private exportSpan(span: {\n traceId: string;\n spanId: string;\n name: string;\n startMs: number;\n endMs: number;\n attributes: Attributes;\n error?: unknown;\n }): void {\n if (!this.settings.observabilityOtlpEndpoint) {\n return;\n }\n const endpoint = `${this.settings.observabilityOtlpEndpoint.replace(/\\/$/, \"\")}/v1/traces`;\n const body = {\n resourceSpans: [{\n resource: {\n attributes: otlpAttributes(this.resourceAttributes),\n },\n scopeSpans: [{\n scope: {\n name: \"@opengeni/observability\",\n version: \"0.1.0\",\n },\n spans: [{\n traceId: span.traceId,\n spanId: span.spanId,\n name: span.name,\n kind: 1,\n startTimeUnixNano: millisToNanos(span.startMs),\n endTimeUnixNano: millisToNanos(span.endMs),\n attributes: otlpAttributes(span.attributes),\n status: span.error ? { code: 2, message: errorMessage(span.error) } : { code: 1 },\n }],\n }],\n }],\n };\n void this.exporter(endpoint, body, parseHeaders(this.settings.observabilityOtlpHeaders)).catch((error) => {\n this.warn(\"OTLP span export failed\", { error: errorMessage(error), endpoint });\n });\n }\n}\n\nexport type StartupDependencyRetryEvent = {\n label: string;\n attempt: number;\n attempts: number;\n delayMs: number;\n error: unknown;\n};\n\nexport function logStartupDependencyRetry(observability: Observability, event: StartupDependencyRetryEvent): void {\n const message = event.error instanceof Error ? event.error.message : String(event.error);\n observability.warn(\"Startup dependency connection failed; retrying\", {\n dependency: event.label,\n attempt: event.attempt,\n attempts: event.attempts,\n delayMs: event.delayMs,\n error: message,\n });\n}\n\nfunction normalizeLabels(labels: MetricLabels = {}): Record<string, string> {\n return Object.fromEntries(\n Object.entries(labels)\n .filter(([, value]) => value !== undefined && value !== null)\n .map(([key, value]): [string, string] => [key, String(value)])\n .sort((left, right) => left[0].localeCompare(right[0])),\n );\n}\n\nfunction buildVersion(): string {\n return process.env.OPENGENI_VERSION\n ?? process.env.npm_package_version\n ?? \"dev\";\n}\n\nfunction cleanAttributes(attributes: Attributes): Record<string, string | number | boolean | null> {\n return Object.fromEntries(Object.entries(attributes).filter(([, value]) => value !== undefined)) as Record<string, string | number | boolean | null>;\n}\n\nfunction errorToAttributes(error: unknown): Attributes {\n return {\n \"error.type\": error instanceof Error ? error.name : \"Error\",\n \"error.message\": errorMessage(error),\n };\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction otlpAttributes(attributes: Attributes): Array<{ key: string; value: Record<string, string | number | boolean> }> {\n return Object.entries(cleanAttributes(attributes)).map(([key, value]) => ({\n key,\n value: otlpValue(value),\n }));\n}\n\nfunction otlpValue(value: string | number | boolean | null): Record<string, string | number | boolean> {\n if (typeof value === \"number\") {\n return Number.isInteger(value) ? { intValue: value } : { doubleValue: value };\n }\n if (typeof value === \"boolean\") {\n return { boolValue: value };\n }\n return { stringValue: value === null ? \"\" : value };\n}\n\nfunction millisToNanos(ms: number): string {\n return String(BigInt(Math.round(ms)) * 1_000_000n);\n}\n\nfunction randomHex(bytes: number): string {\n const values = crypto.getRandomValues(new Uint8Array(bytes));\n return Array.from(values, (value) => value.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nexport function parseHeaders(value: string): Record<string, string> {\n if (!value.trim()) {\n return {};\n }\n const entries: Array<[string, string]> = value.split(\",\").map((pair): [string, string] => {\n const separator = pair.indexOf(\"=\");\n if (separator === -1) {\n return [pair.trim(), \"\"];\n }\n return [pair.slice(0, separator).trim(), pair.slice(separator + 1).trim()];\n }).filter(([key]) => key.length > 0);\n return Object.fromEntries(entries);\n}\n\nasync function defaultExporter(url: string, body: unknown, headers: Record<string, string>): Promise<void> {\n const response = await fetch(url, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n ...headers,\n },\n body: JSON.stringify(body),\n });\n if (!response.ok) {\n throw new Error(`OTLP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ACpB,aAAO,CAAC,KAAK,KAAK,GAAG,EAAE;AAAA,IACzB;AACA,WAAO,CAAC,KAAK,MAAM,GAAG,SAAS,EAAE,KAAK,GAAG,KAAK,MAAM,YAAY,CAAC,EAAE,KAAK,CAAC;AAAA,EAC3E,CAAC,EAAE,OAAO,CAAC,CAAC,GAAG,MAAM,IAAI,SAAS,CAAC;AACnC,SAAO,OAAO,YAAY,OAAO;AACnC;AAEA,eAAe,gBAAgB,KAAa,MAAe,SAAgD;AACzG,QAAM,WAAW,MAAM,MAAM,KAAK;AAAA,IAChC,QAAQ;AAAA,IACR,SAAS;AAAA,MACP,gBAAgB;AAAA,MAChB,GAAG;AAAA,IACL;AAAA,IACA,MAAM,KAAK,UAAU,IAAI;AAAA,EAC3B,CAAC;AACD,MAAI,CAAC,SAAS,IAAI;AAChB,UAAM,IAAI,MAAM,+BAA+B,SAAS,MAAM,EAAE;AAAA,EAClE;AACF;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@opengeni/observability",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"type": "module",
|
|
5
|
+
"license": "Apache-2.0",
|
|
5
6
|
"main": "./dist/index.js",
|
|
6
7
|
"module": "./dist/index.js",
|
|
7
8
|
"types": "./dist/index.d.ts",
|
|
@@ -21,15 +22,15 @@
|
|
|
21
22
|
},
|
|
22
23
|
"scripts": {
|
|
23
24
|
"build": "tsup",
|
|
24
|
-
"typecheck": "tsc --noEmit"
|
|
25
|
-
|
|
26
|
-
"devDependencies": {
|
|
27
|
-
"tsup": "^8.5.0",
|
|
28
|
-
"typescript": "^6.0.3"
|
|
25
|
+
"typecheck": "tsc --noEmit",
|
|
26
|
+
"prepublishOnly": "bash ../../scripts/prepublish-guard"
|
|
29
27
|
},
|
|
30
28
|
"repository": {
|
|
31
29
|
"type": "git",
|
|
32
30
|
"url": "git+https://github.com/Cloudgeni-ai/opengeni.git",
|
|
33
31
|
"directory": "packages/observability"
|
|
32
|
+
},
|
|
33
|
+
"dependencies": {
|
|
34
|
+
"prom-client": "^15.1.3"
|
|
34
35
|
}
|
|
35
36
|
}
|
package/src/index.ts
CHANGED
|
@@ -1,9 +1,18 @@
|
|
|
1
|
+
import {
|
|
2
|
+
collectDefaultMetrics,
|
|
3
|
+
Counter,
|
|
4
|
+
Gauge,
|
|
5
|
+
Histogram,
|
|
6
|
+
Registry,
|
|
7
|
+
} from "prom-client";
|
|
8
|
+
|
|
1
9
|
export type AttributeValue = string | number | boolean | null | undefined;
|
|
2
10
|
export type Attributes = Record<string, AttributeValue>;
|
|
3
11
|
|
|
4
12
|
export type ObservabilitySettings = {
|
|
5
13
|
serviceName: string;
|
|
6
14
|
environment: string;
|
|
15
|
+
deploymentRevision?: string | undefined;
|
|
7
16
|
observabilityStructuredLogs: boolean;
|
|
8
17
|
observabilityMetricsEnabled: boolean;
|
|
9
18
|
observabilityOtlpEndpoint?: string | undefined;
|
|
@@ -22,14 +31,26 @@ export type Span = {
|
|
|
22
31
|
end: (input?: { attributes?: Attributes; error?: unknown }) => void;
|
|
23
32
|
};
|
|
24
33
|
|
|
25
|
-
|
|
34
|
+
export type MetricLabels = Record<string, AttributeValue>;
|
|
35
|
+
|
|
36
|
+
const httpHistogramBuckets = [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10];
|
|
37
|
+
const durationHistogramBuckets = [0.01, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60, 120, 300, 900, 1800, 3600];
|
|
26
38
|
|
|
27
39
|
export function createObservability(settings: ObservabilitySettings, options: ObservabilityOptions): Observability {
|
|
28
40
|
return new Observability(settings, options);
|
|
29
41
|
}
|
|
30
42
|
|
|
43
|
+
type MetricRegistration = {
|
|
44
|
+
kind: "counter" | "gauge" | "histogram";
|
|
45
|
+
labelNames: string[];
|
|
46
|
+
};
|
|
47
|
+
|
|
31
48
|
export class Observability {
|
|
32
|
-
private readonly
|
|
49
|
+
private readonly registry = new Registry();
|
|
50
|
+
private readonly counters = new Map<string, Counter<string>>();
|
|
51
|
+
private readonly gauges = new Map<string, Gauge<string>>();
|
|
52
|
+
private readonly histograms = new Map<string, Histogram<string>>();
|
|
53
|
+
private readonly registrations = new Map<string, MetricRegistration>();
|
|
33
54
|
private readonly now: () => number;
|
|
34
55
|
private readonly exporter: (url: string, body: unknown, headers: Record<string, string>) => Promise<void>;
|
|
35
56
|
private readonly resourceAttributes: Attributes;
|
|
@@ -42,6 +63,27 @@ export class Observability {
|
|
|
42
63
|
"deployment.environment": settings.environment,
|
|
43
64
|
"opengeni.component": options.component,
|
|
44
65
|
};
|
|
66
|
+
this.registry.setDefaultLabels({
|
|
67
|
+
service: settings.serviceName,
|
|
68
|
+
environment: settings.environment,
|
|
69
|
+
component: options.component,
|
|
70
|
+
});
|
|
71
|
+
if (settings.observabilityMetricsEnabled) {
|
|
72
|
+
collectDefaultMetrics({ register: this.registry, prefix: "opengeni_" });
|
|
73
|
+
this.setGauge({
|
|
74
|
+
name: "opengeni_build_info",
|
|
75
|
+
help: "OpenGeni build information.",
|
|
76
|
+
labels: {
|
|
77
|
+
version: buildVersion(),
|
|
78
|
+
revision: settings.deploymentRevision ?? "dev",
|
|
79
|
+
},
|
|
80
|
+
value: 1,
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
debug(message: string, attributes: Attributes = {}): void {
|
|
86
|
+
this.log("debug", message, attributes);
|
|
45
87
|
}
|
|
46
88
|
|
|
47
89
|
info(message: string, attributes: Attributes = {}): void {
|
|
@@ -119,45 +161,154 @@ export class Observability {
|
|
|
119
161
|
}
|
|
120
162
|
|
|
121
163
|
recordHttpRequest(input: { method: string; route: string; status: number; durationSeconds: number }): void {
|
|
164
|
+
this.incrementCounter({
|
|
165
|
+
name: "opengeni_http_requests_total",
|
|
166
|
+
help: "Total HTTP requests handled by OpenGeni.",
|
|
167
|
+
labels: {
|
|
168
|
+
method: input.method,
|
|
169
|
+
route: input.route,
|
|
170
|
+
status: String(input.status),
|
|
171
|
+
component: this.options.component,
|
|
172
|
+
},
|
|
173
|
+
});
|
|
174
|
+
this.observeHistogram({
|
|
175
|
+
name: "opengeni_http_request_duration_seconds",
|
|
176
|
+
help: "HTTP request duration in seconds.",
|
|
177
|
+
buckets: httpHistogramBuckets,
|
|
178
|
+
value: input.durationSeconds,
|
|
179
|
+
labels: {
|
|
180
|
+
method: input.method,
|
|
181
|
+
route: input.route,
|
|
182
|
+
component: this.options.component,
|
|
183
|
+
},
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
recordWorkerActivity(input: { activity: string; status: string; durationSeconds: number }): void {
|
|
188
|
+
this.incrementCounter({
|
|
189
|
+
name: "opengeni_worker_activity_runs_total",
|
|
190
|
+
help: "Total worker activity executions.",
|
|
191
|
+
labels: {
|
|
192
|
+
activity: input.activity,
|
|
193
|
+
status: input.status,
|
|
194
|
+
component: this.options.component,
|
|
195
|
+
},
|
|
196
|
+
});
|
|
197
|
+
this.observeHistogram({
|
|
198
|
+
name: "opengeni_worker_activity_duration_seconds",
|
|
199
|
+
help: "Worker activity duration in seconds.",
|
|
200
|
+
buckets: durationHistogramBuckets,
|
|
201
|
+
value: input.durationSeconds,
|
|
202
|
+
labels: {
|
|
203
|
+
activity: input.activity,
|
|
204
|
+
component: this.options.component,
|
|
205
|
+
},
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
incrementCounter(input: { name: string; help?: string; labels?: MetricLabels; amount?: number }): void {
|
|
122
210
|
if (!this.settings.observabilityMetricsEnabled) {
|
|
123
211
|
return;
|
|
124
212
|
}
|
|
125
|
-
const labels =
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
status: String(input.status),
|
|
129
|
-
component: this.options.component,
|
|
130
|
-
};
|
|
131
|
-
this.metrics.increment("opengeni_http_requests_total", labels);
|
|
132
|
-
this.metrics.observe("opengeni_http_request_duration_seconds", histogramBuckets, input.durationSeconds, {
|
|
133
|
-
method: input.method,
|
|
134
|
-
route: input.route,
|
|
135
|
-
component: this.options.component,
|
|
136
|
-
});
|
|
213
|
+
const labels = normalizeLabels(input.labels);
|
|
214
|
+
const counter = this.counter(input.name, input.help ?? `${input.name} counter.`, Object.keys(labels));
|
|
215
|
+
counter.inc(labels as never, input.amount ?? 1);
|
|
137
216
|
}
|
|
138
217
|
|
|
139
|
-
|
|
218
|
+
setGauge(input: { name: string; help?: string; labels?: MetricLabels; value: number }): void {
|
|
140
219
|
if (!this.settings.observabilityMetricsEnabled) {
|
|
141
220
|
return;
|
|
142
221
|
}
|
|
143
|
-
const labels =
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
component: this.options.component,
|
|
147
|
-
};
|
|
148
|
-
this.metrics.increment("opengeni_worker_activity_runs_total", labels);
|
|
149
|
-
this.metrics.observe("opengeni_worker_activity_duration_seconds", histogramBuckets, input.durationSeconds, {
|
|
150
|
-
activity: input.activity,
|
|
151
|
-
component: this.options.component,
|
|
152
|
-
});
|
|
222
|
+
const labels = normalizeLabels(input.labels);
|
|
223
|
+
const gauge = this.gauge(input.name, input.help ?? `${input.name} gauge.`, Object.keys(labels));
|
|
224
|
+
gauge.set(labels as never, input.value);
|
|
153
225
|
}
|
|
154
226
|
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
});
|
|
227
|
+
incrementGauge(input: { name: string; help?: string; labels?: MetricLabels; amount?: number }): void {
|
|
228
|
+
if (!this.settings.observabilityMetricsEnabled) {
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
const labels = normalizeLabels(input.labels);
|
|
232
|
+
const gauge = this.gauge(input.name, input.help ?? `${input.name} gauge.`, Object.keys(labels));
|
|
233
|
+
gauge.inc(labels as never, input.amount ?? 1);
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
observeHistogram(input: { name: string; help?: string; labels?: MetricLabels; value: number; buckets?: number[] }): void {
|
|
237
|
+
if (!this.settings.observabilityMetricsEnabled) {
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
const labels = normalizeLabels(input.labels);
|
|
241
|
+
const histogram = this.histogram(
|
|
242
|
+
input.name,
|
|
243
|
+
input.help ?? `${input.name} histogram.`,
|
|
244
|
+
Object.keys(labels),
|
|
245
|
+
input.buckets ?? durationHistogramBuckets,
|
|
246
|
+
);
|
|
247
|
+
histogram.observe(labels as never, input.value);
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
async prometheusMetrics(): Promise<string> {
|
|
251
|
+
if (!this.settings.observabilityMetricsEnabled) {
|
|
252
|
+
return "";
|
|
253
|
+
}
|
|
254
|
+
return await this.registry.metrics();
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
private counter(name: string, help: string, labelNames: string[]): Counter<string> {
|
|
258
|
+
const existing = this.counters.get(name);
|
|
259
|
+
if (existing) {
|
|
260
|
+
this.assertRegistration(name, "counter", labelNames);
|
|
261
|
+
return existing;
|
|
262
|
+
}
|
|
263
|
+
this.register(name, "counter", labelNames);
|
|
264
|
+
const metric = new Counter({ name, help, labelNames, registers: [this.registry] });
|
|
265
|
+
this.counters.set(name, metric);
|
|
266
|
+
return metric;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
private gauge(name: string, help: string, labelNames: string[]): Gauge<string> {
|
|
270
|
+
const existing = this.gauges.get(name);
|
|
271
|
+
if (existing) {
|
|
272
|
+
this.assertRegistration(name, "gauge", labelNames);
|
|
273
|
+
return existing;
|
|
274
|
+
}
|
|
275
|
+
this.register(name, "gauge", labelNames);
|
|
276
|
+
const metric = new Gauge({ name, help, labelNames, registers: [this.registry] });
|
|
277
|
+
this.gauges.set(name, metric);
|
|
278
|
+
return metric;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
private histogram(name: string, help: string, labelNames: string[], buckets: number[]): Histogram<string> {
|
|
282
|
+
const existing = this.histograms.get(name);
|
|
283
|
+
if (existing) {
|
|
284
|
+
this.assertRegistration(name, "histogram", labelNames);
|
|
285
|
+
return existing;
|
|
286
|
+
}
|
|
287
|
+
this.register(name, "histogram", labelNames);
|
|
288
|
+
const metric = new Histogram({ name, help, labelNames, buckets, registers: [this.registry] });
|
|
289
|
+
this.histograms.set(name, metric);
|
|
290
|
+
return metric;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
private register(name: string, kind: MetricRegistration["kind"], labelNames: string[]): void {
|
|
294
|
+
const sorted = [...labelNames].sort();
|
|
295
|
+
this.registrations.set(name, { kind, labelNames: sorted });
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
private assertRegistration(name: string, kind: MetricRegistration["kind"], labelNames: string[]): void {
|
|
299
|
+
const registration = this.registrations.get(name);
|
|
300
|
+
const sorted = [...labelNames].sort();
|
|
301
|
+
if (
|
|
302
|
+
!registration
|
|
303
|
+
|| registration.kind !== kind
|
|
304
|
+
|| registration.labelNames.length !== sorted.length
|
|
305
|
+
|| registration.labelNames.some((label, index) => label !== sorted[index])
|
|
306
|
+
) {
|
|
307
|
+
throw new Error(
|
|
308
|
+
`Metric ${name} was already registered as ${registration?.kind ?? "unknown"} `
|
|
309
|
+
+ `with labels [${registration?.labelNames.join(",") ?? ""}], not ${kind} [${sorted.join(",")}]`,
|
|
310
|
+
);
|
|
311
|
+
}
|
|
161
312
|
}
|
|
162
313
|
|
|
163
314
|
private exportSpan(span: {
|
|
@@ -221,85 +372,19 @@ export function logStartupDependencyRetry(observability: Observability, event: S
|
|
|
221
372
|
});
|
|
222
373
|
}
|
|
223
374
|
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
observe(name: string, buckets: number[], value: number, labels: Record<string, string>): void {
|
|
234
|
-
const key = metricKey(name, labels);
|
|
235
|
-
const histogram = this.histograms.get(key) ?? {
|
|
236
|
-
buckets,
|
|
237
|
-
counts: buckets.map(() => 0),
|
|
238
|
-
sum: 0,
|
|
239
|
-
count: 0,
|
|
240
|
-
labels,
|
|
241
|
-
};
|
|
242
|
-
histogram.sum += value;
|
|
243
|
-
histogram.count += 1;
|
|
244
|
-
for (let index = 0; index < buckets.length; index += 1) {
|
|
245
|
-
if (value <= buckets[index]!) {
|
|
246
|
-
histogram.counts[index] = (histogram.counts[index] ?? 0) + 1;
|
|
247
|
-
}
|
|
248
|
-
}
|
|
249
|
-
this.histograms.set(key, histogram);
|
|
250
|
-
}
|
|
251
|
-
|
|
252
|
-
toPrometheus(resourceLabels: Record<string, string>): string {
|
|
253
|
-
const lines = [
|
|
254
|
-
"# HELP opengeni_http_requests_total Total HTTP requests handled by the OpenGeni API.",
|
|
255
|
-
"# TYPE opengeni_http_requests_total counter",
|
|
256
|
-
];
|
|
257
|
-
for (const [key, value] of this.counters) {
|
|
258
|
-
const { name, labels } = parseMetricKey(key);
|
|
259
|
-
if (name.endsWith("_total")) {
|
|
260
|
-
lines.push(`${name}${formatLabels({ ...resourceLabels, ...labels })} ${value}`);
|
|
261
|
-
}
|
|
262
|
-
}
|
|
263
|
-
lines.push(
|
|
264
|
-
"# HELP opengeni_http_request_duration_seconds HTTP request duration in seconds.",
|
|
265
|
-
"# TYPE opengeni_http_request_duration_seconds histogram",
|
|
266
|
-
"# HELP opengeni_worker_activity_runs_total Total worker activity executions.",
|
|
267
|
-
"# TYPE opengeni_worker_activity_runs_total counter",
|
|
268
|
-
"# HELP opengeni_worker_activity_duration_seconds Worker activity duration in seconds.",
|
|
269
|
-
"# TYPE opengeni_worker_activity_duration_seconds histogram",
|
|
270
|
-
);
|
|
271
|
-
for (const [key, histogram] of this.histograms) {
|
|
272
|
-
const { name, labels } = parseMetricKey(key);
|
|
273
|
-
const baseLabels = { ...resourceLabels, ...labels };
|
|
274
|
-
for (let index = 0; index < histogram.buckets.length; index += 1) {
|
|
275
|
-
lines.push(`${name}_bucket${formatLabels({ ...baseLabels, le: String(histogram.buckets[index]) })} ${histogram.counts[index]}`);
|
|
276
|
-
}
|
|
277
|
-
lines.push(`${name}_bucket${formatLabels({ ...baseLabels, le: "+Inf" })} ${histogram.count}`);
|
|
278
|
-
lines.push(`${name}_sum${formatLabels(baseLabels)} ${histogram.sum}`);
|
|
279
|
-
lines.push(`${name}_count${formatLabels(baseLabels)} ${histogram.count}`);
|
|
280
|
-
}
|
|
281
|
-
return `${lines.join("\n")}\n`;
|
|
282
|
-
}
|
|
283
|
-
}
|
|
284
|
-
|
|
285
|
-
function metricKey(name: string, labels: Record<string, string>): string {
|
|
286
|
-
return JSON.stringify({ name, labels: Object.fromEntries(Object.entries(labels).sort(([a], [b]) => a.localeCompare(b))) });
|
|
287
|
-
}
|
|
288
|
-
|
|
289
|
-
function parseMetricKey(key: string): { name: string; labels: Record<string, string> } {
|
|
290
|
-
return JSON.parse(key) as { name: string; labels: Record<string, string> };
|
|
291
|
-
}
|
|
292
|
-
|
|
293
|
-
function formatLabels(labels: Record<string, string>): string {
|
|
294
|
-
const entries = Object.entries(labels).filter(([, value]) => value.length > 0);
|
|
295
|
-
if (entries.length === 0) {
|
|
296
|
-
return "";
|
|
297
|
-
}
|
|
298
|
-
return `{${entries.map(([key, value]) => `${key}="${escapeMetricLabel(value)}"`).join(",")}}`;
|
|
375
|
+
function normalizeLabels(labels: MetricLabels = {}): Record<string, string> {
|
|
376
|
+
return Object.fromEntries(
|
|
377
|
+
Object.entries(labels)
|
|
378
|
+
.filter(([, value]) => value !== undefined && value !== null)
|
|
379
|
+
.map(([key, value]): [string, string] => [key, String(value)])
|
|
380
|
+
.sort((left, right) => left[0].localeCompare(right[0])),
|
|
381
|
+
);
|
|
299
382
|
}
|
|
300
383
|
|
|
301
|
-
function
|
|
302
|
-
return
|
|
384
|
+
function buildVersion(): string {
|
|
385
|
+
return process.env.OPENGENI_VERSION
|
|
386
|
+
?? process.env.npm_package_version
|
|
387
|
+
?? "dev";
|
|
303
388
|
}
|
|
304
389
|
|
|
305
390
|
function cleanAttributes(attributes: Attributes): Record<string, string | number | boolean | null> {
|