cloudflare-worker-metrics 1.0.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 +201 -0
- package/README.md +55 -0
- package/dist/exporter.d.ts +86 -0
- package/dist/exporter.js +151 -0
- package/dist/index.d.ts +27 -0
- package/dist/index.js +135 -0
- package/dist/types-D3Z3Eir6.d.ts +21 -0
- package/package.json +38 -0
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 2026 Tempo Contributors
|
|
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
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
# cloudflare-worker-metrics
|
|
2
|
+
|
|
3
|
+
Lightweight metrics collection for Cloudflare Workers with OTEL export via LogPush + R2.
|
|
4
|
+
|
|
5
|
+
## Worker-side usage
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import { metrics } from 'cloudflare-worker-metrics';
|
|
9
|
+
|
|
10
|
+
export default {
|
|
11
|
+
async fetch(request, env, ctx) {
|
|
12
|
+
metrics.count('http.requests', 1, { method: request.method });
|
|
13
|
+
metrics.gauge('connections.active', getActiveCount());
|
|
14
|
+
metrics.histogram('response.duration', elapsed, {
|
|
15
|
+
percentiles: [0.5, 0.95, 0.99],
|
|
16
|
+
aggregates: ['avg', 'max'],
|
|
17
|
+
}, { endpoint: '/api' });
|
|
18
|
+
|
|
19
|
+
const response = await handleRequest(request);
|
|
20
|
+
metrics.flush();
|
|
21
|
+
return response;
|
|
22
|
+
},
|
|
23
|
+
};
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
## Exporter (scheduled worker)
|
|
27
|
+
|
|
28
|
+
```ts
|
|
29
|
+
import { MetricsExporter } from 'cloudflare-worker-metrics/exporter';
|
|
30
|
+
|
|
31
|
+
export default new MetricsExporter({
|
|
32
|
+
endpoint: 'https://otel-collector.example.com/v1/metrics',
|
|
33
|
+
headers: { Authorization: 'Bearer TOKEN' },
|
|
34
|
+
r2Prefix: 'workers-logs/',
|
|
35
|
+
resourceAttributes: { 'service.name': 'my-worker' },
|
|
36
|
+
});
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Configure a Cloudflare LogPush job to write Workers Trace Events to the R2 bucket bound as `METRICS_BUCKET`, then set a cron trigger to run the exporter on a schedule.
|
|
40
|
+
|
|
41
|
+
## API
|
|
42
|
+
|
|
43
|
+
### `metrics.count(name, value?, tags?)`
|
|
44
|
+
Increment a counter. Values with the same name+tags are summed.
|
|
45
|
+
|
|
46
|
+
### `metrics.gauge(name, value, tags?)`
|
|
47
|
+
Set a gauge. Last write wins for the same name+tags.
|
|
48
|
+
|
|
49
|
+
### `metrics.histogram(name, value, options?, tags?)`
|
|
50
|
+
Record a histogram observation. Expanded into percentile/aggregate metrics at flush time.
|
|
51
|
+
- `options.percentiles`: e.g. `[0.5, 0.95, 0.99]` → `name.p50`, `name.p95`, `name.p99`
|
|
52
|
+
- `options.aggregates`: e.g. `['min', 'max', 'avg', 'sum', 'median', 'count']`
|
|
53
|
+
|
|
54
|
+
### `metrics.flush()`
|
|
55
|
+
Flush all metrics to `console.log` as `cwm-` prefixed JSON. Auto-splits at 250 KiB.
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { M as MetricEntry } from './types-D3Z3Eir6.js';
|
|
2
|
+
|
|
3
|
+
interface OtelAttribute {
|
|
4
|
+
key: string;
|
|
5
|
+
value: {
|
|
6
|
+
stringValue: string;
|
|
7
|
+
} | {
|
|
8
|
+
doubleValue: number;
|
|
9
|
+
} | {
|
|
10
|
+
boolValue: boolean;
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
interface OtelDataPoint {
|
|
14
|
+
asDouble: number;
|
|
15
|
+
timeUnixNano: string;
|
|
16
|
+
startTimeUnixNano?: string;
|
|
17
|
+
attributes: OtelAttribute[];
|
|
18
|
+
}
|
|
19
|
+
interface OtelMetric {
|
|
20
|
+
name: string;
|
|
21
|
+
sum?: {
|
|
22
|
+
dataPoints: OtelDataPoint[];
|
|
23
|
+
aggregationTemporality: number;
|
|
24
|
+
isMonotonic: boolean;
|
|
25
|
+
};
|
|
26
|
+
gauge?: {
|
|
27
|
+
dataPoints: OtelDataPoint[];
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
interface OtelExportRequest {
|
|
31
|
+
resourceMetrics: Array<{
|
|
32
|
+
resource: {
|
|
33
|
+
attributes: OtelAttribute[];
|
|
34
|
+
};
|
|
35
|
+
scopeMetrics: Array<{
|
|
36
|
+
scope: {
|
|
37
|
+
name: string;
|
|
38
|
+
version: string;
|
|
39
|
+
};
|
|
40
|
+
metrics: OtelMetric[];
|
|
41
|
+
}>;
|
|
42
|
+
}>;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Convert an array of MetricEntry records into an OTEL-compatible export request.
|
|
46
|
+
* Re-aggregates: counters with same name+tags are summed; gauges keep latest value.
|
|
47
|
+
*/
|
|
48
|
+
declare function toOtelPayload(entries: MetricEntry[], resourceAttrs?: Record<string, string>): OtelExportRequest;
|
|
49
|
+
|
|
50
|
+
interface ExporterConfig {
|
|
51
|
+
/** OTLP/HTTP JSON endpoint, e.g. "https://otel.example.com/v1/metrics" */
|
|
52
|
+
endpoint: string;
|
|
53
|
+
/** Extra headers (e.g. auth tokens). */
|
|
54
|
+
headers?: Record<string, string>;
|
|
55
|
+
/** R2 key prefix for LogPush files. Default: '' */
|
|
56
|
+
r2Prefix?: string;
|
|
57
|
+
/** Env binding name for the R2 bucket. Default: 'METRICS_BUCKET' */
|
|
58
|
+
bucketBinding?: string;
|
|
59
|
+
/** Delete R2 objects after successful export. Default: true */
|
|
60
|
+
deleteAfterExport?: boolean;
|
|
61
|
+
/** OTEL resource attributes (e.g. service.name). */
|
|
62
|
+
resourceAttributes?: Record<string, string>;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Scheduled worker that reads cwm- log entries from R2 (via LogPush)
|
|
66
|
+
* and exports them as OTEL-compatible metrics.
|
|
67
|
+
*
|
|
68
|
+
* Usage:
|
|
69
|
+
* ```ts
|
|
70
|
+
* import { MetricsExporter } from 'cloudflare-worker-metrics/exporter';
|
|
71
|
+
* export default new MetricsExporter({ endpoint: '...' });
|
|
72
|
+
* ```
|
|
73
|
+
*/
|
|
74
|
+
declare class MetricsExporter {
|
|
75
|
+
private endpoint;
|
|
76
|
+
private headers;
|
|
77
|
+
private r2Prefix;
|
|
78
|
+
private bucketBinding;
|
|
79
|
+
private deleteAfterExport;
|
|
80
|
+
private resourceAttributes;
|
|
81
|
+
constructor(cfg: ExporterConfig);
|
|
82
|
+
scheduled(_controller: unknown, env: Record<string, unknown>, _ctx: unknown): Promise<void>;
|
|
83
|
+
private readAll;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export { type ExporterConfig, MetricEntry, MetricsExporter, type OtelAttribute, type OtelDataPoint, type OtelExportRequest, type OtelMetric, toOtelPayload };
|
package/dist/exporter.js
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
// src/otel.ts
|
|
2
|
+
function tagsToAttributes(tags) {
|
|
3
|
+
const attrs = [];
|
|
4
|
+
for (const key of Object.keys(tags)) {
|
|
5
|
+
const val = tags[key];
|
|
6
|
+
if (val == null) continue;
|
|
7
|
+
if (typeof val === "string") attrs.push({ key, value: { stringValue: val } });
|
|
8
|
+
else if (typeof val === "boolean") attrs.push({ key, value: { boolValue: val } });
|
|
9
|
+
else attrs.push({ key, value: { doubleValue: val } });
|
|
10
|
+
}
|
|
11
|
+
return attrs;
|
|
12
|
+
}
|
|
13
|
+
function msToNano(ms) {
|
|
14
|
+
return (BigInt(ms) * 1000000n).toString();
|
|
15
|
+
}
|
|
16
|
+
function toOtelPayload(entries, resourceAttrs = {}) {
|
|
17
|
+
const groups = /* @__PURE__ */ new Map();
|
|
18
|
+
for (const e of entries) {
|
|
19
|
+
const key = `${e.t}:${e.n}`;
|
|
20
|
+
const g = groups.get(key);
|
|
21
|
+
if (g) g.entries.push(e);
|
|
22
|
+
else groups.set(key, { type: e.t, entries: [e] });
|
|
23
|
+
}
|
|
24
|
+
const metrics = [];
|
|
25
|
+
for (const { type, entries: groupEntries } of groups.values()) {
|
|
26
|
+
const byTags = /* @__PURE__ */ new Map();
|
|
27
|
+
for (const e of groupEntries) {
|
|
28
|
+
const tk = Object.keys(e.tags).sort().map((k) => `${k}=${e.tags[k]}`).join(",");
|
|
29
|
+
const existing = byTags.get(tk);
|
|
30
|
+
if (existing) existing.items.push(e);
|
|
31
|
+
else byTags.set(tk, { items: [e], tags: e.tags });
|
|
32
|
+
}
|
|
33
|
+
const name = groupEntries[0].n;
|
|
34
|
+
if (type === "c") {
|
|
35
|
+
const dataPoints = [];
|
|
36
|
+
for (const { items, tags } of byTags.values()) {
|
|
37
|
+
const sum = items.reduce((a, e) => a + e.v, 0);
|
|
38
|
+
const minTs = Math.min(...items.map((e) => e.ts));
|
|
39
|
+
const maxTs = Math.max(...items.map((e) => e.ts));
|
|
40
|
+
dataPoints.push({
|
|
41
|
+
asDouble: sum,
|
|
42
|
+
startTimeUnixNano: msToNano(minTs),
|
|
43
|
+
timeUnixNano: msToNano(maxTs),
|
|
44
|
+
attributes: tagsToAttributes(tags)
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
metrics.push({
|
|
48
|
+
name,
|
|
49
|
+
sum: { dataPoints, aggregationTemporality: 1, isMonotonic: true }
|
|
50
|
+
});
|
|
51
|
+
} else {
|
|
52
|
+
const dataPoints = [];
|
|
53
|
+
for (const { items, tags } of byTags.values()) {
|
|
54
|
+
let latest = items[0];
|
|
55
|
+
for (let i = 1; i < items.length; i++) {
|
|
56
|
+
if (items[i].ts >= latest.ts) latest = items[i];
|
|
57
|
+
}
|
|
58
|
+
dataPoints.push({
|
|
59
|
+
asDouble: latest.v,
|
|
60
|
+
timeUnixNano: msToNano(latest.ts),
|
|
61
|
+
attributes: tagsToAttributes(tags)
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
metrics.push({ name, gauge: { dataPoints } });
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return {
|
|
68
|
+
resourceMetrics: [{
|
|
69
|
+
resource: {
|
|
70
|
+
attributes: Object.entries(resourceAttrs).map(([key, val]) => ({
|
|
71
|
+
key,
|
|
72
|
+
value: { stringValue: val }
|
|
73
|
+
}))
|
|
74
|
+
},
|
|
75
|
+
scopeMetrics: [{
|
|
76
|
+
scope: { name: "cloudflare-worker-metrics", version: "1.0.0" },
|
|
77
|
+
metrics
|
|
78
|
+
}]
|
|
79
|
+
}]
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// src/exporter.ts
|
|
84
|
+
var MetricsExporter = class {
|
|
85
|
+
endpoint;
|
|
86
|
+
headers;
|
|
87
|
+
r2Prefix;
|
|
88
|
+
bucketBinding;
|
|
89
|
+
deleteAfterExport;
|
|
90
|
+
resourceAttributes;
|
|
91
|
+
constructor(cfg) {
|
|
92
|
+
this.endpoint = cfg.endpoint;
|
|
93
|
+
this.headers = cfg.headers ?? {};
|
|
94
|
+
this.r2Prefix = cfg.r2Prefix ?? "";
|
|
95
|
+
this.bucketBinding = cfg.bucketBinding ?? "METRICS_BUCKET";
|
|
96
|
+
this.deleteAfterExport = cfg.deleteAfterExport ?? true;
|
|
97
|
+
this.resourceAttributes = cfg.resourceAttributes ?? {};
|
|
98
|
+
}
|
|
99
|
+
async scheduled(_controller, env, _ctx) {
|
|
100
|
+
const bucket = env[this.bucketBinding];
|
|
101
|
+
const { metrics, keys } = await this.readAll(bucket);
|
|
102
|
+
if (!metrics.length) return;
|
|
103
|
+
const payload = toOtelPayload(metrics, this.resourceAttributes);
|
|
104
|
+
const res = await fetch(this.endpoint, {
|
|
105
|
+
method: "POST",
|
|
106
|
+
headers: { "Content-Type": "application/json", ...this.headers },
|
|
107
|
+
body: JSON.stringify(payload)
|
|
108
|
+
});
|
|
109
|
+
if (!res.ok) {
|
|
110
|
+
throw new Error(`OTEL export failed: ${res.status} ${await res.text()}`);
|
|
111
|
+
}
|
|
112
|
+
if (this.deleteAfterExport) {
|
|
113
|
+
for (const key of keys) await bucket.delete(key);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
async readAll(bucket) {
|
|
117
|
+
const metrics = [];
|
|
118
|
+
const keys = [];
|
|
119
|
+
let cursor;
|
|
120
|
+
do {
|
|
121
|
+
const listed = await bucket.list({ prefix: this.r2Prefix || void 0, cursor });
|
|
122
|
+
for (const obj of listed.objects) {
|
|
123
|
+
keys.push(obj.key);
|
|
124
|
+
const body = await bucket.get(obj.key);
|
|
125
|
+
if (!body) continue;
|
|
126
|
+
const text = obj.key.endsWith(".gz") ? await new Response(body.body.pipeThrough(new DecompressionStream("gzip"))).text() : await body.text();
|
|
127
|
+
for (const line of text.split("\n")) {
|
|
128
|
+
if (!line) continue;
|
|
129
|
+
try {
|
|
130
|
+
const event = JSON.parse(line);
|
|
131
|
+
if (!event.Logs) continue;
|
|
132
|
+
for (const log of event.Logs) {
|
|
133
|
+
const msg = Array.isArray(log.Message) ? log.Message[0] : log.Message;
|
|
134
|
+
if (typeof msg === "string" && msg.startsWith("cwm-")) {
|
|
135
|
+
const parsed = JSON.parse(msg.slice(4));
|
|
136
|
+
if (Array.isArray(parsed)) metrics.push(...parsed);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
} catch {
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
cursor = listed.truncated ? listed.cursor : void 0;
|
|
144
|
+
} while (cursor);
|
|
145
|
+
return { metrics, keys };
|
|
146
|
+
}
|
|
147
|
+
};
|
|
148
|
+
export {
|
|
149
|
+
MetricsExporter,
|
|
150
|
+
toOtelPayload
|
|
151
|
+
};
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { T as Tags, H as HistogramOptions } from './types-D3Z3Eir6.js';
|
|
2
|
+
export { a as HistogramAgg, M as MetricEntry } from './types-D3Z3Eir6.js';
|
|
3
|
+
|
|
4
|
+
declare class Metrics {
|
|
5
|
+
private c;
|
|
6
|
+
private g;
|
|
7
|
+
private h;
|
|
8
|
+
/** Build a stable dedup key from name + sorted tags. */
|
|
9
|
+
private k;
|
|
10
|
+
/** Increment a counter. Values with the same name+tags are summed. */
|
|
11
|
+
count(name: string, value?: number, tags?: Tags): void;
|
|
12
|
+
/** Set a gauge. Last write wins for the same name+tags. */
|
|
13
|
+
gauge(name: string, value: number, tags?: Tags): void;
|
|
14
|
+
/** Record a histogram observation. Expanded into percentile/aggregate metrics at flush. */
|
|
15
|
+
histogram(name: string, value: number, options?: HistogramOptions, tags?: Tags): void;
|
|
16
|
+
/**
|
|
17
|
+
* Flush all accumulated metrics to console.log as "cwm-" prefixed JSON.
|
|
18
|
+
* Splits into multiple entries if the payload exceeds 250 KiB.
|
|
19
|
+
* Clears all internal state after flushing.
|
|
20
|
+
*/
|
|
21
|
+
flush(): void;
|
|
22
|
+
private emit;
|
|
23
|
+
}
|
|
24
|
+
/** Default singleton instance. */
|
|
25
|
+
declare const metrics: Metrics;
|
|
26
|
+
|
|
27
|
+
export { HistogramOptions, Metrics, Tags, metrics };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
var MAX_SIZE = 250 * 1024;
|
|
3
|
+
var Metrics = class {
|
|
4
|
+
c = /* @__PURE__ */ new Map();
|
|
5
|
+
g = /* @__PURE__ */ new Map();
|
|
6
|
+
h = /* @__PURE__ */ new Map();
|
|
7
|
+
/** Build a stable dedup key from name + sorted tags. */
|
|
8
|
+
k(name, tags) {
|
|
9
|
+
let s = name;
|
|
10
|
+
const keys = Object.keys(tags).sort();
|
|
11
|
+
for (let i = 0; i < keys.length; i++) s += "\0" + keys[i] + "\0" + tags[keys[i]];
|
|
12
|
+
return s;
|
|
13
|
+
}
|
|
14
|
+
/** Increment a counter. Values with the same name+tags are summed. */
|
|
15
|
+
count(name, value = 1, tags = {}) {
|
|
16
|
+
const k = this.k(name, tags);
|
|
17
|
+
const e = this.c.get(k);
|
|
18
|
+
if (e) e.v += value;
|
|
19
|
+
else this.c.set(k, { n: name, v: value, tags });
|
|
20
|
+
}
|
|
21
|
+
/** Set a gauge. Last write wins for the same name+tags. */
|
|
22
|
+
gauge(name, value, tags = {}) {
|
|
23
|
+
this.g.set(this.k(name, tags), { n: name, v: value, tags });
|
|
24
|
+
}
|
|
25
|
+
/** Record a histogram observation. Expanded into percentile/aggregate metrics at flush. */
|
|
26
|
+
histogram(name, value, options = {}, tags = {}) {
|
|
27
|
+
const k = this.k(name, tags);
|
|
28
|
+
const e = this.h.get(k);
|
|
29
|
+
if (e) {
|
|
30
|
+
e.vs.push(value);
|
|
31
|
+
if (options.percentiles) {
|
|
32
|
+
const set = new Set(e.opts.percentiles);
|
|
33
|
+
for (const p of options.percentiles) set.add(p);
|
|
34
|
+
e.opts.percentiles = [...set];
|
|
35
|
+
}
|
|
36
|
+
if (options.aggregates) {
|
|
37
|
+
const set = new Set(e.opts.aggregates);
|
|
38
|
+
for (const a of options.aggregates) set.add(a);
|
|
39
|
+
e.opts.aggregates = [...set];
|
|
40
|
+
}
|
|
41
|
+
} else {
|
|
42
|
+
this.h.set(k, {
|
|
43
|
+
n: name,
|
|
44
|
+
vs: [value],
|
|
45
|
+
tags,
|
|
46
|
+
opts: { percentiles: options.percentiles?.slice(), aggregates: options.aggregates?.slice() }
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Flush all accumulated metrics to console.log as "cwm-" prefixed JSON.
|
|
52
|
+
* Splits into multiple entries if the payload exceeds 250 KiB.
|
|
53
|
+
* Clears all internal state after flushing.
|
|
54
|
+
*/
|
|
55
|
+
flush() {
|
|
56
|
+
const ts = Date.now();
|
|
57
|
+
const entries = [];
|
|
58
|
+
for (const { n, v, tags } of this.c.values())
|
|
59
|
+
entries.push({ t: "c", n, v, tags, ts });
|
|
60
|
+
for (const { n, v, tags } of this.g.values())
|
|
61
|
+
entries.push({ t: "g", n, v, tags, ts });
|
|
62
|
+
for (const { n, vs, tags, opts } of this.h.values()) {
|
|
63
|
+
const sorted = vs.slice().sort((a, b) => a - b);
|
|
64
|
+
const len = sorted.length;
|
|
65
|
+
if (opts.percentiles) {
|
|
66
|
+
for (const p of opts.percentiles) {
|
|
67
|
+
const i = Math.max(0, Math.ceil(p * len) - 1);
|
|
68
|
+
entries.push({ t: "g", n: `${n}.p${Math.round(p * 100)}`, v: sorted[i], tags, ts });
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
if (opts.aggregates) {
|
|
72
|
+
for (const a of opts.aggregates) {
|
|
73
|
+
if (a === "count") {
|
|
74
|
+
entries.push({ t: "c", n: `${n}.count`, v: len, tags, ts });
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
let v;
|
|
78
|
+
switch (a) {
|
|
79
|
+
case "sum":
|
|
80
|
+
v = vs.reduce((x, y) => x + y, 0);
|
|
81
|
+
break;
|
|
82
|
+
case "avg":
|
|
83
|
+
v = vs.reduce((x, y) => x + y, 0) / len;
|
|
84
|
+
break;
|
|
85
|
+
case "min":
|
|
86
|
+
v = sorted[0];
|
|
87
|
+
break;
|
|
88
|
+
case "max":
|
|
89
|
+
v = sorted[len - 1];
|
|
90
|
+
break;
|
|
91
|
+
case "median": {
|
|
92
|
+
const m = len >> 1;
|
|
93
|
+
v = len & 1 ? sorted[m] : (sorted[m - 1] + sorted[m]) / 2;
|
|
94
|
+
break;
|
|
95
|
+
}
|
|
96
|
+
default:
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
entries.push({ t: "g", n: `${n}.${a}`, v, tags, ts });
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
this.c.clear();
|
|
104
|
+
this.g.clear();
|
|
105
|
+
this.h.clear();
|
|
106
|
+
if (!entries.length) return;
|
|
107
|
+
this.emit(entries);
|
|
108
|
+
}
|
|
109
|
+
emit(entries) {
|
|
110
|
+
const parts = entries.map((e) => JSON.stringify(e));
|
|
111
|
+
const total = 5 + parts.length + parts.reduce((a, s) => a + s.length, 0);
|
|
112
|
+
if (total <= MAX_SIZE) {
|
|
113
|
+
console.log("cwm-[" + parts.join(",") + "]");
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
let buf = [];
|
|
117
|
+
let bufLen = 0;
|
|
118
|
+
for (const p of parts) {
|
|
119
|
+
const wouldBe = 5 + (buf.length + 1) + bufLen + p.length;
|
|
120
|
+
if (buf.length > 0 && wouldBe > MAX_SIZE) {
|
|
121
|
+
console.log("cwm-[" + buf.join(",") + "]");
|
|
122
|
+
buf = [];
|
|
123
|
+
bufLen = 0;
|
|
124
|
+
}
|
|
125
|
+
buf.push(p);
|
|
126
|
+
bufLen += p.length;
|
|
127
|
+
}
|
|
128
|
+
if (buf.length) console.log("cwm-[" + buf.join(",") + "]");
|
|
129
|
+
}
|
|
130
|
+
};
|
|
131
|
+
var metrics = new Metrics();
|
|
132
|
+
export {
|
|
133
|
+
Metrics,
|
|
134
|
+
metrics
|
|
135
|
+
};
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
type Tags = Record<string, string | number | boolean | undefined | null>;
|
|
2
|
+
type HistogramAgg = 'max' | 'min' | 'sum' | 'avg' | 'median' | 'count';
|
|
3
|
+
interface HistogramOptions {
|
|
4
|
+
aggregates?: HistogramAgg[];
|
|
5
|
+
percentiles?: number[];
|
|
6
|
+
}
|
|
7
|
+
/** Compact metric entry emitted via console.log. Short keys to minimize JSON size. */
|
|
8
|
+
interface MetricEntry {
|
|
9
|
+
/** 'c' = counter, 'g' = gauge */
|
|
10
|
+
t: 'c' | 'g';
|
|
11
|
+
/** metric name */
|
|
12
|
+
n: string;
|
|
13
|
+
/** value */
|
|
14
|
+
v: number;
|
|
15
|
+
/** tags */
|
|
16
|
+
tags: Tags;
|
|
17
|
+
/** timestamp in ms */
|
|
18
|
+
ts: number;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export type { HistogramOptions as H, MetricEntry as M, Tags as T, HistogramAgg as a };
|
package/package.json
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "cloudflare-worker-metrics",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Lightweight metrics collection for Cloudflare Workers with OTEL export via LogPush + R2",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.js",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"import": "./dist/index.js"
|
|
12
|
+
},
|
|
13
|
+
"./exporter": {
|
|
14
|
+
"types": "./dist/exporter.d.ts",
|
|
15
|
+
"import": "./dist/exporter.js"
|
|
16
|
+
}
|
|
17
|
+
},
|
|
18
|
+
"sideEffects": false,
|
|
19
|
+
"files": [
|
|
20
|
+
"dist"
|
|
21
|
+
],
|
|
22
|
+
"scripts": {
|
|
23
|
+
"build": "tsup",
|
|
24
|
+
"test": "vitest run",
|
|
25
|
+
"test:watch": "vitest",
|
|
26
|
+
"prepublishOnly": "npm run build"
|
|
27
|
+
},
|
|
28
|
+
"license": "Apache-2.0",
|
|
29
|
+
"engines": {
|
|
30
|
+
"node": ">=18"
|
|
31
|
+
},
|
|
32
|
+
"devDependencies": {
|
|
33
|
+
"@cloudflare/workers-types": "^4.20241218.0",
|
|
34
|
+
"tsup": "^8.3.0",
|
|
35
|
+
"typescript": "^5.7.0",
|
|
36
|
+
"vitest": "^4.0.18"
|
|
37
|
+
}
|
|
38
|
+
}
|