@libo11y/workers 0.8.0 → 0.9.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/README.md +114 -50
- package/dist/adapters.d.ts +102 -0
- package/dist/adapters.js +282 -0
- package/dist/env.d.ts +0 -6
- package/dist/env.js +2 -18
- package/dist/exporters.d.ts +16 -18
- package/dist/exporters.js +206 -95
- package/dist/flush.d.ts +25 -10
- package/dist/flush.js +32 -5
- package/dist/index.d.ts +12 -8
- package/dist/index.js +10 -6
- package/dist/instrument.d.ts +28 -33
- package/dist/instrument.js +35 -77
- package/dist/log-processor.d.ts +23 -0
- package/dist/log-processor.js +157 -0
- package/dist/metric-reader.d.ts +23 -3
- package/dist/metric-reader.js +189 -30
- package/dist/platform.d.ts +15 -4
- package/dist/platform.js +16 -3
- package/dist/rum-proxy.d.ts +69 -0
- package/dist/rum-proxy.js +174 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +6 -7
package/dist/metric-reader.js
CHANGED
|
@@ -1,15 +1,7 @@
|
|
|
1
|
-
|
|
2
|
-
* The metric reader of a Worker. A periodic reader cannot work in a Worker: a timer runs only while
|
|
3
|
-
* an invocation is alive, and one armed in one invocation never fires once that invocation is
|
|
4
|
-
* gone. This reader has no timer. It collects and exports when the telemetry flushes, which the
|
|
5
|
-
* Workers helpers do after every invocation, and at most once per intervalMillis, so a busy isolate
|
|
6
|
-
* does not ship metrics with every request. Shutdown always exports.
|
|
7
|
-
*
|
|
8
|
-
* With CUMULATIVE temporality, which the exporters ask for, a skipped flush loses nothing: the next
|
|
9
|
-
* export carries every measurement since the isolate started.
|
|
10
|
-
*/
|
|
1
|
+
import { hasPendingExemplars } from "@libo11y/core/internal";
|
|
11
2
|
import { ExportResultCode, globalErrorHandler } from "@opentelemetry/core";
|
|
12
|
-
import { MetricReader } from "@opentelemetry/sdk-metrics";
|
|
3
|
+
import { AggregationTemporality, DataPointType, MetricReader, } from "@opentelemetry/sdk-metrics";
|
|
4
|
+
import { activeFlushContext } from "./flush.js";
|
|
13
5
|
function exportOnce(exporter, metrics) {
|
|
14
6
|
return new Promise((resolve) => {
|
|
15
7
|
try {
|
|
@@ -20,13 +12,115 @@ function exportOnce(exporter, metrics) {
|
|
|
20
12
|
}
|
|
21
13
|
});
|
|
22
14
|
}
|
|
23
|
-
|
|
15
|
+
function hasAnyDataPoints(rm) {
|
|
16
|
+
for (const sm of rm.scopeMetrics) {
|
|
17
|
+
for (const metric of sm.metrics) {
|
|
18
|
+
if (metric.dataPoints.length > 0)
|
|
19
|
+
return true;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
return false;
|
|
23
|
+
}
|
|
24
|
+
function hasDeltaPoints(rm) {
|
|
25
|
+
for (const sm of rm.scopeMetrics) {
|
|
26
|
+
for (const metric of sm.metrics) {
|
|
27
|
+
if (metric.aggregationTemporality === AggregationTemporality.DELTA && metric.dataPoints.length > 0) {
|
|
28
|
+
return true;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
return false;
|
|
33
|
+
}
|
|
34
|
+
function formatNumber(n) {
|
|
35
|
+
if (n === undefined)
|
|
36
|
+
return "u";
|
|
37
|
+
if (Object.is(n, -0))
|
|
38
|
+
return "-0";
|
|
39
|
+
return String(n);
|
|
40
|
+
}
|
|
41
|
+
function canonicalAttributes(attrs) {
|
|
42
|
+
const keys = Object.keys(attrs)
|
|
43
|
+
.filter((k) => attrs[k] !== undefined)
|
|
44
|
+
.sort();
|
|
45
|
+
if (keys.length === 0)
|
|
46
|
+
return "";
|
|
47
|
+
return JSON.stringify(keys.map((k) => [k, attrs[k]]));
|
|
48
|
+
}
|
|
49
|
+
function canonicalValue(metric, value) {
|
|
50
|
+
switch (metric.dataPointType) {
|
|
51
|
+
case DataPointType.SUM:
|
|
52
|
+
case DataPointType.GAUGE:
|
|
53
|
+
return formatNumber(value);
|
|
54
|
+
case DataPointType.HISTOGRAM: {
|
|
55
|
+
const h = value;
|
|
56
|
+
return JSON.stringify([
|
|
57
|
+
h.count,
|
|
58
|
+
formatNumber(h.sum),
|
|
59
|
+
formatNumber(h.min),
|
|
60
|
+
formatNumber(h.max),
|
|
61
|
+
h.buckets.boundaries,
|
|
62
|
+
h.buckets.counts,
|
|
63
|
+
]);
|
|
64
|
+
}
|
|
65
|
+
case DataPointType.EXPONENTIAL_HISTOGRAM: {
|
|
66
|
+
const eh = value;
|
|
67
|
+
return JSON.stringify([
|
|
68
|
+
eh.count,
|
|
69
|
+
formatNumber(eh.sum),
|
|
70
|
+
formatNumber(eh.min),
|
|
71
|
+
formatNumber(eh.max),
|
|
72
|
+
eh.scale,
|
|
73
|
+
eh.zeroCount,
|
|
74
|
+
eh.positive.offset,
|
|
75
|
+
eh.positive.bucketCounts,
|
|
76
|
+
eh.negative.offset,
|
|
77
|
+
eh.negative.bucketCounts,
|
|
78
|
+
]);
|
|
79
|
+
}
|
|
80
|
+
default:
|
|
81
|
+
return JSON.stringify(value);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Deterministic canonical fingerprint of all CUMULATIVE data points in rm, independent of
|
|
86
|
+
* collection timestamps and insertion order.
|
|
87
|
+
*/
|
|
88
|
+
function fingerprintCumulative(rm) {
|
|
89
|
+
const entries = [];
|
|
90
|
+
for (const sm of rm.scopeMetrics) {
|
|
91
|
+
const scope = `${sm.scope.name}\u0000${sm.scope.version ?? ""}\u0000${sm.scope.schemaUrl ?? ""}`;
|
|
92
|
+
for (const metric of sm.metrics) {
|
|
93
|
+
if (metric.aggregationTemporality !== AggregationTemporality.CUMULATIVE)
|
|
94
|
+
continue;
|
|
95
|
+
if (metric.dataPoints.length === 0)
|
|
96
|
+
continue;
|
|
97
|
+
const monotonic = metric.dataPointType === DataPointType.SUM ? (metric.isMonotonic ? "1" : "0") : "";
|
|
98
|
+
const metricType = String(metric.descriptor.type ?? "");
|
|
99
|
+
const descriptor = `${metric.descriptor.name}\u0000${metricType}\u0000${metric.descriptor.unit}\u0000${metric.dataPointType}\u0000${monotonic}`;
|
|
100
|
+
const points = metric.dataPoints
|
|
101
|
+
.map((dp) => `${canonicalAttributes(dp.attributes)}=${canonicalValue(metric, dp.value)}`)
|
|
102
|
+
.sort();
|
|
103
|
+
entries.push(`${scope}\u0001${descriptor}\u0002${points.join("\u0003")}`);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
entries.sort();
|
|
107
|
+
return entries.join("\u0004");
|
|
108
|
+
}
|
|
109
|
+
/** A dirty-aware metric reader that exports on flush, optionally throttled, and on shutdown. */
|
|
24
110
|
export class FlushMetricReader extends MetricReader {
|
|
25
111
|
exporter;
|
|
112
|
+
exemplars;
|
|
26
113
|
intervalMillis;
|
|
27
114
|
timeoutMillis;
|
|
28
115
|
now;
|
|
29
116
|
last;
|
|
117
|
+
collectingSince;
|
|
118
|
+
collectingToken = 0;
|
|
119
|
+
lastExportedKey;
|
|
120
|
+
latestDispatchedKey;
|
|
121
|
+
lastSuccessSeq = 0;
|
|
122
|
+
nextSeq = 0;
|
|
123
|
+
inFlightCount = 0;
|
|
30
124
|
constructor(opts) {
|
|
31
125
|
const exporter = opts.exporter;
|
|
32
126
|
super({
|
|
@@ -38,11 +132,12 @@ export class FlushMetricReader extends MetricReader {
|
|
|
38
132
|
: { aggregationTemporalitySelector: exporter.selectAggregationTemporality.bind(exporter) }),
|
|
39
133
|
});
|
|
40
134
|
this.exporter = exporter;
|
|
135
|
+
this.exemplars = opts.exemplars;
|
|
41
136
|
this.intervalMillis = Math.max(0, Number.isFinite(opts.intervalMillis) ? opts.intervalMillis : 0);
|
|
42
137
|
this.timeoutMillis = opts.timeoutMillis;
|
|
43
138
|
this.now = opts.now ?? Date.now;
|
|
44
139
|
}
|
|
45
|
-
/** Whether a flush now would
|
|
140
|
+
/** Whether a flush now would collect: the interval has passed since the last export began. */
|
|
46
141
|
due() {
|
|
47
142
|
if (this.last === undefined)
|
|
48
143
|
return true;
|
|
@@ -50,34 +145,98 @@ export class FlushMetricReader extends MetricReader {
|
|
|
50
145
|
// A clock that went backwards is due, so a skewed clock cannot stop exports.
|
|
51
146
|
return elapsed < 0 || elapsed >= this.intervalMillis;
|
|
52
147
|
}
|
|
148
|
+
isCollecting() {
|
|
149
|
+
if (this.collectingSince === undefined)
|
|
150
|
+
return false;
|
|
151
|
+
const elapsed = this.now() - this.collectingSince;
|
|
152
|
+
const windowMillis = this.timeoutMillis > 0 ? this.timeoutMillis : this.intervalMillis;
|
|
153
|
+
// Match due(): a backwards clock or elapsed >= windowMillis releases a stale guard
|
|
154
|
+
// left behind if workerd cancelled an earlier invocation before finally ran.
|
|
155
|
+
if (elapsed < 0 || elapsed >= windowMillis) {
|
|
156
|
+
this.collectingSince = undefined;
|
|
157
|
+
return false;
|
|
158
|
+
}
|
|
159
|
+
return true;
|
|
160
|
+
}
|
|
53
161
|
async onForceFlush() {
|
|
54
|
-
|
|
162
|
+
const forced = activeFlushContext()?.forceMetrics === true;
|
|
163
|
+
const reserve = !forced && this.intervalMillis > 0;
|
|
164
|
+
if (reserve && (this.isCollecting() || !this.due()))
|
|
55
165
|
return;
|
|
56
|
-
await this.run();
|
|
57
|
-
|
|
166
|
+
const dispatched = await this.run(reserve);
|
|
167
|
+
if (dispatched)
|
|
168
|
+
await this.exporter.forceFlush();
|
|
58
169
|
}
|
|
59
170
|
async onShutdown() {
|
|
60
|
-
await this.run();
|
|
171
|
+
await this.run(false);
|
|
61
172
|
await this.exporter.shutdown();
|
|
62
173
|
}
|
|
63
|
-
// run collects and exports
|
|
64
|
-
//
|
|
65
|
-
//
|
|
66
|
-
//
|
|
67
|
-
//
|
|
68
|
-
|
|
69
|
-
|
|
174
|
+
// run collects once and exports when dirty. Two flushes never share one export promise: in
|
|
175
|
+
// workerd a promise belongs to the invocation that made it, so a flush that waited for another
|
|
176
|
+
// invocation's export could be left waiting when that invocation ends. Instead, inFlightCount
|
|
177
|
+
// and latestDispatchedKey are updated synchronously before awaiting export so concurrent
|
|
178
|
+
// read-only flushes never stampede, while intervening transitions such as 1 -> 2 -> 1 while 2 is
|
|
179
|
+
// in flight always dispatch.
|
|
180
|
+
async run(reserveCollection) {
|
|
181
|
+
let dispatched = false;
|
|
182
|
+
let myToken = 0;
|
|
183
|
+
if (reserveCollection) {
|
|
184
|
+
myToken = ++this.collectingToken;
|
|
185
|
+
this.collectingSince = this.now();
|
|
186
|
+
}
|
|
70
187
|
try {
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
188
|
+
let resourceMetrics;
|
|
189
|
+
let key;
|
|
190
|
+
let trackCumulative;
|
|
191
|
+
let seq;
|
|
192
|
+
try {
|
|
193
|
+
const collected = await this.collect({ timeoutMillis: this.timeoutMillis });
|
|
194
|
+
resourceMetrics = collected.resourceMetrics;
|
|
195
|
+
if (!hasAnyDataPoints(resourceMetrics))
|
|
196
|
+
return false;
|
|
197
|
+
const hasDelta = hasDeltaPoints(resourceMetrics);
|
|
198
|
+
key = fingerprintCumulative(resourceMetrics);
|
|
199
|
+
const hasExemplars = this.exemplars !== undefined && hasPendingExemplars(this.exemplars, resourceMetrics);
|
|
200
|
+
if (!hasDelta && !hasExemplars) {
|
|
201
|
+
if ((this.inFlightCount === 0 && key === this.lastExportedKey) ||
|
|
202
|
+
(this.inFlightCount > 0 && key === this.latestDispatchedKey)) {
|
|
203
|
+
return false;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
trackCumulative = key !== "";
|
|
207
|
+
seq = ++this.nextSeq;
|
|
208
|
+
if (trackCumulative) {
|
|
209
|
+
this.inFlightCount += 1;
|
|
210
|
+
this.latestDispatchedKey = key;
|
|
211
|
+
}
|
|
212
|
+
this.last = this.now();
|
|
213
|
+
dispatched = true;
|
|
214
|
+
}
|
|
215
|
+
finally {
|
|
216
|
+
if (reserveCollection && this.collectingToken === myToken) {
|
|
217
|
+
this.collectingSince = undefined;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
let result;
|
|
221
|
+
try {
|
|
222
|
+
result = await exportOnce(this.exporter, resourceMetrics);
|
|
223
|
+
}
|
|
224
|
+
finally {
|
|
225
|
+
if (trackCumulative)
|
|
226
|
+
this.inFlightCount -= 1;
|
|
227
|
+
}
|
|
228
|
+
if (result.code === ExportResultCode.SUCCESS) {
|
|
229
|
+
if (trackCumulative && seq > this.lastSuccessSeq) {
|
|
230
|
+
this.lastSuccessSeq = seq;
|
|
231
|
+
this.lastExportedKey = key;
|
|
232
|
+
}
|
|
233
|
+
return true;
|
|
77
234
|
}
|
|
235
|
+
throw result.error ?? new Error("o11y: metric export failed");
|
|
78
236
|
}
|
|
79
237
|
catch (err) {
|
|
80
238
|
globalErrorHandler(err);
|
|
239
|
+
return dispatched;
|
|
81
240
|
}
|
|
82
241
|
}
|
|
83
242
|
}
|
package/dist/platform.d.ts
CHANGED
|
@@ -7,8 +7,17 @@
|
|
|
7
7
|
*/
|
|
8
8
|
import type { Platform } from "@libo11y/core";
|
|
9
9
|
import { type WorkersExporterOptions } from "./exporters.ts";
|
|
10
|
-
/**
|
|
11
|
-
|
|
10
|
+
/**
|
|
11
|
+
* The default of WorkersPlatformOptions.metricsFlushIntervalMillis for setup() and
|
|
12
|
+
* createTelemetry(): 0 (flush changed metrics within each invocation; unchanged cumulative
|
|
13
|
+
* snapshots are skipped).
|
|
14
|
+
*/
|
|
15
|
+
export declare const DEFAULT_METRICS_FLUSH_INTERVAL_MILLIS = 0;
|
|
16
|
+
/**
|
|
17
|
+
* The default metricsFlushIntervalMillis applied by instrument() when HTTP RED metrics are
|
|
18
|
+
* enabled (serve !== false): 15 s.
|
|
19
|
+
*/
|
|
20
|
+
export declare const DEFAULT_INSTRUMENT_METRICS_FLUSH_INTERVAL_MILLIS = 15000;
|
|
12
21
|
/** Options for workersPlatform. */
|
|
13
22
|
export interface WorkersPlatformOptions {
|
|
14
23
|
/**
|
|
@@ -20,8 +29,10 @@ export interface WorkersPlatformOptions {
|
|
|
20
29
|
readonly exporter?: WorkersExporterOptions;
|
|
21
30
|
/**
|
|
22
31
|
* The least time between two metric exports of one isolate, in milliseconds. Traces and logs
|
|
23
|
-
* export on every flush; metrics
|
|
24
|
-
*
|
|
32
|
+
* export on every flush; metrics export when changed (or on any DELTA data point) once this
|
|
33
|
+
* interval has passed since the last export. Default 0 for setup() (flush-on-change);
|
|
34
|
+
* instrument() defaults to 15000 when wrapping fetch with instrumentServe (while queue and
|
|
35
|
+
* scheduled flushes force changed metrics via forceMetrics: true).
|
|
25
36
|
*/
|
|
26
37
|
readonly metricsFlushIntervalMillis?: number;
|
|
27
38
|
}
|
package/dist/platform.js
CHANGED
|
@@ -1,9 +1,20 @@
|
|
|
1
|
+
import { setLogProcessorFactory } from "@libo11y/core/internal";
|
|
1
2
|
import { createContextManager } from "./context.js";
|
|
2
3
|
import { otelEnv } from "./env.js";
|
|
3
4
|
import { buildExporters } from "./exporters.js";
|
|
5
|
+
import { IsolatedBatchLogRecordProcessor } from "./log-processor.js";
|
|
4
6
|
import { detectWorkersResource } from "./resource.js";
|
|
5
|
-
/**
|
|
6
|
-
|
|
7
|
+
/**
|
|
8
|
+
* The default of WorkersPlatformOptions.metricsFlushIntervalMillis for setup() and
|
|
9
|
+
* createTelemetry(): 0 (flush changed metrics within each invocation; unchanged cumulative
|
|
10
|
+
* snapshots are skipped).
|
|
11
|
+
*/
|
|
12
|
+
export const DEFAULT_METRICS_FLUSH_INTERVAL_MILLIS = 0;
|
|
13
|
+
/**
|
|
14
|
+
* The default metricsFlushIntervalMillis applied by instrument() when HTTP RED metrics are
|
|
15
|
+
* enabled (serve !== false): 15 s.
|
|
16
|
+
*/
|
|
17
|
+
export const DEFAULT_INSTRUMENT_METRICS_FLUSH_INTERVAL_MILLIS = 15000;
|
|
7
18
|
/** A new Workers Platform for createTelemetryWith and setupWith. */
|
|
8
19
|
export function workersPlatform(opts = {}) {
|
|
9
20
|
const env = otelEnv(opts.env);
|
|
@@ -14,7 +25,7 @@ export function workersPlatform(opts = {}) {
|
|
|
14
25
|
// Bound now, before captureConsole patches the console, so a sink line never re-enters capture.
|
|
15
26
|
const log = console.log.bind(console);
|
|
16
27
|
const warn = console.warn.bind(console);
|
|
17
|
-
|
|
28
|
+
const platform = {
|
|
18
29
|
name: "workers",
|
|
19
30
|
env: () => env,
|
|
20
31
|
detectResource: (hermetic) => detectWorkersResource(hermetic, env),
|
|
@@ -28,4 +39,6 @@ export function workersPlatform(opts = {}) {
|
|
|
28
39
|
// Each flush belongs to one invocation: workerd ties a promise to the invocation that made it.
|
|
29
40
|
isolatedFlushes: true,
|
|
30
41
|
};
|
|
42
|
+
setLogProcessorFactory(platform, (exporter, batch) => new IsolatedBatchLogRecordProcessor({ exporter, ...batch }));
|
|
43
|
+
return platform;
|
|
31
44
|
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Authenticated RUM gateway proxy helper for Cloudflare Workers.
|
|
3
|
+
*
|
|
4
|
+
* Forwards same-origin `/_o11y/...` RUM ingest, replay, remote config, and source map/dSYM upload
|
|
5
|
+
* requests to `o11yrum-gateway` (typically over a Workers VPC Service binding), stripping
|
|
6
|
+
* untrusted client forwarding headers, inbound `cf-*` headers (including `cf-ipcountry`), cookies,
|
|
7
|
+
* non-upload `authorization`, and any inbound hop-credential header.
|
|
8
|
+
*
|
|
9
|
+
* When `trustedEdge` is configured with a non-blank shared secret, `cf-ipcountry` is populated
|
|
10
|
+
* strictly from Cloudflare's platform-authenticated `request.cf.country` (valid 2-letter ASCII
|
|
11
|
+
* ISO code excluding `XX` and `T1`) and the configured hop-credential header is attached so the
|
|
12
|
+
* gateway's dedicated trusted-edge listener authenticates the hop.
|
|
13
|
+
*/
|
|
14
|
+
import type { WorkersFetch } from "./exporters.ts";
|
|
15
|
+
/** Default URL path prefix served by the RUM proxy. */
|
|
16
|
+
export declare const DEFAULT_RUM_PROXY_PREFIX = "/_o11y";
|
|
17
|
+
/** Default HTTP header carrying the shared trusted-edge hop credential. */
|
|
18
|
+
export declare const DEFAULT_TRUSTED_EDGE_HEADER = "x-o11y-edge-secret";
|
|
19
|
+
/** Trusted-edge hop authentication settings for {@link RumProxyOptions}. */
|
|
20
|
+
export interface RumTrustedEdgeOptions {
|
|
21
|
+
/** Shared secret matching the gateway's `edge.trusted_ingresses[].secret_file`. */
|
|
22
|
+
readonly secret: string;
|
|
23
|
+
/** Header carrying the shared secret. Defaults to `"x-o11y-edge-secret"`. */
|
|
24
|
+
readonly header?: string;
|
|
25
|
+
}
|
|
26
|
+
/** Configuration for {@link buildRumUpstreamRequest}, {@link proxyRum}, and {@link createRumProxy}. */
|
|
27
|
+
export interface RumProxyOptions {
|
|
28
|
+
/** Upstream RUM gateway origin (e.g. `"http://o11yrum-gateway.o11y-rum.svc.cluster.local:8081"`). */
|
|
29
|
+
readonly gatewayOrigin: string;
|
|
30
|
+
/**
|
|
31
|
+
* Fetch function reaching the gateway (e.g. `(req) => env.RUM_GATEWAY.fetch(req)`).
|
|
32
|
+
* When omitted (such as local development without a gateway binding), `proxyRum` returns 404.
|
|
33
|
+
*/
|
|
34
|
+
readonly fetch?: WorkersFetch;
|
|
35
|
+
/** URL path prefix forwarded by the proxy. Defaults to `"/_o11y"`. */
|
|
36
|
+
readonly prefix?: string;
|
|
37
|
+
/**
|
|
38
|
+
* Optional trusted-edge authentication configuration. When provided with a non-blank `secret`,
|
|
39
|
+
* populates `cf-ipcountry` strictly from Cloudflare's `request.cf.country` (never trusting any
|
|
40
|
+
* inbound `cf-ipcountry` header) and sets the configured hop-credential header.
|
|
41
|
+
*/
|
|
42
|
+
readonly trustedEdge?: RumTrustedEdgeOptions;
|
|
43
|
+
/** Optional error callback invoked on upstream transport failure. Defaults to `console.warn`. */
|
|
44
|
+
readonly onError?: (error: unknown) => void;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Reports whether `pathname` belongs to the RUM proxy prefix (default `"/_o11y"`), rejecting
|
|
48
|
+
* scheme-relative authorities (`//...`, `/\...`) and path traversal outside the prefix.
|
|
49
|
+
*/
|
|
50
|
+
export declare function isRumProxyPath(pathname: string, prefix?: string): boolean;
|
|
51
|
+
/**
|
|
52
|
+
* Constructs the sanitized upstream `Request` to forward to `o11yrum-gateway`.
|
|
53
|
+
*
|
|
54
|
+
* Always strips `authorization` (except on `POST` to `${prefix}/v1/sourcemaps` and
|
|
55
|
+
* `${prefix}/v1/dsyms`), `cookie`, `host`, `forwarded`, `x-forwarded-*`, `x-real-ip`,
|
|
56
|
+
* `true-client-ip`, all inbound `cf-*` headers, and any inbound hop-credential header.
|
|
57
|
+
* Rebuilds `x-forwarded-for` strictly from `cf-connecting-ip`.
|
|
58
|
+
*/
|
|
59
|
+
export declare function buildRumUpstreamRequest(request: Request, options: RumProxyOptions): Request;
|
|
60
|
+
/**
|
|
61
|
+
* Forwards a single RUM request to the configured gateway, returning 404 for non-RUM paths or
|
|
62
|
+
* when `options.fetch` is undefined, and 502 (after logging a warning) on upstream transport error.
|
|
63
|
+
*/
|
|
64
|
+
export declare function proxyRum(request: Request, options: RumProxyOptions): Promise<Response>;
|
|
65
|
+
/**
|
|
66
|
+
* Creates a reusable Worker fetch handler for forwarding `/_o11y/...` RUM requests to
|
|
67
|
+
* `o11yrum-gateway`.
|
|
68
|
+
*/
|
|
69
|
+
export declare function createRumProxy(options: RumProxyOptions): (request: Request) => Promise<Response>;
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
/** Default URL path prefix served by the RUM proxy. */
|
|
2
|
+
export const DEFAULT_RUM_PROXY_PREFIX = "/_o11y";
|
|
3
|
+
/** Default HTTP header carrying the shared trusted-edge hop credential. */
|
|
4
|
+
export const DEFAULT_TRUSTED_EDGE_HEADER = "x-o11y-edge-secret";
|
|
5
|
+
const DROPPED_HEADERS = new Set([
|
|
6
|
+
"authorization",
|
|
7
|
+
"cookie",
|
|
8
|
+
"host",
|
|
9
|
+
"forwarded",
|
|
10
|
+
"x-real-ip",
|
|
11
|
+
"true-client-ip",
|
|
12
|
+
]);
|
|
13
|
+
const COUNTRY_CODE_RE = /^[A-Z]{2}$/;
|
|
14
|
+
const UNKNOWN_COUNTRIES = new Set(["XX", "T1"]);
|
|
15
|
+
function normalizePrefix(prefix) {
|
|
16
|
+
const trimmed = (prefix ?? DEFAULT_RUM_PROXY_PREFIX).trim();
|
|
17
|
+
if (trimmed === "" || trimmed === "/")
|
|
18
|
+
return "/";
|
|
19
|
+
const withLead = trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
|
|
20
|
+
let end = withLead.length;
|
|
21
|
+
while (end > 1 && withLead.charCodeAt(end - 1) === 0x2f)
|
|
22
|
+
end--;
|
|
23
|
+
return withLead.slice(0, end);
|
|
24
|
+
}
|
|
25
|
+
function validCountryCode(raw) {
|
|
26
|
+
if (typeof raw !== "string")
|
|
27
|
+
return undefined;
|
|
28
|
+
const upper = raw.trim().toUpperCase();
|
|
29
|
+
if (!COUNTRY_CODE_RE.test(upper) || UNKNOWN_COUNTRIES.has(upper))
|
|
30
|
+
return undefined;
|
|
31
|
+
return upper;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Reports whether `pathname` belongs to the RUM proxy prefix (default `"/_o11y"`), rejecting
|
|
35
|
+
* scheme-relative authorities (`//...`, `/\...`) and path traversal outside the prefix.
|
|
36
|
+
*/
|
|
37
|
+
export function isRumProxyPath(pathname, prefix = DEFAULT_RUM_PROXY_PREFIX) {
|
|
38
|
+
if (!pathname.startsWith("/") || pathname.startsWith("//") || pathname.startsWith("/\\"))
|
|
39
|
+
return false;
|
|
40
|
+
let resolvedUrl;
|
|
41
|
+
try {
|
|
42
|
+
resolvedUrl = new URL(pathname, "http://worker");
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
return false;
|
|
46
|
+
}
|
|
47
|
+
if (resolvedUrl.origin !== "http://worker")
|
|
48
|
+
return false;
|
|
49
|
+
const resolved = resolvedUrl.pathname;
|
|
50
|
+
const normalized = normalizePrefix(prefix);
|
|
51
|
+
if (normalized === "/")
|
|
52
|
+
return true;
|
|
53
|
+
return resolved === normalized || resolved.startsWith(`${normalized}/`);
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Constructs the sanitized upstream `Request` to forward to `o11yrum-gateway`.
|
|
57
|
+
*
|
|
58
|
+
* Always strips `authorization` (except on `POST` to `${prefix}/v1/sourcemaps` and
|
|
59
|
+
* `${prefix}/v1/dsyms`), `cookie`, `host`, `forwarded`, `x-forwarded-*`, `x-real-ip`,
|
|
60
|
+
* `true-client-ip`, all inbound `cf-*` headers, and any inbound hop-credential header.
|
|
61
|
+
* Rebuilds `x-forwarded-for` strictly from `cf-connecting-ip`.
|
|
62
|
+
*/
|
|
63
|
+
export function buildRumUpstreamRequest(request, options) {
|
|
64
|
+
const prefix = normalizePrefix(options.prefix);
|
|
65
|
+
const url = new URL(request.url);
|
|
66
|
+
const secret = options.trustedEdge?.secret.trim();
|
|
67
|
+
const trustedActive = secret !== undefined && secret !== "";
|
|
68
|
+
const configuredHeader = options.trustedEdge?.header?.trim().toLowerCase();
|
|
69
|
+
const secretHeader = configuredHeader !== undefined && configuredHeader !== ""
|
|
70
|
+
? configuredHeader
|
|
71
|
+
: DEFAULT_TRUSTED_EDGE_HEADER;
|
|
72
|
+
const headers = new Headers();
|
|
73
|
+
request.headers.forEach((value, name) => {
|
|
74
|
+
const lower = name.toLowerCase();
|
|
75
|
+
if (DROPPED_HEADERS.has(lower))
|
|
76
|
+
return;
|
|
77
|
+
if (lower.startsWith("x-forwarded-"))
|
|
78
|
+
return;
|
|
79
|
+
if (lower === DEFAULT_TRUSTED_EDGE_HEADER || lower === secretHeader)
|
|
80
|
+
return;
|
|
81
|
+
if (lower.startsWith("cf-"))
|
|
82
|
+
return;
|
|
83
|
+
headers.set(lower, value);
|
|
84
|
+
});
|
|
85
|
+
const base = prefix === "/" ? "" : prefix;
|
|
86
|
+
const uploadPaths = new Set([`${base}/v1/sourcemaps`, `${base}/v1/dsyms`]);
|
|
87
|
+
const authorization = request.headers.get("authorization");
|
|
88
|
+
if (authorization !== null && request.method.toUpperCase() === "POST" && uploadPaths.has(url.pathname)) {
|
|
89
|
+
headers.set("authorization", authorization);
|
|
90
|
+
}
|
|
91
|
+
const visitor = request.headers.get("cf-connecting-ip")?.trim();
|
|
92
|
+
if (visitor !== undefined && visitor !== "") {
|
|
93
|
+
headers.set("x-forwarded-for", visitor);
|
|
94
|
+
}
|
|
95
|
+
const cfCountry = validCountryCode(request.cf?.country);
|
|
96
|
+
if (trustedActive) {
|
|
97
|
+
// Trusted-edge mode: never copy client-supplied cf-ipcountry; use only Cloudflare's request.cf.country.
|
|
98
|
+
if (cfCountry !== undefined)
|
|
99
|
+
headers.set("cf-ipcountry", cfCountry);
|
|
100
|
+
headers.set(secretHeader, secret);
|
|
101
|
+
}
|
|
102
|
+
else {
|
|
103
|
+
// Legacy non-enforcing ingress: prefer request.cf.country, else preserve inbound cf-ipcountry.
|
|
104
|
+
if (cfCountry !== undefined) {
|
|
105
|
+
headers.set("cf-ipcountry", cfCountry);
|
|
106
|
+
}
|
|
107
|
+
else {
|
|
108
|
+
const inboundCountry = request.headers.get("cf-ipcountry");
|
|
109
|
+
if (inboundCountry !== null)
|
|
110
|
+
headers.set("cf-ipcountry", inboundCountry);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
const method = request.method.toUpperCase();
|
|
114
|
+
const hasBody = method !== "GET" && method !== "HEAD" && request.body !== null;
|
|
115
|
+
const upstreamUrl = new URL(options.gatewayOrigin);
|
|
116
|
+
upstreamUrl.pathname = url.pathname;
|
|
117
|
+
upstreamUrl.search = url.search;
|
|
118
|
+
upstreamUrl.hash = "";
|
|
119
|
+
return new Request(upstreamUrl.toString(), {
|
|
120
|
+
method: request.method,
|
|
121
|
+
headers,
|
|
122
|
+
redirect: "manual",
|
|
123
|
+
...(hasBody ? { body: request.body, duplex: "half" } : {}),
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Forwards a single RUM request to the configured gateway, returning 404 for non-RUM paths or
|
|
128
|
+
* when `options.fetch` is undefined, and 502 (after logging a warning) on upstream transport error.
|
|
129
|
+
*/
|
|
130
|
+
export async function proxyRum(request, options) {
|
|
131
|
+
let pathname;
|
|
132
|
+
try {
|
|
133
|
+
pathname = new URL(request.url).pathname;
|
|
134
|
+
}
|
|
135
|
+
catch {
|
|
136
|
+
return new Response("Not Found", { status: 404 });
|
|
137
|
+
}
|
|
138
|
+
if (!isRumProxyPath(pathname, options.prefix)) {
|
|
139
|
+
return new Response("Not Found", { status: 404 });
|
|
140
|
+
}
|
|
141
|
+
if (options.fetch === undefined) {
|
|
142
|
+
return new Response("no RUM gateway configured", { status: 404 });
|
|
143
|
+
}
|
|
144
|
+
const upstream = buildRumUpstreamRequest(request, options);
|
|
145
|
+
try {
|
|
146
|
+
return await options.fetch(upstream);
|
|
147
|
+
}
|
|
148
|
+
catch (err) {
|
|
149
|
+
if (options.onError !== undefined) {
|
|
150
|
+
try {
|
|
151
|
+
options.onError(err);
|
|
152
|
+
}
|
|
153
|
+
catch {
|
|
154
|
+
// Error callback never breaks the 502 response.
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
else {
|
|
158
|
+
try {
|
|
159
|
+
console.warn(`o11y: RUM gateway unreachable: ${err instanceof Error ? err.message : String(err)}`);
|
|
160
|
+
}
|
|
161
|
+
catch {
|
|
162
|
+
// Nothing left to log to.
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
return new Response("RUM gateway unreachable", { status: 502 });
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* Creates a reusable Worker fetch handler for forwarding `/_o11y/...` RUM requests to
|
|
170
|
+
* `o11yrum-gateway`.
|
|
171
|
+
*/
|
|
172
|
+
export function createRumProxy(options) {
|
|
173
|
+
return (request) => proxyRum(request, options);
|
|
174
|
+
}
|
package/dist/version.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/** The `@libo11y/workers` package version. scripts/release.ts keeps it equal to package.json. */
|
|
2
|
-
export declare const VERSION = "0.
|
|
2
|
+
export declare const VERSION = "0.9.0";
|
package/dist/version.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/** The `@libo11y/workers` package version. scripts/release.ts keeps it equal to package.json. */
|
|
2
|
-
export const VERSION = "0.
|
|
2
|
+
export const VERSION = "0.9.0";
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@libo11y/workers",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "The libo11y platform for Cloudflare Workers and Durable Objects (workerd): setup memoized per isolate, OTLP/HTTP export over fetch or a service binding,
|
|
3
|
+
"version": "0.9.0",
|
|
4
|
+
"description": "The libo11y platform for Cloudflare Workers and Durable Objects (workerd): setup memoized per isolate, OTLP/HTTP export with bounded retry over fetch or a service binding, AsyncLocalStorage context, dirty-aware snapshot-diffing metrics exported on flush, waitUntil flushing, composable DO/alarm/scheduled/queue tracing adapters, and an authenticated RUM gateway proxy.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"sideEffects": false,
|
|
@@ -17,9 +17,8 @@
|
|
|
17
17
|
"directory": "ts/packages/workers"
|
|
18
18
|
},
|
|
19
19
|
"dependencies": {
|
|
20
|
-
"@libo11y/core": "0.
|
|
21
|
-
"@libo11y/
|
|
22
|
-
"@libo11y/spec": "0.8.0",
|
|
20
|
+
"@libo11y/core": "0.9.0",
|
|
21
|
+
"@libo11y/spec": "0.9.0",
|
|
23
22
|
"@opentelemetry/core": "3.1.1",
|
|
24
23
|
"@opentelemetry/otlp-transformer": "0.301.1",
|
|
25
24
|
"@opentelemetry/sdk-logs": "3.1.1",
|
|
@@ -31,8 +30,8 @@
|
|
|
31
30
|
},
|
|
32
31
|
"devDependencies": {
|
|
33
32
|
"@effect/opentelemetry": "4.2.0",
|
|
34
|
-
"@libo11y/effect": "0.
|
|
35
|
-
"@libo11y/test": "0.
|
|
33
|
+
"@libo11y/effect": "0.9.0",
|
|
34
|
+
"@libo11y/test": "0.9.0",
|
|
36
35
|
"@opentelemetry/api": "1.10.0",
|
|
37
36
|
"effect": "4.2.0",
|
|
38
37
|
"workerd": "1.20261120.1"
|