@libo11y/effect 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 +119 -55
- package/dist/client.d.ts +176 -0
- package/dist/client.js +583 -0
- package/dist/index.d.ts +7 -5
- package/dist/index.js +6 -4
- package/dist/layer.d.ts +3 -0
- package/dist/layer.js +1 -1
- package/dist/logger.d.ts +5 -0
- package/dist/logger.js +16 -20
- package/dist/metrics.d.ts +28 -15
- package/dist/metrics.js +284 -57
- package/dist/span-context.d.ts +15 -0
- package/dist/span-context.js +56 -0
- package/dist/tracer.d.ts +21 -1
- package/dist/tracer.js +36 -2
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/workers.d.ts +101 -0
- package/dist/workers.js +352 -0
- package/package.json +5 -5
package/dist/client.js
ADDED
|
@@ -0,0 +1,583 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Effect 4 client telemetry and single-carrier gated propagation layers:
|
|
3
|
+
*
|
|
4
|
+
* - createTelemetryRef / clientLayer: late-bound Effect Tracer, Logger, and Metrics layers built on
|
|
5
|
+
* @effect/opentelemetry's OtelTracer.layerWithoutOtelTracer (never creating a duplicate SDK) so
|
|
6
|
+
* module-level runtimes activate seamlessly once lazy browser RUM or native setup finishes.
|
|
7
|
+
* - httpClientLayer / stripHttpRpcSerialization / rpcProtocolHttpLayer: enforces one gated carrier
|
|
8
|
+
* per HTTP hop. Injects configured propagator headers inside FetchHttpClient.Fetch with
|
|
9
|
+
* HttpClient.TracerPropagationEnabled = false, uses PropagationConfig.fetch (pristineFetch on
|
|
10
|
+
* web, depth-guarded untracedFetch on bare React Native), strips all propagator fields before
|
|
11
|
+
* injection and on blocked requests, applies runtime-explicit redirect handling, and strips
|
|
12
|
+
* { traceId, spanId, sampled } from HTTP RPC request bodies at the RpcSerialization boundary.
|
|
13
|
+
* - gateWebSocketConstructor / webSocketConstructorLayer / gateSocketRpcProtocol: enforces
|
|
14
|
+
* write-time consent and destination gating on WebSocket RPC envelopes right before wire send
|
|
15
|
+
* (after Socket.fromWebSocket's latch.whenOpen resumes), plus protocol-level gating for custom
|
|
16
|
+
* or binary socket serializations.
|
|
17
|
+
*/
|
|
18
|
+
import * as OtelTracer from "@effect/opentelemetry/OtelTracer";
|
|
19
|
+
import { getPropagationConfig } from "@libo11y/core/internal";
|
|
20
|
+
import { INVALID_SPAN_CONTEXT, context as otelContext, trace as otelTrace, } from "@opentelemetry/api";
|
|
21
|
+
import * as Context from "effect/Context";
|
|
22
|
+
import * as Effect from "effect/Effect";
|
|
23
|
+
import * as Fiber from "effect/Fiber";
|
|
24
|
+
import { constFalse, constTrue } from "effect/Function";
|
|
25
|
+
import * as FetchHttpClient from "effect/http/FetchHttpClient";
|
|
26
|
+
import * as HttpBody from "effect/http/HttpBody";
|
|
27
|
+
import * as HttpClient from "effect/http/HttpClient";
|
|
28
|
+
import * as HttpClientRequest from "effect/http/HttpClientRequest";
|
|
29
|
+
import * as Layer from "effect/Layer";
|
|
30
|
+
import * as Logger from "effect/Logger";
|
|
31
|
+
import * as References from "effect/References";
|
|
32
|
+
import * as RpcClient from "effect/rpc/RpcClient";
|
|
33
|
+
import * as RpcSerialization from "effect/rpc/RpcSerialization";
|
|
34
|
+
import * as Socket from "effect/socket/Socket";
|
|
35
|
+
import * as Tracer from "effect/Tracer";
|
|
36
|
+
import * as Version from "effect/Version";
|
|
37
|
+
import { makeDynamicLogger } from "./logger.js";
|
|
38
|
+
import { dynamicMetricsLayer } from "./metrics.js";
|
|
39
|
+
import { activePropagatedSpan, contextOfSpan } from "./span-context.js";
|
|
40
|
+
const refSubscribers = new WeakMap();
|
|
41
|
+
/** Creates a live TelemetryRef, optionally seeded with an already-initialized Telemetry handle. */
|
|
42
|
+
export function createTelemetryRef(initial) {
|
|
43
|
+
let current = initial;
|
|
44
|
+
const listeners = new Set();
|
|
45
|
+
const ref = {
|
|
46
|
+
get: () => current,
|
|
47
|
+
set: (telemetry) => {
|
|
48
|
+
current = telemetry;
|
|
49
|
+
for (const listener of listeners) {
|
|
50
|
+
try {
|
|
51
|
+
listener(telemetry);
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
// Listeners must never break telemetry attachment.
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
},
|
|
58
|
+
};
|
|
59
|
+
refSubscribers.set(ref, listeners);
|
|
60
|
+
return ref;
|
|
61
|
+
}
|
|
62
|
+
function isTelemetryRef(source) {
|
|
63
|
+
return typeof source.get === "function";
|
|
64
|
+
}
|
|
65
|
+
function resolveTelemetry(source) {
|
|
66
|
+
if (source === undefined)
|
|
67
|
+
return undefined;
|
|
68
|
+
return isTelemetryRef(source) ? source.get() : source;
|
|
69
|
+
}
|
|
70
|
+
function subscribeTelemetry(source, listener) {
|
|
71
|
+
if (!isTelemetryRef(source))
|
|
72
|
+
return;
|
|
73
|
+
refSubscribers.get(source)?.add(listener);
|
|
74
|
+
}
|
|
75
|
+
function makeNoopOtelSpan() {
|
|
76
|
+
return otelTrace.wrapSpanContext(INVALID_SPAN_CONTEXT);
|
|
77
|
+
}
|
|
78
|
+
function makeDelegatingOtelTracer(getTelemetry) {
|
|
79
|
+
let cachedProvider;
|
|
80
|
+
let cachedTracer;
|
|
81
|
+
const currentTracer = () => {
|
|
82
|
+
const provider = getTelemetry()?.tracerProvider;
|
|
83
|
+
if (provider === undefined) {
|
|
84
|
+
cachedProvider = undefined;
|
|
85
|
+
cachedTracer = undefined;
|
|
86
|
+
return undefined;
|
|
87
|
+
}
|
|
88
|
+
if (provider !== cachedProvider || cachedTracer === undefined) {
|
|
89
|
+
cachedProvider = provider;
|
|
90
|
+
cachedTracer = provider.getTracer("effect", Version.getCurrentVersion());
|
|
91
|
+
}
|
|
92
|
+
return cachedTracer;
|
|
93
|
+
};
|
|
94
|
+
function startSpan(name, options, ctx) {
|
|
95
|
+
const tracer = currentTracer();
|
|
96
|
+
if (tracer === undefined)
|
|
97
|
+
return makeNoopOtelSpan();
|
|
98
|
+
return tracer.startSpan(name, options, ctx);
|
|
99
|
+
}
|
|
100
|
+
function startActiveSpan(name, arg2, arg3, arg4) {
|
|
101
|
+
const tracer = currentTracer();
|
|
102
|
+
if (typeof arg2 === "function") {
|
|
103
|
+
return tracer === undefined ? arg2(makeNoopOtelSpan()) : tracer.startActiveSpan(name, arg2);
|
|
104
|
+
}
|
|
105
|
+
if (typeof arg3 === "function") {
|
|
106
|
+
return tracer === undefined ? arg3(makeNoopOtelSpan()) : tracer.startActiveSpan(name, arg2, arg3);
|
|
107
|
+
}
|
|
108
|
+
const fn = arg4;
|
|
109
|
+
return tracer === undefined
|
|
110
|
+
? fn(makeNoopOtelSpan())
|
|
111
|
+
: tracer.startActiveSpan(name, arg2, arg3, fn);
|
|
112
|
+
}
|
|
113
|
+
return { startSpan, startActiveSpan };
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Installs an Effect Tracer, Logger, and Metrics bridge over a concrete Telemetry or live
|
|
117
|
+
* TelemetryRef using `@effect/opentelemetry`'s `OtelTracer.layerWithoutOtelTracer` (never creating
|
|
118
|
+
* a duplicate SDK or touching globals). When backed by a TelemetryRef that starts undefined, spans
|
|
119
|
+
* and logs stay silent until `ref.set(telemetry)` runs and activate seamlessly thereafter.
|
|
120
|
+
*/
|
|
121
|
+
export function clientLayer(telemetryOrRef, options = {}) {
|
|
122
|
+
const getTelemetry = () => resolveTelemetry(telemetryOrRef);
|
|
123
|
+
const delegatingTracer = makeDelegatingOtelTracer(getTelemetry);
|
|
124
|
+
const tracer = OtelTracer.layerWithoutOtelTracer.pipe(Layer.provideMerge(Layer.succeed(OtelTracer.OtelTracer, delegatingTracer)));
|
|
125
|
+
const logger = options.logger === "none"
|
|
126
|
+
? Layer.empty
|
|
127
|
+
: Logger.layer([makeDynamicLogger(getTelemetry)], {
|
|
128
|
+
mergeWithExisting: options.logger === "merge",
|
|
129
|
+
});
|
|
130
|
+
const metrics = options.metrics === false
|
|
131
|
+
? Layer.empty
|
|
132
|
+
: dynamicMetricsLayer(telemetryOrRef, getTelemetry, (listener) => subscribeTelemetry(telemetryOrRef, listener));
|
|
133
|
+
return Layer.mergeAll(tracer, logger, metrics);
|
|
134
|
+
}
|
|
135
|
+
const DEFAULT_CARRIER_HEADERS = ["traceparent", "tracestate", "baggage"];
|
|
136
|
+
const DEFAULT_MAX_REDIRECTS = 20;
|
|
137
|
+
const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
|
|
138
|
+
const CROSS_ORIGIN_STRIP_HEADERS = ["authorization", "proxy-authorization", "cookie"];
|
|
139
|
+
const BODY_ENTITY_HEADERS = [
|
|
140
|
+
"content-type",
|
|
141
|
+
"content-length",
|
|
142
|
+
"content-encoding",
|
|
143
|
+
"content-language",
|
|
144
|
+
"content-location",
|
|
145
|
+
];
|
|
146
|
+
const HEADERS_SETTER = {
|
|
147
|
+
set: (carrier, key, value) => {
|
|
148
|
+
carrier.set(key, value);
|
|
149
|
+
},
|
|
150
|
+
};
|
|
151
|
+
function parseUrlSafe(raw) {
|
|
152
|
+
try {
|
|
153
|
+
const loc = globalThis.location;
|
|
154
|
+
const base = typeof loc?.href === "string" ? loc.href : undefined;
|
|
155
|
+
return base === undefined ? new URL(raw) : new URL(raw, base);
|
|
156
|
+
}
|
|
157
|
+
catch {
|
|
158
|
+
return undefined;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
function carrierHeaderNames(telemetry, extraFields) {
|
|
162
|
+
const names = new Set();
|
|
163
|
+
const propFields = telemetry?.propagator.fields() ?? [];
|
|
164
|
+
if (propFields.length === 0) {
|
|
165
|
+
for (const f of DEFAULT_CARRIER_HEADERS)
|
|
166
|
+
names.add(f);
|
|
167
|
+
}
|
|
168
|
+
else {
|
|
169
|
+
for (const f of propFields)
|
|
170
|
+
names.add(f);
|
|
171
|
+
}
|
|
172
|
+
if (extraFields !== undefined) {
|
|
173
|
+
for (const f of extraFields)
|
|
174
|
+
names.add(f);
|
|
175
|
+
}
|
|
176
|
+
return [...names];
|
|
177
|
+
}
|
|
178
|
+
function canPropagate(telemetry, propagation, url, predicates) {
|
|
179
|
+
if (telemetry === undefined)
|
|
180
|
+
return false;
|
|
181
|
+
try {
|
|
182
|
+
if (propagation !== undefined) {
|
|
183
|
+
if (!propagation.isRecording())
|
|
184
|
+
return false;
|
|
185
|
+
if (propagation.isIgnored(url))
|
|
186
|
+
return false;
|
|
187
|
+
if (!propagation.shouldPropagate(url))
|
|
188
|
+
return false;
|
|
189
|
+
}
|
|
190
|
+
if (predicates.isIgnored?.(url) === true)
|
|
191
|
+
return false;
|
|
192
|
+
if (predicates.shouldPropagate !== undefined && !predicates.shouldPropagate(url))
|
|
193
|
+
return false;
|
|
194
|
+
return true;
|
|
195
|
+
}
|
|
196
|
+
catch {
|
|
197
|
+
return false;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
function activeInjectionContext() {
|
|
201
|
+
const active = otelContext.active();
|
|
202
|
+
if (otelTrace.getSpan(active) !== undefined)
|
|
203
|
+
return active;
|
|
204
|
+
const span = activePropagatedSpan();
|
|
205
|
+
return span === undefined ? active : contextOfSpan(span, active);
|
|
206
|
+
}
|
|
207
|
+
function isReadableStreamBody(body) {
|
|
208
|
+
return typeof ReadableStream !== "undefined" && body instanceof ReadableStream;
|
|
209
|
+
}
|
|
210
|
+
function isHopTracerDisabled(disabledWhen, method, url, headers, body) {
|
|
211
|
+
try {
|
|
212
|
+
const base = HttpClientRequest.make(method)(url.href, { headers });
|
|
213
|
+
const hopRequest = HttpClientRequest.makeWith(base.method, base.url, base.urlParams, base.hash, base.headers, body);
|
|
214
|
+
return disabledWhen(hopRequest);
|
|
215
|
+
}
|
|
216
|
+
catch {
|
|
217
|
+
return true;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
const identityPreprocess = (request) => Effect.succeed(request);
|
|
221
|
+
function makeGatedFetch(telemetryOrRef, options, browserDefaultRedirect, fallbackFetch, requestTracerDisabled, disabledWhen, requestBody) {
|
|
222
|
+
const maxRedirects = options.maxRedirects ?? DEFAULT_MAX_REDIRECTS;
|
|
223
|
+
const predicates = {
|
|
224
|
+
shouldPropagate: options.shouldPropagate,
|
|
225
|
+
isIgnored: options.isIgnored,
|
|
226
|
+
};
|
|
227
|
+
async function gatedFetch(input, init) {
|
|
228
|
+
const telemetry = resolveTelemetry(telemetryOrRef);
|
|
229
|
+
const propagation = getPropagationConfig(telemetry);
|
|
230
|
+
const baseFetch = options.fetch ?? propagation?.fetch ?? fallbackFetch ?? globalThis.fetch;
|
|
231
|
+
const requestObj = input instanceof Request ? input : undefined;
|
|
232
|
+
const rawUrl = requestObj !== undefined ? requestObj.url : input instanceof URL ? input.href : String(input);
|
|
233
|
+
const stripFields = carrierHeaderNames(telemetry, options.propagatorFields);
|
|
234
|
+
const headers = new Headers(init?.headers ?? requestObj?.headers);
|
|
235
|
+
for (const name of stripFields) {
|
|
236
|
+
headers.delete(name);
|
|
237
|
+
}
|
|
238
|
+
const url = parseUrlSafe(rawUrl);
|
|
239
|
+
if (url === undefined) {
|
|
240
|
+
return baseFetch(input, { ...init, headers });
|
|
241
|
+
}
|
|
242
|
+
const runtime = options.runtime ?? propagation?.runtime ?? (telemetry === undefined ? "browser" : "server");
|
|
243
|
+
const currentFiber = Fiber.getCurrent();
|
|
244
|
+
const tracerDisabled = requestTracerDisabled ||
|
|
245
|
+
(currentFiber !== undefined &&
|
|
246
|
+
(!currentFiber.getRef(References.TracerEnabled) || currentFiber.getRef(Tracer.DisablePropagation)));
|
|
247
|
+
const activeCtx = activeInjectionContext();
|
|
248
|
+
let injected = false;
|
|
249
|
+
if (!tracerDisabled && canPropagate(telemetry, propagation, url, predicates) && telemetry !== undefined) {
|
|
250
|
+
try {
|
|
251
|
+
telemetry.propagator.inject(activeCtx, headers, HEADERS_SETTER);
|
|
252
|
+
injected = true;
|
|
253
|
+
}
|
|
254
|
+
catch {
|
|
255
|
+
for (const name of stripFields) {
|
|
256
|
+
headers.delete(name);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
const defaultRedirect = runtime === "browser" && browserDefaultRedirect !== undefined ? browserDefaultRedirect : undefined;
|
|
261
|
+
const effectiveRedirect = init?.redirect ?? options.redirect ?? defaultRedirect;
|
|
262
|
+
// Non-browser runtimes (Node, Bun, Workers): validate redirects hop-by-hop whenever trace
|
|
263
|
+
// headers were injected and redirect following is active.
|
|
264
|
+
if (runtime === "server" &&
|
|
265
|
+
injected &&
|
|
266
|
+
(effectiveRedirect === undefined || effectiveRedirect === "follow")) {
|
|
267
|
+
const seenStripFields = new Set(stripFields);
|
|
268
|
+
let currentUrl = url;
|
|
269
|
+
let currentMethod = (init?.method ?? requestObj?.method ?? "GET").toUpperCase();
|
|
270
|
+
let currentBody = init !== undefined && "body" in init ? init.body : requestObj?.body;
|
|
271
|
+
let currentEffectBody = requestBody;
|
|
272
|
+
let currentHeaders = headers;
|
|
273
|
+
let currentDuplex = init?.duplex;
|
|
274
|
+
for (let hops = 0;; hops++) {
|
|
275
|
+
const hopInit = {
|
|
276
|
+
...init,
|
|
277
|
+
method: currentMethod,
|
|
278
|
+
headers: currentHeaders,
|
|
279
|
+
body: currentBody ?? null,
|
|
280
|
+
redirect: "manual",
|
|
281
|
+
};
|
|
282
|
+
if (currentBody === undefined || currentBody === null) {
|
|
283
|
+
delete hopInit.body;
|
|
284
|
+
}
|
|
285
|
+
if (currentDuplex !== undefined) {
|
|
286
|
+
hopInit.duplex = currentDuplex;
|
|
287
|
+
}
|
|
288
|
+
else {
|
|
289
|
+
delete hopInit.duplex;
|
|
290
|
+
}
|
|
291
|
+
const response = await baseFetch(currentUrl, hopInit);
|
|
292
|
+
if (!REDIRECT_STATUSES.has(response.status)) {
|
|
293
|
+
return response;
|
|
294
|
+
}
|
|
295
|
+
const location = response.headers.get("location");
|
|
296
|
+
if (location === null || location === "") {
|
|
297
|
+
return response;
|
|
298
|
+
}
|
|
299
|
+
let nextUrl;
|
|
300
|
+
try {
|
|
301
|
+
nextUrl = new URL(location, currentUrl);
|
|
302
|
+
}
|
|
303
|
+
catch {
|
|
304
|
+
return response;
|
|
305
|
+
}
|
|
306
|
+
if (hops >= maxRedirects) {
|
|
307
|
+
await response.body?.cancel().catch(() => { });
|
|
308
|
+
throw new TypeError(`Too many redirects (limit ${maxRedirects})`);
|
|
309
|
+
}
|
|
310
|
+
await response.body?.cancel().catch(() => { });
|
|
311
|
+
const nextHeaders = new Headers(currentHeaders);
|
|
312
|
+
let nextMethod = currentMethod;
|
|
313
|
+
let nextBody = currentBody;
|
|
314
|
+
let nextEffectBody = currentEffectBody;
|
|
315
|
+
let nextDuplex = currentDuplex;
|
|
316
|
+
if (((response.status === 301 || response.status === 302) && currentMethod === "POST") ||
|
|
317
|
+
(response.status === 303 && currentMethod !== "GET" && currentMethod !== "HEAD")) {
|
|
318
|
+
nextMethod = "GET";
|
|
319
|
+
nextBody = undefined;
|
|
320
|
+
nextEffectBody = HttpBody.empty;
|
|
321
|
+
nextDuplex = undefined;
|
|
322
|
+
for (const h of BODY_ENTITY_HEADERS)
|
|
323
|
+
nextHeaders.delete(h);
|
|
324
|
+
}
|
|
325
|
+
else if (isReadableStreamBody(nextBody)) {
|
|
326
|
+
throw new TypeError("Cannot follow redirect with a ReadableStream body");
|
|
327
|
+
}
|
|
328
|
+
if (nextUrl.origin !== currentUrl.origin) {
|
|
329
|
+
for (const h of CROSS_ORIGIN_STRIP_HEADERS)
|
|
330
|
+
nextHeaders.delete(h);
|
|
331
|
+
}
|
|
332
|
+
const hopTelemetry = resolveTelemetry(telemetryOrRef);
|
|
333
|
+
const hopPropagation = getPropagationConfig(hopTelemetry);
|
|
334
|
+
const hopStripFields = carrierHeaderNames(hopTelemetry, options.propagatorFields);
|
|
335
|
+
for (const name of hopStripFields) {
|
|
336
|
+
seenStripFields.add(name);
|
|
337
|
+
}
|
|
338
|
+
for (const name of seenStripFields) {
|
|
339
|
+
nextHeaders.delete(name);
|
|
340
|
+
}
|
|
341
|
+
const hopDisabled = isHopTracerDisabled(disabledWhen, nextMethod, nextUrl, nextHeaders, nextEffectBody);
|
|
342
|
+
if (!hopDisabled &&
|
|
343
|
+
canPropagate(hopTelemetry, hopPropagation, nextUrl, predicates) &&
|
|
344
|
+
hopTelemetry !== undefined) {
|
|
345
|
+
try {
|
|
346
|
+
hopTelemetry.propagator.inject(activeCtx, nextHeaders, HEADERS_SETTER);
|
|
347
|
+
}
|
|
348
|
+
catch {
|
|
349
|
+
for (const name of seenStripFields) {
|
|
350
|
+
nextHeaders.delete(name);
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
currentUrl = nextUrl;
|
|
355
|
+
currentMethod = nextMethod;
|
|
356
|
+
currentBody = nextBody;
|
|
357
|
+
currentEffectBody = nextEffectBody;
|
|
358
|
+
currentHeaders = nextHeaders;
|
|
359
|
+
currentDuplex = nextDuplex;
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
const finalInit = {
|
|
363
|
+
...init,
|
|
364
|
+
headers,
|
|
365
|
+
...(effectiveRedirect === undefined ? {} : { redirect: effectiveRedirect }),
|
|
366
|
+
};
|
|
367
|
+
return baseFetch(input, finalInit);
|
|
368
|
+
}
|
|
369
|
+
return gatedFetch;
|
|
370
|
+
}
|
|
371
|
+
function buildHttpClientLayer(telemetryOrRef, options, browserDefaultRedirect) {
|
|
372
|
+
return Layer.effect(HttpClient.HttpClient, Effect.gen(function* () {
|
|
373
|
+
const baseClient = yield* HttpClient.HttpClient;
|
|
374
|
+
const buildContext = yield* Effect.context();
|
|
375
|
+
const buildTimeFetch = Context.getOrUndefined(buildContext, FetchHttpClient.Fetch);
|
|
376
|
+
return HttpClient.makeWith((requestEffect) => Effect.flatMap(requestEffect, (request) => Effect.withFiber((fiber) => {
|
|
377
|
+
const merged = Context.merge(buildContext, fiber.context);
|
|
378
|
+
const disabledWhen = Context.get(merged, HttpClient.TracerDisabledWhen);
|
|
379
|
+
const tracerDisabled = !Context.get(merged, References.TracerEnabled) ||
|
|
380
|
+
Context.get(merged, Tracer.DisablePropagation) ||
|
|
381
|
+
disabledWhen(request);
|
|
382
|
+
const explicitFiberFetch = Context.getOrUndefined(fiber.context, FetchHttpClient.Fetch);
|
|
383
|
+
const gated = makeGatedFetch(telemetryOrRef, options, browserDefaultRedirect, explicitFiberFetch ?? buildTimeFetch, tracerDisabled, disabledWhen, request.body);
|
|
384
|
+
return baseClient
|
|
385
|
+
.execute(request)
|
|
386
|
+
.pipe(Effect.provideService(HttpClient.TracerPropagationEnabled, false), Effect.provideService(HttpClient.TracerDisabledWhen, tracerDisabled ? constTrue : constFalse), Effect.provideService(FetchHttpClient.Fetch, gated));
|
|
387
|
+
})), identityPreprocess);
|
|
388
|
+
})).pipe(Layer.provide(FetchHttpClient.layer));
|
|
389
|
+
}
|
|
390
|
+
/**
|
|
391
|
+
* Provides an Effect `HttpClient` over `FetchHttpClient` with gated single-carrier propagation:
|
|
392
|
+
*
|
|
393
|
+
* - Disables Effect's built-in `b3` + ungated `traceparent` injection
|
|
394
|
+
* (`HttpClient.TracerPropagationEnabled = false`) while keeping Effect's `CLIENT` HTTP span.
|
|
395
|
+
* - Uses `PropagationConfig.fetch` (`pristineFetch` on web, `depth`-guarded `untracedFetch` on
|
|
396
|
+
* bare React Native) so global RUM fetch/XHR patches never emit duplicate spans or headers.
|
|
397
|
+
* - Strips all configured `propagator.fields()` (plus `options.propagatorFields` / W3C defaults)
|
|
398
|
+
* before injection and on blocked requests.
|
|
399
|
+
* - Applies runtime-explicit redirect handling (`"server"`: hop-by-hop manual validation;
|
|
400
|
+
* `"browser"`: preserves `"follow"` by default, overridable via `redirect: "error"`;
|
|
401
|
+
* `"react-native"`: runs over `untracedFetch`).
|
|
402
|
+
*/
|
|
403
|
+
export function httpClientLayer(telemetryOrRef, options = {}) {
|
|
404
|
+
return buildHttpClientLayer(telemetryOrRef, options, undefined);
|
|
405
|
+
}
|
|
406
|
+
function stripRequestTraceFields(value) {
|
|
407
|
+
if (Array.isArray(value)) {
|
|
408
|
+
let changed = false;
|
|
409
|
+
const mapped = value.map((item) => {
|
|
410
|
+
const next = stripRequestTraceFields(item);
|
|
411
|
+
if (next !== item)
|
|
412
|
+
changed = true;
|
|
413
|
+
return next;
|
|
414
|
+
});
|
|
415
|
+
return changed ? mapped : value;
|
|
416
|
+
}
|
|
417
|
+
if (typeof value === "object" &&
|
|
418
|
+
value !== null &&
|
|
419
|
+
value._tag === "Request") {
|
|
420
|
+
const record = value;
|
|
421
|
+
if (!("traceId" in record) && !("spanId" in record) && !("sampled" in record)) {
|
|
422
|
+
return value;
|
|
423
|
+
}
|
|
424
|
+
const { traceId: _traceId, spanId: _spanId, sampled: _sampled, ...rest } = record;
|
|
425
|
+
return rest;
|
|
426
|
+
}
|
|
427
|
+
return value;
|
|
428
|
+
}
|
|
429
|
+
/**
|
|
430
|
+
* Wraps an Effect `RpcSerialization` layer so HTTP RPC requests omit `{ traceId, spanId, sampled }`
|
|
431
|
+
* from encoded `Request` envelopes (single or batched arrays) right before wire serialization.
|
|
432
|
+
*
|
|
433
|
+
* Preserves Effect's `HttpClient` spans and batched `RpcClient.batch` `withBatchSpan` links
|
|
434
|
+
* (unlike `Tracer.DisablePropagation`, which turns spans into no-ops).
|
|
435
|
+
*/
|
|
436
|
+
export function stripHttpRpcSerialization(serializationLayer) {
|
|
437
|
+
return Layer.effect(RpcSerialization.RpcSerialization, Effect.map(Effect.service(RpcSerialization.RpcSerialization), (base) => RpcSerialization.RpcSerialization.of({
|
|
438
|
+
...base,
|
|
439
|
+
makeUnsafe: (options) => {
|
|
440
|
+
const parser = base.makeUnsafe(options);
|
|
441
|
+
return {
|
|
442
|
+
decode: parser.decode,
|
|
443
|
+
encode: (value) => parser.encode(stripRequestTraceFields(value)),
|
|
444
|
+
};
|
|
445
|
+
},
|
|
446
|
+
}))).pipe(Layer.provide(serializationLayer));
|
|
447
|
+
}
|
|
448
|
+
/**
|
|
449
|
+
* Convenience layer for Effect HTTP RPC clients enforcing the single-carrier invariant:
|
|
450
|
+
*
|
|
451
|
+
* - Combines {@link httpClientLayer} (with `redirect: "error"` by default on `"browser"` so Effect
|
|
452
|
+
* HTTP RPC POSTs never carry trace headers across redirects, overridable via `redirect: "follow"`,
|
|
453
|
+
* and hop-by-hop manual redirect validation on `"server"`)
|
|
454
|
+
* - With {@link stripHttpRpcSerialization} (defaulting to `RpcSerialization.layerNdjson`) so HTTP
|
|
455
|
+
* RPC request bodies carry no `{ traceId, spanId, sampled }` fields.
|
|
456
|
+
*/
|
|
457
|
+
export function rpcProtocolHttpLayer(telemetryOrRef, options) {
|
|
458
|
+
const { url, transformClient, batch, serialization, ...httpOptions } = options;
|
|
459
|
+
const clientLayerImpl = buildHttpClientLayer(telemetryOrRef, httpOptions, "error");
|
|
460
|
+
const serializationLayer = stripHttpRpcSerialization((serialization ?? RpcSerialization.layerNdjson));
|
|
461
|
+
return RpcClient.layerProtocolHttp({
|
|
462
|
+
url,
|
|
463
|
+
...(transformClient === undefined ? {} : { transformClient }),
|
|
464
|
+
...(batch === undefined ? {} : { batch }),
|
|
465
|
+
}).pipe(Layer.provide(Layer.merge(clientLayerImpl, serializationLayer)));
|
|
466
|
+
}
|
|
467
|
+
function scrubJsonFrameText(frame) {
|
|
468
|
+
const trimmed = frame.trim();
|
|
469
|
+
if (trimmed === "" || (trimmed[0] !== "{" && trimmed[0] !== "["))
|
|
470
|
+
return frame;
|
|
471
|
+
try {
|
|
472
|
+
const parsed = JSON.parse(frame);
|
|
473
|
+
const stripped = stripRequestTraceFields(parsed);
|
|
474
|
+
return stripped === parsed ? frame : JSON.stringify(stripped);
|
|
475
|
+
}
|
|
476
|
+
catch {
|
|
477
|
+
return frame;
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
function scrubSocketTextData(data) {
|
|
481
|
+
if (!data.includes("\n")) {
|
|
482
|
+
return scrubJsonFrameText(data);
|
|
483
|
+
}
|
|
484
|
+
const lines = data.split("\n");
|
|
485
|
+
let changed = false;
|
|
486
|
+
for (let i = 0; i < lines.length; i++) {
|
|
487
|
+
const raw = lines[i];
|
|
488
|
+
if (raw === "")
|
|
489
|
+
continue;
|
|
490
|
+
const hasCr = raw.endsWith("\r");
|
|
491
|
+
const content = hasCr ? raw.slice(0, -1) : raw;
|
|
492
|
+
const scrubbed = scrubJsonFrameText(content);
|
|
493
|
+
if (scrubbed !== content) {
|
|
494
|
+
lines[i] = hasCr ? `${scrubbed}\r` : scrubbed;
|
|
495
|
+
changed = true;
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
return changed ? lines.join("\n") : data;
|
|
499
|
+
}
|
|
500
|
+
function wrapWebSocketLike(ws, parsedUrl, telemetryOrRef, predicates) {
|
|
501
|
+
const gatedSend = (data) => {
|
|
502
|
+
const telemetry = resolveTelemetry(telemetryOrRef);
|
|
503
|
+
const propagation = getPropagationConfig(telemetry);
|
|
504
|
+
const allowed = parsedUrl !== undefined && canPropagate(telemetry, propagation, parsedUrl, predicates);
|
|
505
|
+
if (allowed || typeof data !== "string") {
|
|
506
|
+
ws.send(data);
|
|
507
|
+
return;
|
|
508
|
+
}
|
|
509
|
+
ws.send(scrubSocketTextData(data));
|
|
510
|
+
};
|
|
511
|
+
return new Proxy(ws, {
|
|
512
|
+
get(target, prop) {
|
|
513
|
+
if (prop === "send")
|
|
514
|
+
return gatedSend;
|
|
515
|
+
const value = Reflect.get(target, prop, target);
|
|
516
|
+
return typeof value === "function" ? value.bind(target) : value;
|
|
517
|
+
},
|
|
518
|
+
set(target, prop, value) {
|
|
519
|
+
return Reflect.set(target, prop, value, target);
|
|
520
|
+
},
|
|
521
|
+
});
|
|
522
|
+
}
|
|
523
|
+
/**
|
|
524
|
+
* Wraps a `Socket.WebSocketConstructor` function so every opened `WebSocketLike` evaluates the
|
|
525
|
+
* telemetry recording and destination gate synchronously at `ws.send()` time (after Effect's
|
|
526
|
+
* `Socket.fromWebSocket` `latch.whenOpen` resumes).
|
|
527
|
+
*
|
|
528
|
+
* When the gate is closed (before setup, pending consent, revoked while opening/reconnecting,
|
|
529
|
+
* killed/safe mode, or disallowed/ignored `ws:`/`wss:` origin), strips `{ traceId, spanId, sampled }`
|
|
530
|
+
* from outbound JSON and NDJSON RPC Request frames right before wire transmission. For binary
|
|
531
|
+
* serializations, pair with {@link gateSocketRpcProtocol}.
|
|
532
|
+
*/
|
|
533
|
+
export function gateWebSocketConstructor(ctor, telemetryOrRef, options = {}) {
|
|
534
|
+
const predicates = {
|
|
535
|
+
shouldPropagate: options.shouldPropagate,
|
|
536
|
+
isIgnored: options.isIgnored,
|
|
537
|
+
};
|
|
538
|
+
return (url, wsOptions) => {
|
|
539
|
+
const ws = ctor(url, wsOptions);
|
|
540
|
+
return wrapWebSocketLike(ws, parseUrlSafe(url), telemetryOrRef, predicates);
|
|
541
|
+
};
|
|
542
|
+
}
|
|
543
|
+
const defaultGlobalWebSocketConstructor = (url, options) => {
|
|
544
|
+
if (options !== undefined && typeof options !== "string" && !Array.isArray(options)) {
|
|
545
|
+
throw new TypeError("WebSocket client options are not supported by the global WebSocket constructor");
|
|
546
|
+
}
|
|
547
|
+
return new globalThis.WebSocket(url, options);
|
|
548
|
+
};
|
|
549
|
+
/**
|
|
550
|
+
* Drop-in replacement for `Socket.layerWebSocketConstructorGlobal` that enforces write-time
|
|
551
|
+
* propagation gating on every WebSocket RPC frame right before `ws.send()`.
|
|
552
|
+
*/
|
|
553
|
+
export function webSocketConstructorLayer(telemetryOrRef, options = {}) {
|
|
554
|
+
const base = options.webSocketConstructor ?? defaultGlobalWebSocketConstructor;
|
|
555
|
+
return Layer.succeed(Socket.WebSocketConstructor, gateWebSocketConstructor(base, telemetryOrRef, options));
|
|
556
|
+
}
|
|
557
|
+
/**
|
|
558
|
+
* Wraps an Effect `RpcClient.Protocol` layer to gate `{ traceId, spanId, sampled }` at
|
|
559
|
+
* `Protocol.send` before serialization. Use for custom socket protocols or binary RPC
|
|
560
|
+
* serializations (where wire-level JSON/NDJSON scrubbing in `webSocketConstructorLayer` does not
|
|
561
|
+
* inspect binary frames).
|
|
562
|
+
*/
|
|
563
|
+
export function gateSocketRpcProtocol(protocolLayer, telemetryOrRef, options) {
|
|
564
|
+
const predicates = {
|
|
565
|
+
shouldPropagate: options.shouldPropagate,
|
|
566
|
+
isIgnored: options.isIgnored,
|
|
567
|
+
};
|
|
568
|
+
return Layer.effect(RpcClient.Protocol, Effect.map(Effect.service(RpcClient.Protocol), (base) => RpcClient.Protocol.of({
|
|
569
|
+
...base,
|
|
570
|
+
send: (clientId, request, transferables) => {
|
|
571
|
+
if (request._tag !== "Request") {
|
|
572
|
+
return base.send(clientId, request, transferables);
|
|
573
|
+
}
|
|
574
|
+
const rawUrl = typeof options.url === "function" ? options.url() : options.url;
|
|
575
|
+
const parsedUrl = rawUrl instanceof URL ? rawUrl : parseUrlSafe(rawUrl);
|
|
576
|
+
const telemetry = resolveTelemetry(telemetryOrRef);
|
|
577
|
+
const propagation = getPropagationConfig(telemetry);
|
|
578
|
+
const allowed = parsedUrl !== undefined && canPropagate(telemetry, propagation, parsedUrl, predicates);
|
|
579
|
+
const gatedRequest = allowed ? request : stripRequestTraceFields(request);
|
|
580
|
+
return base.send(clientId, gatedRequest, transferables);
|
|
581
|
+
},
|
|
582
|
+
}))).pipe(Layer.provide(protocolLayer));
|
|
583
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* The libo11y bridge for Effect 4
|
|
3
|
-
*
|
|
4
|
-
* @libo11y/
|
|
5
|
-
*
|
|
2
|
+
* The libo11y bridge for Effect 4: layers that report an Effect program to a libo11y telemetry
|
|
3
|
+
* from any platform package (@libo11y/server, @libo11y/workers, @libo11y/web, @libo11y/react-native,
|
|
4
|
+
* @libo11y/rum), gated single-carrier client HTTP/WebSocket RPC propagation, and server/Workers
|
|
5
|
+
* Effect combinators over @libo11y/core and @libo11y/core/edge.
|
|
6
6
|
*/
|
|
7
|
+
export { type ClientLayerOptions, type ClientRuntime, clientLayer, createTelemetryRef, gateSocketRpcProtocol, gateWebSocketConstructor, type HttpClientLayerOptions, httpClientLayer, type RedirectMode, type RpcProtocolHttpLayerOptions, rpcProtocolHttpLayer, type SocketRpcProtocolGateOptions, stripHttpRpcSerialization, type TelemetryRef, type TelemetrySource, type WebSocketConstructorFn, type WebSocketConstructorLayerOptions, type WebSocketGateOptions, webSocketConstructorLayer, } from "./client.ts";
|
|
7
8
|
export { flush, flushWith, type LayerOptions, type Libo11yServices, Libo11yTelemetry, layer, layerScoped, type ScopedLayerOptions, } from "./layer.ts";
|
|
8
9
|
export { type LoggerLayerOptions, loggerLayer, makeLogger } from "./logger.ts";
|
|
9
10
|
export { metricsLayer } from "./metrics.ts";
|
|
10
|
-
export { tracerLayer } from "./tracer.ts";
|
|
11
|
+
export { type SqlLayerOptions, type TracerLayerOptions, tracerLayer } from "./tracer.ts";
|
|
11
12
|
export { VERSION } from "./version.ts";
|
|
13
|
+
export { type AlarmSpanOptions, type CarrierInput, captureContext, enrichDurableObjectRpc, type LinkedContextOptions, linkCarriers, type QueueBatchSpanOptions, traceDurableObjectCall, traceDurableObjectMethods, traceDurableObjectStub, withAlarmSpan, withCronSpan, withLinkedContext, withQueueBatchSpan, } from "./workers.ts";
|
package/dist/index.js
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* The libo11y bridge for Effect 4
|
|
3
|
-
*
|
|
4
|
-
* @libo11y/
|
|
5
|
-
*
|
|
2
|
+
* The libo11y bridge for Effect 4: layers that report an Effect program to a libo11y telemetry
|
|
3
|
+
* from any platform package (@libo11y/server, @libo11y/workers, @libo11y/web, @libo11y/react-native,
|
|
4
|
+
* @libo11y/rum), gated single-carrier client HTTP/WebSocket RPC propagation, and server/Workers
|
|
5
|
+
* Effect combinators over @libo11y/core and @libo11y/core/edge.
|
|
6
6
|
*/
|
|
7
|
+
export { clientLayer, createTelemetryRef, gateSocketRpcProtocol, gateWebSocketConstructor, httpClientLayer, rpcProtocolHttpLayer, stripHttpRpcSerialization, webSocketConstructorLayer, } from "./client.js";
|
|
7
8
|
export { flush, flushWith, Libo11yTelemetry, layer, layerScoped, } from "./layer.js";
|
|
8
9
|
export { loggerLayer, makeLogger } from "./logger.js";
|
|
9
10
|
export { metricsLayer } from "./metrics.js";
|
|
10
11
|
export { tracerLayer } from "./tracer.js";
|
|
11
12
|
export { VERSION } from "./version.js";
|
|
13
|
+
export { captureContext, enrichDurableObjectRpc, linkCarriers, traceDurableObjectCall, traceDurableObjectMethods, traceDurableObjectStub, withAlarmSpan, withCronSpan, withLinkedContext, withQueueBatchSpan, } from "./workers.js";
|
package/dist/layer.d.ts
CHANGED
|
@@ -8,6 +8,7 @@ import type * as Cause from "effect/Cause";
|
|
|
8
8
|
import * as Context from "effect/Context";
|
|
9
9
|
import * as Effect from "effect/Effect";
|
|
10
10
|
import * as Layer from "effect/Layer";
|
|
11
|
+
import { type SqlLayerOptions } from "./tracer.ts";
|
|
11
12
|
/** The identifier of the Libo11yTelemetry service in an Effect context. */
|
|
12
13
|
export interface Libo11yTelemetry {
|
|
13
14
|
readonly "~@libo11y/effect/Libo11yTelemetry": "~@libo11y/effect/Libo11yTelemetry";
|
|
@@ -24,6 +25,8 @@ export interface LayerOptions {
|
|
|
24
25
|
readonly logger?: "replace" | "merge" | "none";
|
|
25
26
|
/** Bridge Effect metrics to the telemetry's meter provider. Default true. */
|
|
26
27
|
readonly metrics?: boolean;
|
|
28
|
+
/** Optional SQL span parenting behavior (e.g. `{ parentConnectSpans: true }` for `@effect/sql-pg`). */
|
|
29
|
+
readonly sql?: SqlLayerOptions;
|
|
27
30
|
}
|
|
28
31
|
/** What layer provides: the telemetry, and the OtelTracer service of `@effect/opentelemetry`. */
|
|
29
32
|
export type Libo11yServices = Libo11yTelemetry | OtelTracer.OtelTracer;
|
package/dist/layer.js
CHANGED
|
@@ -14,7 +14,7 @@ export const Libo11yTelemetry = Context.Service("@libo11y/effect/Libo11yTelemetr
|
|
|
14
14
|
*/
|
|
15
15
|
export function layer(telemetry, options = {}) {
|
|
16
16
|
const service = Layer.succeed(Libo11yTelemetry, telemetry);
|
|
17
|
-
const tracer = tracerLayer(telemetry);
|
|
17
|
+
const tracer = tracerLayer(telemetry, options.sql === undefined ? undefined : { sql: options.sql });
|
|
18
18
|
const logger = options.logger === "none"
|
|
19
19
|
? Layer.empty
|
|
20
20
|
: loggerLayer(telemetry, { mergeWithExisting: options.logger === "merge" });
|
package/dist/logger.d.ts
CHANGED
|
@@ -19,6 +19,11 @@
|
|
|
19
19
|
import type { Telemetry } from "@libo11y/core";
|
|
20
20
|
import type * as Layer from "effect/Layer";
|
|
21
21
|
import * as Logger from "effect/Logger";
|
|
22
|
+
/**
|
|
23
|
+
* Internal helper backing both makeLogger and dynamic clientLayer logging. Resolves the telemetry
|
|
24
|
+
* handle per record so late-bound client refs activate seamlessly once setup finishes.
|
|
25
|
+
*/
|
|
26
|
+
export declare function makeDynamicLogger(getTelemetry: () => Telemetry | undefined): Logger.Logger<unknown, void>;
|
|
22
27
|
/** An Effect Logger that writes every record through telemetry.logger. It never throws. */
|
|
23
28
|
export declare function makeLogger(telemetry: Telemetry): Logger.Logger<unknown, void>;
|
|
24
29
|
/** Options for loggerLayer. */
|