forked from aws/agentcore-cli
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtransforms.ts
More file actions
286 lines (259 loc) · 10.6 KB
/
Copy pathtransforms.ts
File metadata and controls
286 lines (259 loc) · 10.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
import type { OtlpAttribute, OtlpAttributeValue, OtlpResource, OtlpResourceLog, OtlpResourceSpan } from './types';
// ---------------------------------------------------------------------------
// Trace metadata extraction (from raw OTLP data)
// ---------------------------------------------------------------------------
export interface TraceMeta {
traceId?: string;
firstSeen: number;
lastSeen: number;
sessionId?: string;
serviceName?: string;
spanCount: number;
}
/** Extract metadata from raw OTLP resource arrays. */
export function extractTraceMeta(resourceSpans: OtlpResourceSpan[], resourceLogs: OtlpResourceLog[]): TraceMeta {
let traceId: string | undefined;
let firstSeen = Infinity;
let lastSeen = 0;
let sessionId: string | undefined;
let serviceName: string | undefined;
let spanCount = 0;
for (const rs of resourceSpans) {
serviceName ??= getResourceAttribute(rs.resource, 'service.name');
for (const ss of rs.scopeSpans ?? []) {
for (const span of ss.spans ?? []) {
spanCount++;
traceId ??= hexFromB64OrString(span.traceId) || undefined;
const startMs = nanoToMs(span.startTimeUnixNano);
const endMs = nanoToMs(span.endTimeUnixNano);
if (startMs && startMs < firstSeen) firstSeen = startMs;
if (endMs && endMs > lastSeen) lastSeen = endMs;
if (!sessionId) {
const attrs = span.attributes;
sessionId = getAttrValue(attrs, 'session.id') ?? getAttrValue(attrs, 'attributes.session.id');
}
}
}
}
for (const rl of resourceLogs) {
serviceName ??= getResourceAttribute(rl.resource, 'service.name');
for (const sl of rl.scopeLogs ?? []) {
for (const lr of sl.logRecords ?? []) {
spanCount++;
traceId ??= hexFromB64OrString(lr.traceId) || undefined;
const timeMs = nanoToMs(lr.timeUnixNano) || nanoToMs(lr.observedTimeUnixNano);
if (timeMs && timeMs < firstSeen) firstSeen = timeMs;
if (timeMs && timeMs > lastSeen) lastSeen = timeMs;
}
}
}
const now = Date.now();
if (firstSeen === Infinity) firstSeen = now;
if (lastSeen === 0) lastSeen = now;
return { traceId, firstSeen, lastSeen, sessionId, serviceName, spanCount };
}
/** Extract traceId and serviceName from the first span/log in a payload. */
export function extractFirstTraceInfo(data: { resourceSpans?: OtlpResourceSpan[]; resourceLogs?: OtlpResourceLog[] }): {
traceId?: string;
serviceName?: string;
} {
if (data.resourceSpans) {
for (const rs of data.resourceSpans) {
const svc = getResourceAttribute(rs.resource, 'service.name');
for (const ss of rs.scopeSpans ?? []) {
for (const span of ss.spans ?? []) {
if (span.traceId) return { traceId: hexFromB64OrString(span.traceId), serviceName: svc };
}
}
}
}
if (data.resourceLogs) {
for (const rl of data.resourceLogs) {
const svc = getResourceAttribute(rl.resource, 'service.name');
for (const sl of rl.scopeLogs ?? []) {
for (const lr of sl.logRecords ?? []) {
if (lr.traceId) return { traceId: hexFromB64OrString(lr.traceId), serviceName: svc };
}
}
}
}
return {};
}
// ---------------------------------------------------------------------------
// Trace detail: flatten attributes, filter noise, extract log bodies
// ---------------------------------------------------------------------------
/**
* Build frontend-ready trace detail from raw OTLP resource arrays.
* Flattens attributes to Record<string, unknown>, filters noise spans,
* and extracts log body values.
*/
export function buildTraceDetail(
resourceSpans: OtlpResourceSpan[],
resourceLogs: OtlpResourceLog[]
): { resourceSpans?: unknown[]; resourceLogs?: unknown[] } {
const filteredSpans = resourceSpans
.map(rs => ({
resource: rs.resource ? { attributes: flattenAttributes(rs.resource.attributes) } : undefined,
scopeSpans: rs.scopeSpans
?.map(ss => ({
scope: ss.scope,
spans: ss.spans
?.map(span => ({
...span,
traceId: hexFromB64OrString(span.traceId),
spanId: hexFromB64OrString(span.spanId),
parentSpanId: hexFromB64OrString(span.parentSpanId),
attributes: flattenAttributes(span.attributes),
}))
.filter(span => isMeaningfulSpan(span)),
}))
.filter(ss => ss.spans && ss.spans.length > 0),
}))
.filter(rs => rs.scopeSpans && rs.scopeSpans.length > 0);
const flattenedLogs = resourceLogs
.map(rl => ({
resource: rl.resource ? { attributes: flattenAttributes(rl.resource.attributes) } : undefined,
scopeLogs: rl.scopeLogs?.map(sl => ({
scope: sl.scope,
logRecords: sl.logRecords?.map(lr => ({
...lr,
traceId: hexFromB64OrString(lr.traceId),
spanId: hexFromB64OrString(lr.spanId),
body: lr.body ? extractAnyValue(lr.body) : undefined,
attributes: flattenAttributes(lr.attributes),
})),
})),
}))
.filter(rl => rl.scopeLogs && rl.scopeLogs.length > 0);
return {
resourceSpans: filteredSpans.length > 0 ? filteredSpans : undefined,
resourceLogs: flattenedLogs.length > 0 ? flattenedLogs : undefined,
};
}
// ---------------------------------------------------------------------------
// Span filtering
// ---------------------------------------------------------------------------
/**
* Determine if a trace span contains meaningful application data.
* Filters out ASGI transport noise, HTTP client noise, and other
* low-level framework spans that add no value in the trace UI.
*/
function isMeaningfulSpan(span: {
name?: string;
kind?: number | string;
attributes?: Record<string, unknown>;
}): boolean {
const name = span.name ?? '';
const attrs = span.attributes ?? {};
const kind = normalizeSpanKind(span.kind);
if (name.endsWith(' http send') || name.endsWith(' http receive')) return false;
if (attrs['asgi.event.type']) return false;
if (Object.keys(attrs).some(k => k.startsWith('gen_ai.'))) return true;
if (attrs['rpc.system'] || attrs['rpc.method']) return true;
const scopeHints = ['strands', 'bedrock', 'langchain', 'crewai', 'autogen', 'google_adk'];
if (scopeHints.some(h => name.toLowerCase().includes(h))) return true;
if (name === 'tool_use' || name === 'tool_call' || attrs['tool.name']) return true;
if (kind === 3 && (name === 'POST' || name === 'GET' || name.startsWith('HTTP '))) return false;
if (kind === 2 && name.startsWith('POST /') && attrs['http.method']) return false;
return true;
}
/** Normalize span kind from string enum name or number to a numeric value. */
function normalizeSpanKind(kind: number | string | undefined): number {
if (typeof kind === 'number') return kind;
if (typeof kind === 'string') {
const map: Record<string, number> = {
SPAN_KIND_INTERNAL: 1,
SPAN_KIND_SERVER: 2,
SPAN_KIND_CLIENT: 3,
SPAN_KIND_PRODUCER: 4,
SPAN_KIND_CONSUMER: 5,
};
return map[kind] ?? 0;
}
return 0;
}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
/** Convert nanosecond timestamp (string) to milliseconds. */
export function nanoToMs(nano: string | undefined): number {
if (!nano) return 0;
return Math.floor(Number(nano) / 1_000_000);
}
/**
* Convert a value that may be base64 (from protobuf JSON roundtrip) or
* already a hex string into a hex string.
*/
export function hexFromB64OrString(val: string | undefined): string {
if (!val) return '';
// Already hex (32 chars for traceId, 16 for spanId)
if (/^[0-9a-f]+$/i.test(val) && (val.length === 32 || val.length === 16)) return val.toLowerCase();
// Base64 from protobuf JSON.stringify roundtrip
try {
return Buffer.from(val, 'base64').toString('hex');
} catch {
return val;
}
}
/** Get a string attribute from an OTLP resource. */
function getResourceAttribute(resource: OtlpResource | undefined, key: string): string | undefined {
return getAttrValue(resource?.attributes, key);
}
/** Get a string value from attributes (handles both array and flat record formats). */
function getAttrValue(attrs: OtlpAttribute[] | Record<string, unknown> | undefined, key: string): string | undefined {
if (!attrs) return undefined;
if (Array.isArray(attrs)) {
const attr = attrs.find(a => a.key === key);
if (!attr?.value) return undefined;
return attr.value.stringValue ?? (attr.value.intValue != null ? String(attr.value.intValue) : undefined);
}
const val = attrs[key];
return typeof val === 'string' ? val : undefined;
}
/**
* Flatten OTLP attributes to a plain Record<string, unknown>.
* Handles both OTLP key/value array format and already-flat records.
*/
export function flattenAttributes(
attrs: OtlpAttribute[] | Record<string, unknown> | undefined
): Record<string, unknown> | undefined {
if (!attrs) return undefined;
if (!Array.isArray(attrs)) return attrs;
if (attrs.length === 0) return undefined;
const result: Record<string, unknown> = {};
for (const attr of attrs) {
if (!attr.value) continue;
if (attr.value.stringValue !== undefined) result[attr.key] = attr.value.stringValue;
else if (attr.value.intValue !== undefined) result[attr.key] = Number(attr.value.intValue);
else if (attr.value.doubleValue !== undefined) result[attr.key] = attr.value.doubleValue;
else if (attr.value.boolValue !== undefined) result[attr.key] = attr.value.boolValue;
else if (attr.value.arrayValue?.values) {
result[attr.key] = attr.value.arrayValue.values.map(
(v: OtlpAttributeValue) => v.stringValue ?? v.intValue ?? v.doubleValue ?? v.boolValue ?? null
);
}
}
return result;
}
/** Extract a usable value from an OTLP AnyValue. */
export function extractAnyValue(val: unknown): unknown {
if (!val || typeof val !== 'object') return val;
const v = val as Record<string, unknown>;
if (v.stringValue !== undefined) return v.stringValue;
if (v.intValue !== undefined) return Number(v.intValue);
if (v.doubleValue !== undefined) return v.doubleValue;
if (v.boolValue !== undefined) return v.boolValue;
if (v.arrayValue && typeof v.arrayValue === 'object') {
const arr = v.arrayValue as { values?: unknown[] };
return (arr.values ?? []).map(extractAnyValue);
}
if (v.kvlistValue && typeof v.kvlistValue === 'object') {
const kvlist = v.kvlistValue as { values?: { key: string; value?: unknown }[] };
const obj: Record<string, unknown> = {};
for (const kv of kvlist.values ?? []) {
obj[kv.key] = kv.value ? extractAnyValue(kv.value) : undefined;
}
return obj;
}
return val;
}