@watchtowerobservability/node 0.0.0-stage → 0.2.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/LICENSE +202 -0
- package/README.md +121 -2
- package/dist/cjs/buffer.d.ts +49 -0
- package/dist/cjs/buffer.js +134 -0
- package/dist/cjs/errors.d.ts +17 -0
- package/dist/cjs/errors.js +55 -0
- package/dist/cjs/index.d.ts +120 -0
- package/dist/cjs/index.js +302 -0
- package/dist/cjs/integrations/azure-functions.d.ts +18 -0
- package/dist/cjs/integrations/azure-functions.js +97 -0
- package/dist/cjs/integrations/express.d.ts +25 -0
- package/dist/cjs/integrations/express.js +58 -0
- package/dist/cjs/integrations/fastify.d.ts +6 -0
- package/dist/cjs/integrations/fastify.js +44 -0
- package/dist/cjs/integrations/genai-agents.d.ts +36 -0
- package/dist/cjs/integrations/genai-agents.js +124 -0
- package/dist/cjs/integrations/genai-stream.d.ts +19 -0
- package/dist/cjs/integrations/genai-stream.js +135 -0
- package/dist/cjs/integrations/genai.d.ts +18 -0
- package/dist/cjs/integrations/genai.js +150 -0
- package/dist/cjs/integrations/koa.d.ts +19 -0
- package/dist/cjs/integrations/koa.js +34 -0
- package/dist/cjs/integrations/lambda.d.ts +11 -0
- package/dist/cjs/integrations/lambda.js +68 -0
- package/dist/cjs/integrations/logs.d.ts +10 -0
- package/dist/cjs/integrations/logs.js +77 -0
- package/dist/cjs/integrations/nestjs.d.ts +16 -0
- package/dist/cjs/integrations/nestjs.js +30 -0
- package/dist/cjs/integrations/next.d.ts +11 -0
- package/dist/cjs/integrations/next.js +59 -0
- package/dist/cjs/integrations/prisma.d.ts +3 -0
- package/dist/cjs/integrations/prisma.js +33 -0
- package/dist/cjs/integrations/util.d.ts +9 -0
- package/dist/cjs/integrations/util.js +37 -0
- package/dist/cjs/jest.d.ts +21 -0
- package/dist/cjs/jest.js +45 -0
- package/dist/cjs/load.d.ts +1 -0
- package/dist/cjs/load.js +11 -0
- package/dist/cjs/metrics.d.ts +10 -0
- package/dist/cjs/metrics.js +81 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/payload.d.ts +42 -0
- package/dist/cjs/payload.js +145 -0
- package/dist/cjs/probes.d.ts +97 -0
- package/dist/cjs/probes.js +422 -0
- package/dist/cjs/profiling.d.ts +81 -0
- package/dist/cjs/profiling.js +253 -0
- package/dist/cjs/reporter-core.d.ts +32 -0
- package/dist/cjs/reporter-core.js +102 -0
- package/dist/cjs/test-plan.d.ts +93 -0
- package/dist/cjs/test-plan.js +262 -0
- package/dist/cjs/vitest.d.ts +27 -0
- package/dist/cjs/vitest.js +52 -0
- package/dist/esm/buffer.d.ts +49 -0
- package/dist/esm/buffer.js +92 -0
- package/dist/esm/errors.d.ts +17 -0
- package/dist/esm/errors.js +50 -0
- package/dist/esm/index.d.ts +120 -0
- package/dist/esm/index.js +251 -0
- package/dist/esm/integrations/azure-functions.d.ts +18 -0
- package/dist/esm/integrations/azure-functions.js +60 -0
- package/dist/esm/integrations/express.d.ts +25 -0
- package/dist/esm/integrations/express.js +54 -0
- package/dist/esm/integrations/fastify.d.ts +6 -0
- package/dist/esm/integrations/fastify.js +41 -0
- package/dist/esm/integrations/genai-agents.d.ts +36 -0
- package/dist/esm/integrations/genai-agents.js +118 -0
- package/dist/esm/integrations/genai-stream.d.ts +19 -0
- package/dist/esm/integrations/genai-stream.js +130 -0
- package/dist/esm/integrations/genai.d.ts +18 -0
- package/dist/esm/integrations/genai.js +138 -0
- package/dist/esm/integrations/koa.d.ts +19 -0
- package/dist/esm/integrations/koa.js +31 -0
- package/dist/esm/integrations/lambda.d.ts +11 -0
- package/dist/esm/integrations/lambda.js +32 -0
- package/dist/esm/integrations/logs.d.ts +10 -0
- package/dist/esm/integrations/logs.js +40 -0
- package/dist/esm/integrations/nestjs.d.ts +16 -0
- package/dist/esm/integrations/nestjs.js +26 -0
- package/dist/esm/integrations/next.d.ts +11 -0
- package/dist/esm/integrations/next.js +22 -0
- package/dist/esm/integrations/prisma.d.ts +3 -0
- package/dist/esm/integrations/prisma.js +30 -0
- package/dist/esm/integrations/util.d.ts +9 -0
- package/dist/esm/integrations/util.js +32 -0
- package/dist/esm/jest.d.ts +21 -0
- package/dist/esm/jest.js +41 -0
- package/dist/esm/load.d.ts +1 -0
- package/dist/esm/load.js +5 -0
- package/dist/esm/metrics.d.ts +10 -0
- package/dist/esm/metrics.js +44 -0
- package/dist/esm/package.json +1 -0
- package/dist/esm/payload.d.ts +42 -0
- package/dist/esm/payload.js +131 -0
- package/dist/esm/probes.d.ts +97 -0
- package/dist/esm/probes.js +412 -0
- package/dist/esm/profiling.d.ts +81 -0
- package/dist/esm/profiling.js +242 -0
- package/dist/esm/reporter-core.d.ts +32 -0
- package/dist/esm/reporter-core.js +63 -0
- package/dist/esm/test-plan.d.ts +93 -0
- package/dist/esm/test-plan.js +248 -0
- package/dist/esm/vitest.d.ts +27 -0
- package/dist/esm/vitest.js +48 -0
- package/package.json +219 -4
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { inspect } from 'node:util';
|
|
2
|
+
import { metrics, trace } from '@opentelemetry/api';
|
|
3
|
+
import type { Tracer } from '@opentelemetry/api';
|
|
4
|
+
import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node';
|
|
5
|
+
import { LoggerProvider } from '@opentelemetry/sdk-logs';
|
|
6
|
+
import type { MeterProvider } from '@opentelemetry/sdk-metrics';
|
|
7
|
+
import { captureException } from './errors.js';
|
|
8
|
+
import type { CaptureContext } from './errors.js';
|
|
9
|
+
export { captureException, metrics, trace };
|
|
10
|
+
export { setCaptureRules, capturePayload } from './payload.js';
|
|
11
|
+
export type { CaptureRule } from './payload.js';
|
|
12
|
+
export type { CaptureContext };
|
|
13
|
+
export declare const DEFAULT_ENDPOINT = "http://localhost:4318";
|
|
14
|
+
export type LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal';
|
|
15
|
+
export interface InitOptions {
|
|
16
|
+
/** Ingest key; defaults to WT_INGEST_KEY. */
|
|
17
|
+
apiKey?: string;
|
|
18
|
+
/** Defaults to WT_ENVIRONMENT. */
|
|
19
|
+
environment?: string;
|
|
20
|
+
/** Defaults to WT_RELEASE. */
|
|
21
|
+
release?: string;
|
|
22
|
+
/** Hook uncaughtException / unhandledRejection (default true). */
|
|
23
|
+
captureProcessErrors?: boolean;
|
|
24
|
+
/** Replace the log exporter (tests). */
|
|
25
|
+
logExporter?: unknown;
|
|
26
|
+
/** Export OTLP logs; defaults to WATCHTOWER_LOGS (on unless `off`; OTEL_LOGS_EXPORTER=none also turns it off). */
|
|
27
|
+
logs?: boolean;
|
|
28
|
+
/** Export OTLP metrics; defaults to WATCHTOWER_METRICS (on unless `off`; OTEL_METRICS_EXPORTER=none also turns it off). */
|
|
29
|
+
metrics?: boolean;
|
|
30
|
+
/** Replace the metric exporter (tests). */
|
|
31
|
+
metricExporter?: unknown;
|
|
32
|
+
/** OTLP/HTTP base URL; defaults to WT_OTLP_ENDPOINT or http://localhost:4318. */
|
|
33
|
+
endpoint?: string;
|
|
34
|
+
/** REST API base URL for getPrompt/score; defaults to WT_API_URL or endpoint. */
|
|
35
|
+
apiUrl?: string;
|
|
36
|
+
project?: string;
|
|
37
|
+
/** Defaults to WT_SERVICE. */
|
|
38
|
+
serviceName?: string;
|
|
39
|
+
/** Resource attributes; keys starting with `wt.` are dropped. */
|
|
40
|
+
resource?: Record<string, string | number | boolean>;
|
|
41
|
+
/** Called for every span attribute before export; return the value to keep. */
|
|
42
|
+
redact?: (key: string, value: unknown) => unknown;
|
|
43
|
+
/** Directory for the offline buffer. */
|
|
44
|
+
bufferDir?: string;
|
|
45
|
+
/** Fetch the service's payload capture rules (APM-016) and record bodies/GraphQL where a rule matches; defaults to WT_CAPTURE_RULES=1. */
|
|
46
|
+
captureRules?: boolean;
|
|
47
|
+
/** Replace the span exporter (tests). */
|
|
48
|
+
exporter?: unknown;
|
|
49
|
+
fetch?: typeof fetch;
|
|
50
|
+
}
|
|
51
|
+
export interface EvalRow {
|
|
52
|
+
case: number;
|
|
53
|
+
traceId: string;
|
|
54
|
+
scores: Record<string, unknown>;
|
|
55
|
+
errors: Record<string, string>;
|
|
56
|
+
}
|
|
57
|
+
export interface EvalOptions {
|
|
58
|
+
name?: string;
|
|
59
|
+
errorTolerance?: boolean;
|
|
60
|
+
/** Rows of an earlier run; cases that finished without errors are kept, not re-run. */
|
|
61
|
+
resume?: EvalRow[];
|
|
62
|
+
}
|
|
63
|
+
export type Scorers = Record<string, (testCase: any, output: any) => unknown | Promise<unknown>>;
|
|
64
|
+
export type EvalTask = (input: any) => unknown | Promise<unknown>;
|
|
65
|
+
export interface ScoreOptions {
|
|
66
|
+
name?: string;
|
|
67
|
+
spanId?: string;
|
|
68
|
+
comment?: string;
|
|
69
|
+
}
|
|
70
|
+
/** Drop caller-supplied wt.* keys: tenant identity comes only from the key. */
|
|
71
|
+
export declare function safeResource(attrs?: Record<string, unknown>): Record<string, unknown>;
|
|
72
|
+
export declare class Client {
|
|
73
|
+
readonly endpoint: string;
|
|
74
|
+
readonly apiUrl: string;
|
|
75
|
+
readonly project: string | undefined;
|
|
76
|
+
readonly headers: {
|
|
77
|
+
Authorization: string;
|
|
78
|
+
};
|
|
79
|
+
readonly fetch: typeof fetch;
|
|
80
|
+
readonly redact: InitOptions['redact'];
|
|
81
|
+
readonly provider: NodeTracerProvider;
|
|
82
|
+
readonly tracer: Tracer;
|
|
83
|
+
readonly loggerProvider: LoggerProvider;
|
|
84
|
+
readonly logger: ReturnType<LoggerProvider['getLogger']>;
|
|
85
|
+
/** Set when metrics are on; `init` makes it the global meter provider (`metrics.getMeter`). */
|
|
86
|
+
readonly meterProvider?: MeterProvider;
|
|
87
|
+
private readonly stopRuntime;
|
|
88
|
+
uninstall?: () => void;
|
|
89
|
+
constructor(opts: InitOptions);
|
|
90
|
+
/** Emit an OTLP log record; trace and span ids come from the active context. */
|
|
91
|
+
log(level: LogLevel, body: string, attributes?: Record<string, unknown>): void;
|
|
92
|
+
forceFlush(): Promise<unknown>;
|
|
93
|
+
toJSON(): {
|
|
94
|
+
endpoint: string;
|
|
95
|
+
project: string | undefined;
|
|
96
|
+
headers: {
|
|
97
|
+
Authorization: string;
|
|
98
|
+
};
|
|
99
|
+
};
|
|
100
|
+
[inspect.custom](): string;
|
|
101
|
+
private _call;
|
|
102
|
+
getPrompt(promptId: string): Promise<unknown>;
|
|
103
|
+
score(traceId: string, value: number | boolean | string, o?: ScoreOptions): Promise<unknown>;
|
|
104
|
+
/** Run task per case under a span; record each scorer result as a score when a project is set. */
|
|
105
|
+
evaluate(dataset: unknown[], task: EvalTask, scorers: Scorers, o?: EvalOptions): Promise<EvalRow[]>;
|
|
106
|
+
/** Re-run only the cases that errored or are missing in `previous`. */
|
|
107
|
+
evaluateResume(dataset: unknown[], task: EvalTask, scorers: Scorers, previous: EvalRow[], o?: EvalOptions): Promise<EvalRow[]>;
|
|
108
|
+
/** Wrap fn in a span. */
|
|
109
|
+
observe<A extends unknown[], R>(name: string, fn: (...a: A) => R): (...a: A) => R;
|
|
110
|
+
shutdown(): Promise<void>;
|
|
111
|
+
}
|
|
112
|
+
export declare function init(opts: InitOptions): Client;
|
|
113
|
+
export declare const flush: () => Promise<unknown>;
|
|
114
|
+
export declare const log: (l: LogLevel, b: string, a?: Record<string, unknown>) => void;
|
|
115
|
+
export declare const getPrompt: (id: string) => Promise<unknown>;
|
|
116
|
+
export declare const score: (t: string, v: number | boolean | string, o?: ScoreOptions) => Promise<unknown>;
|
|
117
|
+
export declare const evaluate: (d: unknown[], t: EvalTask, s: Scorers, o?: EvalOptions) => Promise<EvalRow[]>;
|
|
118
|
+
export declare const evaluateResume: (d: unknown[], t: EvalTask, s: Scorers, prev: EvalRow[], o?: EvalOptions) => Promise<EvalRow[]>;
|
|
119
|
+
export declare const observe: <A extends unknown[], R>(n: string, f: (...a: A) => R) => ((...a: A) => R);
|
|
120
|
+
export declare const shutdown: () => Promise<void>;
|
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
+
exports.shutdown = exports.observe = exports.evaluateResume = exports.evaluate = exports.score = exports.getPrompt = exports.log = exports.flush = exports.Client = exports.DEFAULT_ENDPOINT = exports.capturePayload = exports.setCaptureRules = exports.trace = exports.metrics = exports.captureException = void 0;
|
|
37
|
+
exports.safeResource = safeResource;
|
|
38
|
+
exports.init = init;
|
|
39
|
+
// Thin Watchtower layer over the OpenTelemetry Node SDK: key header, endpoint default,
|
|
40
|
+
// offline buffer, wt.*-safe resource attributes, redaction hook, getPrompt/score/evaluate/observe.
|
|
41
|
+
const node_util_1 = require("node:util");
|
|
42
|
+
const api_1 = require("@opentelemetry/api");
|
|
43
|
+
Object.defineProperty(exports, "metrics", { enumerable: true, get: function () { return api_1.metrics; } });
|
|
44
|
+
Object.defineProperty(exports, "trace", { enumerable: true, get: function () { return api_1.trace; } });
|
|
45
|
+
const resources_1 = require("@opentelemetry/resources");
|
|
46
|
+
const sdk_trace_base_1 = require("@opentelemetry/sdk-trace-base");
|
|
47
|
+
const sdk_trace_node_1 = require("@opentelemetry/sdk-trace-node");
|
|
48
|
+
const sdk_logs_1 = require("@opentelemetry/sdk-logs");
|
|
49
|
+
const exporter_trace_otlp_http_1 = require("@opentelemetry/exporter-trace-otlp-http");
|
|
50
|
+
const exporter_logs_otlp_http_1 = require("@opentelemetry/exporter-logs-otlp-http");
|
|
51
|
+
const buffer_js_1 = require("./buffer.js");
|
|
52
|
+
const metrics_js_1 = require("./metrics.js");
|
|
53
|
+
const nodePath = __importStar(require("node:path"));
|
|
54
|
+
const errors_js_1 = require("./errors.js");
|
|
55
|
+
Object.defineProperty(exports, "captureException", { enumerable: true, get: function () { return errors_js_1.captureException; } });
|
|
56
|
+
const payload_js_1 = require("./payload.js");
|
|
57
|
+
var payload_js_2 = require("./payload.js");
|
|
58
|
+
Object.defineProperty(exports, "setCaptureRules", { enumerable: true, get: function () { return payload_js_2.setCaptureRules; } });
|
|
59
|
+
Object.defineProperty(exports, "capturePayload", { enumerable: true, get: function () { return payload_js_2.capturePayload; } });
|
|
60
|
+
exports.DEFAULT_ENDPOINT = 'http://localhost:4318';
|
|
61
|
+
const SEVERITY = { trace: 1, debug: 5, info: 9, warn: 13, error: 17, fatal: 21 };
|
|
62
|
+
/** Drop caller-supplied wt.* keys: tenant identity comes only from the key. */
|
|
63
|
+
function safeResource(attrs) {
|
|
64
|
+
return (0, errors_js_1.dropReserved)(attrs);
|
|
65
|
+
}
|
|
66
|
+
const errMessage = (e) => String(e?.message || e);
|
|
67
|
+
class Client {
|
|
68
|
+
endpoint;
|
|
69
|
+
apiUrl;
|
|
70
|
+
project;
|
|
71
|
+
headers;
|
|
72
|
+
fetch;
|
|
73
|
+
redact;
|
|
74
|
+
provider;
|
|
75
|
+
tracer;
|
|
76
|
+
loggerProvider;
|
|
77
|
+
logger;
|
|
78
|
+
/** Set when metrics are on; `init` makes it the global meter provider (`metrics.getMeter`). */
|
|
79
|
+
meterProvider;
|
|
80
|
+
stopRuntime = () => { };
|
|
81
|
+
uninstall;
|
|
82
|
+
constructor(opts) {
|
|
83
|
+
const o = opts || {};
|
|
84
|
+
const env = process.env;
|
|
85
|
+
const apiKey = o.apiKey || env.WT_INGEST_KEY;
|
|
86
|
+
if (!apiKey)
|
|
87
|
+
throw new Error('apiKey is required (or set WT_INGEST_KEY)');
|
|
88
|
+
this.endpoint = (o.endpoint || env.WT_OTLP_ENDPOINT || exports.DEFAULT_ENDPOINT).replace(/\/+$/, '');
|
|
89
|
+
this.apiUrl = (o.apiUrl || env.WT_API_URL || this.endpoint).replace(/\/+$/, '');
|
|
90
|
+
this.project = o.project || env.WT_PROJECT_ID;
|
|
91
|
+
this.headers = { Authorization: `Bearer ${apiKey}` };
|
|
92
|
+
this.fetch = o.fetch || globalThis.fetch;
|
|
93
|
+
const environment = o.environment || env.WT_ENVIRONMENT;
|
|
94
|
+
const release = o.release || env.WT_RELEASE;
|
|
95
|
+
const resource = new resources_1.Resource({
|
|
96
|
+
'service.name': o.serviceName || env.WT_SERVICE || 'app',
|
|
97
|
+
...(environment ? { 'deployment.environment.name': environment } : {}),
|
|
98
|
+
...(release ? { 'service.version': release } : {}),
|
|
99
|
+
...safeResource(o.resource),
|
|
100
|
+
});
|
|
101
|
+
this.redact = o.redact;
|
|
102
|
+
this.provider = new sdk_trace_node_1.NodeTracerProvider({ resource });
|
|
103
|
+
if (o.redact)
|
|
104
|
+
this.provider.addSpanProcessor(redactor(o.redact));
|
|
105
|
+
let exporter = o.exporter;
|
|
106
|
+
if (!exporter) {
|
|
107
|
+
const url = `${this.endpoint}/v1/traces`;
|
|
108
|
+
exporter = new exporter_trace_otlp_http_1.OTLPTraceExporter({ url, headers: this.headers });
|
|
109
|
+
// spans and log records spool to their own subdirectories
|
|
110
|
+
if (o.bufferDir)
|
|
111
|
+
exporter = new buffer_js_1.SpoolExporter(exporter, nodePath.join(o.bufferDir, 'traces'), url, this.headers, this.fetch);
|
|
112
|
+
}
|
|
113
|
+
this.provider.addSpanProcessor(new sdk_trace_base_1.BatchSpanProcessor(exporter));
|
|
114
|
+
this.tracer = this.provider.getTracer('watchtower');
|
|
115
|
+
this.loggerProvider = new sdk_logs_1.LoggerProvider({ resource });
|
|
116
|
+
const logsOn = (0, metrics_js_1.switchOn)('WATCHTOWER_LOGS', 'OTEL_LOGS_EXPORTER', o.logs);
|
|
117
|
+
let logExporter = logsOn ? o.logExporter : undefined;
|
|
118
|
+
if (logsOn && !logExporter && !o.exporter) {
|
|
119
|
+
const url = `${this.endpoint}/v1/logs`;
|
|
120
|
+
logExporter = new exporter_logs_otlp_http_1.OTLPLogExporter({ url, headers: this.headers });
|
|
121
|
+
if (o.bufferDir)
|
|
122
|
+
logExporter = (0, buffer_js_1.spoolLogs)(logExporter, nodePath.join(o.bufferDir, 'logs'), url, this.headers, this.fetch);
|
|
123
|
+
}
|
|
124
|
+
if (logExporter) {
|
|
125
|
+
this.loggerProvider.addLogRecordProcessor(o.logExporter ? new sdk_logs_1.SimpleLogRecordProcessor(logExporter) : new sdk_logs_1.BatchLogRecordProcessor(logExporter));
|
|
126
|
+
}
|
|
127
|
+
this.logger = this.loggerProvider.getLogger('watchtower');
|
|
128
|
+
// with a test span exporter only an explicit metric exporter is used, as for logs
|
|
129
|
+
if ((0, metrics_js_1.switchOn)('WATCHTOWER_METRICS', 'OTEL_METRICS_EXPORTER', o.metrics) && (o.metricExporter || !o.exporter)) {
|
|
130
|
+
const m = (0, metrics_js_1.startMetrics)(this.endpoint, this.headers, resource, o.bufferDir, this.fetch, o.metricExporter);
|
|
131
|
+
this.meterProvider = m.provider;
|
|
132
|
+
this.stopRuntime = m.stop;
|
|
133
|
+
}
|
|
134
|
+
if (o.captureRules ?? env.WT_CAPTURE_RULES === '1') {
|
|
135
|
+
void (0, payload_js_1.loadCaptureRules)({ apiUrl: this.apiUrl, key: apiKey, service: String(resource.attributes['service.name']), fetch: this.fetch });
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
/** Emit an OTLP log record; trace and span ids come from the active context. */
|
|
139
|
+
log(level, body, attributes) {
|
|
140
|
+
let attrs = (0, errors_js_1.dropReserved)(attributes);
|
|
141
|
+
const redact = this.redact;
|
|
142
|
+
if (redact)
|
|
143
|
+
attrs = Object.fromEntries(Object.entries(attrs).map(([k, v]) => [k, redact(k, v)]));
|
|
144
|
+
this.logger.emit({
|
|
145
|
+
severityNumber: SEVERITY[level] || SEVERITY.info,
|
|
146
|
+
severityText: String(level).toUpperCase(),
|
|
147
|
+
body,
|
|
148
|
+
attributes: attrs,
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
forceFlush() {
|
|
152
|
+
return Promise.all([this.provider.forceFlush(), this.loggerProvider.forceFlush(), this.meterProvider?.forceFlush()]);
|
|
153
|
+
}
|
|
154
|
+
// keep the key out of console.log / JSON.stringify
|
|
155
|
+
toJSON() {
|
|
156
|
+
return { endpoint: this.endpoint, project: this.project, headers: { Authorization: 'Bearer ****' } };
|
|
157
|
+
}
|
|
158
|
+
[node_util_1.inspect.custom]() {
|
|
159
|
+
return `Client ${JSON.stringify(this)}`;
|
|
160
|
+
}
|
|
161
|
+
async _call(method, path, body) {
|
|
162
|
+
const url = `${this.apiUrl}/v1/projects/${this.project}/llm/${path}`;
|
|
163
|
+
const res = await this.fetch(url, {
|
|
164
|
+
method,
|
|
165
|
+
headers: { ...this.headers, 'Content-Type': 'application/json' },
|
|
166
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
167
|
+
});
|
|
168
|
+
if (!res.ok)
|
|
169
|
+
throw new Error(`watchtower ${method} ${path}: HTTP ${res.status}`);
|
|
170
|
+
return res.json();
|
|
171
|
+
}
|
|
172
|
+
getPrompt(promptId) {
|
|
173
|
+
return this._call('GET', `prompts/${promptId}`);
|
|
174
|
+
}
|
|
175
|
+
score(traceId, value, o) {
|
|
176
|
+
const x = o || {};
|
|
177
|
+
const body = { trace_id: traceId, value, name: x.name || 'user_feedback', source: 'sdk' };
|
|
178
|
+
if (x.spanId)
|
|
179
|
+
body.span_id = x.spanId;
|
|
180
|
+
if (x.comment)
|
|
181
|
+
body.comment = x.comment;
|
|
182
|
+
return this._call('POST', 'scores', body);
|
|
183
|
+
}
|
|
184
|
+
/** Run task per case under a span; record each scorer result as a score when a project is set. */
|
|
185
|
+
async evaluate(dataset, task, scorers, o) {
|
|
186
|
+
const x = { name: 'evaluate', errorTolerance: true, ...o };
|
|
187
|
+
const rows = [];
|
|
188
|
+
// resume: rows of an earlier run; cases that finished without errors are kept, not re-run
|
|
189
|
+
const done = new Map((x.resume || []).filter((r) => !Object.keys(r.errors || {}).length).map((r) => [r.case, r]));
|
|
190
|
+
for (const [i, c] of dataset.entries()) {
|
|
191
|
+
const kept = done.get(i);
|
|
192
|
+
if (kept) {
|
|
193
|
+
rows.push(kept);
|
|
194
|
+
continue;
|
|
195
|
+
}
|
|
196
|
+
await this.tracer.startActiveSpan(`${x.name}.case`, async (span) => {
|
|
197
|
+
const traceId = span.spanContext().traceId;
|
|
198
|
+
const row = { case: i, traceId, scores: {}, errors: {} };
|
|
199
|
+
rows.push(row);
|
|
200
|
+
try {
|
|
201
|
+
const input = c !== null && c !== undefined ? c.input : undefined;
|
|
202
|
+
const out = await task(input !== undefined ? input : c);
|
|
203
|
+
for (const [name, fn] of Object.entries(scorers)) {
|
|
204
|
+
try {
|
|
205
|
+
row.scores[name] = await fn(c, out);
|
|
206
|
+
if (this.project)
|
|
207
|
+
await this.score(traceId, row.scores[name], { name });
|
|
208
|
+
}
|
|
209
|
+
catch (e) {
|
|
210
|
+
if (!x.errorTolerance)
|
|
211
|
+
throw e;
|
|
212
|
+
row.errors[name] = errMessage(e);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
catch (e) {
|
|
217
|
+
if (!x.errorTolerance)
|
|
218
|
+
throw e;
|
|
219
|
+
row.errors.task = errMessage(e);
|
|
220
|
+
}
|
|
221
|
+
finally {
|
|
222
|
+
span.end();
|
|
223
|
+
}
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
return rows;
|
|
227
|
+
}
|
|
228
|
+
/** Re-run only the cases that errored or are missing in `previous`. */
|
|
229
|
+
evaluateResume(dataset, task, scorers, previous, o) {
|
|
230
|
+
return this.evaluate(dataset, task, scorers, { ...o, resume: previous });
|
|
231
|
+
}
|
|
232
|
+
/** Wrap fn in a span. */
|
|
233
|
+
observe(name, fn) {
|
|
234
|
+
return (...args) => this.tracer.startActiveSpan(name, (span) => {
|
|
235
|
+
const end = () => span.end();
|
|
236
|
+
try {
|
|
237
|
+
const r = fn(...args);
|
|
238
|
+
if (r && typeof r.then === 'function')
|
|
239
|
+
return r.finally(end);
|
|
240
|
+
end();
|
|
241
|
+
return r;
|
|
242
|
+
}
|
|
243
|
+
catch (e) {
|
|
244
|
+
end();
|
|
245
|
+
throw e;
|
|
246
|
+
}
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
shutdown() {
|
|
250
|
+
this.stopRuntime();
|
|
251
|
+
return Promise.all([this.provider.shutdown(), this.loggerProvider.shutdown(), this.meterProvider?.shutdown()]).then(() => undefined);
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
exports.Client = Client;
|
|
255
|
+
function redactor(hook) {
|
|
256
|
+
return {
|
|
257
|
+
onStart() { },
|
|
258
|
+
onEnd(span) {
|
|
259
|
+
for (const k of Object.keys(span.attributes))
|
|
260
|
+
span.attributes[k] = hook(k, span.attributes[k]);
|
|
261
|
+
},
|
|
262
|
+
shutdown: () => Promise.resolve(),
|
|
263
|
+
forceFlush: () => Promise.resolve(),
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
let current;
|
|
267
|
+
function init(opts) {
|
|
268
|
+
if (current && current.uninstall)
|
|
269
|
+
current.uninstall();
|
|
270
|
+
const c = new Client(opts);
|
|
271
|
+
current = c;
|
|
272
|
+
c.provider.register(); // global tracer + async context so trace.getActiveSpan() works
|
|
273
|
+
if (c.meterProvider) {
|
|
274
|
+
api_1.metrics.disable(); // a re-init replaces the previous client's provider
|
|
275
|
+
api_1.metrics.setGlobalMeterProvider(c.meterProvider);
|
|
276
|
+
}
|
|
277
|
+
if ((opts || {}).captureProcessErrors !== false) {
|
|
278
|
+
c.uninstall = (0, errors_js_1.installProcessHandlers)(() => c.forceFlush());
|
|
279
|
+
}
|
|
280
|
+
return c;
|
|
281
|
+
}
|
|
282
|
+
function need() {
|
|
283
|
+
if (!current)
|
|
284
|
+
throw new Error('watchtower.init() has not been called');
|
|
285
|
+
return current;
|
|
286
|
+
}
|
|
287
|
+
const flush = () => (current ? current.forceFlush() : Promise.resolve());
|
|
288
|
+
exports.flush = flush;
|
|
289
|
+
const log = (l, b, a) => need().log(l, b, a);
|
|
290
|
+
exports.log = log;
|
|
291
|
+
const getPrompt = (id) => need().getPrompt(id);
|
|
292
|
+
exports.getPrompt = getPrompt;
|
|
293
|
+
const score = (t, v, o) => need().score(t, v, o);
|
|
294
|
+
exports.score = score;
|
|
295
|
+
const evaluate = (d, t, s, o) => need().evaluate(d, t, s, o);
|
|
296
|
+
exports.evaluate = evaluate;
|
|
297
|
+
const evaluateResume = (d, t, s, prev, o) => need().evaluateResume(d, t, s, prev, o);
|
|
298
|
+
exports.evaluateResume = evaluateResume;
|
|
299
|
+
const observe = (n, f) => need().observe(n, f);
|
|
300
|
+
exports.observe = observe;
|
|
301
|
+
const shutdown = () => (current ? current.shutdown() : Promise.resolve());
|
|
302
|
+
exports.shutdown = shutdown;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/** The slice of the Azure Functions v4 InvocationContext this wrapper reads. */
|
|
2
|
+
export interface AzureContextLike {
|
|
3
|
+
invocationId?: string;
|
|
4
|
+
functionName?: string;
|
|
5
|
+
options?: {
|
|
6
|
+
trigger?: {
|
|
7
|
+
type?: string;
|
|
8
|
+
};
|
|
9
|
+
};
|
|
10
|
+
}
|
|
11
|
+
/** Maps an Azure binding type to the OTel `faas.trigger` value. */
|
|
12
|
+
export declare function faasTrigger(type: string | undefined): string;
|
|
13
|
+
/** app.http('fn', { handler: wrapFunction(async (request, context) => ...) }). One span per
|
|
14
|
+
* invocation with cold start, invocation id and trigger; errors captured; HTTP 5xx results mark the
|
|
15
|
+
* span failed; spans flushed before the host may freeze the worker. */
|
|
16
|
+
export declare function wrapFunction<T, R, C extends AzureContextLike = AzureContextLike>(handler: (trigger: T, context: C) => Promise<R>, o?: {
|
|
17
|
+
name?: string;
|
|
18
|
+
}): (trigger: T, context: C) => Promise<R>;
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
+
exports.faasTrigger = faasTrigger;
|
|
37
|
+
exports.wrapFunction = wrapFunction;
|
|
38
|
+
const api_1 = require("@opentelemetry/api");
|
|
39
|
+
const errors_js_1 = require("../errors.js");
|
|
40
|
+
const wt = __importStar(require("../index.js"));
|
|
41
|
+
const PUBSUB = ['serviceBusTrigger', 'eventHubTrigger', 'queueTrigger', 'eventGridTrigger', 'kafkaTrigger', 'rabbitMQTrigger'];
|
|
42
|
+
const DATASOURCE = ['blobTrigger', 'cosmosDBTrigger', 'sqlTrigger'];
|
|
43
|
+
/** Maps an Azure binding type to the OTel `faas.trigger` value. */
|
|
44
|
+
function faasTrigger(type) {
|
|
45
|
+
if (type === 'httpTrigger')
|
|
46
|
+
return 'http';
|
|
47
|
+
if (type === 'timerTrigger')
|
|
48
|
+
return 'timer';
|
|
49
|
+
if (type && PUBSUB.includes(type))
|
|
50
|
+
return 'pubsub';
|
|
51
|
+
if (type && DATASOURCE.includes(type))
|
|
52
|
+
return 'datasource';
|
|
53
|
+
return 'other';
|
|
54
|
+
}
|
|
55
|
+
let cold = true;
|
|
56
|
+
/** app.http('fn', { handler: wrapFunction(async (request, context) => ...) }). One span per
|
|
57
|
+
* invocation with cold start, invocation id and trigger; errors captured; HTTP 5xx results mark the
|
|
58
|
+
* span failed; spans flushed before the host may freeze the worker. */
|
|
59
|
+
function wrapFunction(handler, o) {
|
|
60
|
+
return async (input, context) => {
|
|
61
|
+
const c = context || {};
|
|
62
|
+
const coldstart = cold;
|
|
63
|
+
cold = false;
|
|
64
|
+
const kind = faasTrigger(c.options?.trigger?.type);
|
|
65
|
+
return api_1.trace.getTracer('watchtower').startActiveSpan(o?.name || c.functionName || 'function', {
|
|
66
|
+
kind: kind === 'http' ? api_1.SpanKind.SERVER : api_1.SpanKind.CONSUMER,
|
|
67
|
+
attributes: {
|
|
68
|
+
'cloud.provider': 'azure',
|
|
69
|
+
'cloud.platform': 'azure_functions',
|
|
70
|
+
'faas.name': c.functionName,
|
|
71
|
+
'faas.invocation_id': c.invocationId,
|
|
72
|
+
'faas.trigger': kind,
|
|
73
|
+
'faas.coldstart': coldstart,
|
|
74
|
+
},
|
|
75
|
+
}, async (span) => {
|
|
76
|
+
try {
|
|
77
|
+
const r = await handler(input, context);
|
|
78
|
+
const status = r?.status;
|
|
79
|
+
if (kind === 'http' && typeof status === 'number') {
|
|
80
|
+
span.setAttribute('http.response.status_code', status);
|
|
81
|
+
if (status >= 500)
|
|
82
|
+
span.setStatus({ code: api_1.SpanStatusCode.ERROR });
|
|
83
|
+
}
|
|
84
|
+
return r;
|
|
85
|
+
}
|
|
86
|
+
catch (e) {
|
|
87
|
+
span.setStatus({ code: api_1.SpanStatusCode.ERROR });
|
|
88
|
+
(0, errors_js_1.captureException)(e, { handled: false, attributes: { 'error.mechanism': 'azure_functions' } });
|
|
89
|
+
throw e;
|
|
90
|
+
}
|
|
91
|
+
finally {
|
|
92
|
+
span.end();
|
|
93
|
+
await wt.flush().catch(() => { });
|
|
94
|
+
}
|
|
95
|
+
});
|
|
96
|
+
};
|
|
97
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/** The slice of an Express request this integration reads. */
|
|
2
|
+
export interface ExpressRequest {
|
|
3
|
+
method: string;
|
|
4
|
+
originalUrl?: string;
|
|
5
|
+
url?: string;
|
|
6
|
+
baseUrl?: string;
|
|
7
|
+
route?: {
|
|
8
|
+
path: string;
|
|
9
|
+
};
|
|
10
|
+
/** Parsed by a body parser before this handler's span ends (payload capture). */
|
|
11
|
+
body?: unknown;
|
|
12
|
+
headers?: Record<string, string | string[] | undefined>;
|
|
13
|
+
}
|
|
14
|
+
/** The slice of an Express response this integration reads. */
|
|
15
|
+
export interface ExpressResponse {
|
|
16
|
+
statusCode: number;
|
|
17
|
+
on(event: string, listener: () => void): unknown;
|
|
18
|
+
write?: (...a: unknown[]) => boolean;
|
|
19
|
+
end?: (...a: unknown[]) => unknown;
|
|
20
|
+
getHeader?: (name: string) => unknown;
|
|
21
|
+
}
|
|
22
|
+
/** app.use(requestHandler()) first: a server span per request, named by the matched route. */
|
|
23
|
+
export declare function requestHandler(): (req: ExpressRequest, res: ExpressResponse, next: (err?: unknown) => void) => void;
|
|
24
|
+
/** app.use(errorHandler()) after all routes: captures 5xx errors, then passes them on. */
|
|
25
|
+
export declare function errorHandler(): (err: unknown, req: ExpressRequest, res: ExpressResponse, next: (err?: unknown) => void) => void;
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.requestHandler = requestHandler;
|
|
4
|
+
exports.errorHandler = errorHandler;
|
|
5
|
+
const api_1 = require("@opentelemetry/api");
|
|
6
|
+
const errors_js_1 = require("../errors.js");
|
|
7
|
+
const payload_js_1 = require("../payload.js");
|
|
8
|
+
const util_js_1 = require("./util.js");
|
|
9
|
+
/** Keep the first HARD_MAX * 2 response bytes for payload capture; the response itself is untouched. */
|
|
10
|
+
function tapBody(res) {
|
|
11
|
+
const chunks = [];
|
|
12
|
+
let size = 0;
|
|
13
|
+
const keep = (c) => {
|
|
14
|
+
if (size >= payload_js_1.HARD_MAX * 2 || (typeof c !== 'string' && !Buffer.isBuffer(c)))
|
|
15
|
+
return;
|
|
16
|
+
const b = Buffer.isBuffer(c) ? c : Buffer.from(c);
|
|
17
|
+
chunks.push(b);
|
|
18
|
+
size += b.length;
|
|
19
|
+
};
|
|
20
|
+
const { write, end } = res;
|
|
21
|
+
if (write)
|
|
22
|
+
res.write = (...a) => { keep(a[0]); return write.apply(res, a); };
|
|
23
|
+
if (end)
|
|
24
|
+
res.end = (...a) => { if (typeof a[0] !== 'function')
|
|
25
|
+
keep(a[0]); return end.apply(res, a); };
|
|
26
|
+
return () => Buffer.concat(chunks).toString('utf8');
|
|
27
|
+
}
|
|
28
|
+
/** app.use(requestHandler()) first: a server span per request, named by the matched route. */
|
|
29
|
+
function requestHandler() {
|
|
30
|
+
return (req, res, next) => {
|
|
31
|
+
const s = (0, util_js_1.serverSpan)(req.method, req.originalUrl || req.url);
|
|
32
|
+
let body = (0, payload_js_1.captureActive)() ? tapBody(res) : undefined;
|
|
33
|
+
const end = () => {
|
|
34
|
+
const route = req.route ? `${req.baseUrl || ''}${req.route.path}` : undefined;
|
|
35
|
+
if (body) {
|
|
36
|
+
const h = req.headers || {};
|
|
37
|
+
(0, payload_js_1.capturePayload)(s.span, {
|
|
38
|
+
route: route || String(req.originalUrl || req.url || '').split('?')[0],
|
|
39
|
+
reqType: String(h['content-type'] || ''), reqBody: req.body,
|
|
40
|
+
resType: String((res.getHeader && res.getHeader('content-type')) || ''), resBody: body(),
|
|
41
|
+
});
|
|
42
|
+
body = undefined; // 'finish' and 'close' both fire; capture once
|
|
43
|
+
}
|
|
44
|
+
s.finish(res.statusCode, route);
|
|
45
|
+
};
|
|
46
|
+
res.on('finish', end);
|
|
47
|
+
res.on('close', end);
|
|
48
|
+
api_1.context.with(s.ctx, next);
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
/** app.use(errorHandler()) after all routes: captures 5xx errors, then passes them on. */
|
|
52
|
+
function errorHandler() {
|
|
53
|
+
return (err, req, _res, next) => {
|
|
54
|
+
if ((0, util_js_1.statusOf)(err) >= 500)
|
|
55
|
+
(0, errors_js_1.captureException)(err, { attributes: { 'http.route': req.route && req.route.path } });
|
|
56
|
+
next(err);
|
|
57
|
+
};
|
|
58
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** The slice of a Fastify instance this plugin uses. `any` args: Fastify types each hook's handler separately. */
|
|
2
|
+
export interface FastifyLike {
|
|
3
|
+
addHook(name: string, fn: (...args: any[]) => void): unknown;
|
|
4
|
+
}
|
|
5
|
+
/** await app.register(plugin): server span per request plus 5xx error capture. */
|
|
6
|
+
export declare function plugin(fastify: FastifyLike, _opts: unknown, done: (err?: Error) => void): void;
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.plugin = plugin;
|
|
4
|
+
const api_1 = require("@opentelemetry/api");
|
|
5
|
+
const errors_js_1 = require("../errors.js");
|
|
6
|
+
const payload_js_1 = require("../payload.js");
|
|
7
|
+
const util_js_1 = require("./util.js");
|
|
8
|
+
const KEY = Symbol('wt.span');
|
|
9
|
+
const SENT = Symbol('wt.sent');
|
|
10
|
+
/** await app.register(plugin): server span per request plus 5xx error capture. */
|
|
11
|
+
function plugin(fastify, _opts, done) {
|
|
12
|
+
fastify.addHook('onRequest', (req, _reply, next) => {
|
|
13
|
+
const s = (0, util_js_1.serverSpan)(req.method, req.url);
|
|
14
|
+
req[KEY] = s;
|
|
15
|
+
api_1.context.with(s.ctx, next);
|
|
16
|
+
});
|
|
17
|
+
fastify.addHook('onError', (_req, _reply, err, next) => {
|
|
18
|
+
if ((0, util_js_1.statusOf)(err) >= 500)
|
|
19
|
+
(0, errors_js_1.captureException)(err);
|
|
20
|
+
next();
|
|
21
|
+
});
|
|
22
|
+
// the serialized response body (string, Buffer or stream); passed on unchanged
|
|
23
|
+
fastify.addHook('onSend', (req, _reply, payload, next) => {
|
|
24
|
+
if ((0, payload_js_1.captureActive)())
|
|
25
|
+
req[SENT] = payload;
|
|
26
|
+
next(null, payload);
|
|
27
|
+
});
|
|
28
|
+
fastify.addHook('onResponse', (req, reply, next) => {
|
|
29
|
+
const route = (req.routeOptions && req.routeOptions.url) || req.routerPath;
|
|
30
|
+
const s = req[KEY];
|
|
31
|
+
if (s && (0, payload_js_1.captureActive)()) {
|
|
32
|
+
(0, payload_js_1.capturePayload)(s.span, {
|
|
33
|
+
route: route || req.url.split('?')[0],
|
|
34
|
+
reqType: String((req.headers && req.headers['content-type']) || ''), reqBody: req.body,
|
|
35
|
+
resType: String((reply.getHeader && reply.getHeader('content-type')) || ''), resBody: req[SENT],
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
if (s)
|
|
39
|
+
s.finish(reply.statusCode, route);
|
|
40
|
+
next();
|
|
41
|
+
});
|
|
42
|
+
done();
|
|
43
|
+
}
|
|
44
|
+
plugin[Symbol.for('skip-override')] = true; // what fastify-plugin sets: hooks apply app-wide
|