@juspay/neurolink 12.14.5 → 12.14.7
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/CHANGELOG.md +2 -2
- package/dist/browser/neurolink.min.js +412 -412
- package/dist/cli/commands/proxy.d.ts +1 -1
- package/dist/cli/commands/proxy.js +123 -14
- package/dist/cli/commands/proxyRestart.d.ts +3 -0
- package/dist/cli/commands/proxyRestart.js +88 -0
- package/dist/cli/parser.js +3 -1
- package/dist/proxy/bodyCaptureWorker.js +26 -1
- package/dist/proxy/codexUsage.js +83 -2
- package/dist/proxy/otelLogSink.d.ts +13 -0
- package/dist/proxy/otelLogSink.js +62 -1
- package/dist/proxy/proxyTraceContext.d.ts +21 -0
- package/dist/proxy/proxyTraceContext.js +47 -0
- package/dist/proxy/proxyTracer.d.ts +9 -5
- package/dist/proxy/proxyTracer.js +81 -2
- package/dist/proxy/requestLogger.js +24 -18
- package/dist/proxy/restartControl.d.ts +12 -0
- package/dist/proxy/restartControl.js +283 -0
- package/dist/proxy/rollingWorkerSupervisor.js +8 -0
- package/dist/server/routes/codexProxyRoutes.js +414 -332
- package/dist/types/cli.d.ts +7 -1
- package/dist/types/index.d.ts +1 -0
- package/dist/types/index.js +1 -0
- package/dist/types/proxy.d.ts +119 -3
- package/dist/types/proxyRestart.d.ts +49 -0
- package/dist/types/proxyRestart.js +1 -0
- package/docs-site/static/search-index.json +1 -1
- package/package.json +2 -1
- package/scripts/observability/check-proxy-telemetry.mjs +29 -241
- package/scripts/observability/proxy-telemetry-backend.mjs +202 -0
- package/scripts/observability/proxy-telemetry-check.mjs +544 -0
- package/scripts/observability/query-proxy-history.mjs +30 -19
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
/* eslint-disable no-console -- This proxy-only sink replaces console methods with OTLP emission. */
|
|
2
2
|
import { inspect } from "node:util";
|
|
3
|
+
import { randomUUID } from "node:crypto";
|
|
4
|
+
import { getProxyRequestTraceContext, proxyLogContext, } from "./proxyTraceContext.js";
|
|
3
5
|
import { setImmediate as yieldToRequests } from "node:timers/promises";
|
|
4
6
|
import { SeverityNumber } from "@opentelemetry/api-logs";
|
|
5
7
|
import { ExportResultCode } from "@opentelemetry/core";
|
|
@@ -45,6 +47,52 @@ function createTrackedProcessor(url, capacity, kind) {
|
|
|
45
47
|
lastAcknowledgedAt: undefined,
|
|
46
48
|
lastFailureAt: undefined,
|
|
47
49
|
highWaterOutstanding: 0,
|
|
50
|
+
recentFailures: [],
|
|
51
|
+
failureHistoryEvicted: 0,
|
|
52
|
+
};
|
|
53
|
+
const diagnostics = [];
|
|
54
|
+
let diagnosticScheduled = false;
|
|
55
|
+
const rememberFailure = (records, reason, error) => {
|
|
56
|
+
const stringAttribute = (record, name) => {
|
|
57
|
+
const value = record.attributes[name];
|
|
58
|
+
return typeof value === "string" ? value.slice(0, 128) : undefined;
|
|
59
|
+
};
|
|
60
|
+
const failure = {
|
|
61
|
+
id: randomUUID(),
|
|
62
|
+
at: new Date().toISOString(),
|
|
63
|
+
reason,
|
|
64
|
+
...(error ? { error: sanitizeForLog(error.message).slice(0, 256) } : {}),
|
|
65
|
+
records: records.slice(0, 64).map((record) => ({
|
|
66
|
+
eventId: stringAttribute(record, "proxy.event_id") ?? "unavailable",
|
|
67
|
+
kind: stringAttribute(record, "proxy.record_kind"),
|
|
68
|
+
requestId: stringAttribute(record, "request.id"),
|
|
69
|
+
captureId: stringAttribute(record, "body.capture_id"),
|
|
70
|
+
})),
|
|
71
|
+
};
|
|
72
|
+
if (state.recentFailures.length === 16) {
|
|
73
|
+
state.recentFailures.shift();
|
|
74
|
+
state.failureHistoryEvicted++;
|
|
75
|
+
}
|
|
76
|
+
state.recentFailures.push(failure);
|
|
77
|
+
// A failed diagnostic must not generate another diagnostic recursively.
|
|
78
|
+
if (records.some((record) => record.attributes["proxy.record_kind"] !== "telemetry_delivery")) {
|
|
79
|
+
if (diagnostics.length === 16) {
|
|
80
|
+
diagnostics.shift();
|
|
81
|
+
}
|
|
82
|
+
diagnostics.push(failure);
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
const publishRecoveredDiagnostics = () => {
|
|
86
|
+
if (diagnosticScheduled || !diagnostics.length || shuttingDown) {
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
diagnosticScheduled = true;
|
|
90
|
+
queueMicrotask(() => {
|
|
91
|
+
diagnosticScheduled = false;
|
|
92
|
+
for (const failure of diagnostics.splice(0)) {
|
|
93
|
+
emitProxyOtelEvent("telemetry_delivery", { queue: kind, ...failure });
|
|
94
|
+
}
|
|
95
|
+
});
|
|
48
96
|
};
|
|
49
97
|
const transport = new OTLPLogExporter({ url, timeoutMillis: 5000 });
|
|
50
98
|
const exporter = {
|
|
@@ -65,10 +113,12 @@ function createTrackedProcessor(url, capacity, kind) {
|
|
|
65
113
|
if (result.code === ExportResultCode.SUCCESS) {
|
|
66
114
|
state.transportAcknowledged += records.length;
|
|
67
115
|
state.lastAcknowledgedAt = new Date().toISOString();
|
|
116
|
+
publishRecoveredDiagnostics();
|
|
68
117
|
}
|
|
69
118
|
else {
|
|
70
119
|
state.exportUnconfirmed += records.length;
|
|
71
120
|
state.lastFailureAt = new Date().toISOString();
|
|
121
|
+
rememberFailure(records, "export_unconfirmed", result.error);
|
|
72
122
|
}
|
|
73
123
|
for (const record of records) {
|
|
74
124
|
unsettled.delete(record);
|
|
@@ -109,6 +159,7 @@ function createTrackedProcessor(url, capacity, kind) {
|
|
|
109
159
|
});
|
|
110
160
|
const processor = {
|
|
111
161
|
onEmit(record) {
|
|
162
|
+
record.attributes["proxy.event_id"] ??= randomUUID();
|
|
112
163
|
state.attempted++;
|
|
113
164
|
const id = record.attributes?.["body.capture_id"];
|
|
114
165
|
const publication = typeof id === "string" ? bodyPublications.get(id) : undefined;
|
|
@@ -117,6 +168,7 @@ function createTrackedProcessor(url, capacity, kind) {
|
|
|
117
168
|
}
|
|
118
169
|
if (state.outstanding >= capacity) {
|
|
119
170
|
state.dropped++;
|
|
171
|
+
rememberFailure([record], "queue_full");
|
|
120
172
|
if (publication) {
|
|
121
173
|
publication.dropped++;
|
|
122
174
|
publication.notify?.();
|
|
@@ -355,12 +407,17 @@ export function emitProxyOtelEvent(kind, record) {
|
|
|
355
407
|
return;
|
|
356
408
|
}
|
|
357
409
|
try {
|
|
410
|
+
const ids = typeof record.requestId === "string" && !record.traceId
|
|
411
|
+
? getProxyRequestTraceContext(record.requestId)
|
|
412
|
+
: undefined;
|
|
413
|
+
const correlated = ids ? { ...record, ...ids } : record;
|
|
358
414
|
initializeProxyOtelLogs()
|
|
359
415
|
?.getLogger("neurolink-proxy-events")
|
|
360
416
|
.emit({
|
|
417
|
+
context: proxyLogContext(correlated),
|
|
361
418
|
severityNumber: SeverityNumber.INFO,
|
|
362
419
|
severityText: "INFO",
|
|
363
|
-
body: JSON.stringify(
|
|
420
|
+
body: JSON.stringify(correlated),
|
|
364
421
|
attributes: {
|
|
365
422
|
"proxy.record_kind": kind,
|
|
366
423
|
"event.name": `proxy.${kind}`,
|
|
@@ -444,6 +501,10 @@ export function getProxyOtelLogSnapshot() {
|
|
|
444
501
|
kind: q.kind,
|
|
445
502
|
capacity: q.capacity,
|
|
446
503
|
...q.state,
|
|
504
|
+
recentFailures: q.state.recentFailures.map((failure) => ({
|
|
505
|
+
...failure,
|
|
506
|
+
records: failure.records.map((record) => ({ ...record })),
|
|
507
|
+
})),
|
|
447
508
|
})),
|
|
448
509
|
};
|
|
449
510
|
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { ProxyLogTraceContext } from "../types/index.js";
|
|
2
|
+
/** Correlation belongs to the in-flight HTTP request, not to an async callback. */
|
|
3
|
+
export declare function registerProxyRequestTraceContext(requestId: string, ids: ProxyLogTraceContext): void;
|
|
4
|
+
/** Release once transport and terminal accounting have settled. */
|
|
5
|
+
export declare function releaseProxyRequestTraceContext(requestId: string): void;
|
|
6
|
+
/** Internal fallback records share their parent request's trace. */
|
|
7
|
+
export declare function getProxyRequestTraceContext(requestId: string): ProxyLogTraceContext | undefined;
|
|
8
|
+
/** Retain IDs and sampling flags before deferred processing leaves the request. */
|
|
9
|
+
export declare function resolveProxyLogTraceContext(record: {
|
|
10
|
+
traceId?: unknown;
|
|
11
|
+
spanId?: unknown;
|
|
12
|
+
traceFlags?: unknown;
|
|
13
|
+
requestId?: unknown;
|
|
14
|
+
}): ProxyLogTraceContext | undefined;
|
|
15
|
+
/** Populate native OTLP correlation, including valid unsampled contexts. */
|
|
16
|
+
export declare function proxyLogContext(record: {
|
|
17
|
+
traceId?: unknown;
|
|
18
|
+
spanId?: unknown;
|
|
19
|
+
traceFlags?: unknown;
|
|
20
|
+
requestId?: unknown;
|
|
21
|
+
}): import("@opentelemetry/api").Context;
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { context, ROOT_CONTEXT, trace, isSpanContextValid, } from "@opentelemetry/api";
|
|
2
|
+
const requests = new Map();
|
|
3
|
+
/** Correlation belongs to the in-flight HTTP request, not to an async callback. */
|
|
4
|
+
export function registerProxyRequestTraceContext(requestId, ids) {
|
|
5
|
+
requests.set(requestId, ids);
|
|
6
|
+
}
|
|
7
|
+
/** Release once transport and terminal accounting have settled. */
|
|
8
|
+
export function releaseProxyRequestTraceContext(requestId) {
|
|
9
|
+
requests.delete(requestId);
|
|
10
|
+
}
|
|
11
|
+
/** Internal fallback records share their parent request's trace. */
|
|
12
|
+
export function getProxyRequestTraceContext(requestId) {
|
|
13
|
+
return (requests.get(requestId) ??
|
|
14
|
+
requests.get(requestId.replace(/:codex-fallback$/, "")));
|
|
15
|
+
}
|
|
16
|
+
/** Retain IDs and sampling flags before deferred processing leaves the request. */
|
|
17
|
+
export function resolveProxyLogTraceContext(record) {
|
|
18
|
+
const saved = typeof record.requestId === "string"
|
|
19
|
+
? getProxyRequestTraceContext(record.requestId)
|
|
20
|
+
: undefined;
|
|
21
|
+
const active = trace.getSpanContext(context.active());
|
|
22
|
+
const ids = typeof record.traceId === "string" && typeof record.spanId === "string"
|
|
23
|
+
? { traceId: record.traceId, spanId: record.spanId }
|
|
24
|
+
: (saved ?? active);
|
|
25
|
+
if (!ids) {
|
|
26
|
+
return undefined;
|
|
27
|
+
}
|
|
28
|
+
const traceFlags = typeof record.traceFlags === "number" &&
|
|
29
|
+
Number.isInteger(record.traceFlags) &&
|
|
30
|
+
record.traceFlags >= 0 &&
|
|
31
|
+
record.traceFlags <= 255
|
|
32
|
+
? record.traceFlags
|
|
33
|
+
: saved?.traceId === ids.traceId
|
|
34
|
+
? saved.traceFlags
|
|
35
|
+
: active?.traceId === ids.traceId
|
|
36
|
+
? active.traceFlags
|
|
37
|
+
: 0;
|
|
38
|
+
const result = { ...ids, traceFlags };
|
|
39
|
+
return isSpanContextValid(result)
|
|
40
|
+
? { traceId: result.traceId, spanId: result.spanId, traceFlags }
|
|
41
|
+
: undefined;
|
|
42
|
+
}
|
|
43
|
+
/** Populate native OTLP correlation, including valid unsampled contexts. */
|
|
44
|
+
export function proxyLogContext(record) {
|
|
45
|
+
const ids = resolveProxyLogTraceContext(record);
|
|
46
|
+
return ids ? trace.setSpanContext(ROOT_CONTEXT, ids) : context.active();
|
|
47
|
+
}
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
* - TelemetryService for metrics recording
|
|
15
15
|
*/
|
|
16
16
|
import { type Span } from "@opentelemetry/api";
|
|
17
|
-
import type { AccountSelectionContext, ProxyRequestContext, ResponseInfoContext, UpstreamAttemptContext, UsageContext } from "../types/index.js";
|
|
17
|
+
import type { AccountSelectionContext, ProxyRequestContext, ResponseInfoContext, UpstreamAttemptContext, UsageContext, RuntimeRequestMetadata, ProxyLogTraceContext } from "../types/index.js";
|
|
18
18
|
declare class ProxyTracer {
|
|
19
19
|
private readonly rootSpan;
|
|
20
20
|
private readonly proxyTracer;
|
|
@@ -34,6 +34,8 @@ declare class ProxyTracer {
|
|
|
34
34
|
private billingProvider;
|
|
35
35
|
private readonly startTime;
|
|
36
36
|
private readonly isStream;
|
|
37
|
+
private ended;
|
|
38
|
+
private recordRequestMetrics;
|
|
37
39
|
private accountEmail?;
|
|
38
40
|
private usage?;
|
|
39
41
|
private mode;
|
|
@@ -102,10 +104,7 @@ declare class ProxyTracer {
|
|
|
102
104
|
/** Record request and/or response body sizes for bandwidth tracking. */
|
|
103
105
|
recordBodySizes(requestBytes?: number, responseBytes?: number): void;
|
|
104
106
|
/** Return the OTel trace/span IDs for this request (for log correlation). */
|
|
105
|
-
getTraceContext():
|
|
106
|
-
traceId: string;
|
|
107
|
-
spanId: string;
|
|
108
|
-
};
|
|
107
|
+
getTraceContext(): ProxyLogTraceContext;
|
|
109
108
|
/** Return the captured usage (set by setUsage). */
|
|
110
109
|
getUsage(): UsageContext | undefined;
|
|
111
110
|
/** End the root span with final HTTP status and duration, and emit OTEL metrics. */
|
|
@@ -126,3 +125,8 @@ export declare function recordFallbackAttempt(attrs: {
|
|
|
126
125
|
durationMs: number;
|
|
127
126
|
}): void;
|
|
128
127
|
export { ProxyTracer };
|
|
128
|
+
/** Standard SERVER span covers every proxy door, including parsing and admission failures. */
|
|
129
|
+
export declare function startProxyHttpTrace(metadata: RuntimeRequestMetadata, headers: Record<string, string>): {
|
|
130
|
+
run: <T>(fn: () => T) => T;
|
|
131
|
+
end: (status: number, outcome: string, errorType?: string) => void;
|
|
132
|
+
};
|
|
@@ -13,12 +13,13 @@
|
|
|
13
13
|
* - calculateCost() from pricing.ts for cost tracking
|
|
14
14
|
* - TelemetryService for metrics recording
|
|
15
15
|
*/
|
|
16
|
-
import { SpanStatusCode, context, metrics, trace, } from "@opentelemetry/api";
|
|
16
|
+
import { SpanStatusCode, SpanKind, ROOT_CONTEXT, isSpanContextValid, propagation, context, metrics, trace, } from "@opentelemetry/api";
|
|
17
17
|
import { getTracer, setLangfuseContext, } from "../services/server/ai/observability/instrumentation.js";
|
|
18
18
|
import { OtelBridge } from "../observability/otelBridge.js";
|
|
19
19
|
import { calculateCost } from "../utils/pricing.js";
|
|
20
20
|
import { TelemetryService } from "../telemetry/telemetryService.js";
|
|
21
21
|
import { logger } from "../utils/logger.js";
|
|
22
|
+
import { registerProxyRequestTraceContext, releaseProxyRequestTraceContext, } from "./proxyTraceContext.js";
|
|
22
23
|
const LOG_PREFIX = "[ProxyTracer]";
|
|
23
24
|
// ---------------------------------------------------------------------------
|
|
24
25
|
// OTEL Metric Instruments — lazy singleton
|
|
@@ -205,6 +206,8 @@ class ProxyTracer {
|
|
|
205
206
|
billingProvider;
|
|
206
207
|
startTime;
|
|
207
208
|
isStream;
|
|
209
|
+
ended = false;
|
|
210
|
+
recordRequestMetrics = true;
|
|
208
211
|
accountEmail;
|
|
209
212
|
usage;
|
|
210
213
|
mode = "full";
|
|
@@ -226,7 +229,7 @@ class ProxyTracer {
|
|
|
226
229
|
const tracer = getTracer("neurolink.proxy");
|
|
227
230
|
// Extract parent context from incoming headers (Claude Code may send traceparent)
|
|
228
231
|
let parentContext = context.active();
|
|
229
|
-
if (incomingHeaders) {
|
|
232
|
+
if (incomingHeaders && !trace.getSpan(context.active())) {
|
|
230
233
|
const bridge = new OtelBridge();
|
|
231
234
|
const extracted = bridge.extractContext(incomingHeaders);
|
|
232
235
|
if (extracted) {
|
|
@@ -270,6 +273,7 @@ class ProxyTracer {
|
|
|
270
273
|
rootSpan.setAttribute("neurolink.conversation_id", nlConversationId);
|
|
271
274
|
}
|
|
272
275
|
const instance = new ProxyTracer(rootSpan, ctx.requestId, ctx.model, ctx.stream, ctx.provider ?? "anthropic");
|
|
276
|
+
instance.recordRequestMetrics = ctx.recordRequestMetrics !== false;
|
|
273
277
|
// Set Langfuse context (fire-and-forget — non-blocking)
|
|
274
278
|
// Prefer NeuroLink session/user from calling SDK over Claude Code session
|
|
275
279
|
setLangfuseContext({
|
|
@@ -607,6 +611,7 @@ class ProxyTracer {
|
|
|
607
611
|
return {
|
|
608
612
|
traceId: spanCtx.traceId,
|
|
609
613
|
spanId: spanCtx.spanId,
|
|
614
|
+
traceFlags: spanCtx.traceFlags,
|
|
610
615
|
};
|
|
611
616
|
}
|
|
612
617
|
/** Return the captured usage (set by setUsage). */
|
|
@@ -618,6 +623,10 @@ class ProxyTracer {
|
|
|
618
623
|
// -------------------------------------------------------------------------
|
|
619
624
|
/** End the root span with final HTTP status and duration, and emit OTEL metrics. */
|
|
620
625
|
end(responseStatus, durationMs) {
|
|
626
|
+
if (this.ended) {
|
|
627
|
+
return;
|
|
628
|
+
}
|
|
629
|
+
this.ended = true;
|
|
621
630
|
this.rootSpan.setAttributes({
|
|
622
631
|
"http.status_code": responseStatus,
|
|
623
632
|
"proxy.duration_ms": durationMs,
|
|
@@ -636,6 +645,9 @@ class ProxyTracer {
|
|
|
636
645
|
this.rootSpan.setStatus({ code: SpanStatusCode.OK });
|
|
637
646
|
}
|
|
638
647
|
this.rootSpan.end();
|
|
648
|
+
if (!this.recordRequestMetrics) {
|
|
649
|
+
return;
|
|
650
|
+
}
|
|
639
651
|
// ---- Emit OTEL metrics (lazy-init instruments) ----
|
|
640
652
|
const m = getProxyMetrics();
|
|
641
653
|
const labels = {
|
|
@@ -745,3 +757,70 @@ export function recordFallbackAttempt(attrs) {
|
|
|
745
757
|
}
|
|
746
758
|
}
|
|
747
759
|
export { ProxyTracer };
|
|
760
|
+
/** Standard SERVER span covers every proxy door, including parsing and admission failures. */
|
|
761
|
+
export function startProxyHttpTrace(metadata, headers) {
|
|
762
|
+
try {
|
|
763
|
+
// Match OtelBridge's existing compatibility policy for HTTP-combined
|
|
764
|
+
// traceparent values: retain the first injected parent.
|
|
765
|
+
const normalizedHeaders = { ...headers };
|
|
766
|
+
if (normalizedHeaders.traceparent?.includes(",")) {
|
|
767
|
+
normalizedHeaders.traceparent = normalizedHeaders.traceparent
|
|
768
|
+
.split(",", 1)[0]
|
|
769
|
+
.trim();
|
|
770
|
+
}
|
|
771
|
+
const parent = propagation.extract(ROOT_CONTEXT, normalizedHeaders);
|
|
772
|
+
const span = getTracer("neurolink.proxy").startSpan("proxy.http.request", {
|
|
773
|
+
kind: SpanKind.SERVER,
|
|
774
|
+
attributes: {
|
|
775
|
+
"http.request.method": metadata.method,
|
|
776
|
+
"url.path": metadata.path,
|
|
777
|
+
"proxy.request_id": metadata.requestId,
|
|
778
|
+
},
|
|
779
|
+
}, parent);
|
|
780
|
+
const spanContext = span.spanContext();
|
|
781
|
+
if (isSpanContextValid(spanContext)) {
|
|
782
|
+
metadata.traceId = spanContext.traceId;
|
|
783
|
+
metadata.spanId = spanContext.spanId;
|
|
784
|
+
metadata.traceFlags = spanContext.traceFlags;
|
|
785
|
+
registerProxyRequestTraceContext(metadata.requestId, {
|
|
786
|
+
traceId: spanContext.traceId,
|
|
787
|
+
spanId: spanContext.spanId,
|
|
788
|
+
traceFlags: spanContext.traceFlags,
|
|
789
|
+
});
|
|
790
|
+
}
|
|
791
|
+
const active = trace.setSpan(parent, span);
|
|
792
|
+
let ended = false;
|
|
793
|
+
return {
|
|
794
|
+
run: (fn) => context.with(active, fn),
|
|
795
|
+
end: (status, outcome, errorType) => {
|
|
796
|
+
if (ended) {
|
|
797
|
+
return;
|
|
798
|
+
}
|
|
799
|
+
ended = true;
|
|
800
|
+
try {
|
|
801
|
+
span.setAttributes({
|
|
802
|
+
"http.response.status_code": status,
|
|
803
|
+
"proxy.terminal_outcome": outcome,
|
|
804
|
+
...(errorType ? { "error.type": errorType } : {}),
|
|
805
|
+
});
|
|
806
|
+
if (status >= 500 ||
|
|
807
|
+
outcome === "stream_error" ||
|
|
808
|
+
outcome === "unknown") {
|
|
809
|
+
span.setStatus({ code: SpanStatusCode.ERROR });
|
|
810
|
+
}
|
|
811
|
+
span.end();
|
|
812
|
+
}
|
|
813
|
+
catch {
|
|
814
|
+
// Telemetry must not interrupt transport cleanup.
|
|
815
|
+
}
|
|
816
|
+
finally {
|
|
817
|
+
releaseProxyRequestTraceContext(metadata.requestId);
|
|
818
|
+
}
|
|
819
|
+
},
|
|
820
|
+
};
|
|
821
|
+
}
|
|
822
|
+
catch {
|
|
823
|
+
releaseProxyRequestTraceContext(metadata.requestId);
|
|
824
|
+
return { run: (fn) => fn(), end: () => undefined };
|
|
825
|
+
}
|
|
826
|
+
}
|
|
@@ -21,6 +21,7 @@ import { SeverityNumber } from "@opentelemetry/api-logs";
|
|
|
21
21
|
import { configureProxyLifecycleLogger } from "./proxyLifecycle.js";
|
|
22
22
|
import { notifyProxyFinalLog, notifyProxyAttemptLog } from "./proxyActivity.js";
|
|
23
23
|
import { withTimeout } from "../utils/async/withTimeout.js";
|
|
24
|
+
import { resolveProxyLogTraceContext, proxyLogContext, } from "./proxyTraceContext.js";
|
|
24
25
|
let logDir = null;
|
|
25
26
|
let logEnabled = false;
|
|
26
27
|
const pendingLogOperations = new Set();
|
|
@@ -184,6 +185,12 @@ export function initRequestLogger(enabled = true, customLogsDir) {
|
|
|
184
185
|
}
|
|
185
186
|
}
|
|
186
187
|
export async function logRequest(entry) {
|
|
188
|
+
if (!entry.traceId || entry.traceFlags === undefined) {
|
|
189
|
+
const traceCtx = resolveProxyLogTraceContext(entry);
|
|
190
|
+
if (traceCtx) {
|
|
191
|
+
Object.assign(entry, traceCtx);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
187
194
|
entry.terminalOutcome ??=
|
|
188
195
|
entry.errorType === "client_cancelled" || entry.responseStatus === 499
|
|
189
196
|
? "client_cancelled"
|
|
@@ -196,17 +203,6 @@ export async function logRequest(entry) {
|
|
|
196
203
|
if (!logEnabled || (!logDir && !isProxyOtelOnly())) {
|
|
197
204
|
return;
|
|
198
205
|
}
|
|
199
|
-
// Only use OtelBridge if traceId not already provided by caller.
|
|
200
|
-
// Deferred .then() callbacks lose async context, so OtelBridge would
|
|
201
|
-
// return undefined and overwrite the valid traceId the caller passed.
|
|
202
|
-
if (!entry.traceId) {
|
|
203
|
-
const bridge = new OtelBridge();
|
|
204
|
-
const traceCtx = bridge.getCurrentTraceContext();
|
|
205
|
-
if (traceCtx) {
|
|
206
|
-
entry.traceId = traceCtx.traceId;
|
|
207
|
-
entry.spanId = traceCtx.spanId;
|
|
208
|
-
}
|
|
209
|
-
}
|
|
210
206
|
if (isProxyOtelOnly()) {
|
|
211
207
|
await emitOtlpLogRecord(entry);
|
|
212
208
|
return;
|
|
@@ -228,12 +224,12 @@ export async function logRequest(entry) {
|
|
|
228
224
|
* or OTLP-derived dashboard panels.
|
|
229
225
|
*/
|
|
230
226
|
export async function logRequestAttempt(entry) {
|
|
231
|
-
if (!entry.traceId) {
|
|
232
|
-
const
|
|
233
|
-
const traceCtx = bridge.getCurrentTraceContext();
|
|
227
|
+
if (!entry.traceId || entry.traceFlags === undefined) {
|
|
228
|
+
const traceCtx = resolveProxyLogTraceContext(entry);
|
|
234
229
|
if (traceCtx) {
|
|
235
230
|
entry.traceId = traceCtx.traceId;
|
|
236
231
|
entry.spanId = traceCtx.spanId;
|
|
232
|
+
entry.traceFlags = traceCtx.traceFlags;
|
|
237
233
|
}
|
|
238
234
|
}
|
|
239
235
|
notifyProxyAttemptLog(entry);
|
|
@@ -313,6 +309,7 @@ function emitOtlpLogRecord(entry) {
|
|
|
313
309
|
: SeverityNumber.INFO;
|
|
314
310
|
const severityText = isError ? (isRateLimit ? "WARN" : "ERROR") : "INFO";
|
|
315
311
|
otelLogger.emit({
|
|
312
|
+
context: proxyLogContext(entry),
|
|
316
313
|
severityNumber,
|
|
317
314
|
severityText,
|
|
318
315
|
body: isProxyOtelOnly()
|
|
@@ -453,6 +450,7 @@ function emitOtlpBodyLogRecord(entry, stored) {
|
|
|
453
450
|
const captureId = entry.captureId ?? randomUUID();
|
|
454
451
|
const emit = (chunk, chunkIndex, totalChunks) => {
|
|
455
452
|
otelLogger.emit({
|
|
453
|
+
context: proxyLogContext(entry),
|
|
456
454
|
severityNumber: (entry.responseStatus ?? 0) >= 400
|
|
457
455
|
? SeverityNumber.WARN
|
|
458
456
|
: SeverityNumber.INFO,
|
|
@@ -526,12 +524,16 @@ export async function logBodyCapture(entry) {
|
|
|
526
524
|
// not something a share token can be read as consenting to. The request is
|
|
527
525
|
// still logged; only the bodies are dropped.
|
|
528
526
|
if (isBorrowedRequest()) {
|
|
527
|
+
emitProxyOtelEvent("body_capture_index", {
|
|
528
|
+
timestamp: entry.timestamp,
|
|
529
|
+
requestId: entry.requestId,
|
|
530
|
+
captureId: entry.captureId ?? randomUUID(),
|
|
531
|
+
phase: entry.phase,
|
|
532
|
+
bodyDelivery: { status: "policy_excluded", reason: "borrowed_traffic" },
|
|
533
|
+
});
|
|
529
534
|
return;
|
|
530
535
|
}
|
|
531
|
-
const
|
|
532
|
-
const traceCtx = entry.traceId && entry.spanId
|
|
533
|
-
? { traceId: entry.traceId, spanId: entry.spanId }
|
|
534
|
-
: bridge.getCurrentTraceContext();
|
|
536
|
+
const traceCtx = resolveProxyLogTraceContext(entry);
|
|
535
537
|
const destination = logDir;
|
|
536
538
|
// Publication callbacks retain metadata and the bounded redacted result,
|
|
537
539
|
// never the original unbounded body while a sink is slow.
|
|
@@ -573,6 +575,7 @@ export async function logBodyCapture(entry) {
|
|
|
573
575
|
originalRedactedBodyBytes: stored.originalRedactedBodyBytes,
|
|
574
576
|
bodyWriteFailed: stored.bodyWriteFailed,
|
|
575
577
|
captureError: processed.error,
|
|
578
|
+
captureAdmission: processed.admission,
|
|
576
579
|
captureQueueWaitMs: processed.queueWaitMs,
|
|
577
580
|
captureProcessingMs: processed.processingMs,
|
|
578
581
|
metadata: processed.error ? undefined : metadata.metadata,
|
|
@@ -580,12 +583,14 @@ export async function logBodyCapture(entry) {
|
|
|
580
583
|
if (traceCtx) {
|
|
581
584
|
indexEntry.traceId = traceCtx.traceId;
|
|
582
585
|
indexEntry.spanId = traceCtx.spanId;
|
|
586
|
+
indexEntry.traceFlags = traceCtx.traceFlags;
|
|
583
587
|
}
|
|
584
588
|
if (isProxyOtelOnly()) {
|
|
585
589
|
const delivery = await emitOtlpBodyLogRecord({
|
|
586
590
|
...metadata,
|
|
587
591
|
traceId: traceCtx?.traceId ?? metadata.traceId,
|
|
588
592
|
spanId: traceCtx?.spanId ?? metadata.spanId,
|
|
593
|
+
traceFlags: traceCtx?.traceFlags ?? metadata.traceFlags,
|
|
589
594
|
}, stored);
|
|
590
595
|
indexEntry.bodyDelivery = delivery ?? {
|
|
591
596
|
status: processed.error
|
|
@@ -612,6 +617,7 @@ export async function logBodyCapture(entry) {
|
|
|
612
617
|
...metadata,
|
|
613
618
|
traceId: traceCtx?.traceId ?? metadata.traceId,
|
|
614
619
|
spanId: traceCtx?.spanId ?? metadata.spanId,
|
|
620
|
+
traceFlags: traceCtx?.traceFlags ?? metadata.traceFlags,
|
|
615
621
|
}, stored);
|
|
616
622
|
};
|
|
617
623
|
const operation = trackLogOperation(captureProxyBody(entry, destination, consume));
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { ProxyRestartControlIdentity, ProxyRestartControlOptions, ProxyRestartResult } from "../types/index.js";
|
|
2
|
+
/**
|
|
3
|
+
* Own restart completion in the supervisor, so a disconnected CLI cannot leave
|
|
4
|
+
* admission closed. The control socket is private to the service's OS user.
|
|
5
|
+
* No update history, launcher, environment file or launchd unit is rewritten.
|
|
6
|
+
*/
|
|
7
|
+
export declare function startProxyRestartControl(options: ProxyRestartControlOptions): Promise<{
|
|
8
|
+
identity: ProxyRestartControlIdentity;
|
|
9
|
+
close: () => Promise<void>;
|
|
10
|
+
}>;
|
|
11
|
+
/** Perform one local control operation; never fall back to killing a process. */
|
|
12
|
+
export declare function requestProxyRestart(identity: ProxyRestartControlIdentity, check: boolean): Promise<ProxyRestartResult>;
|