release: WRNexusJS 0.8.0
This commit is contained in:
@@ -129,4 +129,81 @@ export function createHttpMetricExporter(
|
||||
};
|
||||
}
|
||||
|
||||
export function createOtlpMetricExporter(
|
||||
endpoint: string,
|
||||
options: { headers?: HeadersInit; fetch?: typeof fetch; serviceName?: string } = {},
|
||||
): MetricExporter {
|
||||
const send = options.fetch ?? fetch;
|
||||
return {
|
||||
async export(points) {
|
||||
if (!points.length) return;
|
||||
const metrics = points.map((point) => {
|
||||
const attributes = Object.entries(point.labels).map(([key, value]) => ({
|
||||
key,
|
||||
value:
|
||||
typeof value === "boolean"
|
||||
? { boolValue: value }
|
||||
: typeof value === "number"
|
||||
? { doubleValue: value }
|
||||
: { stringValue: value },
|
||||
}));
|
||||
const timeUnixNano = String(BigInt(Math.trunc(point.timestamp)) * 1_000_000n);
|
||||
if (point.type === "histogram") {
|
||||
return {
|
||||
name: point.name,
|
||||
histogram: {
|
||||
aggregationTemporality: 2,
|
||||
dataPoints: [
|
||||
{
|
||||
attributes,
|
||||
timeUnixNano,
|
||||
count: String(point.count ?? 0),
|
||||
sum: point.sum ?? 0,
|
||||
min: point.min,
|
||||
max: point.max,
|
||||
bucketCounts: [String(point.count ?? 0)],
|
||||
explicitBounds: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
}
|
||||
const kind = point.type === "counter" ? "sum" : "gauge";
|
||||
return {
|
||||
name: point.name,
|
||||
[kind]: {
|
||||
...(kind === "sum" ? { aggregationTemporality: 2, isMonotonic: true } : {}),
|
||||
dataPoints: [{ attributes, timeUnixNano, asDouble: point.value }],
|
||||
},
|
||||
};
|
||||
});
|
||||
const response = await send(endpoint, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
...Object.fromEntries(new Headers(options.headers)),
|
||||
},
|
||||
body: JSON.stringify({
|
||||
resourceMetrics: [
|
||||
{
|
||||
resource: {
|
||||
attributes: [
|
||||
{ key: "service.name", value: { stringValue: options.serviceName ?? "wrnexus" } },
|
||||
],
|
||||
},
|
||||
scopeMetrics: [
|
||||
{
|
||||
scope: { name: "@wrnexus/observability", version: "0.8.0" },
|
||||
metrics,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
}),
|
||||
});
|
||||
if (!response.ok) throw new Error(`OTLP metric export failed with ${response.status}.`);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export const defaultMetrics = new MetricsRegistry();
|
||||
|
||||
Reference in New Issue
Block a user