Skip to content

Commit 9cfb6eb

Browse files
committed
📦 NEW: Extract traceid from response headers
1 parent 00aa8a9 commit 9cfb6eb

File tree

1 file changed

+41
-12
lines changed

1 file changed

+41
-12
lines changed

packages/langbase/src/langbase/workflows.ts

Lines changed: 41 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -88,21 +88,50 @@ export class Workflow {
8888

8989
// Replace with intercepted version
9090
obj[method] = async function (...args: any[]) {
91-
// Call original method with the correct 'this' context
92-
const result = await originalMethod.apply(this, args);
91+
// Add custom arguments for tracing
92+
// Add rawResponse to the options if it's an object
93+
const lastArg = args[args.length - 1];
94+
const newArgs = [...args];
95+
96+
if (lastArg && typeof lastArg === 'object') {
97+
newArgs[newArgs.length - 1] = {
98+
...lastArg,
99+
rawResponse: true,
100+
};
101+
}
102+
// Append a new object if the last argument is not an object
103+
else {
104+
newArgs.push({rawResponse: true});
105+
}
106+
107+
const result = await originalMethod.apply(this, newArgs);
108+
console.log(`🔄 Intercepted method: ${fullPath}`, result);
93109

94110
// Process result for tracing if we have an active collector
95-
if (
96-
global._activeTraceCollector &&
97-
result &&
98-
typeof result === 'object'
99-
) {
111+
if (global._activeTraceCollector) {
100112
// Extract or create traceId
101-
let traceId: string;
102-
103-
if ('traceId' in result && result.traceId) {
104-
traceId = result.traceId;
105-
global._activeTraceCollector(traceId);
113+
let traceId: string | undefined;
114+
115+
// Check if result is an object with response headers
116+
if (result && typeof result === 'object') {
117+
// Extract from response headers
118+
if ('rawResponse' in result && result.rawResponse) {
119+
// Check for lb-trace-id in headers
120+
if (result.rawResponse.headers['lb-trace-id']) {
121+
// Plain object headers
122+
traceId =
123+
result.rawResponse.headers['lb-trace-id'];
124+
}
125+
}
126+
127+
// Notify collector if traceId was found
128+
if (traceId && global._activeTraceCollector) {
129+
if (debug)
130+
console.log(
131+
`🔍 Trace ID extracted: ${traceId}`,
132+
);
133+
global._activeTraceCollector(traceId);
134+
}
106135
}
107136
}
108137

0 commit comments

Comments
 (0)