@libo11y/workers 0.0.0-stage → 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.
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Workers resource detection, in the two layers core merges.
3
+ *
4
+ * The detected layer holds what an isolate can say about itself without inventing attributes: the
5
+ * upstream telemetry.sdk.* attributes with telemetry.sdk.language "webjs" (a Worker is a V8 isolate
6
+ * with the web platform's APIs, whichever upstream build a bundler picked), cloud.provider
7
+ * "cloudflare", and process.runtime.name "workerd" with its description when the runtime says it
8
+ * is Cloudflare Workers. A Worker has no host name, process ID or container to report. Core adds
9
+ * service.instance.id, a random UUID per isolate.
10
+ *
11
+ * The environment layer is OTEL_RESOURCE_ATTRIBUTES, then OTEL_SERVICE_NAME, from the Worker's env
12
+ * bindings. It is empty in hermetic mode.
13
+ */
14
+ import type { ResourceLayers } from "@libo11y/core";
15
+ import { type OtelEnv } from "./env.ts";
16
+ /** Detects the Workers resource layers from env. fromEnv is empty when hermetic is true. */
17
+ export declare function detectWorkersResource(hermetic: boolean, env: OtelEnv): Promise<ResourceLayers>;
@@ -0,0 +1,30 @@
1
+ import { SDK_INFO } from "@opentelemetry/core";
2
+ import { parseKeyValues } from "./env.js";
3
+ const WORKERS_USER_AGENT = "Cloudflare-Workers";
4
+ function isWorkerd() {
5
+ try {
6
+ return (globalThis.navigator?.userAgent === WORKERS_USER_AGENT);
7
+ }
8
+ catch {
9
+ return false;
10
+ }
11
+ }
12
+ /** Detects the Workers resource layers from env. fromEnv is empty when hermetic is true. */
13
+ export async function detectWorkersResource(hermetic, env) {
14
+ const sdk = Object.fromEntries(Object.entries(SDK_INFO).filter(([k]) => k.startsWith("telemetry.sdk.")));
15
+ const detected = {
16
+ ...sdk,
17
+ "telemetry.sdk.language": "webjs",
18
+ "cloud.provider": "cloudflare",
19
+ ...(isWorkerd()
20
+ ? { "process.runtime.name": "workerd", "process.runtime.description": "Cloudflare Workers" }
21
+ : {}),
22
+ };
23
+ if (hermetic)
24
+ return { detected, fromEnv: {} };
25
+ const fromEnv = parseKeyValues(env.OTEL_RESOURCE_ATTRIBUTES);
26
+ const serviceName = env.OTEL_SERVICE_NAME?.trim();
27
+ if (serviceName !== undefined && serviceName !== "")
28
+ fromEnv["service.name"] = serviceName;
29
+ return { detected, fromEnv };
30
+ }
@@ -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
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * setup and createTelemetry bound to the Workers platform.
3
+ *
4
+ * A Worker isolate serves many invocations, and its global scope may not start timers or I/O, so
5
+ * telemetry is set up inside the first invocation and kept for the isolate's life. setup is
6
+ * memoized per isolate: every call made while a telemetry from it is live, or while one is being
7
+ * built, returns the same promise, so concurrent first requests build one telemetry. A call after
8
+ * that telemetry shut down, or after a setup that failed, builds a new one. Core's process-wide
9
+ * guard still applies: while a telemetry from another setup is live, setup fails with ALREADY_SETUP.
10
+ */
11
+ import { type Telemetry, type TelemetryOptions } from "@libo11y/core";
12
+ import { type WorkersPlatformOptions } from "./platform.ts";
13
+ /** The libo11y telemetry options, and the Workers platform's. */
14
+ export interface WorkersOptions extends TelemetryOptions, WorkersPlatformOptions {
15
+ }
16
+ /**
17
+ * Builds telemetry on the Workers platform once per isolate, emits the o11y.telemetry.configured
18
+ * canary and installs it globally: the AsyncLocalStorage context manager, the tracer, meter and
19
+ * logger providers, the propagator and the error handler. Call it inside a handler, never at module
20
+ * scope, which workerd does not let start timers. Every later call returns the first call's
21
+ * promise while its telemetry is live, whatever options it passes. It rejects with O11yError as
22
+ * core's setupWith does, and the next call tries again.
23
+ */
24
+ export declare function setup(options?: WorkersOptions): Promise<Telemetry>;
25
+ /**
26
+ * Builds telemetry on the Workers platform without touching any global, without the canary and
27
+ * without memoizing it, as a test or a second pipeline wants.
28
+ */
29
+ export declare function createTelemetry(options?: WorkersOptions): Promise<Telemetry>;
package/dist/setup.js ADDED
@@ -0,0 +1,69 @@
1
+ /**
2
+ * setup and createTelemetry bound to the Workers platform.
3
+ *
4
+ * A Worker isolate serves many invocations, and its global scope may not start timers or I/O, so
5
+ * telemetry is set up inside the first invocation and kept for the isolate's life. setup is
6
+ * memoized per isolate: every call made while a telemetry from it is live, or while one is being
7
+ * built, returns the same promise, so concurrent first requests build one telemetry. A call after
8
+ * that telemetry shut down, or after a setup that failed, builds a new one. Core's process-wide
9
+ * guard still applies: while a telemetry from another setup is live, setup fails with ALREADY_SETUP.
10
+ */
11
+ import { createTelemetryWith, setupWith } from "@libo11y/core";
12
+ import { workersPlatform } from "./platform.js";
13
+ // The guard core's setupWith holds while a global telemetry is live, shared by every copy of core.
14
+ const GUARD = Symbol.for("libo11y.setup");
15
+ function guardHeld() {
16
+ return globalThis[GUARD] === true;
17
+ }
18
+ let memo;
19
+ function split(options) {
20
+ const { env, exporter, metricsFlushIntervalMillis, ...core } = options;
21
+ return {
22
+ core,
23
+ platform: {
24
+ ...(env === undefined ? {} : { env }),
25
+ ...(exporter === undefined ? {} : { exporter }),
26
+ ...(metricsFlushIntervalMillis === undefined ? {} : { metricsFlushIntervalMillis }),
27
+ },
28
+ };
29
+ }
30
+ /**
31
+ * Builds telemetry on the Workers platform once per isolate, emits the o11y.telemetry.configured
32
+ * canary and installs it globally: the AsyncLocalStorage context manager, the tracer, meter and
33
+ * logger providers, the propagator and the error handler. Call it inside a handler, never at module
34
+ * scope, which workerd does not let start timers. Every later call returns the first call's
35
+ * promise while its telemetry is live, whatever options it passes. It rejects with O11yError as
36
+ * core's setupWith does, and the next call tries again.
37
+ */
38
+ export function setup(options = {}) {
39
+ const current = memo;
40
+ if (current !== undefined) {
41
+ // A settled telemetry is handed out in a promise of this invocation's own. workerd ties a
42
+ // promise to the invocation that made it, and awaiting one from an invocation that has ended
43
+ // queues work into a context that no longer runs.
44
+ if (current.telemetry !== undefined && guardHeld())
45
+ return Promise.resolve(current.telemetry);
46
+ if (current.telemetry === undefined)
47
+ return current.promise;
48
+ }
49
+ const { core, platform } = split(options);
50
+ const entry = { promise: Promise.resolve(undefined), telemetry: undefined };
51
+ entry.promise = setupWith(core, workersPlatform(platform)).then((telemetry) => {
52
+ entry.telemetry = telemetry;
53
+ return telemetry;
54
+ }, (err) => {
55
+ if (memo === entry)
56
+ memo = undefined;
57
+ throw err;
58
+ });
59
+ memo = entry;
60
+ return entry.promise;
61
+ }
62
+ /**
63
+ * Builds telemetry on the Workers platform without touching any global, without the canary and
64
+ * without memoizing it, as a test or a second pipeline wants.
65
+ */
66
+ export function createTelemetry(options = {}) {
67
+ const { core, platform } = split(options);
68
+ return createTelemetryWith(core, workersPlatform(platform));
69
+ }
@@ -0,0 +1,2 @@
1
+ /** The `@libo11y/workers` package version. scripts/release.ts keeps it equal to package.json. */
2
+ export declare const VERSION = "0.9.0";
@@ -0,0 +1,2 @@
1
+ /** The `@libo11y/workers` package version. scripts/release.ts keeps it equal to package.json. */
2
+ export const VERSION = "0.9.0";
package/package.json CHANGED
@@ -1,6 +1,48 @@
1
1
  {
2
2
  "name": "@libo11y/workers",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
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
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "sideEffects": false,
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "default": "./dist/index.js"
12
+ }
13
+ },
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/libo11y/libo11y.git",
17
+ "directory": "ts/packages/workers"
18
+ },
19
+ "dependencies": {
20
+ "@libo11y/core": "0.9.0",
21
+ "@libo11y/spec": "0.9.0",
22
+ "@opentelemetry/core": "3.1.1",
23
+ "@opentelemetry/otlp-transformer": "0.301.1",
24
+ "@opentelemetry/sdk-logs": "3.1.1",
25
+ "@opentelemetry/sdk-metrics": "3.1.1",
26
+ "@opentelemetry/sdk-trace": "3.1.1"
27
+ },
28
+ "peerDependencies": {
29
+ "@opentelemetry/api": ">=1.10.0 <1.11.0"
30
+ },
31
+ "devDependencies": {
32
+ "@effect/opentelemetry": "4.2.0",
33
+ "@libo11y/effect": "0.9.0",
34
+ "@libo11y/test": "0.9.0",
35
+ "@opentelemetry/api": "1.10.0",
36
+ "effect": "4.2.0",
37
+ "workerd": "1.20261120.1"
38
+ },
39
+ "files": [
40
+ "dist",
41
+ "README.md",
42
+ "LICENSE"
43
+ ],
44
+ "publishConfig": {
45
+ "access": "public",
46
+ "provenance": true
47
+ }
48
+ }