src/vs/platform/otel/node/otlp/localOtlpReceiver.ts
227 LOC · 209 covered · 18 uncovered · 40 ranges · 19 concepts · 19 introducers · 11 tests
File neighbourhood
The centred file is linked to every concept that introduces one of its ranges, every test that runs code from the file, and the gray connector concepts standing between those tests and the file's own introducer concepts. Undirected links join concepts to every file where they introduce source and concepts to the tests they introduce; arrows show specialization between the displayed concepts and bridge only concepts omitted from this view. Concept colors match the source ranges below; connector concepts have no source color and are shown in gray.
Focused file, its introducer and connector concepts, their introduced files, and tests that run code from the file
In the embedded map, ordinary wheel input scrolls the page; use the visible controls to zoom and drag to pan. Open the full-screen map for canvas navigation: wheel pans, Ctrl/Command plus wheel zooms, and arrow keys pan when this region is focused. On touch screens, open the full-screen map to pan or pinch. If JavaScript or WebGL is unavailable, use the related-file, concept, and source links on this page.
Graph controls are ready.
Interactive rendering requires JavaScript and WebGL. Use the related-file, concept, and source links on this page while the interactive map is unavailable.
/*---------------------------------------------------------------------------------------------
localOtlpReceiver.ts ×6
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import type { AddressInfo } from 'net';
import type * as http from 'http';
import { IDisposable, toDisposable } from '../../../../base/common/lifecycle.js';
import { ILogService } from '../../../log/common/log.js';
import { decodeExportTraceRequest, IDecodeResult } from './otlpJsonDecode.js';
import { IOtlpExportTraceServiceRequest, IOtlpExportTraceServiceResponse } from './otlpJsonTypes.js';
/** Path the OTLP/HTTP spec mandates for trace export. */
export const OTLP_TRACES_PATH = '/v1/traces';
/** Default request body cap, matching the collector's `confighttp` default. */
const DEFAULT_MAX_BODY_BYTES = 64 * 1024 * 1024;
/** Callbacks the receiver invokes for each accepted request. */
export interface IOtlpReceiverHandlers {
/** Invoked with the decoded spans for every successfully-parsed request. */
onSpans(result: IDecodeResult): void;
/**
* Invoked with the raw request body and content-type so the caller can
* forward the bytes to an upstream collector unchanged. Called before
* the receiver responds, but failures here MUST NOT affect the response.
*/
onForward?(body: Buffer, contentType: string): void;
}
export interface IOtlpReceiverOptions {
/**
* Cap on request body size. Anything larger gets HTTP 413. Defaults to
* 64 MiB, matching the OpenTelemetry Collector default.
*/
readonly maxBodyBytes?: number;
}
export interface ILocalOtlpHttpReceiver extends IDisposable {
/** Loopback URL clients should POST to (without the trailing `/v1/traces`). */
readonly baseUrl: string;
/** Ephemeral port chosen by the OS. */
readonly port: number;
}
/**
* Loopback OTLP/HTTP receiver. Listens on `127.0.0.1` at an OS-assigned
* ephemeral port. Accepts `POST /v1/traces` with `Content-Type: application/json`
* and forwards the parsed result to the caller's handlers.
*
* Only `application/json` is supported. `application/x-protobuf` is rejected
* with HTTP 415; we explicitly require the SDK to use OTLP/HTTP+JSON for the
* loopback path.
*
* Returns `200 OK` with an empty body on full success, or with a
* `{ partialSuccess: { rejectedSpans, errorMessage } }` body when the
* decoder dropped some spans. Per OTLP spec, partial success is NOT a retry
* signal — the SDK will move on.
*/
export async function startLocalOtlpHttpReceiver(
handlers: IOtlpReceiverHandlers,
logService: ILogService,
options: IOtlpReceiverOptions = {},
): Promise<ILocalOtlpHttpReceiver> {
const maxBodyBytes = options.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES;
const httpModule = await import('http');
const server = httpModule.createServer();
server.on('request', (req, res) => {
handleRequest(req, res, handlers, logService, maxBodyBytes).catch(err => {
localOtlpReceiver.ts ×6
logService.error(`[agentHost-otel] receiver: unhandled error: ${err instanceof Error ? err.message : String(err)}`);
if (!res.headersSent) {
writePlain(res, 500, 'internal error');
} else if (!res.writableEnded) {
try { res.end(); } catch { /* ignore */ }
}
await new Promise<void>((resolve, reject) => {
const onError = (err: Error) => reject(err);
server.once('error', onError);
server.listen(0, '127.0.0.1', () => {
server.removeListener('error', onError);
resolve();
});
});
const address = server.address();
if (!address || typeof address === 'string') {
server.close();
throw new Error(`local OTLP receiver failed to bind: unexpected address ${String(address)}`);
}
const baseUrl = `http://127.0.0.1:${port}`;
logService.info(`[agentHost-otel] receiver listening on ${baseUrl}`);
const disposable = toDisposable(() => {
server.closeAllConnections();
server.close(err => {
if (err) {
logService.warn(`[agentHost-otel] receiver close error: ${err.message}`);
}
});
return Object.assign(disposable, { baseUrl, port });
}
req: http.IncomingMessage,
res: http.ServerResponse,
handlers: IOtlpReceiverHandlers,
logService: ILogService,
maxBodyBytes: number,
): Promise<void> {
// Reject anything that isn't the trace export path.
const url = req.url ?? '';
const pathname = url.split('?', 1)[0];
if (pathname !== OTLP_TRACES_PATH) {
return;
}
writePlain(res, 405, 'method not allowed');
return;
}
const contentType = (req.headers['content-type'] ?? '').toString().toLowerCase();
localOtlpReceiver.ts ×6
if (!contentType.includes('application/json')) {
writePlain(res, 415, 'unsupported content-type; this receiver only accepts application/json');
localOtlpReceiver.ts ×1
return;
}
const encoding = (req.headers['content-encoding'] ?? '').toString().toLowerCase();
localOtlpReceiver.ts ×6
if (encoding && encoding !== 'identity') {
// Compression negotiation is out of scope for v1; let the SDK fall back to identity.
localOtlpReceiver.ts ×1
writePlain(res, 415, `unsupported content-encoding: ${encoding}`);
return;
}
let body: Buffer;
try {
body = await readBody(req, maxBodyBytes);
} catch (err) {
writePlain(res, 413, 'payload too large');
} else {
writePlain(res, 400, 'failed to read body');
}
}
// Best-effort forward of raw bytes BEFORE decoding so the upstream
// collector sees an identical payload to what the SDK emitted. Failures
// here are isolated from the local-decode path.
if (handlers.onForward) {
handlers.onForward(body, contentType);
} catch (err) {
logService.warn(`[agentHost-otel] forward callback threw: ${err instanceof Error ? err.message : String(err)}`);
localOtlpReceiver.ts ×1
}
let parsed: IOtlpExportTraceServiceRequest;
try {
parsed = JSON.parse(body.toString('utf8')) as IOtlpExportTraceServiceRequest;
} catch (err) {
writePlain(res, 400, `invalid json: ${err instanceof Error ? err.message : String(err)}`);
localOtlpReceiver.ts ×1
return;
}
const result = decodeExportTraceRequest(parsed);
try {
handlers.onSpans(result);
} catch (err) {
logService.warn(`[agentHost-otel] onSpans handler threw: ${err instanceof Error ? err.message : String(err)}`);
}
const responseBody: IOtlpExportTraceServiceResponse = result.rejected > 0
? { partialSuccess: { rejectedSpans: result.rejected, errorMessage: result.errors.join('; ').slice(0, 1024) } }
localOtlpReceiver.ts ×1
res.setHeader('content-type', 'application/json');
res.end(JSON.stringify(responseBody));
}
class PayloadTooLargeError extends Error { }
function readBody(req: http.IncomingMessage, maxBytes: number): Promise<Buffer> {
localOtlpReceiver.ts ×5
return new Promise((resolve, reject) => {
const chunks: Buffer[] = [];
let received = 0;
const onData = (chunk: Buffer) => {
received += chunk.length;
if (received > maxBytes) {
reject(new PayloadTooLargeError(`body exceeds ${maxBytes} bytes`));
return;
}
const onEnd = () => {
resolve(Buffer.concat(chunks));
};
cleanup();
reject(err);
};
req.removeListener('data', onData);
req.removeListener('end', onEnd);
req.removeListener('error', onError);
};
req.on('data', onData);
req.on('end', onEnd);
req.on('error', onError);
});
}
function writePlain(res: http.ServerResponse, status: number, message: string): void {
localOtlpReceiver.ts ×1
res.statusCode = status;
res.setHeader('content-type', 'text/plain; charset=utf-8');
res.end(message);
}