Skip to content

Commit fcdda49

Browse files
committed
feat(deno): add anthropic integration
1 parent 9ea3b80 commit fcdda49

4 files changed

Lines changed: 115 additions & 0 deletions

File tree

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
// <reference lib="deno.ns" />
2+
3+
import { tracingChannel } from 'node:diagnostics_channel';
4+
import type { TransactionEvent } from '@sentry/core';
5+
import type { DenoClient } from '@sentry/deno';
6+
import { getCurrentScope, getGlobalScope, getIsolationScope, init, startSpan } from '@sentry/deno';
7+
import { assert } from 'https://deno.land/std@0.212.0/assert/assert.ts';
8+
import { assertExists } from 'https://deno.land/std@0.212.0/assert/assert_exists.ts';
9+
import { assertEquals } from 'https://deno.land/std@0.212.0/assert/assert_equals.ts';
10+
11+
function resetGlobals(): void {
12+
getCurrentScope().clear();
13+
getCurrentScope().setClient(undefined);
14+
getIsolationScope().clear();
15+
getGlobalScope().clear();
16+
}
17+
18+
/** See deno-redis.test.ts — same sink shape, deduped for clarity. */
19+
function transactionSink(): {
20+
beforeSendTransaction: (event: TransactionEvent) => null;
21+
waitFor: (predicate: (event: TransactionEvent) => boolean) => Promise<TransactionEvent>;
22+
} {
23+
const transactions: TransactionEvent[] = [];
24+
const waiters: { predicate: (e: TransactionEvent) => boolean; resolve: (e: TransactionEvent) => void }[] = [];
25+
return {
26+
beforeSendTransaction(event) {
27+
transactions.push(event);
28+
for (let i = waiters.length - 1; i >= 0; i--) {
29+
const w = waiters[i]!;
30+
if (w.predicate(event)) {
31+
waiters.splice(i, 1);
32+
w.resolve(event);
33+
}
34+
}
35+
return null;
36+
},
37+
waitFor(predicate) {
38+
const already = transactions.find(predicate);
39+
if (already) return Promise.resolve(already);
40+
return new Promise<TransactionEvent>(resolve => {
41+
waiters.push({ predicate, resolve });
42+
});
43+
},
44+
};
45+
}
46+
47+
function withTimeout<T>(p: Promise<T>, ms: number, what: string): Promise<T> {
48+
let timer: ReturnType<typeof setTimeout> | undefined;
49+
const timeout = new Promise<T>((_, reject) => {
50+
timer = setTimeout(() => reject(new Error(`Timed out waiting for ${what} after ${ms}ms`)), ms);
51+
});
52+
return Promise.race([p, timeout]).finally(() => {
53+
if (timer !== undefined) clearTimeout(timer);
54+
});
55+
}
56+
57+
Deno.test('anthropic instrumentation: included in default integrations (Deno 2.8.0+)', () => {
58+
resetGlobals();
59+
const client = init({ dsn: 'https://username@domain/123' }) as DenoClient;
60+
const names = client.getOptions().integrations.map(i => i.name);
61+
assert(names.includes('Anthropic_AI'), `Anthropic_AI should be in defaults, got ${names.join(', ')}`);
62+
});
63+
64+
// Drives the `orchestrion:@anthropic-ai/sdk:chat` channel — the same events the
65+
// orchestrion transform publishes around the SDK's `messages.create` — so no live
66+
// Anthropic client is needed. The subscriber reads the request body off
67+
// `arguments[0]` and opens a `gen_ai.chat` span, then enriches it from the settled
68+
// `result`.
69+
Deno.test('anthropic instrumentation: orchestrion @anthropic-ai/sdk:chat channel produces a nested gen_ai span', async () => {
70+
resetGlobals();
71+
const sink = transactionSink();
72+
init({
73+
dsn: 'https://username@domain/123',
74+
tracesSampleRate: 1,
75+
beforeSendTransaction: sink.beforeSendTransaction,
76+
});
77+
78+
const channel = tracingChannel('orchestrion:@anthropic-ai/sdk:chat');
79+
80+
// `arguments[0]` is the request body passed to `messages.create(body, options)`.
81+
const body = { model: 'claude-3-5-sonnet-latest', messages: [{ role: 'user', content: 'hi' }] };
82+
const ctx: Record<string, unknown> = { arguments: [body] };
83+
84+
startSpan({ name: 'parent', op: 'test' }, () => {
85+
channel.start.runStores(ctx, () => undefined);
86+
// A non-streaming (non-async-iterable, no `on`) result ends the span via
87+
// `beforeSpanEnd`, which reads the response id, model and token usage off it.
88+
ctx.result = {
89+
id: 'msg_1',
90+
model: 'claude-3-5-sonnet-20241022',
91+
usage: { input_tokens: 10, output_tokens: 5 },
92+
};
93+
channel.end.publish(ctx);
94+
channel.asyncEnd.publish(ctx);
95+
});
96+
97+
const parent = await withTimeout(sink.waitFor(t => t.transaction === 'parent'), 5000, "'parent' transaction");
98+
99+
const aiSpan = parent.spans?.find(s => s.op === 'gen_ai.chat');
100+
assertExists(aiSpan, `expected a gen_ai.chat child span, got ops: ${parent.spans?.map(s => s.op).join(', ')}`);
101+
assertEquals(aiSpan!.description, 'chat claude-3-5-sonnet-latest');
102+
assertEquals(aiSpan!.data?.['gen_ai.system'], 'anthropic');
103+
assertEquals(aiSpan!.data?.['gen_ai.operation.name'], 'chat');
104+
assertEquals(aiSpan!.data?.['gen_ai.request.model'], 'claude-3-5-sonnet-latest');
105+
assertEquals(aiSpan!.data?.['gen_ai.response.model'], 'claude-3-5-sonnet-20241022');
106+
assertEquals(aiSpan!.data?.['gen_ai.usage.total_tokens'], 15);
107+
assertEquals(aiSpan!.data?.['sentry.origin'], 'auto.ai.orchestrion.anthropic');
108+
});

packages/deno/src/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,7 @@ export type { DenoRedisIntegrationOptions } from './integrations/redis';
117117
// adds to the defaults, so users who customize `defaultIntegrations` can re-add it.
118118
export {
119119
amqplibChannelIntegration,
120+
anthropicChannelIntegration,
120121
awsChannelIntegration,
121122
dataloaderChannelIntegration,
122123
expressChannelIntegration,

packages/deno/src/sdk.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import {
1313
} from '@sentry/core';
1414
import {
1515
amqplibChannelIntegration,
16+
anthropicChannelIntegration,
1617
awsChannelIntegration,
1718
expressChannelIntegration,
1819
firebaseChannelIntegration,
@@ -89,6 +90,7 @@ export function getDefaultIntegrations(_options: Options): Integration[] {
8990
...(MODULE_REGISTER_HOOKS_SUPPORTED
9091
? [
9192
amqplibChannelIntegration(),
93+
anthropicChannelIntegration(),
9294
awsChannelIntegration(),
9395
expressChannelIntegration(),
9496
firebaseChannelIntegration(),

packages/deno/test/__snapshots__/mod.test.ts.snap

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,7 @@ snapshot[`captureException 1`] = `
117117
"DenoRedis",
118118
"Graphql",
119119
"Amqplib",
120+
"Anthropic_AI",
120121
"Aws",
121122
"Express",
122123
"Firebase",
@@ -210,6 +211,7 @@ snapshot[`captureMessage 1`] = `
210211
"DenoRedis",
211212
"Graphql",
212213
"Amqplib",
214+
"Anthropic_AI",
213215
"Aws",
214216
"Express",
215217
"Firebase",
@@ -310,6 +312,7 @@ snapshot[`captureMessage twice 1`] = `
310312
"DenoRedis",
311313
"Graphql",
312314
"Amqplib",
315+
"Anthropic_AI",
313316
"Aws",
314317
"Express",
315318
"Firebase",
@@ -417,6 +420,7 @@ snapshot[`captureMessage twice 2`] = `
417420
"DenoRedis",
418421
"Graphql",
419422
"Amqplib",
423+
"Anthropic_AI",
420424
"Aws",
421425
"Express",
422426
"Firebase",

0 commit comments

Comments
 (0)