Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@
"webpack-cli": "^5.1.4"
},
"dependencies": {
"buffer": "^6.0.3"
"buffer": "^6.0.3",
"nanoid": "^5.1.5"
}
}
76 changes: 62 additions & 14 deletions src/AnamClient.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { nanoid } from 'nanoid';
import { ClientError, ErrorCode } from './lib/ClientError';
import {
ClientError,
ClientMetricMeasurement,
DEFAULT_ANAM_API_VERSION,
DEFAULT_ANAM_METRICS_BASE_URL,
ErrorCode,
setErrorMetricsBaseUrl,
setCurrentSessionInfo,
} from './lib/ClientError';
setClientMetricsBaseUrl,
sendClientMetric,
setMetricsContext,
} from './lib/ClientMetrics';
import {
CoreApiRestClient,
InternalEventEmitter,
Expand All @@ -21,6 +23,7 @@ import {
PersonaConfig,
StartSessionOptions,
StartSessionResponse,
ConnectionClosedCode,
} from './types';
import { TalkMessageStream } from './types/TalkMessageStream';
import { Buffer } from 'buffer';
Expand Down Expand Up @@ -64,7 +67,7 @@ export default class AnamClient {
this.clientOptions = options;

if (options?.api?.baseUrl || options?.api?.apiVersion) {
setErrorMetricsBaseUrl(
setClientMetricsBaseUrl(
options.api.baseUrl || DEFAULT_ANAM_METRICS_BASE_URL,
options.api.apiVersion || DEFAULT_ANAM_API_VERSION,
);
Expand Down Expand Up @@ -114,7 +117,9 @@ export default class AnamClient {
if (sessionToken) {
const decodedToken = this.decodeJwt(sessionToken);
this.organizationId = decodedToken.accountId;
setCurrentSessionInfo(this.sessionId, this.organizationId);
setMetricsContext({
organizationId: this.organizationId,
});

const tokenType = decodedToken.type?.toLowerCase();

Expand Down Expand Up @@ -187,6 +192,11 @@ export default class AnamClient {
const { heartbeatIntervalSeconds, maxWsReconnectionAttempts, iceServers } =
clientConfig;

this.sessionId = sessionId;
setMetricsContext({
sessionId: this.sessionId,
});

try {
this.streamingClient = new StreamingClient(
sessionId,
Expand All @@ -212,11 +222,22 @@ export default class AnamClient {
audioDeviceId: this.clientOptions?.audioDeviceId,
disableInputAudio: this.clientOptions?.disableInputAudio,
},
metrics: {
showPeerConnectionStatsReport:
this.clientOptions?.metrics?.showPeerConnectionStatsReport ??
false,
peerConnectionStatsReportOutputFormat:
this.clientOptions?.metrics
?.peerConnectionStatsReportOutputFormat ?? 'console',
},
},
this.publicEventEmitter,
this.internalEventEmitter,
);
} catch (error) {
setMetricsContext({
sessionId: null,
});
throw new ClientError(
'Failed to initialize streaming client',
ErrorCode.CLIENT_ERROR_CODE_SERVER_ERROR,
Expand All @@ -228,8 +249,6 @@ export default class AnamClient {
);
}

this.sessionId = sessionId;
setCurrentSessionInfo(this.sessionId, this.organizationId);
return sessionId;
}

Expand All @@ -253,15 +272,26 @@ export default class AnamClient {
public async stream(
userProvidedAudioStream?: MediaStream,
): Promise<MediaStream[]> {
if (this._isStreaming) {
throw new Error('Already streaming');
}
// generate a new ID here to track the attempt
const attemptCorrelationId = nanoid();
setMetricsContext({
attemptCorrelationId,
sessionId: null, // reset sessionId
});
sendClientMetric(
ClientMetricMeasurement.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT,
'1',
);
if (this.clientOptions?.disableInputAudio && userProvidedAudioStream) {
console.warn(
'AnamClient:Input audio is disabled. User provided audio stream will be ignored.',
);
}
await this.startSessionIfNeeded(userProvidedAudioStream);
if (this._isStreaming) {
throw new Error('Already streaming');
}

this._isStreaming = true;
return new Promise<MediaStream[]>((resolve) => {
// set stream callbacks to capture the stream
Expand Down Expand Up @@ -311,6 +341,16 @@ export default class AnamClient {
videoElementId: string,
userProvidedAudioStream?: MediaStream,
): Promise<void> {
// generate a new ID here to track the attempt
const attemptCorrelationId = nanoid();
setMetricsContext({
attemptCorrelationId,
sessionId: null, // reset sessionId
});
sendClientMetric(
ClientMetricMeasurement.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT,
'1',
);
if (this.clientOptions?.disableInputAudio && userProvidedAudioStream) {
console.warn(
'AnamClient:Input audio is disabled. User provided audio stream will be ignored.',
Expand Down Expand Up @@ -371,10 +411,18 @@ export default class AnamClient {

public async stopStreaming(): Promise<void> {
if (this.streamingClient) {
this.streamingClient.stopConnection();
this.publicEventEmitter.emit(
AnamEvent.CONNECTION_CLOSED,
ConnectionClosedCode.NORMAL,
);
await this.streamingClient.stopConnection();
this.streamingClient = null;
this.sessionId = null;
setCurrentSessionInfo(null, this.organizationId);
setMetricsContext({
attemptCorrelationId: null,
sessionId: null,
organizationId: this.organizationId,
});
this._isStreaming = false;
}
}
Expand Down
73 changes: 2 additions & 71 deletions src/lib/ClientError.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { CLIENT_METADATA } from './constants';
import { ClientMetricMeasurement, sendClientMetric } from './ClientMetrics';

export enum ErrorCode {
CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED = 'CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED',
Expand All @@ -12,75 +12,6 @@ export enum ErrorCode {
CLIENT_ERROR_CODE_CONFIGURATION_ERROR = 'CLIENT_ERROR_CODE_CONFIGURATION_ERROR',
}

export const DEFAULT_ANAM_METRICS_BASE_URL = 'https://api.anam.ai';
export const DEFAULT_ANAM_API_VERSION = '/v1';

export enum ClientMetricMeasurement {
CLIENT_METRIC_MEASUREMENT_ERROR = 'client_error',
CLIENT_METRIC_MEASUREMENT_CONNECTION_CLOSED = 'client_connection_closed',
CLIENT_METRIC_MEASUREMENT_CONNECTION_ESTABLISHED = 'client_connection_established',
}

let anamCurrentBaseUrl = DEFAULT_ANAM_METRICS_BASE_URL;
let anamCurrentApiVersion = DEFAULT_ANAM_API_VERSION;

let currentSessionId: string | null = null;
let currentOrganizationId: string | null = null;

export const setErrorMetricsBaseUrl = (
baseUrl: string,
apiVersion: string = DEFAULT_ANAM_API_VERSION,
) => {
anamCurrentBaseUrl = baseUrl;
anamCurrentApiVersion = apiVersion;
};

export const setCurrentSessionInfo = (
sessionId: string | null,
organizationId: string | null,
) => {
currentSessionId = sessionId;
currentOrganizationId = organizationId;
};

export const sendErrorMetric = async (
name: string,
value: string,
tags?: Record<string, string | number>,
) => {
try {
const metricTags: Record<string, string | number> = {
...CLIENT_METADATA,
...tags,
};

// Add session and organization IDs if available
if (currentSessionId) {
metricTags.sessionId = currentSessionId;
}
if (currentOrganizationId) {
metricTags.organizationId = currentOrganizationId;
}

await fetch(
`${anamCurrentBaseUrl}${anamCurrentApiVersion}/metrics/client`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
name,
value,
tags: metricTags,
}),
},
);
} catch (error) {
console.error('Failed to send error metric:', error);
}
};

export class ClientError extends Error {
code: ErrorCode;
statusCode: number;
Expand All @@ -101,7 +32,7 @@ export class ClientError extends Error {
Object.setPrototypeOf(this, ClientError.prototype);

// Send error metric when error is created
sendErrorMetric(
sendClientMetric(
ClientMetricMeasurement.CLIENT_METRIC_MEASUREMENT_ERROR,
code,
{
Expand Down
Loading