@ultimat3/core 30.8.0 → 31.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CLAUDE.md +54 -58
- package/README.md +70 -27
- package/package.json +3 -2
- package/src/adapter-slot.ts +42 -0
- package/src/adapter.ts +24 -0
- package/src/audit.ts +31 -14
- package/src/aws-sigv4.ts +9 -3
- package/src/cache-vocabulary.ts +1 -1
- package/src/client-problem.ts +10 -3
- package/src/clock.ts +68 -14
- package/src/config-defaults.ts +4 -4
- package/src/config-keys.ts +1 -1
- package/src/config-removed.ts +11 -1
- package/src/config.ts +16 -20
- package/src/context.ts +2 -2
- package/src/cursor.ts +3 -11
- package/src/der.ts +65 -0
- package/src/error-render.ts +27 -1
- package/src/error-reporter-chain.ts +1 -1
- package/src/error-reporter-sentry-hooks.ts +85 -0
- package/src/error-reporter-sentry.ts +99 -7
- package/src/error-reporter.ts +39 -11
- package/src/errors.ts +3 -1
- package/src/exports/error-contract.ts +4 -14
- package/src/exports/observability.ts +57 -17
- package/src/exports/secrets.ts +4 -18
- package/src/failure-capture.ts +22 -13
- package/src/gate-shapes.ts +88 -0
- package/src/host-rules.ts +13 -1
- package/src/html-escape.ts +7 -1
- package/src/ids.ts +59 -10
- package/src/image/png-pixels.ts +14 -8
- package/src/index.ts +123 -136
- package/src/instrument-events.ts +272 -0
- package/src/instrument-semconv.ts +65 -0
- package/src/instrument-stacks.ts +38 -0
- package/src/instrument.ts +194 -0
- package/src/keyed-fingerprint.ts +7 -11
- package/src/lifecycle-signals.ts +5 -3
- package/src/lifecycle.ts +27 -0
- package/src/logger-record.ts +35 -0
- package/src/logger.ts +24 -16
- package/src/mcp-exposure.ts +17 -0
- package/src/metrics-semconv.ts +124 -0
- package/src/metrics.ts +19 -16
- package/src/otlp-batch.ts +78 -0
- package/src/otlp-log-exporter.ts +180 -0
- package/src/otlp-metric-exporter.ts +2 -1
- package/src/otlp-post.ts +22 -2
- package/src/otlp-span-exporter.ts +10 -59
- package/src/otlp.ts +27 -9
- package/src/outbound-instrument.ts +82 -0
- package/src/outbound.ts +5 -4
- package/src/page-meta.ts +6 -0
- package/src/page.ts +23 -5
- package/src/registrar.ts +269 -0
- package/src/route-vocabulary.ts +11 -2
- package/src/safe-url.ts +10 -8
- package/src/seal-errors.ts +14 -4
- package/src/seal-keys.ts +11 -7
- package/src/secret-source.ts +125 -0
- package/src/secrets-errors.ts +32 -12
- package/src/secrets-store.ts +30 -26
- package/src/sleep-clock.ts +70 -0
- package/src/telemetry.ts +90 -31
- package/src/type-pins.ts +19 -16
- package/src/log-tee.ts +0 -73
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
// Single responsibility: OTLP/HTTP JSON logs (`/v1/logs`) — a `log.record` subscriber that batches
|
|
2
|
+
// the process logger's lines to a collector, each stamped with the span active when it was written.
|
|
3
|
+
// Installed by subscribing: `subscribe('log.record', (event) => logs.export(event.payload))`.
|
|
4
|
+
|
|
5
|
+
import { renderThrowable } from './error-render';
|
|
6
|
+
import type { LogRecordEvent } from './instrument-events';
|
|
7
|
+
import { logger } from './logger';
|
|
8
|
+
import {
|
|
9
|
+
assertFiniteOtlpBound,
|
|
10
|
+
OTLP_SCOPE,
|
|
11
|
+
type OtlpKeyValue,
|
|
12
|
+
type OtlpPostOptions,
|
|
13
|
+
otlpAttributes,
|
|
14
|
+
otlpEndpoint,
|
|
15
|
+
otlpEndpointLabel,
|
|
16
|
+
otlpHeaders,
|
|
17
|
+
otlpResource,
|
|
18
|
+
postOtlp,
|
|
19
|
+
unixNano,
|
|
20
|
+
} from './otlp';
|
|
21
|
+
import { otlpBatcher } from './otlp-batch';
|
|
22
|
+
import {
|
|
23
|
+
type AttributeValue,
|
|
24
|
+
currentSpanContext,
|
|
25
|
+
type SpanContext,
|
|
26
|
+
type SpanResource,
|
|
27
|
+
serviceResource,
|
|
28
|
+
} from './telemetry';
|
|
29
|
+
|
|
30
|
+
/** OTLP's `SeverityNumber`: the first number of each band. */
|
|
31
|
+
const SEVERITY = Object.freeze<Record<LogRecordEvent['level'], number>>({
|
|
32
|
+
trace: 1,
|
|
33
|
+
debug: 5,
|
|
34
|
+
info: 9,
|
|
35
|
+
warn: 13,
|
|
36
|
+
error: 17,
|
|
37
|
+
fatal: 21,
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
/** One record as the exporter holds it: the event, and the span it was written under. */
|
|
41
|
+
export interface ExportedLogRecord {
|
|
42
|
+
readonly record: LogRecordEvent;
|
|
43
|
+
readonly span: SpanContext | undefined;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** A field as an OTLP attribute. A nested value is its JSON — already redacted by the logger. */
|
|
47
|
+
function attributeOf(value: unknown): AttributeValue | undefined {
|
|
48
|
+
if (typeof value === 'string' || typeof value === 'boolean') return value;
|
|
49
|
+
if (typeof value === 'number') return value;
|
|
50
|
+
if (value === null || value === undefined) return undefined;
|
|
51
|
+
try {
|
|
52
|
+
return JSON.stringify(value);
|
|
53
|
+
} catch {
|
|
54
|
+
return renderThrowable(value);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function recordJson(entry: ExportedLogRecord): unknown {
|
|
59
|
+
const { record, span } = entry;
|
|
60
|
+
const attributes: Record<string, AttributeValue> = {};
|
|
61
|
+
for (const [key, value] of Object.entries(record.fields)) {
|
|
62
|
+
const attribute = attributeOf(value);
|
|
63
|
+
if (attribute !== undefined) attributes[key] = attribute;
|
|
64
|
+
}
|
|
65
|
+
// The synthetic context span (empty id) carries a trace id only: correlate on what exists.
|
|
66
|
+
const ids =
|
|
67
|
+
span === undefined
|
|
68
|
+
? {}
|
|
69
|
+
: {
|
|
70
|
+
traceId: span.traceId,
|
|
71
|
+
...(span.spanId === '' ? {} : { spanId: span.spanId }),
|
|
72
|
+
flags: span.traceFlags & 0xff,
|
|
73
|
+
};
|
|
74
|
+
return {
|
|
75
|
+
timeUnixNano: unixNano(record.at),
|
|
76
|
+
observedTimeUnixNano: unixNano(record.at),
|
|
77
|
+
severityNumber: SEVERITY[record.level],
|
|
78
|
+
severityText: record.level.toUpperCase(),
|
|
79
|
+
body: { stringValue: record.message },
|
|
80
|
+
attributes: otlpAttributes(attributes) satisfies readonly OtlpKeyValue[],
|
|
81
|
+
...ids,
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Pure, so the wire format is a unit test rather than something discovered against a collector. */
|
|
86
|
+
export function otlpLogsRequest(
|
|
87
|
+
records: readonly ExportedLogRecord[],
|
|
88
|
+
resource: SpanResource,
|
|
89
|
+
): unknown {
|
|
90
|
+
return {
|
|
91
|
+
resourceLogs: [
|
|
92
|
+
{
|
|
93
|
+
resource: otlpResource(resource),
|
|
94
|
+
scopeLogs: [{ scope: OTLP_SCOPE, logRecords: records.map(recordJson) }],
|
|
95
|
+
},
|
|
96
|
+
],
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export interface OtlpLogExporterOptions {
|
|
101
|
+
/** Overrides `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT` / `OTEL_EXPORTER_OTLP_ENDPOINT`. */
|
|
102
|
+
readonly endpoint?: string | undefined;
|
|
103
|
+
/** Merged over `OTEL_EXPORTER_OTLP_LOGS_HEADERS` (else `OTEL_EXPORTER_OTLP_HEADERS`). */
|
|
104
|
+
readonly headers?: Readonly<Record<string, string>> | undefined;
|
|
105
|
+
/** Records per POST. Default 512, the OTel batch log processor's default. */
|
|
106
|
+
readonly maxBatchSize?: number | undefined;
|
|
107
|
+
/** Default 1000ms — the OTel batch log processor's schedule delay. */
|
|
108
|
+
readonly flushIntervalMs?: number | undefined;
|
|
109
|
+
/** Records held before the oldest are dropped. Default 2048. */
|
|
110
|
+
readonly maxQueueSize?: number | undefined;
|
|
111
|
+
/** Default 10000ms, the whole export, retries included. */
|
|
112
|
+
readonly timeoutMs?: number | undefined;
|
|
113
|
+
readonly fetch?: typeof globalThis.fetch | undefined;
|
|
114
|
+
readonly sleep?: OtlpPostOptions['sleep'];
|
|
115
|
+
readonly random?: OtlpPostOptions['random'];
|
|
116
|
+
readonly now?: OtlpPostOptions['now'];
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export interface OtlpLogExporter {
|
|
120
|
+
/** Call from the `log.record` handler — synchronously, so the active span is the writer's. */
|
|
121
|
+
export(record: LogRecordEvent): void;
|
|
122
|
+
flush(): Promise<void>;
|
|
123
|
+
/** Stop the timer and flush. Wire into `onShutdown('otlp', …, { phase: 'close' })`. */
|
|
124
|
+
shutdown(): Promise<void>;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* The exporter's own complaints (`otlp export failed`, `otlp … dropped`) are not exported: with the
|
|
129
|
+
* collector down they would be queued for the collector that is down, one more per interval.
|
|
130
|
+
*/
|
|
131
|
+
const OWN_LINES = /^otlp /;
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Throws `X_OTLP_ENDPOINT_INVALID` at construction when nothing configured an endpoint. Ask
|
|
135
|
+
* `tryOtlpEndpoint('logs')` first when the exporter is optional.
|
|
136
|
+
*/
|
|
137
|
+
export function otlpLogExporter(options: OtlpLogExporterOptions = {}): OtlpLogExporter {
|
|
138
|
+
const url = otlpEndpoint('logs', options.endpoint);
|
|
139
|
+
const headers = otlpHeaders(options.headers, process.env, 'logs');
|
|
140
|
+
const maxBatchSize = assertFiniteOtlpBound('maxBatchSize', options.maxBatchSize ?? 512);
|
|
141
|
+
const maxQueueSize = assertFiniteOtlpBound('maxQueueSize', options.maxQueueSize ?? 2048);
|
|
142
|
+
const timeoutMs = assertFiniteOtlpBound('timeoutMs', options.timeoutMs ?? 10_000);
|
|
143
|
+
const flushIntervalMs = assertFiniteOtlpBound(
|
|
144
|
+
'flushIntervalMs',
|
|
145
|
+
options.flushIntervalMs ?? 1_000,
|
|
146
|
+
);
|
|
147
|
+
const send = options.fetch ?? globalThis.fetch;
|
|
148
|
+
const seams = { sleep: options.sleep, random: options.random, now: options.now };
|
|
149
|
+
|
|
150
|
+
const post = (batch: readonly ExportedLogRecord[]): Promise<void> => {
|
|
151
|
+
let body: string;
|
|
152
|
+
try {
|
|
153
|
+
body = JSON.stringify(otlpLogsRequest(batch, serviceResource()));
|
|
154
|
+
} catch (failure) {
|
|
155
|
+
logger.warn('otlp log batch dropped', {
|
|
156
|
+
url: otlpEndpointLabel(url),
|
|
157
|
+
records: batch.length,
|
|
158
|
+
error: renderThrowable(failure),
|
|
159
|
+
});
|
|
160
|
+
return Promise.resolve();
|
|
161
|
+
}
|
|
162
|
+
return postOtlp({ url, headers, body, timeoutMs, fetch: send, ...seams });
|
|
163
|
+
};
|
|
164
|
+
|
|
165
|
+
const batcher = otlpBatcher<ExportedLogRecord>({
|
|
166
|
+
maxBatchSize,
|
|
167
|
+
maxQueueSize,
|
|
168
|
+
flushIntervalMs,
|
|
169
|
+
post,
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
return {
|
|
173
|
+
export(record: LogRecordEvent): void {
|
|
174
|
+
if (OWN_LINES.test(record.message)) return;
|
|
175
|
+
batcher.push({ record, span: currentSpanContext() });
|
|
176
|
+
},
|
|
177
|
+
flush: batcher.flush,
|
|
178
|
+
shutdown: batcher.shutdown,
|
|
179
|
+
};
|
|
180
|
+
}
|
|
@@ -16,6 +16,7 @@ import {
|
|
|
16
16
|
type OtlpPostOptions,
|
|
17
17
|
otlpAttributes,
|
|
18
18
|
otlpEndpoint,
|
|
19
|
+
otlpEndpointLabel,
|
|
19
20
|
otlpHeaders,
|
|
20
21
|
otlpResource,
|
|
21
22
|
postOtlp,
|
|
@@ -169,7 +170,7 @@ export function otlpMetricExporter(options: OtlpMetricExporterOptions = {}): Otl
|
|
|
169
170
|
body = JSON.stringify(otlpMetricsRequest(collection, startedAtMs));
|
|
170
171
|
} catch (failure) {
|
|
171
172
|
logger.warn('otlp metric snapshot dropped', {
|
|
172
|
-
url,
|
|
173
|
+
url: otlpEndpointLabel(url),
|
|
173
174
|
metrics: collection.metrics.length,
|
|
174
175
|
error: renderThrowable(failure),
|
|
175
176
|
});
|
package/src/otlp-post.ts
CHANGED
|
@@ -78,12 +78,32 @@ const retryTimer = (ms: number): Promise<void> =>
|
|
|
78
78
|
setTimeout(done, ms);
|
|
79
79
|
});
|
|
80
80
|
|
|
81
|
+
/**
|
|
82
|
+
* An endpoint as a log line may print it: origin and path only. A query string can carry a
|
|
83
|
+
* collector token (`?api-key=…`), and userinfo a password — neither is ever logged.
|
|
84
|
+
*/
|
|
85
|
+
export function otlpEndpointLabel(endpoint: string): string {
|
|
86
|
+
try {
|
|
87
|
+
const url = new URL(endpoint);
|
|
88
|
+
// Any other scheme is a value that only parsed by accident (`user:pass@…` reads as scheme
|
|
89
|
+
// `user:`), so its path may BE the credential: name the scheme alone.
|
|
90
|
+
if (url.protocol !== 'http:' && url.protocol !== 'https:') return `a ${url.protocol} URL`;
|
|
91
|
+
return `${url.protocol}//${url.host}${url.pathname}`;
|
|
92
|
+
} catch {
|
|
93
|
+
return 'an OTLP endpoint that is not a URL';
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
81
97
|
function logOutcome(url: string, outcome: Outcome, attempts: number): void {
|
|
82
98
|
if (outcome.kind === 'rejected') {
|
|
83
|
-
logger.warn('otlp export rejected', {
|
|
99
|
+
logger.warn('otlp export rejected', {
|
|
100
|
+
url: otlpEndpointLabel(url),
|
|
101
|
+
status: outcome.status,
|
|
102
|
+
attempts,
|
|
103
|
+
});
|
|
84
104
|
} else if (outcome.kind === 'failed') {
|
|
85
105
|
logger.warn('otlp export failed', {
|
|
86
|
-
url,
|
|
106
|
+
url: otlpEndpointLabel(url),
|
|
87
107
|
attempts,
|
|
88
108
|
// `renderThrowable`: the read that renders a caught value must not itself throw, or the
|
|
89
109
|
// export failure this function exists to swallow escapes as an unhandled rejection.
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// Single responsibility: a `SpanExporter` that POSTs OTLP/HTTP JSON to a collector. Batched,
|
|
2
2
|
// because `SpanExporter.export` is one span and a request per span is a second load generator.
|
|
3
|
+
// Installed as a subscriber: `subscribe('span.end', (event) => exporter.export(event.payload))`.
|
|
3
4
|
|
|
4
5
|
import { renderThrowable } from './error-render';
|
|
5
6
|
import { logger } from './logger';
|
|
@@ -10,11 +11,13 @@ import {
|
|
|
10
11
|
type OtlpPostOptions,
|
|
11
12
|
otlpAttributes,
|
|
12
13
|
otlpEndpoint,
|
|
14
|
+
otlpEndpointLabel,
|
|
13
15
|
otlpHeaders,
|
|
14
16
|
otlpResource,
|
|
15
17
|
postOtlp,
|
|
16
18
|
unixNano,
|
|
17
19
|
} from './otlp';
|
|
20
|
+
import { otlpBatcher } from './otlp-batch';
|
|
18
21
|
import type {
|
|
19
22
|
ReadableSpan,
|
|
20
23
|
SpanContext,
|
|
@@ -49,6 +52,7 @@ interface OtlpSpanJson {
|
|
|
49
52
|
readonly endTimeUnixNano: string;
|
|
50
53
|
readonly attributes: readonly OtlpKeyValue[];
|
|
51
54
|
readonly events: readonly unknown[];
|
|
55
|
+
readonly droppedEventsCount: number;
|
|
52
56
|
readonly links: readonly unknown[];
|
|
53
57
|
readonly status: { readonly code: number; readonly message?: string };
|
|
54
58
|
}
|
|
@@ -72,6 +76,7 @@ function spanJson(span: ReadableSpan): OtlpSpanJson {
|
|
|
72
76
|
name: event.name,
|
|
73
77
|
attributes: otlpAttributes(event.attributes),
|
|
74
78
|
})),
|
|
79
|
+
droppedEventsCount: span.droppedEventsCount,
|
|
75
80
|
links: span.links.map(link),
|
|
76
81
|
status: {
|
|
77
82
|
code: STATUS_CODE[span.status.code],
|
|
@@ -141,10 +146,6 @@ export function otlpSpanExporter(options: OtlpSpanExporterOptions = {}): OtlpSpa
|
|
|
141
146
|
);
|
|
142
147
|
const send = options.fetch ?? globalThis.fetch;
|
|
143
148
|
const seams = { sleep: options.sleep, random: options.random, now: options.now };
|
|
144
|
-
const queue: ReadableSpan[] = [];
|
|
145
|
-
/** The ONE batch in flight, or `undefined`. Never a chain: see `pump`. */
|
|
146
|
-
let sending: Promise<void> | undefined;
|
|
147
|
-
|
|
148
149
|
const post = (batch: readonly ReadableSpan[]): Promise<void> => {
|
|
149
150
|
const first = batch[0];
|
|
150
151
|
if (first === undefined) return Promise.resolve();
|
|
@@ -158,7 +159,7 @@ export function otlpSpanExporter(options: OtlpSpanExporterOptions = {}): OtlpSpa
|
|
|
158
159
|
body = JSON.stringify(otlpTraceRequest(batch, first.resource));
|
|
159
160
|
} catch (failure) {
|
|
160
161
|
logger.warn('otlp span batch dropped', {
|
|
161
|
-
url,
|
|
162
|
+
url: otlpEndpointLabel(url),
|
|
162
163
|
spans: batch.length,
|
|
163
164
|
error: renderThrowable(failure),
|
|
164
165
|
});
|
|
@@ -167,63 +168,13 @@ export function otlpSpanExporter(options: OtlpSpanExporterOptions = {}): OtlpSpa
|
|
|
167
168
|
return postOtlp({ url, headers, body, timeoutMs, fetch: send, ...seams });
|
|
168
169
|
};
|
|
169
170
|
|
|
170
|
-
|
|
171
|
-
* At most ONE batch in flight, and at most `maxBatchSize` spans in it. The queue used to be
|
|
172
|
-
* moved wholesale into a promise chain behind the previous POST, so a stalled collector held
|
|
173
|
-
* every span ever exported — 100k with `maxQueueSize: 2048` — and the bound was a bound on the
|
|
174
|
-
* queue, not on memory. Now spans WAIT IN the queue while a POST is unsettled, where drop-oldest
|
|
175
|
-
* applies, and what is held is `maxQueueSize` plus one batch. One at a time also keeps batches
|
|
176
|
-
* in order, so a parent span never arrives after its child. A POST cannot reject (`postOtlp`
|
|
177
|
-
* degrades to a log line) and `post` catches its own serialisation throw, so nothing here can
|
|
178
|
-
* poison the next send.
|
|
179
|
-
*/
|
|
180
|
-
const pump = (): Promise<void> => {
|
|
181
|
-
if (sending !== undefined) return sending;
|
|
182
|
-
const batch = queue.splice(0, maxBatchSize);
|
|
183
|
-
if (batch.length === 0) return Promise.resolve();
|
|
184
|
-
const current = post(batch).then(
|
|
185
|
-
() => undefined,
|
|
186
|
-
() => undefined,
|
|
187
|
-
);
|
|
188
|
-
sending = current.then(() => {
|
|
189
|
-
sending = undefined;
|
|
190
|
-
// A full batch waiting behind a slow POST goes next without waiting for the timer.
|
|
191
|
-
if (queue.length >= maxBatchSize) void pump();
|
|
192
|
-
});
|
|
193
|
-
return sending;
|
|
194
|
-
};
|
|
195
|
-
|
|
196
|
-
/** Everything queued NOW, batch by batch. Bounded, so a busy exporter cannot keep it looping. */
|
|
197
|
-
const drainQueue = async (): Promise<void> => {
|
|
198
|
-
let rounds = Math.ceil(queue.length / maxBatchSize) + 1;
|
|
199
|
-
while (rounds > 0) {
|
|
200
|
-
rounds -= 1;
|
|
201
|
-
await pump();
|
|
202
|
-
if (queue.length === 0 && sending === undefined) return;
|
|
203
|
-
}
|
|
204
|
-
};
|
|
205
|
-
|
|
206
|
-
// Unref'd, so a pending flush never holds a draining process open — `shutdown()` is what
|
|
207
|
-
// decides the last batch leaves, exactly as `startMetricExport` defers to the drain hook.
|
|
208
|
-
// `pump`, never `drainQueue`: while a POST is stalled `pump` answers the send already in flight
|
|
209
|
-
// and allocates nothing, where a drain per tick would park one more waiter per interval.
|
|
210
|
-
const timer = setInterval(() => void pump(), flushIntervalMs);
|
|
211
|
-
timer.unref();
|
|
171
|
+
const batcher = otlpBatcher<ReadableSpan>({ maxBatchSize, maxQueueSize, flushIntervalMs, post });
|
|
212
172
|
|
|
213
173
|
return {
|
|
214
174
|
export(span: ReadableSpan): void {
|
|
215
|
-
|
|
216
|
-
// the spans an operator wants during an incident are the ones happening now.
|
|
217
|
-
if (queue.length >= maxQueueSize) queue.shift();
|
|
218
|
-
queue.push(span);
|
|
219
|
-
if (queue.length >= maxBatchSize) void pump();
|
|
220
|
-
},
|
|
221
|
-
flush(): Promise<void> {
|
|
222
|
-
return drainQueue();
|
|
223
|
-
},
|
|
224
|
-
async shutdown(): Promise<void> {
|
|
225
|
-
clearInterval(timer);
|
|
226
|
-
await drainQueue();
|
|
175
|
+
batcher.push(span);
|
|
227
176
|
},
|
|
177
|
+
flush: batcher.flush,
|
|
178
|
+
shutdown: batcher.shutdown,
|
|
228
179
|
};
|
|
229
180
|
}
|
package/src/otlp.ts
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
|
-
// Single responsibility: the pieces
|
|
2
|
-
// an operator already sets, header parsing, the OTLP/JSON value encoding,
|
|
3
|
-
// never throws. A serialisation, not a vendor (axiom 7),
|
|
1
|
+
// Single responsibility: the pieces every OTLP exporter (traces, metrics, logs) shares — endpoint
|
|
2
|
+
// resolution from the env an operator already sets, header parsing, the OTLP/JSON value encoding,
|
|
3
|
+
// and (from `otlp-post.ts`) one POST that never throws. A serialisation, not a vendor (axiom 7),
|
|
4
|
+
// exactly as `metrics-text.ts` is to Prometheus.
|
|
4
5
|
|
|
5
6
|
import { assert } from './assert';
|
|
7
|
+
import { renderFixShellArg } from './error-render';
|
|
6
8
|
import { type CodedErrorInit, UltimateError } from './errors';
|
|
9
|
+
import { otlpEndpointLabel } from './otlp-post';
|
|
7
10
|
import type { AttributeValue, SpanResource } from './telemetry';
|
|
8
11
|
|
|
9
12
|
export class OtlpEndpointInvalidError extends UltimateError {
|
|
@@ -36,7 +39,7 @@ export class OtlpProtocolUnsupportedError extends UltimateError {
|
|
|
36
39
|
}
|
|
37
40
|
}
|
|
38
41
|
|
|
39
|
-
export type OtlpSignal = 'traces' | 'metrics';
|
|
42
|
+
export type OtlpSignal = 'traces' | 'metrics' | 'logs';
|
|
40
43
|
|
|
41
44
|
export const OTLP_ENDPOINT_KEY = 'OTEL_EXPORTER_OTLP_ENDPOINT';
|
|
42
45
|
export const OTLP_HEADERS_KEY = 'OTEL_EXPORTER_OTLP_HEADERS';
|
|
@@ -77,17 +80,27 @@ function parseEndpoint(signal: OtlpSignal, raw: string, perSignal: boolean, env:
|
|
|
77
80
|
try {
|
|
78
81
|
url = new URL(raw);
|
|
79
82
|
} catch {
|
|
83
|
+
// Not echoed: an unparsable value may still be `user:password@…` with one character wrong.
|
|
80
84
|
throw new OtlpEndpointInvalidError({
|
|
81
|
-
cause: `
|
|
85
|
+
cause: `the ${signal} OTLP endpoint is not a URL (${raw.length} characters, not echoed: it may carry a credential)`,
|
|
82
86
|
fix: `set ${OTLP_ENDPOINT_KEY}=http://otel-collector:4318`,
|
|
83
|
-
meta: {
|
|
87
|
+
meta: { signal },
|
|
84
88
|
});
|
|
85
89
|
}
|
|
86
90
|
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
|
|
87
91
|
throw new OtlpEndpointInvalidError({
|
|
88
|
-
cause: `"${raw}" is ${url.protocol}, and OTLP/HTTP needs http or https`,
|
|
92
|
+
cause: `"${otlpEndpointLabel(raw)}" is ${url.protocol}, and OTLP/HTTP needs http or https`,
|
|
89
93
|
fix: `set ${OTLP_ENDPOINT_KEY}=http://otel-collector:4318`,
|
|
90
|
-
meta: { endpoint: raw, signal },
|
|
94
|
+
meta: { endpoint: otlpEndpointLabel(raw), signal },
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
// A credential in the URL rides every log line that names the endpoint; the spec's place for
|
|
98
|
+
// one is `OTEL_EXPORTER_OTLP_HEADERS`, whose values are never logged.
|
|
99
|
+
if (url.username !== '' || url.password !== '') {
|
|
100
|
+
throw new OtlpEndpointInvalidError({
|
|
101
|
+
cause: `the OTLP endpoint ${otlpEndpointLabel(url.toString())} carries a user name or password in the URL, which every export log line would print`,
|
|
102
|
+
fix: `export OTEL_EXPORTER_OTLP_ENDPOINT=${renderFixShellArg(otlpEndpointLabel(url.toString()), '<the endpoint, without the credential>')} OTEL_EXPORTER_OTLP_HEADERS='authorization=Basic%20<base64>' # the credential moves to the headers, which are never logged`,
|
|
103
|
+
meta: { endpoint: otlpEndpointLabel(url.toString()), signal },
|
|
91
104
|
});
|
|
92
105
|
}
|
|
93
106
|
assertHttpJson(signal, url, env);
|
|
@@ -269,4 +282,9 @@ export function otlpResource(resource: SpanResource): {
|
|
|
269
282
|
export const OTLP_SCOPE = Object.freeze({ name: '@ultimat3/core' });
|
|
270
283
|
|
|
271
284
|
// Delivery, retry included, is its own module; re-exported so the exporters' one import stays.
|
|
272
|
-
export {
|
|
285
|
+
export {
|
|
286
|
+
OTLP_RETRY_STATUSES,
|
|
287
|
+
type OtlpPostOptions,
|
|
288
|
+
otlpEndpointLabel,
|
|
289
|
+
postOtlp,
|
|
290
|
+
} from './otlp-post';
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
// Single responsibility: what one `outbound()` CALL tells the instrumentation bus — a client span
|
|
2
|
+
// named `outbound.<vendor>` with semconv attributes and one `outbound.request` event, both around
|
|
3
|
+
// the whole call (retries and breaker inside), on the answer and on the failure alike.
|
|
4
|
+
|
|
5
|
+
import { isUltimateError } from './errors';
|
|
6
|
+
import { instrument, subscribed } from './instrument';
|
|
7
|
+
import { SEMCONV } from './instrument-semconv';
|
|
8
|
+
import type { Span } from './telemetry';
|
|
9
|
+
import { withSpan } from './telemetry';
|
|
10
|
+
|
|
11
|
+
export interface OutboundCallSite {
|
|
12
|
+
readonly vendor: string;
|
|
13
|
+
readonly method: string;
|
|
14
|
+
readonly url: URL;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** The status a coded refusal carried (`X_OUTBOUND_REFUSED` and kin); none when no answer came. */
|
|
18
|
+
function refusedStatus(error: unknown): number | undefined {
|
|
19
|
+
if (!isUltimateError(error)) return undefined;
|
|
20
|
+
const status = error.meta?.['status'];
|
|
21
|
+
return typeof status === 'number' ? status : undefined;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Hostname and port only: the path and query may carry a credential, so neither is recorded. */
|
|
25
|
+
function serverAttributes(url: URL): Record<string, string | number> {
|
|
26
|
+
const port = url.port === '' ? undefined : Number(url.port);
|
|
27
|
+
return {
|
|
28
|
+
[SEMCONV.serverAddress]: url.hostname,
|
|
29
|
+
...(port === undefined ? {} : { [SEMCONV.serverPort]: port }),
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Run the call inside its span and report it once it settles. `work` answers the final status; a
|
|
35
|
+
* throw is reported with the status its refusal carried, then rethrown unchanged.
|
|
36
|
+
*/
|
|
37
|
+
export async function instrumentedCall<T extends { readonly status: number }>(
|
|
38
|
+
site: OutboundCallSite,
|
|
39
|
+
work: () => Promise<T>,
|
|
40
|
+
): Promise<T> {
|
|
41
|
+
const started = performance.now();
|
|
42
|
+
const report = (status: number | undefined, error?: unknown): void => {
|
|
43
|
+
if (!subscribed('outbound.request')) return;
|
|
44
|
+
instrument('outbound.request', {
|
|
45
|
+
vendor: site.vendor,
|
|
46
|
+
method: site.method,
|
|
47
|
+
host: site.url.hostname,
|
|
48
|
+
...(status === undefined ? {} : { status }),
|
|
49
|
+
durationMs: performance.now() - started,
|
|
50
|
+
...(error === undefined ? {} : { error }),
|
|
51
|
+
});
|
|
52
|
+
};
|
|
53
|
+
try {
|
|
54
|
+
const answer = await withSpan(
|
|
55
|
+
`outbound.${site.vendor}`,
|
|
56
|
+
async (span: Span) => {
|
|
57
|
+
try {
|
|
58
|
+
const settled = await work();
|
|
59
|
+
span.setAttribute(SEMCONV.httpResponseStatusCode, settled.status);
|
|
60
|
+
return settled;
|
|
61
|
+
} catch (error) {
|
|
62
|
+
const status = refusedStatus(error);
|
|
63
|
+
if (status !== undefined) span.setAttribute(SEMCONV.httpResponseStatusCode, status);
|
|
64
|
+
throw error;
|
|
65
|
+
}
|
|
66
|
+
},
|
|
67
|
+
{
|
|
68
|
+
kind: 'client',
|
|
69
|
+
attributes: {
|
|
70
|
+
...serverAttributes(site.url),
|
|
71
|
+
[SEMCONV.httpRequestMethod]: site.method,
|
|
72
|
+
'ultimate.outbound.vendor': site.vendor,
|
|
73
|
+
},
|
|
74
|
+
},
|
|
75
|
+
);
|
|
76
|
+
report(answer.status);
|
|
77
|
+
return answer;
|
|
78
|
+
} catch (error) {
|
|
79
|
+
report(refusedStatus(error), error);
|
|
80
|
+
throw error;
|
|
81
|
+
}
|
|
82
|
+
}
|
package/src/outbound.ts
CHANGED
|
@@ -17,6 +17,7 @@ import { runAttempt } from './outbound-attempt';
|
|
|
17
17
|
import type { OutboundSite } from './outbound-errors';
|
|
18
18
|
import { isCallerBound, outboundBodyInvalid, outboundRetryUnsafe } from './outbound-errors';
|
|
19
19
|
import { redactedPath } from './outbound-hops';
|
|
20
|
+
import { instrumentedCall } from './outbound-instrument';
|
|
20
21
|
import type {
|
|
21
22
|
OutboundAnswer,
|
|
22
23
|
OutboundDeps,
|
|
@@ -170,10 +171,10 @@ export async function outbound(
|
|
|
170
171
|
now: call.now,
|
|
171
172
|
random: deps.random,
|
|
172
173
|
});
|
|
173
|
-
const answer =
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
174
|
+
const answer = await instrumentedCall(
|
|
175
|
+
{ vendor: call.site.vendor, method: call.method, url: call.url },
|
|
176
|
+
() => (request.breaker === undefined ? work() : guarded(request.breaker, request.signal, work)),
|
|
177
|
+
);
|
|
177
178
|
if ('stream' in answer) return answer;
|
|
178
179
|
return bytesAnswer(call.site, answer);
|
|
179
180
|
}
|
package/src/page-meta.ts
CHANGED
|
@@ -55,6 +55,12 @@ export const CLIENT_SYNC_WORKER_META = 'ultimate-sync-worker';
|
|
|
55
55
|
*/
|
|
56
56
|
export const CLIENT_PERSIST_META = 'ultimate-persist';
|
|
57
57
|
|
|
58
|
+
/**
|
|
59
|
+
* The page outbox's ceiling — `realtime.maxQueued` in `app.config.ts`, as a decimal count. Read by
|
|
60
|
+
* `@ultimat3/realtime`'s page boot, which builds the outbox. Absent = no ceiling.
|
|
61
|
+
*/
|
|
62
|
+
export const CLIENT_OUTBOX_MAX_META = 'ultimate-outbox-max';
|
|
63
|
+
|
|
58
64
|
/**
|
|
59
65
|
* The client router's request headers (`@ultimat3/render`'s `navigation.ts`), read by
|
|
60
66
|
* `@ultimat3/http`'s navigation gate before any app code runs. `soft` is a visit the router will
|
package/src/page.ts
CHANGED
|
@@ -15,13 +15,23 @@ export type { AsyncState } from './async-state';
|
|
|
15
15
|
export type { JitterMode, Random } from './backoff';
|
|
16
16
|
export { backoffDelay } from './backoff';
|
|
17
17
|
export type { FetchLike, TransportRequest } from './client-dispatch';
|
|
18
|
-
export { IDEMPOTENCY_HEADER } from './client-dispatch';
|
|
18
|
+
export { BUILD_ID_HEADER, IDEMPOTENCY_HEADER } from './client-dispatch';
|
|
19
|
+
// Opt-in flight control: a typed client names `ClientFlight` as a TYPE and pays nothing; an island
|
|
20
|
+
// that wants the fence, dedup and retry calls `clientFlight` from here, never through the barrel.
|
|
21
|
+
export type { ClientFlight, ClientFlightOptions, ClientRetry } from './client-flight';
|
|
22
|
+
export { clientFlight } from './client-flight';
|
|
23
|
+
export type { ActionPathStyle } from './client-paths';
|
|
19
24
|
export { actionPath, queryPath, splitWords } from './client-paths';
|
|
20
25
|
export type { ActionPin, PinnedActionMethod } from './client-paths-pins';
|
|
21
26
|
export { renderedActionPin, renderedQueryPin } from './client-paths-pins';
|
|
27
|
+
// A typed client's own decode of a refusal: the body read, its title and request id carried, the
|
|
28
|
+
// retry class its status implies — all off the wire, so an island needs no titles table.
|
|
29
|
+
export { remoteTitleOf, withRequestId, withStatedDelay } from './client-problem';
|
|
22
30
|
export type { ClientScope } from './client-scope';
|
|
23
31
|
export { onRescope, rescope } from './client-scope';
|
|
32
|
+
export { clientStream } from './client-stream';
|
|
24
33
|
export { clientTransport } from './client-transport';
|
|
34
|
+
export { FRAMEWORK_CODE, problemOf, retryForStatus } from './client-wire';
|
|
25
35
|
export { notifyClientWrite, onClientWrite } from './client-writes';
|
|
26
36
|
export { type Clock, systemClock } from './clock';
|
|
27
37
|
export type { ConflictPolicy, Row } from './conflict-policy';
|
|
@@ -31,11 +41,18 @@ export { resolveConflict } from './conflict-policy';
|
|
|
31
41
|
// The registry's one writer, for a package that titles its OWN codes in a browser chunk
|
|
32
42
|
// (`@ultimat3/realtime`'s `error-titles.ts`). A function, not a table: `errors.ts` already retains
|
|
33
43
|
// `error-codes.ts`, so this adds no module — and through the barrel it cost both anchored tables.
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
export {
|
|
44
|
+
// `hasErrorCode` and `ERROR_DOCS_URL` read the registry `errors.ts` already retains; a package's
|
|
45
|
+
// browser-reachable error classes need them, `registerErrorRetry` beside `registerErrorCodes`.
|
|
46
|
+
export { ERROR_DOCS_URL, hasErrorCode, registerErrorCodes } from './error-codes';
|
|
47
|
+
export {
|
|
48
|
+
renderCauseValue,
|
|
49
|
+
renderFixShellArg,
|
|
50
|
+
renderThrowable,
|
|
51
|
+
stringField,
|
|
52
|
+
} from './error-render';
|
|
53
|
+
export { classifyThrown, registerErrorRetry } from './error-retry';
|
|
37
54
|
export type { UltimateErrorInit } from './errors';
|
|
38
|
-
export { isUltimateError, UltimateError } from './errors';
|
|
55
|
+
export { deniedCallerFix, isUltimateError, UltimateError } from './errors';
|
|
39
56
|
export { fillWire } from './fill-wire';
|
|
40
57
|
export { finiteCount, finiteOption } from './finite-option';
|
|
41
58
|
export { isSuperseded } from './generation-fence';
|
|
@@ -50,6 +67,7 @@ export {
|
|
|
50
67
|
CLIENT_NAVIGATION_LOCATION_HEADER,
|
|
51
68
|
CLIENT_NAVIGATION_SCOPE_HEADER,
|
|
52
69
|
CLIENT_NAVIGATION_SURFACE_HEADER,
|
|
70
|
+
CLIENT_OUTBOX_MAX_META,
|
|
53
71
|
CLIENT_PATH_STYLE_META,
|
|
54
72
|
CLIENT_PERSIST_META,
|
|
55
73
|
CLIENT_PINS_META,
|