@watchtowerobservability/node 0.0.0-stage → 0.3.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 +304 -2
- package/dist/cjs/appsec.d.ts +95 -0
- package/dist/cjs/appsec.js +206 -0
- 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 +123 -0
- package/dist/cjs/index.js +315 -0
- package/dist/cjs/integrations/amqp.d.ts +13 -0
- package/dist/cjs/integrations/amqp.js +96 -0
- package/dist/cjs/integrations/azure-functions.d.ts +18 -0
- package/dist/cjs/integrations/azure-functions.js +97 -0
- package/dist/cjs/integrations/bullmq.d.ts +19 -0
- package/dist/cjs/integrations/bullmq.js +83 -0
- package/dist/cjs/integrations/cache.d.ts +13 -0
- package/dist/cjs/integrations/cache.js +51 -0
- package/dist/cjs/integrations/db.d.ts +62 -0
- package/dist/cjs/integrations/db.js +288 -0
- package/dist/cjs/integrations/duckdb.d.ts +22 -0
- package/dist/cjs/integrations/duckdb.js +66 -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/graphile-worker.d.ts +22 -0
- package/dist/cjs/integrations/graphile-worker.js +50 -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/level.d.ts +18 -0
- package/dist/cjs/integrations/level.js +71 -0
- package/dist/cjs/integrations/lmdb.d.ts +26 -0
- package/dist/cjs/integrations/lmdb.js +78 -0
- package/dist/cjs/integrations/logs.d.ts +10 -0
- package/dist/cjs/integrations/logs.js +77 -0
- package/dist/cjs/integrations/messaging.d.ts +17 -0
- package/dist/cjs/integrations/messaging.js +73 -0
- package/dist/cjs/integrations/mqtt.d.ts +7 -0
- package/dist/cjs/integrations/mqtt.js +41 -0
- package/dist/cjs/integrations/nats.d.ts +17 -0
- package/dist/cjs/integrations/nats.js +73 -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/orm.d.ts +47 -0
- package/dist/cjs/integrations/orm.js +93 -0
- package/dist/cjs/integrations/pg-boss.d.ts +8 -0
- package/dist/cjs/integrations/pg-boss.js +63 -0
- package/dist/cjs/integrations/pools.d.ts +41 -0
- package/dist/cjs/integrations/pools.js +94 -0
- package/dist/cjs/integrations/postgres.d.ts +12 -0
- package/dist/cjs/integrations/postgres.js +92 -0
- package/dist/cjs/integrations/prisma.d.ts +3 -0
- package/dist/cjs/integrations/prisma.js +33 -0
- package/dist/cjs/integrations/sqlite.d.ts +36 -0
- package/dist/cjs/integrations/sqlite.js +125 -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/pprof.d.ts +6 -0
- package/dist/cjs/pprof.js +88 -0
- package/dist/cjs/probes.d.ts +97 -0
- package/dist/cjs/probes.js +422 -0
- package/dist/cjs/profiling.d.ts +84 -0
- package/dist/cjs/profiling.js +263 -0
- package/dist/cjs/reporter-core.d.ts +32 -0
- package/dist/cjs/reporter-core.js +102 -0
- package/dist/cjs/sql.d.ts +19 -0
- package/dist/cjs/sql.js +332 -0
- package/dist/cjs/test-plan.d.ts +102 -0
- package/dist/cjs/test-plan.js +352 -0
- package/dist/cjs/vitest.d.ts +27 -0
- package/dist/cjs/vitest.js +52 -0
- package/dist/esm/appsec.d.ts +95 -0
- package/dist/esm/appsec.js +193 -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 +123 -0
- package/dist/esm/index.js +264 -0
- package/dist/esm/integrations/amqp.d.ts +13 -0
- package/dist/esm/integrations/amqp.js +92 -0
- package/dist/esm/integrations/azure-functions.d.ts +18 -0
- package/dist/esm/integrations/azure-functions.js +60 -0
- package/dist/esm/integrations/bullmq.d.ts +19 -0
- package/dist/esm/integrations/bullmq.js +79 -0
- package/dist/esm/integrations/cache.d.ts +13 -0
- package/dist/esm/integrations/cache.js +46 -0
- package/dist/esm/integrations/db.d.ts +62 -0
- package/dist/esm/integrations/db.js +239 -0
- package/dist/esm/integrations/duckdb.d.ts +22 -0
- package/dist/esm/integrations/duckdb.js +29 -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/graphile-worker.d.ts +22 -0
- package/dist/esm/integrations/graphile-worker.js +46 -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/level.d.ts +18 -0
- package/dist/esm/integrations/level.js +35 -0
- package/dist/esm/integrations/lmdb.d.ts +26 -0
- package/dist/esm/integrations/lmdb.js +42 -0
- package/dist/esm/integrations/logs.d.ts +10 -0
- package/dist/esm/integrations/logs.js +40 -0
- package/dist/esm/integrations/messaging.d.ts +17 -0
- package/dist/esm/integrations/messaging.js +64 -0
- package/dist/esm/integrations/mqtt.d.ts +7 -0
- package/dist/esm/integrations/mqtt.js +38 -0
- package/dist/esm/integrations/nats.d.ts +17 -0
- package/dist/esm/integrations/nats.js +70 -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/orm.d.ts +47 -0
- package/dist/esm/integrations/orm.js +86 -0
- package/dist/esm/integrations/pg-boss.d.ts +8 -0
- package/dist/esm/integrations/pg-boss.js +60 -0
- package/dist/esm/integrations/pools.d.ts +41 -0
- package/dist/esm/integrations/pools.js +89 -0
- package/dist/esm/integrations/postgres.d.ts +12 -0
- package/dist/esm/integrations/postgres.js +55 -0
- package/dist/esm/integrations/prisma.d.ts +3 -0
- package/dist/esm/integrations/prisma.js +30 -0
- package/dist/esm/integrations/sqlite.d.ts +36 -0
- package/dist/esm/integrations/sqlite.js +84 -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/pprof.d.ts +6 -0
- package/dist/esm/pprof.js +85 -0
- package/dist/esm/probes.d.ts +97 -0
- package/dist/esm/probes.js +412 -0
- package/dist/esm/profiling.d.ts +84 -0
- package/dist/esm/profiling.js +251 -0
- package/dist/esm/reporter-core.d.ts +32 -0
- package/dist/esm/reporter-core.js +63 -0
- package/dist/esm/sql.d.ts +19 -0
- package/dist/esm/sql.js +324 -0
- package/dist/esm/test-plan.d.ts +102 -0
- package/dist/esm/test-plan.js +336 -0
- package/dist/esm/vitest.d.ts +27 -0
- package/dist/esm/vitest.js +48 -0
- package/package.json +379 -4
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.AgentsProcessor = void 0;
|
|
4
|
+
exports.instrumentLlamaIndex = instrumentLlamaIndex;
|
|
5
|
+
exports.instrumentOpenAIAgents = instrumentOpenAIAgents;
|
|
6
|
+
// GenAI spans for frameworks with their own hooks: LlamaIndex.TS (callback manager events) and the OpenAI Agents
|
|
7
|
+
// SDK (trace processors). Agent runs become `invoke_agent` spans, model calls `chat` spans with usage, tool runs
|
|
8
|
+
// `execute_tool` spans with the tool name, nested as the framework nests them. No message, completion or tool
|
|
9
|
+
// argument text is recorded. Both take the framework's own object, so neither package is a dependency.
|
|
10
|
+
const api_1 = require("@opentelemetry/api");
|
|
11
|
+
const genai_stream_js_1 = require("./genai-stream.js");
|
|
12
|
+
const obj = (v) => (v && typeof v === 'object' ? v : {});
|
|
13
|
+
const s = (v) => (typeof v === 'string' ? v : '');
|
|
14
|
+
function start(name, attrs, parent) {
|
|
15
|
+
const ctx = parent ? api_1.trace.setSpan(api_1.context.active(), parent) : api_1.context.active();
|
|
16
|
+
const clean = Object.fromEntries(Object.entries(attrs).filter(([, v]) => v !== undefined && v !== ''));
|
|
17
|
+
return api_1.trace.getTracer('watchtower').startSpan(name, { kind: api_1.SpanKind.INTERNAL, attributes: clean }, ctx);
|
|
18
|
+
}
|
|
19
|
+
/** instrumentLlamaIndex(Settings) (from `llamaindex`): llm-start/stream/end and tool call events as spans. */
|
|
20
|
+
function instrumentLlamaIndex(settings) {
|
|
21
|
+
const open = new Map(), t0 = new Map();
|
|
22
|
+
const cm = settings.callbackManager;
|
|
23
|
+
cm.on('llm-start', (e) => {
|
|
24
|
+
const id = s(obj(e.detail).id);
|
|
25
|
+
open.set(id, start('chat', { 'gen_ai.operation.name': 'chat', 'gen_ai.system': 'llama_index' }));
|
|
26
|
+
t0.set(id, Date.now());
|
|
27
|
+
});
|
|
28
|
+
cm.on('llm-stream', (e) => {
|
|
29
|
+
const id = s(obj(e.detail).id), at = t0.get(id);
|
|
30
|
+
if (at !== undefined) {
|
|
31
|
+
t0.delete(id);
|
|
32
|
+
open.get(id)?.setAttribute('gen_ai.response.time_to_first_chunk', (Date.now() - at) / 1000);
|
|
33
|
+
}
|
|
34
|
+
});
|
|
35
|
+
cm.on('llm-end', (e) => {
|
|
36
|
+
const d = obj(e.detail), id = s(d.id), span = open.get(id);
|
|
37
|
+
if (!span)
|
|
38
|
+
return;
|
|
39
|
+
open.delete(id);
|
|
40
|
+
t0.delete(id);
|
|
41
|
+
const res = obj(d.response);
|
|
42
|
+
const x = (0, genai_stream_js_1.extract)(res.raw);
|
|
43
|
+
const msg = obj(res.message), opts = obj(msg.options);
|
|
44
|
+
for (const tc of Array.isArray(opts.toolCall) ? opts.toolCall : []) {
|
|
45
|
+
const name = s(obj(tc).name);
|
|
46
|
+
if (name)
|
|
47
|
+
x.tools.push([name, s(obj(tc).id) || undefined]);
|
|
48
|
+
}
|
|
49
|
+
if (x.model)
|
|
50
|
+
span.updateName(`chat ${x.model}`);
|
|
51
|
+
(0, genai_stream_js_1.applyExtract)(span, x);
|
|
52
|
+
span.end();
|
|
53
|
+
});
|
|
54
|
+
cm.on('llm-tool-call', (e) => {
|
|
55
|
+
const name = s(obj(obj(e.detail).toolCall).name);
|
|
56
|
+
start(`execute_tool ${name}`.trim(), { 'gen_ai.operation.name': 'execute_tool', 'gen_ai.tool.name': name }).end();
|
|
57
|
+
});
|
|
58
|
+
return { open };
|
|
59
|
+
}
|
|
60
|
+
/** The processor `addTraceProcessor` takes (`@openai/agents`). */
|
|
61
|
+
class AgentsProcessor {
|
|
62
|
+
open = new Map();
|
|
63
|
+
async onTraceStart() { }
|
|
64
|
+
async onTraceEnd() { }
|
|
65
|
+
async onSpanStart(sp) {
|
|
66
|
+
const d = obj(sp.spanData), type = s(d.type), parent = sp.parentId ? this.open.get(sp.parentId) : undefined;
|
|
67
|
+
let name = type || 'agents';
|
|
68
|
+
let attrs = {};
|
|
69
|
+
if (type === 'agent') {
|
|
70
|
+
name = `invoke_agent ${s(d.name)}`.trim();
|
|
71
|
+
attrs = { 'gen_ai.operation.name': 'invoke_agent', 'gen_ai.agent.name': s(d.name), 'gen_ai.system': 'openai' };
|
|
72
|
+
}
|
|
73
|
+
else if (type === 'generation' || type === 'response') {
|
|
74
|
+
name = `chat ${s(d.model)}`.trim();
|
|
75
|
+
attrs = { 'gen_ai.operation.name': 'chat', 'gen_ai.system': 'openai', 'gen_ai.request.model': s(d.model) };
|
|
76
|
+
}
|
|
77
|
+
else if (type === 'function') {
|
|
78
|
+
name = `execute_tool ${s(d.name)}`.trim();
|
|
79
|
+
attrs = { 'gen_ai.operation.name': 'execute_tool', 'gen_ai.tool.name': s(d.name) };
|
|
80
|
+
}
|
|
81
|
+
else if (type === 'handoff') {
|
|
82
|
+
attrs = { 'gen_ai.operation.name': 'handoff', 'gen_ai.handoff.from_agent': s(d.from_agent), 'gen_ai.handoff.to_agent': s(d.to_agent) };
|
|
83
|
+
}
|
|
84
|
+
else if (type === 'guardrail') {
|
|
85
|
+
name = `guardrail ${s(d.name)}`.trim();
|
|
86
|
+
attrs = { 'gen_ai.guardrail.name': s(d.name) };
|
|
87
|
+
}
|
|
88
|
+
if (sp.spanId)
|
|
89
|
+
this.open.set(sp.spanId, start(name, attrs, parent));
|
|
90
|
+
}
|
|
91
|
+
async onSpanEnd(sp) {
|
|
92
|
+
const span = sp.spanId ? this.open.get(sp.spanId) : undefined;
|
|
93
|
+
if (!span || !sp.spanId)
|
|
94
|
+
return;
|
|
95
|
+
this.open.delete(sp.spanId);
|
|
96
|
+
const d = obj(sp.spanData);
|
|
97
|
+
if (d.type === 'generation') {
|
|
98
|
+
const u = obj(d.usage);
|
|
99
|
+
(0, genai_stream_js_1.applyExtract)(span, { model: s(d.model) || undefined, input: u.input_tokens, output: u.output_tokens, reasons: [], tools: [] });
|
|
100
|
+
}
|
|
101
|
+
else if (d.type === 'response') {
|
|
102
|
+
(0, genai_stream_js_1.applyExtract)(span, (0, genai_stream_js_1.extract)(d._response ?? d.response));
|
|
103
|
+
}
|
|
104
|
+
else if (d.type === 'guardrail') {
|
|
105
|
+
span.setAttribute('gen_ai.guardrail.triggered', Boolean(d.triggered));
|
|
106
|
+
}
|
|
107
|
+
if (sp.error)
|
|
108
|
+
span.setStatus({ code: api_1.SpanStatusCode.ERROR, message: sp.error.message });
|
|
109
|
+
span.end();
|
|
110
|
+
}
|
|
111
|
+
async shutdown() {
|
|
112
|
+
for (const span of this.open.values())
|
|
113
|
+
span.end();
|
|
114
|
+
this.open.clear();
|
|
115
|
+
}
|
|
116
|
+
async forceFlush() { }
|
|
117
|
+
}
|
|
118
|
+
exports.AgentsProcessor = AgentsProcessor;
|
|
119
|
+
/** instrumentOpenAIAgents(addTraceProcessor) with `addTraceProcessor` from `@openai/agents`; the SDK's own tracing keeps running. */
|
|
120
|
+
function instrumentOpenAIAgents(addTraceProcessor) {
|
|
121
|
+
const p = new AgentsProcessor();
|
|
122
|
+
addTraceProcessor(p);
|
|
123
|
+
return p;
|
|
124
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { Span } from '@opentelemetry/api';
|
|
2
|
+
export interface Extract {
|
|
3
|
+
id?: string;
|
|
4
|
+
model?: string;
|
|
5
|
+
input?: number;
|
|
6
|
+
output?: number;
|
|
7
|
+
reasons: string[];
|
|
8
|
+
tools: [string, string | undefined][];
|
|
9
|
+
}
|
|
10
|
+
/** Reads a full response, a stream chunk or a stream event (`{ data }` for Mistral, typed events for Anthropic). */
|
|
11
|
+
export declare function extract(raw: unknown): Extract;
|
|
12
|
+
/** Sets what `x` holds; `seen` keeps a stream's tool calls from repeating. */
|
|
13
|
+
export declare function applyExtract(span: Span, x: Extract, seen?: Set<string>): void;
|
|
14
|
+
/**
|
|
15
|
+
* Hooks the async iterator of a stream object in place (the caller keeps the SDK's own object): the span records
|
|
16
|
+
* time to first chunk, usage, finish reasons and tool calls, and ends when the stream ends, fails or is closed.
|
|
17
|
+
* False when `res` is not async iterable.
|
|
18
|
+
*/
|
|
19
|
+
export declare function tapStream(span: Span, res: unknown, startedMs: number): boolean;
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.extract = extract;
|
|
4
|
+
exports.applyExtract = applyExtract;
|
|
5
|
+
exports.tapStream = tapStream;
|
|
6
|
+
// Response, chunk and stream reading shared by every GenAI wrapper: tokens, finish reasons and tool calls
|
|
7
|
+
// from OpenAI, Anthropic, Mistral (camelCase) and Ollama shapes. Tool calls become `gen_ai.tool.call` span
|
|
8
|
+
// events with the tool name and call id only; prompt, completion and argument text is never recorded.
|
|
9
|
+
const api_1 = require("@opentelemetry/api");
|
|
10
|
+
const obj = (v) => (v && typeof v === 'object' ? v : undefined);
|
|
11
|
+
const num = (...v) => v.find((x) => typeof x === 'number');
|
|
12
|
+
const str = (...v) => v.find((x) => typeof x === 'string' && x !== '');
|
|
13
|
+
const list = (v) => (Array.isArray(v) ? v : []);
|
|
14
|
+
function toolsOf(calls, out) {
|
|
15
|
+
for (const tc of list(calls)) {
|
|
16
|
+
const t = obj(tc);
|
|
17
|
+
const name = str(obj(t?.function)?.name);
|
|
18
|
+
if (name)
|
|
19
|
+
out.push([name, str(t?.id)]);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
/** Reads a full response, a stream chunk or a stream event (`{ data }` for Mistral, typed events for Anthropic). */
|
|
23
|
+
function extract(raw) {
|
|
24
|
+
let o = obj(raw) ?? {};
|
|
25
|
+
if (o.choices === undefined && o.type === undefined && obj(o.data))
|
|
26
|
+
o = obj(o.data);
|
|
27
|
+
const start = o.type === 'message_start' ? obj(o.message) : undefined;
|
|
28
|
+
const u = obj(o.usage) ?? obj(start?.usage) ?? {};
|
|
29
|
+
const g = obj(o.usageMetadata) ?? {};
|
|
30
|
+
const x = {
|
|
31
|
+
id: str(o.id, start?.id, o.responseId),
|
|
32
|
+
model: str(o.model, start?.model, o.modelVersion),
|
|
33
|
+
input: num(u.input_tokens, u.prompt_tokens, u.promptTokens, u.inputTokens, o.prompt_eval_count, g.promptTokenCount),
|
|
34
|
+
output: num(u.output_tokens, u.completion_tokens, u.completionTokens, u.outputTokens, o.eval_count, g.candidatesTokenCount),
|
|
35
|
+
reasons: [],
|
|
36
|
+
tools: [],
|
|
37
|
+
};
|
|
38
|
+
for (const ch of list(o.choices)) {
|
|
39
|
+
const c = obj(ch);
|
|
40
|
+
const r = str(c?.finish_reason, c?.finishReason);
|
|
41
|
+
if (r)
|
|
42
|
+
x.reasons.push(r);
|
|
43
|
+
const m = obj(c?.message) ?? obj(c?.delta);
|
|
44
|
+
toolsOf(m?.tool_calls ?? m?.toolCalls, x.tools);
|
|
45
|
+
}
|
|
46
|
+
for (const r of [o.stop_reason, obj(o.delta)?.stop_reason, o.done_reason, o.stopReason])
|
|
47
|
+
if (str(r))
|
|
48
|
+
x.reasons.push(r);
|
|
49
|
+
for (const b of list(o.content))
|
|
50
|
+
if (obj(b)?.type === 'tool_use')
|
|
51
|
+
x.tools.push([String(obj(b).name), str(obj(b).id)]);
|
|
52
|
+
const cb = obj(o.content_block);
|
|
53
|
+
if (cb?.type === 'tool_use')
|
|
54
|
+
x.tools.push([String(cb.name), str(cb.id)]);
|
|
55
|
+
if (o.choices === undefined)
|
|
56
|
+
toolsOf(obj(o.message)?.tool_calls, x.tools);
|
|
57
|
+
return x;
|
|
58
|
+
}
|
|
59
|
+
/** Sets what `x` holds; `seen` keeps a stream's tool calls from repeating. */
|
|
60
|
+
function applyExtract(span, x, seen = new Set()) {
|
|
61
|
+
if (x.id)
|
|
62
|
+
span.setAttribute('gen_ai.response.id', x.id);
|
|
63
|
+
if (x.model)
|
|
64
|
+
span.setAttribute('gen_ai.response.model', x.model);
|
|
65
|
+
if (x.input != null)
|
|
66
|
+
span.setAttribute('gen_ai.usage.input_tokens', x.input);
|
|
67
|
+
if (x.output != null)
|
|
68
|
+
span.setAttribute('gen_ai.usage.output_tokens', x.output);
|
|
69
|
+
if (x.reasons.length)
|
|
70
|
+
span.setAttribute('gen_ai.response.finish_reasons', x.reasons);
|
|
71
|
+
for (const [name, id] of x.tools) {
|
|
72
|
+
const k = `${name}\u0000${id ?? ''}`;
|
|
73
|
+
if (seen.has(k))
|
|
74
|
+
continue;
|
|
75
|
+
seen.add(k);
|
|
76
|
+
span.addEvent('gen_ai.tool.call', { 'gen_ai.tool.name': name, ...(id ? { 'gen_ai.tool.call.id': id } : {}) });
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Hooks the async iterator of a stream object in place (the caller keeps the SDK's own object): the span records
|
|
81
|
+
* time to first chunk, usage, finish reasons and tool calls, and ends when the stream ends, fails or is closed.
|
|
82
|
+
* False when `res` is not async iterable.
|
|
83
|
+
*/
|
|
84
|
+
function tapStream(span, res, startedMs) {
|
|
85
|
+
const s = obj(res);
|
|
86
|
+
const orig = s?.[Symbol.asyncIterator];
|
|
87
|
+
if (!s || typeof orig !== 'function')
|
|
88
|
+
return false;
|
|
89
|
+
let first = true, done = false;
|
|
90
|
+
const reasons = [], seen = new Set();
|
|
91
|
+
const end = (e) => {
|
|
92
|
+
if (done)
|
|
93
|
+
return;
|
|
94
|
+
done = true;
|
|
95
|
+
if (e !== undefined) {
|
|
96
|
+
span.recordException(e);
|
|
97
|
+
span.setStatus({ code: api_1.SpanStatusCode.ERROR, message: e?.message });
|
|
98
|
+
}
|
|
99
|
+
span.end();
|
|
100
|
+
};
|
|
101
|
+
s[Symbol.asyncIterator] = function () {
|
|
102
|
+
const inner = orig.call(s);
|
|
103
|
+
return {
|
|
104
|
+
async next() {
|
|
105
|
+
let r;
|
|
106
|
+
try {
|
|
107
|
+
r = await inner.next();
|
|
108
|
+
}
|
|
109
|
+
catch (e) {
|
|
110
|
+
end(e);
|
|
111
|
+
throw e;
|
|
112
|
+
}
|
|
113
|
+
if (r.done) {
|
|
114
|
+
end();
|
|
115
|
+
return r;
|
|
116
|
+
}
|
|
117
|
+
if (first) {
|
|
118
|
+
first = false;
|
|
119
|
+
span.setAttribute('gen_ai.response.time_to_first_chunk', (Date.now() - startedMs) / 1000);
|
|
120
|
+
}
|
|
121
|
+
const x = extract(r.value);
|
|
122
|
+
for (const q of x.reasons)
|
|
123
|
+
if (!reasons.includes(q))
|
|
124
|
+
reasons.push(q);
|
|
125
|
+
applyExtract(span, { ...x, reasons }, seen);
|
|
126
|
+
return r;
|
|
127
|
+
},
|
|
128
|
+
async return(v) {
|
|
129
|
+
end();
|
|
130
|
+
return inner.return ? inner.return(v) : { done: true, value: v };
|
|
131
|
+
},
|
|
132
|
+
};
|
|
133
|
+
};
|
|
134
|
+
return true;
|
|
135
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export { instrumentLlamaIndex, instrumentOpenAIAgents } from './genai-agents.js';
|
|
2
|
+
/**
|
|
3
|
+
* instrumentOpenAI(new OpenAI()): chat.completions.create and responses.create. Returns the client.
|
|
4
|
+
* For an OpenAI-compatible gateway pass its name: instrumentOpenAI(new OpenAI({ baseURL: litellmUrl }), 'litellm').
|
|
5
|
+
*/
|
|
6
|
+
export declare function instrumentOpenAI<T>(client: T, system?: string): T;
|
|
7
|
+
/** instrumentBedrock(new BedrockRuntimeClient()): `send` of Converse and InvokeModel commands; others pass through untraced. */
|
|
8
|
+
export declare function instrumentBedrock<T>(client: T): T;
|
|
9
|
+
/** instrumentGoogleGenAI(new GoogleGenAI({...})): models.generateContent (Gemini API or Vertex AI). */
|
|
10
|
+
export declare function instrumentGoogleGenAI<T>(client: T): T;
|
|
11
|
+
/** instrumentAnthropic(new Anthropic()): messages.create. Returns the client. */
|
|
12
|
+
export declare function instrumentAnthropic<T>(client: T): T;
|
|
13
|
+
/** instrumentMistral(new Mistral()): chat.complete and chat.stream (the stream span ends with the stream). */
|
|
14
|
+
export declare function instrumentMistral<T>(client: T): T;
|
|
15
|
+
/** instrumentOllama(new Ollama()) or instrumentOllama(ollama): chat and generate, with `stream: true` too. */
|
|
16
|
+
export declare function instrumentOllama<T>(client: T): T;
|
|
17
|
+
/** generateText({ ..., experimental_telemetry: vercelAiTelemetry() }); inputs/outputs off unless overridden. */
|
|
18
|
+
export declare function vercelAiTelemetry(o?: Record<string, unknown>): Record<string, unknown>;
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.instrumentOpenAIAgents = exports.instrumentLlamaIndex = void 0;
|
|
4
|
+
exports.instrumentOpenAI = instrumentOpenAI;
|
|
5
|
+
exports.instrumentBedrock = instrumentBedrock;
|
|
6
|
+
exports.instrumentGoogleGenAI = instrumentGoogleGenAI;
|
|
7
|
+
exports.instrumentAnthropic = instrumentAnthropic;
|
|
8
|
+
exports.instrumentMistral = instrumentMistral;
|
|
9
|
+
exports.instrumentOllama = instrumentOllama;
|
|
10
|
+
exports.vercelAiTelemetry = vercelAiTelemetry;
|
|
11
|
+
// GenAI spans (OTel GenAI semconv) for the openai, anthropic, AWS Bedrock, Google GenAI, Mistral and Ollama SDKs (and
|
|
12
|
+
// LiteLLM through its OpenAI-compatible proxy), LlamaIndex and the OpenAI Agents SDK (genai-agents.ts), and a
|
|
13
|
+
// telemetry option for the Vercel AI SDK. Streams record time to first chunk, usage and tool calls (genai-stream.ts).
|
|
14
|
+
// Prompt and completion text is never recorded.
|
|
15
|
+
const api_1 = require("@opentelemetry/api");
|
|
16
|
+
const genai_stream_js_1 = require("./genai-stream.js");
|
|
17
|
+
var genai_agents_js_1 = require("./genai-agents.js");
|
|
18
|
+
Object.defineProperty(exports, "instrumentLlamaIndex", { enumerable: true, get: function () { return genai_agents_js_1.instrumentLlamaIndex; } });
|
|
19
|
+
Object.defineProperty(exports, "instrumentOpenAIAgents", { enumerable: true, get: function () { return genai_agents_js_1.instrumentOpenAIAgents; } });
|
|
20
|
+
const DONE = Symbol('wt.instrumented');
|
|
21
|
+
const plain = (b) => (b || {});
|
|
22
|
+
function wrap(target, method, system, req = plain) {
|
|
23
|
+
if (!target || typeof target[method] !== 'function' || target[method][DONE])
|
|
24
|
+
return;
|
|
25
|
+
const orig = target[method];
|
|
26
|
+
const wrapped = function (body, ...rest) {
|
|
27
|
+
const b = req(body);
|
|
28
|
+
const started = Date.now();
|
|
29
|
+
const span = api_1.trace.getTracer('watchtower').startSpan(`chat ${b.model || ''}`.trim(), {
|
|
30
|
+
kind: api_1.SpanKind.CLIENT,
|
|
31
|
+
attributes: {
|
|
32
|
+
'gen_ai.operation.name': 'chat',
|
|
33
|
+
'gen_ai.system': system,
|
|
34
|
+
...(b.model ? { 'gen_ai.request.model': b.model } : {}),
|
|
35
|
+
...(b.max_tokens != null ? { 'gen_ai.request.max_tokens': b.max_tokens } : {}),
|
|
36
|
+
...(b.temperature != null ? { 'gen_ai.request.temperature': b.temperature } : {}),
|
|
37
|
+
},
|
|
38
|
+
});
|
|
39
|
+
const p = api_1.context.with(api_1.trace.setSpan(api_1.context.active(), span), () => orig.call(this, body, ...rest));
|
|
40
|
+
// side branch only: the caller keeps the SDK's own promise (APIPromise helpers stay intact)
|
|
41
|
+
Promise.resolve(p).then((res) => {
|
|
42
|
+
// a stream keeps the span open until it ends (this runs before the caller's own continuation)
|
|
43
|
+
if (b.stream && (0, genai_stream_js_1.tapStream)(span, res, started))
|
|
44
|
+
return;
|
|
45
|
+
// the shared reader adds camelCase usage (Mistral), Ollama counts and tool calls
|
|
46
|
+
if (!b.stream && res) {
|
|
47
|
+
record(span, res);
|
|
48
|
+
(0, genai_stream_js_1.applyExtract)(span, (0, genai_stream_js_1.extract)(res));
|
|
49
|
+
}
|
|
50
|
+
span.end();
|
|
51
|
+
}, (e) => {
|
|
52
|
+
span.recordException(e);
|
|
53
|
+
span.setStatus({ code: api_1.SpanStatusCode.ERROR, message: e?.message });
|
|
54
|
+
span.end();
|
|
55
|
+
});
|
|
56
|
+
return p;
|
|
57
|
+
};
|
|
58
|
+
wrapped[DONE] = true;
|
|
59
|
+
target[method] = wrapped;
|
|
60
|
+
}
|
|
61
|
+
function record(span, res) {
|
|
62
|
+
const u = res.usage || {};
|
|
63
|
+
const g = res.usageMetadata || {};
|
|
64
|
+
const input = u.prompt_tokens ?? u.input_tokens ?? u.inputTokens ?? g.promptTokenCount;
|
|
65
|
+
const output = u.completion_tokens ?? u.output_tokens ?? u.outputTokens ?? g.candidatesTokenCount;
|
|
66
|
+
const one = res.stop_reason ?? res.stopReason;
|
|
67
|
+
const finish = Array.isArray(res.choices) ? res.choices.map((c) => c.finish_reason)
|
|
68
|
+
: Array.isArray(res.candidates) ? res.candidates.map((c) => c.finishReason) : one ? [one] : [];
|
|
69
|
+
const id = res.id ?? res.responseId ?? res.$metadata?.requestId;
|
|
70
|
+
const model = res.model ?? res.modelVersion;
|
|
71
|
+
if (id)
|
|
72
|
+
span.setAttribute('gen_ai.response.id', id);
|
|
73
|
+
if (model)
|
|
74
|
+
span.setAttribute('gen_ai.response.model', model);
|
|
75
|
+
if (finish.length)
|
|
76
|
+
span.setAttribute('gen_ai.response.finish_reasons', finish.filter((f) => Boolean(f)));
|
|
77
|
+
if (input != null)
|
|
78
|
+
span.setAttribute('gen_ai.usage.input_tokens', input);
|
|
79
|
+
if (output != null)
|
|
80
|
+
span.setAttribute('gen_ai.usage.output_tokens', output);
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* instrumentOpenAI(new OpenAI()): chat.completions.create and responses.create. Returns the client.
|
|
84
|
+
* For an OpenAI-compatible gateway pass its name: instrumentOpenAI(new OpenAI({ baseURL: litellmUrl }), 'litellm').
|
|
85
|
+
*/
|
|
86
|
+
function instrumentOpenAI(client, system = 'openai') {
|
|
87
|
+
const c = client;
|
|
88
|
+
wrap(c.chat && c.chat.completions, 'create', system);
|
|
89
|
+
wrap(c.responses, 'create', system);
|
|
90
|
+
return client;
|
|
91
|
+
}
|
|
92
|
+
/** instrumentBedrock(new BedrockRuntimeClient()): `send` of Converse and InvokeModel commands; others pass through untraced. */
|
|
93
|
+
function instrumentBedrock(client) {
|
|
94
|
+
const c = client;
|
|
95
|
+
const send = c.send;
|
|
96
|
+
if (typeof send !== 'function' || send[DONE])
|
|
97
|
+
return client;
|
|
98
|
+
const traced = { send };
|
|
99
|
+
wrap(traced, 'send', 'aws.bedrock', (cmd) => {
|
|
100
|
+
const x = (cmd || {});
|
|
101
|
+
const name = (x.constructor && x.constructor.name) || '';
|
|
102
|
+
return { model: x.input?.modelId, max_tokens: x.input?.inferenceConfig?.maxTokens, temperature: x.input?.inferenceConfig?.temperature, stream: name.includes('Stream') };
|
|
103
|
+
});
|
|
104
|
+
const wrapped = function (cmd, ...rest) {
|
|
105
|
+
const name = (cmd?.constructor?.name) || '';
|
|
106
|
+
return /^(Converse|InvokeModel)/.test(name) ? traced.send.call(this, cmd, ...rest) : send.call(this, cmd, ...rest);
|
|
107
|
+
};
|
|
108
|
+
wrapped[DONE] = true;
|
|
109
|
+
c.send = wrapped;
|
|
110
|
+
return client;
|
|
111
|
+
}
|
|
112
|
+
/** instrumentGoogleGenAI(new GoogleGenAI({...})): models.generateContent (Gemini API or Vertex AI). */
|
|
113
|
+
function instrumentGoogleGenAI(client) {
|
|
114
|
+
const c = client;
|
|
115
|
+
wrap(c.models, 'generateContent', c.vertexai ? 'vertex_ai' : 'gemini', (b) => {
|
|
116
|
+
const x = (b || {});
|
|
117
|
+
return { model: x.model, max_tokens: x.config?.maxOutputTokens, temperature: x.config?.temperature };
|
|
118
|
+
});
|
|
119
|
+
return client;
|
|
120
|
+
}
|
|
121
|
+
/** instrumentAnthropic(new Anthropic()): messages.create. Returns the client. */
|
|
122
|
+
function instrumentAnthropic(client) {
|
|
123
|
+
wrap(client.messages, 'create', 'anthropic');
|
|
124
|
+
return client;
|
|
125
|
+
}
|
|
126
|
+
/** instrumentMistral(new Mistral()): chat.complete and chat.stream (the stream span ends with the stream). */
|
|
127
|
+
function instrumentMistral(client) {
|
|
128
|
+
const c = client.chat;
|
|
129
|
+
wrap(c, 'complete', 'mistral_ai', mistralReq);
|
|
130
|
+
wrap(c, 'stream', 'mistral_ai', (b) => ({ ...mistralReq(b), stream: true }));
|
|
131
|
+
return client;
|
|
132
|
+
}
|
|
133
|
+
const mistralReq = (b) => {
|
|
134
|
+
const x = (b || {});
|
|
135
|
+
return { model: x.model, max_tokens: x.maxTokens, temperature: x.temperature };
|
|
136
|
+
};
|
|
137
|
+
/** instrumentOllama(new Ollama()) or instrumentOllama(ollama): chat and generate, with `stream: true` too. */
|
|
138
|
+
function instrumentOllama(client) {
|
|
139
|
+
const ollamaReq = (b) => {
|
|
140
|
+
const x = (b || {});
|
|
141
|
+
return { model: x.model, stream: x.stream, max_tokens: x.options?.num_predict, temperature: x.options?.temperature };
|
|
142
|
+
};
|
|
143
|
+
wrap(client, 'chat', 'ollama', ollamaReq);
|
|
144
|
+
wrap(client, 'generate', 'ollama', ollamaReq);
|
|
145
|
+
return client;
|
|
146
|
+
}
|
|
147
|
+
/** generateText({ ..., experimental_telemetry: vercelAiTelemetry() }); inputs/outputs off unless overridden. */
|
|
148
|
+
function vercelAiTelemetry(o) {
|
|
149
|
+
return { isEnabled: true, recordInputs: false, recordOutputs: false, tracer: api_1.trace.getTracer('watchtower'), ...o };
|
|
150
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
interface Helpers {
|
|
2
|
+
job?: {
|
|
3
|
+
id?: string | number;
|
|
4
|
+
attempts?: number;
|
|
5
|
+
queue_name?: string | null;
|
|
6
|
+
};
|
|
7
|
+
addJob?: unknown;
|
|
8
|
+
}
|
|
9
|
+
type Task = (payload: unknown, helpers: Helpers) => unknown;
|
|
10
|
+
/**
|
|
11
|
+
* `instrumentAddJob(utils)` (from `makeWorkerUtils`, or the runner from `run`): a PRODUCER span on
|
|
12
|
+
* `addJob` with the trace context in the payload under `_wt` (object payloads only).
|
|
13
|
+
* shortcut: the module-level `quickAddJob` cannot be patched under ESM; use `utils.addJob`.
|
|
14
|
+
*/
|
|
15
|
+
export declare function instrumentAddJob(utilsOrRunner: object): void;
|
|
16
|
+
/**
|
|
17
|
+
* `run({ taskList: wrapTaskList({ send_email: async (payload, helpers) => ... }) })`: each task runs
|
|
18
|
+
* in a CONSUMER span, child of and linked to the `addJob` that queued it; `_wt` is removed from the
|
|
19
|
+
* payload first, and `helpers.addJob` is instrumented so follow-up jobs stay in the trace.
|
|
20
|
+
*/
|
|
21
|
+
export declare function wrapTaskList<T extends Record<string, Task>>(tasks: T): T;
|
|
22
|
+
export {};
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.instrumentAddJob = instrumentAddJob;
|
|
4
|
+
exports.wrapTaskList = wrapTaskList;
|
|
5
|
+
const api_1 = require("@opentelemetry/api");
|
|
6
|
+
const db_js_1 = require("./db.js");
|
|
7
|
+
const messaging_js_1 = require("./messaging.js");
|
|
8
|
+
const attrs = (task, type, op) => ({
|
|
9
|
+
'messaging.system': 'graphile-worker',
|
|
10
|
+
'messaging.destination.name': task,
|
|
11
|
+
'messaging.operation.type': type,
|
|
12
|
+
'messaging.operation.name': op,
|
|
13
|
+
});
|
|
14
|
+
/**
|
|
15
|
+
* `instrumentAddJob(utils)` (from `makeWorkerUtils`, or the runner from `run`): a PRODUCER span on
|
|
16
|
+
* `addJob` with the trace context in the payload under `_wt` (object payloads only).
|
|
17
|
+
* shortcut: the module-level `quickAddJob` cannot be patched under ESM; use `utils.addJob`.
|
|
18
|
+
*/
|
|
19
|
+
function instrumentAddJob(utilsOrRunner) {
|
|
20
|
+
(0, db_js_1.patch)(utilsOrRunner, 'addJob', (orig) => function (identifier, payload, ...rest) {
|
|
21
|
+
return (0, messaging_js_1.produce)(`send ${identifier}`, attrs(identifier, 'send', 'addJob'), () => {
|
|
22
|
+
const span = api_1.trace.getActiveSpan();
|
|
23
|
+
return orig.call(this, identifier, (0, messaging_js_1.injectData)(payload ?? {}), ...rest).then((job) => {
|
|
24
|
+
if (job?.id !== undefined)
|
|
25
|
+
span?.setAttribute('messaging.message.id', String(job.id));
|
|
26
|
+
return job;
|
|
27
|
+
});
|
|
28
|
+
});
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* `run({ taskList: wrapTaskList({ send_email: async (payload, helpers) => ... }) })`: each task runs
|
|
33
|
+
* in a CONSUMER span, child of and linked to the `addJob` that queued it; `_wt` is removed from the
|
|
34
|
+
* payload first, and `helpers.addJob` is instrumented so follow-up jobs stay in the trace.
|
|
35
|
+
*/
|
|
36
|
+
function wrapTaskList(tasks) {
|
|
37
|
+
return Object.fromEntries(Object.entries(tasks).map(([name, fn]) => [name, (payload, helpers) => {
|
|
38
|
+
const carrier = (0, messaging_js_1.takeContext)(payload);
|
|
39
|
+
const a = attrs(name, 'process', 'task');
|
|
40
|
+
if (helpers?.job?.id !== undefined)
|
|
41
|
+
a['messaging.message.id'] = String(helpers.job.id);
|
|
42
|
+
if (helpers?.job?.attempts !== undefined)
|
|
43
|
+
a['messaging.graphile_worker.job.attempt'] = helpers.job.attempts;
|
|
44
|
+
if (helpers?.job?.queue_name)
|
|
45
|
+
a['messaging.consumer.group.name'] = helpers.job.queue_name;
|
|
46
|
+
if (helpers)
|
|
47
|
+
instrumentAddJob(helpers);
|
|
48
|
+
return (0, messaging_js_1.consume)(`process ${name}`, a, [carrier], () => fn(payload, helpers));
|
|
49
|
+
}]));
|
|
50
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/** The slice of a Koa context this integration reads. */
|
|
2
|
+
export interface KoaContext {
|
|
3
|
+
method: string;
|
|
4
|
+
path: string;
|
|
5
|
+
status: number;
|
|
6
|
+
_matchedRoute?: string;
|
|
7
|
+
/** `body` is set by a body parser (koa-bodyparser, koa-body) for payload capture. */
|
|
8
|
+
request?: {
|
|
9
|
+
body?: unknown;
|
|
10
|
+
type?: string;
|
|
11
|
+
};
|
|
12
|
+
/** The response body the handler set (payload capture; streams are skipped). */
|
|
13
|
+
body?: unknown;
|
|
14
|
+
response?: {
|
|
15
|
+
type?: string;
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
/** app.use(middleware()) first: server span per request, errors captured then rethrown. */
|
|
19
|
+
export declare function middleware(): (ctx: KoaContext, next: () => Promise<unknown>) => Promise<void>;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.middleware = middleware;
|
|
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
|
+
/** app.use(middleware()) first: server span per request, errors captured then rethrown. */
|
|
9
|
+
function middleware() {
|
|
10
|
+
return async (ctx, next) => {
|
|
11
|
+
const s = (0, util_js_1.serverSpan)(ctx.method, ctx.path);
|
|
12
|
+
let status;
|
|
13
|
+
try {
|
|
14
|
+
await api_1.context.with(s.ctx, next);
|
|
15
|
+
status = ctx.status;
|
|
16
|
+
}
|
|
17
|
+
catch (e) {
|
|
18
|
+
status = (0, util_js_1.statusOf)(e);
|
|
19
|
+
if (status >= 500)
|
|
20
|
+
api_1.context.with(s.ctx, () => (0, errors_js_1.captureException)(e));
|
|
21
|
+
throw e;
|
|
22
|
+
}
|
|
23
|
+
finally {
|
|
24
|
+
if ((0, payload_js_1.captureActive)()) {
|
|
25
|
+
(0, payload_js_1.capturePayload)(s.span, {
|
|
26
|
+
route: ctx._matchedRoute || ctx.path,
|
|
27
|
+
reqType: ctx.request?.type, reqBody: ctx.request?.body,
|
|
28
|
+
resType: ctx.response?.type, resBody: ctx.body,
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
s.finish(status, ctx._matchedRoute);
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** The slice of the Lambda context this wrapper reads. */
|
|
2
|
+
export interface LambdaContextLike {
|
|
3
|
+
functionName?: string;
|
|
4
|
+
awsRequestId?: string;
|
|
5
|
+
invokedFunctionArn?: string;
|
|
6
|
+
}
|
|
7
|
+
/** exports.handler = wrapHandler(async (event, context) => ...). Async handlers only. Flushes before the
|
|
8
|
+
* runtime freezes, otherwise buffered spans are lost. */
|
|
9
|
+
export declare function wrapHandler<E, R, C extends LambdaContextLike = LambdaContextLike>(handler: (event: E, context: C) => Promise<R>, o?: {
|
|
10
|
+
name?: string;
|
|
11
|
+
}): (event: E, context: C) => Promise<R>;
|
|
@@ -0,0 +1,68 @@
|
|
|
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.wrapHandler = wrapHandler;
|
|
37
|
+
const api_1 = require("@opentelemetry/api");
|
|
38
|
+
const errors_js_1 = require("../errors.js");
|
|
39
|
+
const wt = __importStar(require("../index.js"));
|
|
40
|
+
/** exports.handler = wrapHandler(async (event, context) => ...). Async handlers only. Flushes before the
|
|
41
|
+
* runtime freezes, otherwise buffered spans are lost. */
|
|
42
|
+
function wrapHandler(handler, o) {
|
|
43
|
+
const x = o || {};
|
|
44
|
+
return async (event, context) => {
|
|
45
|
+
const c = context || {};
|
|
46
|
+
return api_1.trace.getTracer('watchtower').startActiveSpan(x.name || c.functionName || 'lambda', {
|
|
47
|
+
kind: api_1.SpanKind.SERVER,
|
|
48
|
+
attributes: {
|
|
49
|
+
'cloud.provider': 'aws',
|
|
50
|
+
'faas.name': c.functionName,
|
|
51
|
+
'faas.invocation_id': c.awsRequestId,
|
|
52
|
+
'cloud.resource_id': c.invokedFunctionArn,
|
|
53
|
+
},
|
|
54
|
+
}, async (span) => {
|
|
55
|
+
try {
|
|
56
|
+
return await handler(event, context);
|
|
57
|
+
}
|
|
58
|
+
catch (e) {
|
|
59
|
+
(0, errors_js_1.captureException)(e, { handled: false, attributes: { 'error.mechanism': 'lambda' } });
|
|
60
|
+
throw e;
|
|
61
|
+
}
|
|
62
|
+
finally {
|
|
63
|
+
span.end();
|
|
64
|
+
await wt.flush().catch(() => { });
|
|
65
|
+
}
|
|
66
|
+
});
|
|
67
|
+
};
|
|
68
|
+
}
|