Same agent Smaller bill. The tools and infrastructure to get more work from your AI. Fewer tokens. Less compute. Lower cost.
TypeScript agent-harnessagent-harness-engineeringai-engineeringai-observabilityamd-gpuclaude-codeclickhousecodexcoding-agentcoding-agentscursorgenaigpu-monitoringllm-observabilityllmopsnvidia-smiobservabilityopen-sourceopenaiopentelemetry
feat(ts-sdk): add Astra DB (DataStax) auto-instrumentation (#1257)
Barry2llen83968aca2625
diff --git a/sdk/typescript/.gitignore b/sdk/typescript/.gitignoreindex 76add878..43df0e48 100644--- a/sdk/typescript/.gitignore+++ b/sdk/typescript/.gitignore@@ -1,2 +1,3 @@node_modules-dist\ No newline at end of file+dist*.tsbuildinfo+tsconfig.tsbuildinfodiff --git a/sdk/typescript/src/instrumentation/__tests__/astra-trace-comparison.test.ts b/sdk/typescript/src/instrumentation/__tests__/astra-trace-comparison.test.tsnew file mode 100644index 00000000..25e318a1--- /dev/null+++ b/sdk/typescript/src/instrumentation/__tests__/astra-trace-comparison.test.ts@@ -0,0 +1,267 @@+/**+ * Cross-language trace comparison tests for Astra DB integration.+ *+ * Verifies TypeScript SDK trace attributes match the Python SDK's Astra+ * instrumentation behavior for Collection operations.+ */++import AstraWrapper from '../astra/wrapper';+import OpenlitConfig from '../../config';+import OpenLitHelper from '../../helpers';+import SemanticConvention from '../../semantic-convention';++jest.mock('../../config');+jest.mock('../../helpers');++describe('Astra DB Cross-Language Trace Comparison', () => {+ let mockSpan: any;+ let mockTracer: any;++ beforeEach(() => {+ mockSpan = {+ setAttribute: jest.fn(),+ addEvent: jest.fn(),+ end: jest.fn(),+ setStatus: jest.fn(),+ };++ mockTracer = {+ startSpan: jest.fn().mockReturnValue(mockSpan),+ };++ (OpenlitConfig as any).environment = 'openlit-testing';+ (OpenlitConfig as any).applicationName = 'openlit-test';+ (OpenlitConfig as any).captureMessageContent = true;+ (OpenLitHelper as any).handleException = jest.fn();+ });++ afterEach(() => {+ jest.clearAllMocks();+ });++ async function invokeAsyncWrapped(+ dbOperation: string,+ args: any[],+ returnValue: any = {},+ instance: any = { name: 'movies' }+ ) {+ const patchFn = AstraWrapper._patchCollectionMethod(mockTracer, dbOperation);+ const originalMethod = jest.fn().mockResolvedValue(returnValue);+ const wrapped = patchFn(originalMethod);+ const response = await wrapped.call(instance, ...args);++ return { originalMethod, response };+ }++ describe('common attributes', () => {+ it('sets Python parity common database and resource attributes', async () => {+ await invokeAsyncWrapped(+ SemanticConvention.DB_OPERATION_INSERT,+ [{ _id: '1', title: 'Dune' }],+ { insertedId: '1' }+ );++ expect(mockSpan.setAttribute).toHaveBeenCalledWith(SemanticConvention.DB_SYSTEM_NAME, 'astra');+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(SemanticConvention.DB_OPERATION_NAME, 'INSERT');+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(SemanticConvention.DB_COLLECTION_NAME, 'movies');+ expect(mockSpan.setAttribute).toHaveBeenCalledWith('telemetry.sdk.name', 'openlit');+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(+ SemanticConvention.GEN_AI_OPERATION,+ SemanticConvention.GEN_AI_OPERATION_TYPE_VECTORDB+ );+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(+ SemanticConvention.ATTR_DEPLOYMENT_ENVIRONMENT,+ 'openlit-testing'+ );+ expect(mockSpan.setAttribute).toHaveBeenCalledWith('service.name', 'openlit-test');+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(SemanticConvention.DB_SDK_VERSION, expect.any(String));+ });++ it('extracts server address and port from a URL endpoint', async () => {+ await invokeAsyncWrapped(+ SemanticConvention.DB_OPERATION_SELECT,+ [{ genre: 'sci-fi' }],+ { _id: '1' },+ { name: 'movies', database: { apiEndpoint: 'https://db.example.apps.astra.datastax.com:8443' } }+ );++ expect(mockSpan.setAttribute).toHaveBeenCalledWith(+ SemanticConvention.SERVER_ADDRESS,+ 'db.example.apps.astra.datastax.com'+ );+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(SemanticConvention.SERVER_PORT, 8443);+ });++ it('extracts server address and port from a host:port endpoint', async () => {+ await invokeAsyncWrapped(+ SemanticConvention.DB_OPERATION_SELECT,+ [{ genre: 'sci-fi' }],+ { _id: '1' },+ { name: 'movies', client: { api_endpoint: 'astra.local:9090' } }+ );++ expect(mockSpan.setAttribute).toHaveBeenCalledWith(SemanticConvention.SERVER_ADDRESS, 'astra.local');+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(SemanticConvention.SERVER_PORT, 9090);+ });++ it('falls back to the Astra default server when no endpoint is present', async () => {+ await invokeAsyncWrapped(SemanticConvention.DB_OPERATION_SELECT, [{}], null);++ expect(mockSpan.setAttribute).toHaveBeenCalledWith(SemanticConvention.SERVER_ADDRESS, 'astra.datastax.com');+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(SemanticConvention.SERVER_PORT, 443);+ });+ });++ describe('insert operations', () => {+ it('sets documents count, query text, returned rows, and summary', async () => {+ const documents = [{ _id: '1' }, { _id: '2' }];+ await invokeAsyncWrapped(+ SemanticConvention.DB_OPERATION_INSERT,+ [documents],+ { insertedIds: ['1', '2'] }+ );++ expect(mockSpan.setAttribute).toHaveBeenCalledWith(SemanticConvention.DB_DOCUMENTS_COUNT, 2);+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(SemanticConvention.DB_QUERY_TEXT, JSON.stringify(documents));+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(SemanticConvention.DB_RESPONSE_RETURNED_ROWS, 2);+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(+ SemanticConvention.DB_QUERY_SUMMARY,+ 'INSERT movies documents_count=2'+ );+ });+ });++ describe('update operations', () => {+ it('sets filter, update query text, returned rows, and summary', async () => {+ const filter = { status: 'draft' };+ const update = { $set: { status: 'published' } };+ await invokeAsyncWrapped(+ SemanticConvention.DB_OPERATION_UPDATE,+ [filter, update],+ { update_info: { nModified: 3 } }+ );++ expect(mockSpan.setAttribute).toHaveBeenCalledWith(SemanticConvention.DB_FILTER, JSON.stringify(filter));+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(SemanticConvention.DB_QUERY_TEXT, JSON.stringify(update));+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(SemanticConvention.DB_RESPONSE_RETURNED_ROWS, 3);+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(+ SemanticConvention.DB_QUERY_SUMMARY,+ `UPDATE movies filter=${JSON.stringify(filter)} update=${JSON.stringify(update)}`+ );+ });+ });++ describe('replace operations', () => {+ it('sets replace filter and summary without upsert', async () => {+ const filter = { _id: '1' };+ await invokeAsyncWrapped(+ SemanticConvention.DB_OPERATION_REPLACE,+ [filter, { _id: '1', title: 'Dune Messiah' }, { upsert: false }],+ { modifiedCount: 1 }+ );++ expect(mockSpan.setAttribute).toHaveBeenCalledWith(SemanticConvention.DB_OPERATION_NAME, 'findAndModify');+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(SemanticConvention.DB_FILTER, JSON.stringify(filter));+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(SemanticConvention.DB_QUERY_TEXT, JSON.stringify(filter));+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(+ SemanticConvention.DB_QUERY_SUMMARY,+ `findAndModify movies filter=${JSON.stringify(filter)} upsert=false`+ );+ });++ it('detects replace upsert and sets db.operation.name = UPSERT', async () => {+ await invokeAsyncWrapped(+ SemanticConvention.DB_OPERATION_REPLACE,+ [{ _id: 'missing' }, { _id: 'missing' }, { upsert: true }],+ { upsertedId: 'missing' }+ );++ expect(mockSpan.setAttribute).toHaveBeenCalledWith(+ SemanticConvention.DB_OPERATION_NAME,+ SemanticConvention.DB_OPERATION_UPSERT+ );+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(+ SemanticConvention.DB_QUERY_SUMMARY,+ 'UPSERT movies filter={"_id":"missing"} upsert=true'+ );+ });+ });++ describe('select operations', () => {+ it('sets findOne filter, query text, returned rows, and summary', async () => {+ const filter = { genre: 'sci-fi' };+ await invokeAsyncWrapped(SemanticConvention.DB_OPERATION_SELECT, [filter], { _id: '1' });++ expect(mockSpan.setAttribute).toHaveBeenCalledWith(SemanticConvention.DB_FILTER, JSON.stringify(filter));+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(SemanticConvention.DB_QUERY_TEXT, JSON.stringify(filter));+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(SemanticConvention.DB_RESPONSE_RETURNED_ROWS, 1);+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(+ SemanticConvention.DB_QUERY_SUMMARY,+ `SELECT movies filter=${JSON.stringify(filter)}`+ );+ });++ it('keeps find() synchronous and returns the original cursor', () => {+ const cursor = { toArray: jest.fn() };+ const patchFn = AstraWrapper._patchSyncFindMethod(mockTracer);+ const originalMethod = jest.fn().mockReturnValue(cursor);+ const wrapped = patchFn(originalMethod);+ const result = wrapped.call({ name: 'movies' }, { genre: 'sci-fi' });++ expect(result).toBe(cursor);+ expect((result as any).then).toBeUndefined();+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(+ SemanticConvention.DB_QUERY_SUMMARY,+ 'SELECT movies filter={"genre":"sci-fi"}'+ );+ expect(mockSpan.end).toHaveBeenCalled();+ });+ });++ describe('delete operations', () => {+ it('sets delete filter, query text, returned rows, and summary', async () => {+ const filter = { expired: true };+ await invokeAsyncWrapped(SemanticConvention.DB_OPERATION_DELETE, [filter], { deletedCount: 4 });++ expect(mockSpan.setAttribute).toHaveBeenCalledWith(SemanticConvention.DB_FILTER, JSON.stringify(filter));+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(SemanticConvention.DB_QUERY_TEXT, JSON.stringify(filter));+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(SemanticConvention.DB_RESPONSE_RETURNED_ROWS, 4);+ expect(mockSpan.setAttribute).toHaveBeenCalledWith(+ SemanticConvention.DB_QUERY_SUMMARY,+ `DELETE movies filter=${JSON.stringify(filter)}`+ );+ });++ it('sets findOneAndDelete returned rows from the deleted document response', async () => {+ await invokeAsyncWrapped(+ SemanticConvention.DB_OPERATION_FIND_AND_DELETE,+ [{ _id: '1' }],+ { _id: '1' }+ );++ expect(mockSpan.setAttribute).toHaveBeenCalledWith(SemanticConvention.DB_RESPONSE_RETURNED_ROWS, 1);+ });+ });++ it('does not set db.query.text when captureMessageContent is false', async () => {+ (OpenlitConfig as any).captureMessageContent = false;++ await invokeAsyncWrapped(SemanticConvention.DB_OPERATION_SELECT, [{ genre: 'sci-fi' }], { _id: '1' });++ expect(mockSpan.setAttribute).not.toHaveBeenCalledWith(+ SemanticConvention.DB_QUERY_TEXT,+ expect.anything()+ );+ });++ it('calls handleException and ends the span on error', async () => {+ const error = new Error('Astra request failed');+ const patchFn = AstraWrapper._patchCollectionMethod(mockTracer, SemanticConvention.DB_OPERATION_SELECT);+ const originalMethod = jest.fn().mockRejectedValue(error);+ const wrapped = patchFn(originalMethod);++ await expect(wrapped.call({ name: 'movies' }, { genre: 'sci-fi' })).rejects.toThrow('Astra request failed');+ expect(OpenLitHelper.handleException).toHaveBeenCalledWith(mockSpan, error);+ expect(mockSpan.end).toHaveBeenCalled();+ });+});diff --git a/sdk/typescript/src/instrumentation/astra/index.ts b/sdk/typescript/src/instrumentation/astra/index.tsnew file mode 100644index 00000000..f26f9598--- /dev/null+++ b/sdk/typescript/src/instrumentation/astra/index.ts@@ -0,0 +1,97 @@+import {+ InstrumentationBase,+ InstrumentationModuleDefinition,+ InstrumentationNodeModuleDefinition,+ isWrapped,+} from '@opentelemetry/instrumentation';+import { InstrumentationConfig } from '@opentelemetry/instrumentation';+import { diag } from '@opentelemetry/api';+import { INSTRUMENTATION_PREFIX } from '../../constant';+import SemanticConvention from '../../semantic-convention';+import AstraWrapper from './wrapper';++export interface AstraInstrumentationConfig extends InstrumentationConfig {}++export default class OpenlitAstraInstrumentation extends InstrumentationBase {+ constructor(config: AstraInstrumentationConfig = {}) {+ super(`${INSTRUMENTATION_PREFIX}/instrumentation-astra`, '1.0.0', config);+ }++ protected init(): void | InstrumentationModuleDefinition | InstrumentationModuleDefinition[] {+ const module = new InstrumentationNodeModuleDefinition(+ '@datastax/astra-db-ts',+ ['>=1.0.0'],+ (moduleExports) => {+ this._patch(moduleExports);+ return moduleExports;+ },+ (moduleExports) => {+ if (moduleExports !== undefined) {+ this._unpatch(moduleExports);+ }+ }+ );+ return [module];+ }++ public manualPatch(astra: any): void {+ this._patch(astra);+ }++ protected _patch(moduleExports: any) {+ try {+ const Collection = moduleExports.Collection;+ if (!Collection?.prototype) return;++ // `find` returns a cursor synchronously — must not be wrapped as async+ if (typeof Collection.prototype['find'] === 'function') {+ if (isWrapped(Collection.prototype['find'])) {+ this._unwrap(Collection.prototype, 'find');+ }+ this._wrap(Collection.prototype, 'find', AstraWrapper._patchSyncFindMethod(this.tracer));+ }++ // All other methods return Promises and use the async wrapper+ const asyncMethods: Array<[string, string]> = [+ ['insertOne', SemanticConvention.DB_OPERATION_INSERT],+ ['insertMany', SemanticConvention.DB_OPERATION_INSERT],+ ['updateOne', SemanticConvention.DB_OPERATION_UPDATE],+ ['updateMany', SemanticConvention.DB_OPERATION_UPDATE],+ ['replaceOne', SemanticConvention.DB_OPERATION_REPLACE],+ ['findOne', SemanticConvention.DB_OPERATION_SELECT],+ ['findOneAndUpdate', SemanticConvention.DB_OPERATION_REPLACE],+ ['findOneAndReplace', SemanticConvention.DB_OPERATION_REPLACE],+ ['findOneAndDelete', SemanticConvention.DB_OPERATION_FIND_AND_DELETE],+ ['deleteOne', SemanticConvention.DB_OPERATION_DELETE],+ ['deleteMany', SemanticConvention.DB_OPERATION_DELETE],+ ];++ for (const [method, dbOp] of asyncMethods) {+ if (typeof Collection.prototype[method] === 'function') {+ if (isWrapped(Collection.prototype[method])) {+ this._unwrap(Collection.prototype, method);+ }+ this._wrap(Collection.prototype, method, AstraWrapper._patchCollectionMethod(this.tracer, dbOp));+ }+ }+ } catch (e) {+ diag.error('Astra instrumentation: error in _patch method', e);+ }+ }++ protected _unpatch(moduleExports: any) {+ try {+ const Collection = moduleExports.Collection;+ if (!Collection?.prototype) return;+ for (const method of [+ 'insertOne', 'insertMany', 'updateOne', 'updateMany', 'replaceOne',+ 'find', 'findOne', 'findOneAndUpdate', 'findOneAndReplace',+ 'findOneAndDelete', 'deleteOne', 'deleteMany',+ ]) {+ if (typeof Collection.prototype[method] === 'function') {+ this._unwrap(Collection.prototype, method);+ }+ }+ } catch { /* ignore */ }+ }+}diff --git a/sdk/typescript/src/instrumentation/astra/wrapper.ts b/sdk/typescript/src/instrumentation/astra/wrapper.tsnew file mode 100644index 00000000..f3012871--- /dev/null+++ b/sdk/typescript/src/instrumentation/astra/wrapper.ts@@ -0,0 +1,392 @@+import { SpanKind, SpanStatusCode, Tracer, context, trace } from '@opentelemetry/api';+import { ATTR_SERVICE_NAME, ATTR_TELEMETRY_SDK_NAME } from '@opentelemetry/semantic-conventions';+import OpenlitConfig from '../../config';+import { SDK_NAME } from '../../constant';+import OpenLitHelper from '../../helpers';+import SemanticConvention from '../../semantic-convention';+import BaseWrapper from '../base-wrapper';++type ServerAddressAndPort = {+ serverAddress: string;+ serverPort: number;+};++type AstraOperationContext = {+ dbOperation: string;+ collectionName: string;+ args: any[];+ response?: any;+};++const DEFAULT_SERVER: ServerAddressAndPort = {+ serverAddress: 'astra.datastax.com',+ serverPort: 443,+};++let astraDbSdkVersion = 'unknown';++try {+ // Optional runtime dependency: keep this guarded so OpenLIT can load without Astra installed.+ // eslint-disable-next-line @typescript-eslint/no-var-requires+ astraDbSdkVersion = require('@datastax/astra-db-ts/package.json')?.version || 'unknown';+} catch {+ astraDbSdkVersion = 'unknown';+}++class AstraWrapper extends BaseWrapper {+ static dbSystem = SemanticConvention.DB_SYSTEM_ASTRA;+ static serverAddress = DEFAULT_SERVER.serverAddress;+ static serverPort = DEFAULT_SERVER.serverPort;++ static _setCommonAttributes(span: any, dbOperation: string, collectionName: string, instance?: any) {+ const applicationName = OpenlitConfig.applicationName || '';+ const environment = OpenlitConfig.environment || '';+ const { serverAddress, serverPort } = AstraWrapper._getServerAddressAndPort(instance);++ span.setAttribute(SemanticConvention.DB_SYSTEM_NAME, AstraWrapper.dbSystem);+ span.setAttribute(SemanticConvention.DB_OPERATION_NAME, dbOperation);+ span.setAttribute(SemanticConvention.DB_COLLECTION_NAME, collectionName);+ span.setAttribute(SemanticConvention.SERVER_ADDRESS, serverAddress);+ span.setAttribute(SemanticConvention.SERVER_PORT, serverPort);+ span.setAttribute(ATTR_TELEMETRY_SDK_NAME, SDK_NAME);+ span.setAttribute(SemanticConvention.GEN_AI_OPERATION, SemanticConvention.GEN_AI_OPERATION_TYPE_VECTORDB);+ span.setAttribute(SemanticConvention.ATTR_DEPLOYMENT_ENVIRONMENT, environment);+ span.setAttribute(ATTR_SERVICE_NAME, applicationName);+ span.setAttribute(SemanticConvention.DB_SDK_VERSION, astraDbSdkVersion);+ span.setAttribute(SemanticConvention.GEN_AI_ENVIRONMENT, environment);+ }++ /**+ * Async wrapper for methods that return Promises (all Collection CRUD methods except `find`).+ */+ static _patchCollectionMethod(tracer: Tracer, dbOperation: string): any {+ return (originalMethod: (...args: any[]) => any) => {+ return async function (this: any, ...args: any[]) {+ const collectionName: string = this?.name || 'unknown';+ const spanName = `${dbOperation} ${collectionName}`;+ const span = tracer.startSpan(spanName, { kind: SpanKind.CLIENT });+ const startTime = Date.now();++ return context.with(trace.setSpan(context.active(), span), async () => {+ try {+ const response = await originalMethod.apply(this, args);+ const duration = (Date.now() - startTime) / 1000;+ const actualDbOperation = AstraWrapper._getActualDbOperation(dbOperation, args);++ AstraWrapper._setCommonAttributes(span, actualDbOperation, collectionName, this);+ span.setAttribute(SemanticConvention.DB_CLIENT_OPERATION_DURATION, duration);+ AstraWrapper._setOperationAttributes(span, {+ dbOperation: actualDbOperation,+ collectionName,+ args,+ response,+ });++ span.setStatus({ code: SpanStatusCode.OK });+ return response;+ } catch (e: any) {+ OpenLitHelper.handleException(span, e);+ throw e;+ } finally {+ span.end();+ }+ });+ };+ };+ }++ /**+ * Synchronous wrapper for `find()` which returns a cursor synchronously.+ * Wrapping it as async would break the cursor API (e.g. `collection.find({}).toArray()`).+ */+ static _patchSyncFindMethod(tracer: Tracer): any {+ return (originalMethod: (...args: any[]) => any) => {+ return function (this: any, ...args: any[]) {+ const collectionName: string = this?.name || 'unknown';+ const spanName = `${SemanticConvention.DB_OPERATION_SELECT} ${collectionName}`;+ const span = tracer.startSpan(spanName, { kind: SpanKind.CLIENT });+ const startTime = Date.now();++ try {+ const cursor = originalMethod.apply(this, args);+ const duration = (Date.now() - startTime) / 1000;++ AstraWrapper._setCommonAttributes(span, SemanticConvention.DB_OPERATION_SELECT, collectionName, this);+ span.setAttribute(SemanticConvention.DB_CLIENT_OPERATION_DURATION, duration);+ AstraWrapper._setOperationAttributes(span, {+ dbOperation: SemanticConvention.DB_OPERATION_SELECT,+ collectionName,+ args,+ response: cursor,+ });++ span.setStatus({ code: SpanStatusCode.OK });+ return cursor;+ } catch (e: any) {+ OpenLitHelper.handleException(span, e);+ throw e;+ } finally {+ span.end();+ }+ };+ };+ }++ private static _setOperationAttributes(span: any, context: AstraOperationContext) {+ switch (context.dbOperation) {+ case SemanticConvention.DB_OPERATION_INSERT:+ AstraWrapper._setInsertAttributes(span, context);+ break;+ case SemanticConvention.DB_OPERATION_UPDATE:+ AstraWrapper._setUpdateAttributes(span, context);+ break;+ case SemanticConvention.DB_OPERATION_REPLACE:+ case SemanticConvention.DB_OPERATION_UPSERT:+ AstraWrapper._setReplaceAttributes(span, context);+ break;+ case SemanticConvention.DB_OPERATION_SELECT:+ AstraWrapper._setSelectAttributes(span, context);+ break;+ case SemanticConvention.DB_OPERATION_DELETE:+ case SemanticConvention.DB_OPERATION_FIND_AND_DELETE:+ AstraWrapper._setDeleteAttributes(span, context);+ break;+ default:+ span.setAttribute(SemanticConvention.DB_QUERY_SUMMARY, `${context.dbOperation} ${context.collectionName}`);+ }+ }++ private static _setInsertAttributes(span: any, { dbOperation, collectionName, args, response }: AstraOperationContext) {+ const documents = args[0];+ const documentsCount = AstraWrapper._objectCount(documents);++ span.setAttribute(SemanticConvention.DB_DOCUMENTS_COUNT, documentsCount);+ if (OpenlitConfig.captureMessageContent) {+ span.setAttribute(SemanticConvention.DB_QUERY_TEXT, AstraWrapper._safeStringify(documents));+ }++ const returnedRows = AstraWrapper._getInsertReturnedRows(response);+ if (returnedRows !== undefined) {+ span.setAttribute(SemanticConvention.DB_RESPONSE_RETURNED_ROWS, returnedRows);+ }++ span.setAttribute(+ SemanticConvention.DB_QUERY_SUMMARY,+ `${dbOperation} ${collectionName} documents_count=${documentsCount}`+ );+ }++ private static _setUpdateAttributes(span: any, { dbOperation, collectionName, args, response }: AstraOperationContext) {+ const filter = args[0] || {};+ const update = args[1] || {};++ AstraWrapper._setFilterAttribute(span, filter);+ if (OpenlitConfig.captureMessageContent) {+ span.setAttribute(SemanticConvention.DB_QUERY_TEXT, AstraWrapper._safeStringify(update));+ }++ const returnedRows = AstraWrapper._getUpdateReturnedRows(response);+ if (returnedRows !== undefined) {+ span.setAttribute(SemanticConvention.DB_RESPONSE_RETURNED_ROWS, returnedRows);+ }++ span.setAttribute(+ SemanticConvention.DB_QUERY_SUMMARY,+ `${dbOperation} ${collectionName} filter=${AstraWrapper._summaryValue(filter)} update=${AstraWrapper._summaryValue(update)}`+ );+ }++ private static _setReplaceAttributes(span: any, { dbOperation, collectionName, args }: AstraOperationContext) {+ const filter = args[0] || {};+ const upsert = AstraWrapper._hasUpsertOption(args);++ AstraWrapper._setFilterAttribute(span, filter);+ if (OpenlitConfig.captureMessageContent) {+ span.setAttribute(SemanticConvention.DB_QUERY_TEXT, AstraWrapper._safeStringify(filter));+ }++ span.setAttribute(+ SemanticConvention.DB_QUERY_SUMMARY,+ `${dbOperation} ${collectionName} filter=${AstraWrapper._summaryValue(filter)} upsert=${upsert}`+ );+ }++ private static _setSelectAttributes(span: any, { dbOperation, collectionName, args, response }: AstraOperationContext) {+ const filter = args[0] || {};++ AstraWrapper._setFilterAttribute(span, filter);+ if (OpenlitConfig.captureMessageContent) {+ span.setAttribute(SemanticConvention.DB_QUERY_TEXT, AstraWrapper._safeStringify(filter));+ }++ const returnedRows = AstraWrapper._getSelectReturnedRows(response);+ if (returnedRows !== undefined) {+ span.setAttribute(SemanticConvention.DB_RESPONSE_RETURNED_ROWS, returnedRows);+ }++ span.setAttribute(+ SemanticConvention.DB_QUERY_SUMMARY,+ `${dbOperation} ${collectionName} filter=${AstraWrapper._summaryValue(filter)}`+ );+ }++ private static _setDeleteAttributes(span: any, { dbOperation, collectionName, args, response }: AstraOperationContext) {+ const filter = args[0] || {};++ AstraWrapper._setFilterAttribute(span, filter);+ if (OpenlitConfig.captureMessageContent) {+ span.setAttribute(SemanticConvention.DB_QUERY_TEXT, AstraWrapper._safeStringify(filter));+ }++ const returnedRows = AstraWrapper._getDeleteReturnedRows(response, dbOperation);+ if (returnedRows !== undefined) {+ span.setAttribute(SemanticConvention.DB_RESPONSE_RETURNED_ROWS, returnedRows);+ }++ span.setAttribute(+ SemanticConvention.DB_QUERY_SUMMARY,+ `${dbOperation} ${collectionName} filter=${AstraWrapper._summaryValue(filter)}`+ );+ }++ private static _getActualDbOperation(dbOperation: string, args: any[]) {+ if (dbOperation === SemanticConvention.DB_OPERATION_REPLACE && AstraWrapper._hasUpsertOption(args)) {+ return SemanticConvention.DB_OPERATION_UPSERT;+ }+ return dbOperation;+ }++ private static _hasUpsertOption(args: any[]) {+ return args.slice(2).some((arg) => arg && typeof arg === 'object' && arg.upsert === true);+ }++ private static _setFilterAttribute(span: any, filter: any) {+ if (filter && typeof filter === 'object' && Object.keys(filter).length > 0) {+ span.setAttribute(SemanticConvention.DB_FILTER, AstraWrapper._safeStringify(filter));+ }+ }++ private static _getInsertReturnedRows(response: any): number | undefined {+ if (!response) return undefined;+ if (typeof response.insertedCount === 'number') return response.insertedCount;+ if (typeof response.inserted_count === 'number') return response.inserted_count;+ if (Array.isArray(response.insertedIds)) return response.insertedIds.length;+ if (Array.isArray(response.inserted_ids)) return response.inserted_ids.length;+ if (response.insertedIds && typeof response.insertedIds === 'object') return Object.keys(response.insertedIds).length;+ if (response.inserted_ids && typeof response.inserted_ids === 'object') return Object.keys(response.inserted_ids).length;+ if (response.insertedId || response.inserted_id) return 1;+ return undefined;+ }++ private static _getUpdateReturnedRows(response: any): number | undefined {+ if (!response) return undefined;+ if (typeof response.modifiedCount === 'number') return response.modifiedCount;+ if (typeof response.modified_count === 'number') return response.modified_count;+ if (typeof response.matchedCount === 'number') return response.matchedCount;+ if (typeof response.matched_count === 'number') return response.matched_count;+ if (typeof response.update_info?.nModified === 'number') return response.update_info.nModified;+ if (typeof response.updateInfo?.nModified === 'number') return response.updateInfo.nModified;+ return undefined;+ }++ private static _getSelectReturnedRows(response: any): number | undefined {+ if (!response || AstraWrapper._isCursorLike(response)) return undefined;+ if (Array.isArray(response)) return response.length;+ if (typeof response.length === 'number') return response.length;+ return 1;+ }++ private static _getDeleteReturnedRows(response: any, dbOperation: string): number | undefined {+ if (!response) return dbOperation === SemanticConvention.DB_OPERATION_FIND_AND_DELETE ? 0 : undefined;+ if (typeof response.deletedCount === 'number') return response.deletedCount;+ if (typeof response.deleted_count === 'number') return response.deleted_count;+ if (dbOperation === SemanticConvention.DB_OPERATION_FIND_AND_DELETE) return 1;+ return undefined;+ }++ private static _objectCount(obj: any): number {+ if (Array.isArray(obj)) return obj.length;+ if (obj !== undefined && obj !== null) return 1;+ return 0;+ }++ private static _isCursorLike(response: any): boolean {+ return !!response && (+ typeof response[Symbol.asyncIterator] === 'function'+ || typeof response[Symbol.iterator] === 'function'+ || typeof response.toArray === 'function'+ || typeof response.next === 'function'+ );+ }++ private static _summaryValue(value: any): string {+ return AstraWrapper._truncate(AstraWrapper._safeStringify(value));+ }++ private static _safeStringify(value: any): string {+ if (typeof value === 'string') return value;+ try {+ return JSON.stringify(value);+ } catch {+ return String(value);+ }+ }++ private static _truncate(value: string, maxLength = 200): string {+ return value.length > maxLength ? `${value.slice(0, maxLength)}...` : value;+ }++ private static _getServerAddressAndPort(instance: any): ServerAddressAndPort {+ const endpoint = AstraWrapper._findEndpoint(instance);+ if (!endpoint) return DEFAULT_SERVER;++ return AstraWrapper._parseEndpoint(endpoint);+ }++ private static _findEndpoint(instance: any): string | undefined {+ const candidates = [+ instance,+ instance?.database,+ instance?.db,+ instance?.client,+ instance?._client,+ instance?.database?.client,+ instance?.db?.client,+ ];+ const keys = ['apiEndpoint', 'api_endpoint', 'endpoint', 'baseUrl', 'base_url'];++ for (const candidate of candidates) {+ if (!candidate || typeof candidate !== 'object') continue;+ for (const key of keys) {+ const value = candidate[key];+ if (typeof value === 'string' && value.length > 0) return value;+ }+ }++ return undefined;+ }++ private static _parseEndpoint(endpoint: string): ServerAddressAndPort {+ const fallbackPort = endpoint.startsWith('http://') ? 80 : DEFAULT_SERVER.serverPort;++ try {+ if (endpoint.startsWith('http://') || endpoint.startsWith('https://')) {+ const parsed = new URL(endpoint);+ return {+ serverAddress: parsed.hostname || DEFAULT_SERVER.serverAddress,+ serverPort: parsed.port ? Number(parsed.port) : fallbackPort,+ };+ }+ } catch {+ return DEFAULT_SERVER;+ }++ const [serverAddress, port] = endpoint.split(':');+ return {+ serverAddress: serverAddress || DEFAULT_SERVER.serverAddress,+ serverPort: port ? Number(port) || DEFAULT_SERVER.serverPort : DEFAULT_SERVER.serverPort,+ };+ }+}++export default AstraWrapper;diff --git a/sdk/typescript/src/instrumentation/index.ts b/sdk/typescript/src/instrumentation/index.tsindex c9f57f97..787189fe 100644--- a/sdk/typescript/src/instrumentation/index.ts+++ b/sdk/typescript/src/instrumentation/index.ts@@ -28,6 +28,7 @@ import StrandsInstrumentation from './strands';import GoogleADKInstrumentation from './google-adk';import ClaudeAgentSDKInstrumentation from './claude-agent-sdk';import CursorSDKInstrumentation from './cursor-sdk';+import AstraInstrumentation from './astra';/*** OTel community instrumentations loaded dynamically (like Python SDK).@@ -98,6 +99,7 @@ export default class Instrumentations {'google-adk': new GoogleADKInstrumentation(),'claude-agent-sdk': new ClaudeAgentSDKInstrumentation(),'cursor-sdk': new CursorSDKInstrumentation(),+ 'astra': new AstraInstrumentation(),};static setup(diff --git a/sdk/typescript/src/semantic-convention.ts b/sdk/typescript/src/semantic-convention.tsindex 6bdf0a19..fb13e034 100644--- a/sdk/typescript/src/semantic-convention.ts+++ b/sdk/typescript/src/semantic-convention.ts@@ -271,6 +271,7 @@ export default class SemanticConvention {static DB_SYSTEM_PINECONE = 'pinecone';static DB_SYSTEM_QDRANT = 'qdrant';static DB_SYSTEM_MILVUS = 'milvus';+ static DB_SYSTEM_ASTRA = 'astra';static DB_COLLECTION_NAME = 'db.collection.name';static DB_OPERATION = 'db.operation';static DB_OPERATION_NAME = 'db.operation.name';@@ -285,6 +286,11 @@ export default class SemanticConvention {static DB_OPERATION_PEEK = 'PEEK';static DB_OPERATION_SEARCH = 'SEARCH';static DB_OPERATION_FETCH = 'FETCH';+ static DB_OPERATION_CREATE_COLLECTION = 'create_collection';+ static DB_OPERATION_DELETE_COLLECTION = 'delete_collection';+ static DB_OPERATION_SELECT = 'SELECT';+ static DB_OPERATION_REPLACE = 'findAndModify';+ static DB_OPERATION_FIND_AND_DELETE = 'findAndDelete';static DB_ID_COUNT = 'db.ids_count';static DB_VECTOR_COUNT = 'db.vector.count';static DB_METADATA_COUNT = 'db.metadatas_count';diff --git a/sdk/typescript/src/types.ts b/sdk/typescript/src/types.tsindex 26f82151..3e082012 100644--- a/sdk/typescript/src/types.ts+++ b/sdk/typescript/src/types.ts@@ -3,7 +3,7 @@ import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node';import { metrics } from '@opentelemetry/api';import type { Guard } from './guard/base';-export type InstrumentationType = 'openai' | 'anthropic' | 'cohere' | 'groq' | 'mistral' | 'google-ai' | 'together' | 'ollama' | 'vercel-ai' | 'langchain' | 'langgraph' | 'pinecone' | 'bedrock' | 'llamaindex' | 'huggingface' | 'replicate' | 'chroma' | 'qdrant' | 'milvus' | 'azure-ai-inference' | 'openai-agents' | 'strands' | 'google-adk' | 'claude-agent-sdk' | 'cursor-sdk' | 'ai21';+export type InstrumentationType = 'openai' | 'anthropic' | 'cohere' | 'groq' | 'mistral' | 'google-ai' | 'together' | 'ollama' | 'vercel-ai' | 'langchain' | 'langgraph' | 'pinecone' | 'bedrock' | 'llamaindex' | 'huggingface' | 'replicate' | 'chroma' | 'qdrant' | 'milvus' | 'astra' | 'azure-ai-inference' | 'openai-agents' | 'strands' | 'google-adk' | 'claude-agent-sdk' | 'cursor-sdk' | 'ai21';export type OpenlitInstrumentations = Partial<Record<InstrumentationType, any>>;diff --git a/sdk/typescript/tsconfig.tsbuildinfo b/sdk/typescript/tsconfig.tsbuildinfodeleted file mode 100644index 97e8c297..00000000--- a/sdk/typescript/tsconfig.tsbuildinfo+++ /dev/null@@ -1 +0,0 @@-{"root":["./src/config.ts","./src/constant.ts","./src/helpers.ts","./src/index.ts","./src/prompt-hub.ts","./src/semantic-convention.ts","./src/types.ts","./src/evals/all.ts","./src/evals/base.ts","./src/evals/bias.ts","./src/evals/hallucination.ts","./src/evals/index.ts","./src/evals/metrics.ts","./src/evals/toxicity.ts","./src/evals/types.ts","./src/evals/utils.ts","./src/evals/__tests__/anthropic.test.ts","./src/evals/__tests__/base.test.ts","./src/evals/__tests__/core.test.ts","./src/evals/__tests__/metrics.test.ts","./src/evals/__tests__/openai.test.ts","./src/evals/__tests__/providers.test.ts","./src/evals/__tests__/utils.test.ts","./src/evals/llm/anthropic.ts","./src/evals/llm/openai.ts","./src/evals/llm/providers.ts","./src/features/base.ts","./src/features/prompt-hub.ts","./src/features/rule-engine.ts","./src/features/vault.ts","./src/features/__tests__/rule-engine.test.ts","./src/guard/all.ts","./src/guard/base.ts","./src/guard/index.ts","./src/guard/prompt-injection.ts","./src/guard/sensitive-topic.ts","./src/guard/topic-restriction.ts","./src/guard/types.ts","./src/guard/utils.ts","./src/guard/__tests__/gaurd.test.ts","./src/guard/__tests__/utils.test.ts","./src/instrumentation/base-wrapper.ts","./src/instrumentation/index.ts","./src/instrumentation/__tests__/anthropic-wrapper.test.ts","./src/instrumentation/__tests__/base-wrapper.test.ts","./src/instrumentation/__tests__/bedrock-trace-comparison.test.ts","./src/instrumentation/__tests__/chroma-trace-comparison.test.ts","./src/instrumentation/__tests__/cohere-wrapper.test.ts","./src/instrumentation/__tests__/google-ai-trace-comparison.test.ts","./src/instrumentation/__tests__/groq-trace-comparison.test.ts","./src/instrumentation/__tests__/huggingface-trace-comparison.test.ts","./src/instrumentation/__tests__/langchain-wrapper.test.ts","./src/instrumentation/__tests__/milvus-trace-comparison.test.ts","./src/instrumentation/__tests__/mistral-trace-comparison.test.ts","./src/instrumentation/__tests__/openai-wrapper.test.ts","./src/instrumentation/__tests__/qdrant-trace-comparison.test.ts","./src/instrumentation/__tests__/replicate-trace-comparison.test.ts","./src/instrumentation/__tests__/together-trace-comparison.test.ts","./src/instrumentation/__tests__/trace-comparison-utils.ts","./src/instrumentation/__tests__/vercel-ai-trace-comparison.test.ts","./src/instrumentation/anthropic/index.ts","./src/instrumentation/anthropic/wrapper.ts","./src/instrumentation/azure-ai-inference/index.ts","./src/instrumentation/azure-ai-inference/wrapper.ts","./src/instrumentation/bedrock/index.ts","./src/instrumentation/bedrock/wrapper.ts","./src/instrumentation/chroma/index.ts","./src/instrumentation/chroma/wrapper.ts","./src/instrumentation/claude-agent-sdk/index.ts","./src/instrumentation/claude-agent-sdk/wrapper.ts","./src/instrumentation/cohere/index.ts","./src/instrumentation/cohere/wrapper.ts","./src/instrumentation/google-adk/index.ts","./src/instrumentation/google-adk/utils.ts","./src/instrumentation/google-adk/wrapper.ts","./src/instrumentation/google-ai/index.ts","./src/instrumentation/google-ai/wrapper.ts","./src/instrumentation/groq/index.ts","./src/instrumentation/groq/wrapper.ts","./src/instrumentation/huggingface/index.ts","./src/instrumentation/huggingface/wrapper.ts","./src/instrumentation/langchain/index.ts","./src/instrumentation/langchain/wrapper.ts","./src/instrumentation/langgraph/index.ts","./src/instrumentation/langgraph/wrapper.ts","./src/instrumentation/llamaindex/index.ts","./src/instrumentation/llamaindex/wrapper.ts","./src/instrumentation/milvus/index.ts","./src/instrumentation/milvus/wrapper.ts","./src/instrumentation/mistral/index.ts","./src/instrumentation/mistral/wrapper.ts","./src/instrumentation/ollama/index.ts","./src/instrumentation/ollama/wrapper.ts","./src/instrumentation/openai/index.ts","./src/instrumentation/openai/wrapper.ts","./src/instrumentation/openai-agents/index.ts","./src/instrumentation/openai-agents/processor.ts","./src/instrumentation/openai-agents/utils.ts","./src/instrumentation/pinecone/index.ts","./src/instrumentation/pinecone/wrapper.ts","./src/instrumentation/qdrant/index.ts","./src/instrumentation/qdrant/wrapper.ts","./src/instrumentation/replicate/index.ts","./src/instrumentation/replicate/wrapper.ts","./src/instrumentation/strands/index.ts","./src/instrumentation/strands/processor.ts","./src/instrumentation/strands/utils.ts","./src/instrumentation/together/index.ts","./src/instrumentation/together/wrapper.ts","./src/instrumentation/vercel-ai/index.ts","./src/instrumentation/vercel-ai/wrapper.ts","./src/llm/anthropic.ts","./src/llm/index.ts","./src/llm/openai.ts","./src/llm/providers.ts","./src/otel/events.ts","./src/otel/metrics.ts","./src/otel/tracing.ts","./src/otel/utils.ts","./src/otel/__tests__/metrics.test.ts"],"version":"5.8.3"}\ No newline at end of file