feat(api-server): add ASR metrics, fix TTS status reporting, and set second-scale histogram buckets

This commit is contained in:
RainbowBird 2026-12-01 18:20:09 +07:00
parent a94f86b704
commit b05f63d439
14 changed files with 832 additions and 36 deletions

View file

@ -298,6 +298,7 @@ export async function buildApp(deps: AppDeps) {
configKV: deps.configKV,
envelopeCrypto: deps.envelopeCrypto,
providerCatalogService: deps.providerCatalogService,
genAi: deps.otel?.genAi,
}))
// Cross-instance config invalidation. The subscriber owns its own

View file

@ -0,0 +1,68 @@
import type { Env } from '../libs/env'
import { metrics } from '@opentelemetry/api'
import { DataPointType, MeterProvider, MetricReader } from '@opentelemetry/sdk-metrics'
import {
METRIC_GEN_AI_CLIENT_INFERENCE_DURATION,
METRIC_GEN_AI_CLIENT_INFERENCE_TIME_TO_FIRST_CHUNK,
METRIC_GEN_AI_CLIENT_OPERATION_DURATION,
} from '@proj-airi/trace-kit/semconv'
import { afterEach, describe, expect, it } from 'vitest'
import { METRIC_AIRI_EMAIL_DURATION } from '../utils/observability'
import { initOtel } from './index'
class TestMetricReader extends MetricReader {
protected async onForceFlush(): Promise<void> {}
protected async onShutdown(): Promise<void> {}
}
describe('initOtel', () => {
let provider: MeterProvider | undefined
afterEach(async () => {
metrics.disable()
await provider?.shutdown()
provider = undefined
})
it('exports second-scale histogram bucket boundaries for GenAI and email duration metrics', async () => {
const reader = new TestMetricReader()
provider = new MeterProvider({ readers: [reader] })
metrics.setGlobalMeterProvider(provider)
const otel = initOtel({
OTEL_EXPORTER_OTLP_ENDPOINT: 'http://collector.example.com:4318',
OTEL_SERVICE_NAME: 'server',
} as Env)
expect(otel).not.toBeNull()
otel!.genAi.timeToFirstChunk.record(0.4)
otel!.genAi.inferenceDuration.record(1.2)
otel!.genAi.operationDuration.record(0.8)
otel!.email.duration.record(0.3)
const { resourceMetrics } = await reader.collect()
const exported = resourceMetrics.scopeMetrics.flatMap(scope => scope.metrics)
const boundariesFor = (name: string) => {
const metric = exported.find(item => item.descriptor.name === name)
expect(metric?.dataPointType).toBe(DataPointType.HISTOGRAM)
if (!metric || metric.dataPointType !== DataPointType.HISTOGRAM)
return []
return metric.dataPoints[0]?.value.buckets.boundaries ?? []
}
const ttfcBounds = boundariesFor(METRIC_GEN_AI_CLIENT_INFERENCE_TIME_TO_FIRST_CHUNK)
const inferenceBounds = boundariesFor(METRIC_GEN_AI_CLIENT_INFERENCE_DURATION)
const operationBounds = boundariesFor(METRIC_GEN_AI_CLIENT_OPERATION_DURATION)
const emailBounds = boundariesFor(METRIC_AIRI_EMAIL_DURATION)
expect(ttfcBounds[0]).toBeLessThan(1)
expect(ttfcBounds).toContain(0.5)
expect(ttfcBounds).toContain(1)
expect(ttfcBounds).toContain(5)
expect(inferenceBounds[0]).toBeLessThan(1)
expect(operationBounds[0]).toBeLessThan(1)
expect(emailBounds[0]).toBeLessThan(1)
})
})

View file

@ -149,7 +149,7 @@ export interface RevenueMetrics {
}
export interface GenAiMetrics {
/** TTS duration. Chat and Responses use `inferenceDuration`. */
/** TTS and ASR operation duration. Chat and Responses use `inferenceDuration`. */
operationDuration: Histogram
inferenceDuration: Histogram
timeToFirstChunk: Histogram
@ -385,19 +385,29 @@ export function initOtel(env: Env): OtelInstance | null {
}),
}
// Explicit second-scale boundaries keep Prometheus P95 interpolation accurate.
// Without advice, @opentelemetry/sdk-metrics falls back to millisecond defaults
// (0, 5, 10, 25, ...), which puts every sub-5s sample in one bucket.
const genAiDurationBoundariesSeconds = [0.05, 0.1, 0.25, 0.5, 1, 2, 3, 5, 8, 12, 20, 30, 60, 120]
const genAiTtfcBoundariesSeconds = [0.05, 0.1, 0.25, 0.5, 0.75, 1, 1.5, 2, 3, 5, 8, 12, 20, 30]
const emailDurationBoundariesSeconds = [0.05, 0.1, 0.25, 0.5, 1, 2, 5, 10]
// GenAI metrics (semconv: gen_ai.client.*)
const genAi: GenAiMetrics = {
operationDuration: meter.createHistogram(METRIC_GEN_AI_CLIENT_OPERATION_DURATION, {
description: 'GenAI client operation duration (TTS)',
description: 'GenAI client operation duration (TTS and ASR)',
unit: 's',
advice: { explicitBucketBoundaries: genAiDurationBoundariesSeconds },
}),
inferenceDuration: meter.createHistogram(METRIC_GEN_AI_CLIENT_INFERENCE_DURATION, {
description: 'GenAI client inference duration (chat and responses)',
unit: 's',
advice: { explicitBucketBoundaries: genAiDurationBoundariesSeconds },
}),
timeToFirstChunk: meter.createHistogram(METRIC_GEN_AI_CLIENT_INFERENCE_TIME_TO_FIRST_CHUNK, {
description: 'Time from request start to the first chunk of a streaming response',
unit: 's',
advice: { explicitBucketBoundaries: genAiTtfcBoundariesSeconds },
}),
inputTokens: meter.createCounter(METRIC_GEN_AI_CLIENT_INFERENCE_USAGE_INPUT_TOKENS, {
description: 'Input (prompt) tokens, including cached tokens',
@ -480,6 +490,7 @@ export function initOtel(env: Env): OtelInstance | null {
duration: meter.createHistogram(METRIC_AIRI_EMAIL_DURATION, {
description: 'Email provider call duration',
unit: 's',
advice: { explicitBucketBoundaries: emailDurationBoundariesSeconds },
}),
}

View file

@ -424,4 +424,75 @@ describe('audio-speech-ws route', () => {
units: 10, // "hello" + "world" = 10 chars
})
})
it('records 503 operation duration metrics when streaming TTS is not configured', async () => {
const deps = makeFakeDeps({ upstreamURL: 'ws://unused', fluxBalance: 100 })
deps.configKV.getOptional = vi.fn(async () => null) as any
const handlers = createAudioSpeechWsHandlers(deps as any)
const events = handlers('user-noconf-metric')
const client = makeMockClientWs()
await driveClientSession(events, client, [
JSON.stringify({ event: 'start', model: 'volcengine/seed-tts-2.0', voice: 'mock' }),
])
expect(deps.genAi.operationDuration.record).toHaveBeenCalledTimes(1)
expect(deps.genAi.operationDuration.record.mock.calls[0][1]).toMatchObject({
'airi.gen_ai.operation.kind': 'tts',
'airi.gen_ai.stream': true,
'http.response.status_code': 503,
'error.type': 'streaming_tts_not_configured',
})
})
it('records 502 operation duration metrics when upstream sends an error event', async () => {
upstream = await startMockUpstream([
{ kind: 'json', payload: { event: 'error', payload: { code: 'upstream_overloaded', message: 'busy' } } },
])
const deps = makeFakeDeps({ upstreamURL: upstream.url, restBaseURL: upstream.restBaseURL, fluxBalance: 100 })
const handlers = createAudioSpeechWsHandlers(deps as any)
const events = handlers('user-upstream-err')
const client = makeMockClientWs()
await driveClientSession(events, client, [
JSON.stringify({ event: 'start', model: 'volcengine/seed-tts-2.0', voice: 'mock' }),
JSON.stringify({ event: 'finish' }),
])
await new Promise(r => setTimeout(r, 150))
expect(deps.genAi.operationDuration.record).toHaveBeenCalledTimes(1)
expect(deps.genAi.operationDuration.record.mock.calls[0][1]).toMatchObject({
'gen_ai.request.model': 'volcengine/seed-tts-2.0',
'airi.gen_ai.operation.kind': 'tts',
'airi.gen_ai.stream': true,
'http.response.status_code': 502,
'error.type': 'upstream_overloaded',
})
events.onClose?.(new Event('close') as any, client.ctx)
})
it('records 499 operation duration metrics when the client closes before completion', async () => {
upstream = await startMockUpstream([])
const deps = makeFakeDeps({ upstreamURL: upstream.url, restBaseURL: upstream.restBaseURL, fluxBalance: 100 })
const handlers = createAudioSpeechWsHandlers(deps as any)
const events = handlers('user-client-cancel')
const client = makeMockClientWs()
await driveClientSession(events, client, [
JSON.stringify({ event: 'start', model: 'volcengine/seed-tts-2.0', voice: 'mock' }),
])
await new Promise(r => setTimeout(r, 100))
events.onClose?.(new Event('close') as any, client.ctx)
expect(deps.genAi.operationDuration.record).toHaveBeenCalledTimes(1)
expect(deps.genAi.operationDuration.record.mock.calls[0][1]).toMatchObject({
'airi.gen_ai.operation.kind': 'tts',
'http.response.status_code': 499,
'error.type': 'client_cancelled',
})
})
})

View file

@ -1,3 +1,4 @@
import type { Attributes } from '@opentelemetry/api'
import type { WSContext } from 'hono/ws'
import type { RawData } from 'ws'
@ -9,8 +10,10 @@ import WebSocket from 'ws'
import { useLogger } from '@guiiai/logg'
import { context as otelContext, SpanStatusCode, trace } from '@opentelemetry/api'
import { ATTR_ERROR_TYPE } from '@opentelemetry/semantic-conventions'
import { ApiError } from '@proj-airi/http-shared'
import {
ATTR_GEN_AI_PROVIDER_NAME,
ATTR_GEN_AI_REQUEST_MODEL,
} from '@proj-airi/trace-kit/semconv'
import { ofetch } from 'ofetch'
@ -97,11 +100,15 @@ export function createSessionState(
let upstreamReady = false
let closed = false
let billed = false
let metricsRecorded = false
let clientClosed = false
let startFrameAccepted = false
let startValidationStarted = false
let dialStarted = false
let totalInputChars = 0
let modelLabel = STREAM_MODEL_LABEL_FALLBACK
let providerLabel = 'unspeech'
let upstreamErrorCode: string | null = null
/**
* Frames the client sent before the upstream finished dialing. Buffered to
* avoid silently dropping the `start` frame; flushed in arrival order once
@ -170,6 +177,7 @@ export function createSessionState(
}
const upstreamURL = upstreamConfig.baseURL
providerLabel = upstreamProviderFromUrl(upstreamURL)
span.setAttribute(AIRI_ATTR_GEN_AI_GATEWAY_UPSTREAM_URL, upstreamURL)
span.setAttribute(AIRI_ATTR_GEN_AI_GATEWAY_KEY_ID, entry.id)
@ -209,6 +217,16 @@ export function createSessionState(
upstream.on('close', (code, reason) => {
log.withFields({ userId, code, reason: reason?.toString() }).debug('upstream ws closed')
if (!billed) {
if (upstreamErrorCode)
recordMetrics(502, upstreamErrorCode)
else if (clientClosed)
recordMetrics(499, 'client_cancelled')
else if (code !== 1000 && code !== 1001)
recordMetrics(502, 'upstream_closed')
else
recordMetrics(200)
}
finalize()
})
@ -216,6 +234,7 @@ export function createSessionState(
log.withError(err).withFields({ userId }).warn('upstream ws error')
span.recordException(err)
span.setStatus({ code: SpanStatusCode.ERROR, message: err.message })
recordMetrics(502, 'upstream_error')
try {
clientWs?.send(JSON.stringify({
event: 'error',
@ -290,6 +309,7 @@ export function createSessionState(
}
catch (err) {
log.withError(err).warn('failed to forward client frame to upstream')
recordMetrics(502, 'upstream_send_failed')
try {
ws.close(1011, 'upstream_send_failed')
}
@ -300,6 +320,9 @@ export function createSessionState(
function handleClientClose() {
if (closed)
return
clientClosed = true
if (dialStarted && !billed)
recordMetrics(499, 'client_cancelled')
// Client dropped — best-effort cancel upstream so the upstream session
// releases its resources. We do not wait for SessionCanceled ack.
if (upstreamWs && upstreamReady) {
@ -353,16 +376,21 @@ export function createSessionState(
// the client-text-frame estimate accumulated in handleClientMessage.
const usageChars = readUsageChars(evt.payload)
const billUnits = usageChars ?? totalInputChars
if (billUnits > 0)
if (billUnits > 0) {
void billSession(billUnits, 'session.finished')
else
}
else {
recordMetrics(200)
finalize()
}
break
}
case 'error': {
const code = typeof evt.payload?.code === 'string' ? evt.payload.code : 'upstream_error'
upstreamErrorCode = code
log.withFields({ userId, code, message: String(evt.payload?.message ?? '') }).warn('upstream sent error event')
span.setStatus({ code: SpanStatusCode.ERROR, message: code })
recordMetrics(502, code)
break
}
// session.started / sentence.* / subtitle — no server-side action, pure
@ -464,19 +492,25 @@ export function createSessionState(
span.setStatus({ code: SpanStatusCode.ERROR, message: 'billing_failed' })
}
recordMetrics()
recordMetrics(200)
finalize()
}
function recordMetrics() {
const attrs = {
function recordMetrics(status: number, errorType?: string) {
if (metricsRecorded)
return
metricsRecorded = true
const attrs: Attributes = {
[ATTR_GEN_AI_REQUEST_MODEL]: modelLabel,
[ATTR_GEN_AI_PROVIDER_NAME]: providerLabel,
[AIRI_ATTR_GEN_AI_OPERATION_KIND]: 'tts',
[AIRI_ATTR_GEN_AI_STREAM]: true,
'http.response.status_code': 200,
'http.response.status_code': status,
}
if (status >= 400)
attrs[ATTR_ERROR_TYPE] = errorType ?? String(status)
opts.genAi?.operationDuration.record((Date.now() - startedAt) / 1000, attrs)
if (firstAudioAt != null)
if (status < 400 && firstAudioAt != null)
opts.genAi?.timeToFirstChunk.record((firstAudioAt - startedAt) / 1000, attrs)
}
@ -498,7 +532,10 @@ export function createSessionState(
function closeWithError(code: number, reason: string) {
if (closed)
return
const status = statusForStreamingTtsError(reason)
span.setAttribute('http.response.status_code', status)
span.setStatus({ code: SpanStatusCode.ERROR, message: reason })
recordMetrics(status, reason)
if (clientWs) {
try {
clientWs.send(JSON.stringify({ event: 'error', code: reason, message: reason }))
@ -516,6 +553,8 @@ export function createSessionState(
function closeWithBlockedPreflight(code: number, reason: string) {
if (closed)
return
span.setAttribute('http.response.status_code', 402)
recordMetrics(402, reason)
if (clientWs) {
try {
clientWs.send(JSON.stringify({ event: 'error', code: reason, message: reason }))
@ -599,3 +638,29 @@ function streamingVoiceId(voice: unknown): string | null {
const id = (voice as { id?: unknown }).id
return typeof id === 'string' && id.length > 0 ? id : null
}
function upstreamProviderFromUrl(upstreamURL: string): string {
try {
return new URL(upstreamURL).hostname || 'unspeech'
}
catch {
return 'unspeech'
}
}
function statusForStreamingTtsError(reason: string): number {
switch (reason) {
case 'invalid_start_frame':
case 'streaming_tts_model_not_enabled':
case 'streaming_tts_voice_not_enabled':
return 400
case 'streaming_tts_not_configured':
case 'config_unavailable':
case 'streaming_tts_voice_catalog_unavailable':
return 503
case 'upstream_send_failed':
return 502
default:
return 500
}
}

View file

@ -3,7 +3,7 @@ import type { AddressInfo } from 'node:net'
import { Buffer } from 'node:buffer'
import { createServer } from 'node:http'
import { afterEach, describe, expect, it } from 'vitest'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { WebSocketServer } from 'ws'
import { createDashScopeFunAsrStreamResponse, joinSentences } from './dashscope-fun-asr-session'
@ -16,7 +16,7 @@ interface MockFunAsr {
close: () => Promise<void>
}
type Behavior = 'success' | 'fail'
type Behavior = 'success' | 'fail' | 'close_early'
async function startMockFunAsr(behavior: Behavior = 'success'): Promise<MockFunAsr> {
const textFrames: string[] = []
@ -27,6 +27,10 @@ async function startMockFunAsr(behavior: Behavior = 'success'): Promise<MockFunA
wss.on('connection', (ws, request) => {
authorization = request.headers.authorization
if (behavior === 'close_early') {
ws.close(1011, 'upstream_down')
return
}
ws.on('message', (data, isBinary) => {
if (isBinary) {
binaryFrames.push(Buffer.from(data as Buffer))
@ -129,13 +133,45 @@ describe('createDashScopeFunAsrStreamResponse', () => {
it('errors the response stream when the task fails', async () => {
upstream = await startMockFunAsr('fail')
const record = vi.fn()
const genAi = { operationDuration: { record } }
const response = createDashScopeFunAsrStreamResponse({
audioStream: streamOf([new Uint8Array(320)]),
credentials: { apiKey: 'sk-test', model: 'bad', websocketURL: upstream.url, maxSentenceSilenceMs: 400 },
genAi,
})
await expect(response.text()).rejects.toThrow('Fun-ASR task failed: InvalidParameter bad model')
expect(record).toHaveBeenCalledTimes(1)
expect(record.mock.calls[0][1]).toMatchObject({
'airi.gen_ai.operation.kind': 'asr',
'gen_ai.provider.name': 'dashscope-fun-asr',
'gen_ai.request.model': 'bad',
'http.response.status_code': 502,
'error.type': 'task_failed',
})
})
it('records 502 upstream_closed_early when the upstream socket drops before task-started', async () => {
upstream = await startMockFunAsr('close_early')
const record = vi.fn()
const genAi = { operationDuration: { record } }
const response = createDashScopeFunAsrStreamResponse({
audioStream: streamOf([new Uint8Array(320)]),
credentials: { apiKey: 'sk-test', model: 'fun-asr-realtime', websocketURL: upstream.url, maxSentenceSilenceMs: 400 },
genAi,
})
await expect(response.text()).rejects.toThrow('Fun-ASR upstream closed early with code 1011')
expect(record).toHaveBeenCalledTimes(1)
expect(record.mock.calls[0][1]).toMatchObject({
'airi.gen_ai.operation.kind': 'asr',
'gen_ai.provider.name': 'dashscope-fun-asr',
'http.response.status_code': 502,
'error.type': 'upstream_closed_early',
})
})
})

View file

@ -1,11 +1,18 @@
import type { AsrErrorType, AsrMetricsSink } from './telemetry'
import { Buffer } from 'node:buffer'
import { randomUUID } from 'node:crypto'
import WebSocket from 'ws'
import { useLogger } from '@guiiai/logg'
import { errorMessageFrom } from '@moeru/std'
import { array, boolean, nullish, number, object, optional, picklist, safeParse, string, unknown } from 'valibot'
import { createAsrSessionTelemetry } from './telemetry'
const logger = useLogger('dashscope-fun-asr').useGlobalConfig()
/** Model Studio realtime inference endpoint in the Singapore region. */
export const DASHSCOPE_INTL_INFERENCE_WS_URL = 'wss://dashscope-intl.aliyuncs.com/api-ws/v1/inference'
export const DASHSCOPE_FUN_ASR_DEFAULT_MODEL = 'fun-asr-realtime'
@ -29,6 +36,7 @@ export interface DashScopeFunAsrCredentials {
interface CreateDashScopeFunAsrStreamResponseOptions {
audioStream: ReadableStream<Uint8Array>
credentials: DashScopeFunAsrCredentials
genAi?: AsrMetricsSink | null
}
const sentenceSchema = object({
@ -153,8 +161,14 @@ async function pipeAudioToUpstream(
* with the full text so far. The stream ends with `transcript.text.done`.
*/
export function createDashScopeFunAsrStreamResponse(options: CreateDashScopeFunAsrStreamResponseOptions): Response {
const telemetry = createAsrSessionTelemetry({
genAi: options.genAi,
provider: 'dashscope-fun-asr',
model: options.credentials.model,
})
let cancelled = false
let finished = false
let started = false
let upstream: WebSocket | undefined
let audioReader: ReadableStreamDefaultReader<Uint8Array> | undefined
@ -165,11 +179,17 @@ export function createDashScopeFunAsrStreamResponse(options: CreateDashScopeFunA
let startMilliseconds: number | undefined
let endMilliseconds = 0
const finish = (error?: Error) => {
const finish = (error?: Error, errorType?: AsrErrorType) => {
if (finished)
return
finished = true
void audioReader?.cancel()
if (error) {
telemetry.fail(errorType ?? 'ws_error', error.message)
}
else if (!cancelled) {
telemetry.complete()
}
if (cancelled)
return
if (error) {
@ -211,6 +231,7 @@ export function createDashScopeFunAsrStreamResponse(options: CreateDashScopeFunA
const event = parsed.output
switch (event.header.event) {
case 'task-started':
started = true
void pipeAudioToUpstream(
options.audioStream,
ws,
@ -220,7 +241,9 @@ export function createDashScopeFunAsrStreamResponse(options: CreateDashScopeFunA
if (!cancelled && !finished && ws.readyState === WebSocket.OPEN)
ws.send(taskMessage('finish-task', taskId, options.credentials))
}, (error: unknown) => {
finish(new Error(errorMessageFrom(error) ?? 'Failed to read audio stream'))
const message = errorMessageFrom(error) ?? 'Failed to read audio stream'
logger.withError(error).warn('Fun-ASR audio stream read failed')
finish(new Error(message), 'audio_read_failed')
ws.close(1011, 'audio_read_failed')
})
break
@ -248,23 +271,38 @@ export function createDashScopeFunAsrStreamResponse(options: CreateDashScopeFunA
finish()
ws.close(1000, 'completed')
break
case 'task-failed':
finish(new Error(`Fun-ASR task failed: ${event.header.error_code ?? 'unknown'} ${event.header.error_message ?? ''}`.trim()))
case 'task-failed': {
const error = new Error(`Fun-ASR task failed: ${event.header.error_code ?? 'unknown'} ${event.header.error_message ?? ''}`.trim())
logger.withFields({
model: options.credentials.model,
errorCode: event.header.error_code,
errorMessage: event.header.error_message,
}).warn('Fun-ASR task failed')
finish(error, 'task_failed')
ws.close(1000, 'task_failed')
break
}
}
})
ws.on('error', (error) => {
finish(error)
logger.withError(error).withFields({ model: options.credentials.model }).warn('Fun-ASR upstream websocket error')
finish(error, 'ws_error')
})
ws.on('close', () => {
ws.on('close', (code) => {
if (!finished && !cancelled && (!started || (code !== 1000 && code !== 1001))) {
const error = new Error(`Fun-ASR upstream closed early with code ${code}`)
logger.withFields({ model: options.credentials.model, code, started }).warn('Fun-ASR upstream closed early')
finish(error, 'upstream_closed_early')
return
}
finish()
})
},
cancel() {
cancelled = true
telemetry.cancel()
if (audioReader)
void audioReader.cancel()
else if (!options.audioStream.locked)

View file

@ -1,3 +1,7 @@
import type { Context } from 'hono'
import type { Database } from '../../libs/db'
import type { Env } from '../../libs/env'
import type { RouterConfig } from '../../services/domain/llm-router/types'
import type { ProviderCatalogService } from '../../services/domain/provider-catalog'
@ -7,7 +11,7 @@ import { ApiError } from '@proj-airi/http-shared'
import { describe, expect, it, vi } from 'vitest'
import { createEnvelopeCrypto } from '../../utils/envelope-crypto'
import { resolveOfficialAliyunNlsCredentials, resolveOfficialAsrRouteFromConfig, resolveOfficialDashScopeFunAsrCredentials } from './route'
import { createAudioTranscriptionStreamHandler, resolveOfficialAliyunNlsCredentials, resolveOfficialAsrRouteFromConfig, resolveOfficialDashScopeFunAsrCredentials } from './route'
function createRouterConfig(overrides?: Partial<RouterConfig>): RouterConfig {
return {
@ -232,3 +236,88 @@ describe('resolveOfficialDashScopeFunAsrCredentials', () => {
})).resolves.toMatchObject({ provider: 'dashscope-fun-asr', credentials: { apiKey: 'sk-test' } })
})
})
describe('createAudioTranscriptionStreamHandler', () => {
function mockContext() {
return Object.assign({} as Context, {
req: {
raw: new Request('http://localhost/api/v1/audio/transcriptions/stream', {
method: 'POST',
body: new Uint8Array([1, 2, 3]),
}),
},
})
}
const resolveAuth = vi.fn(async () => ({ user: { id: 'user-1' } }) as never)
it('throws 502 and records token_error before returning HTTP 200 when Aliyun NLS token creation fails', async () => {
const envelope = createEnvelopeCrypto({ masterKey: Buffer.alloc(32, 7) })
const ciphertext = envelope.encryptKey('secret', { modelName: 'aliyun/asr-primary', keyEntryId: 'nls-1' })
const routerConfig = createRouterConfig({
asr: {
models: {
'aliyun/asr-primary': {
provider: 'aliyun-nls',
upstreams: [{
keys: [{ id: 'nls-1', ciphertext }],
adapterParams: { accessKeyId: 'ak', appKey: 'app', region: 'cn-shanghai' },
}],
},
},
},
})
const record = vi.fn()
const handler = createAudioTranscriptionStreamHandler({
db: {} as Database,
env: {} as Env,
configKV: { getOptional: vi.fn(async () => routerConfig) } as never,
envelopeCrypto: envelope,
providerCatalogService: createProviderCatalogService('aliyun/asr-primary'),
genAi: { operationDuration: { record } },
resolveAuth,
createAliyunToken: async () => {
throw new Error('nls-meta 500')
},
})
await expect(handler(mockContext())).rejects.toMatchObject({
statusCode: 502,
errorCode: 'BAD_GATEWAY',
})
expect(record).toHaveBeenCalledTimes(1)
expect(record.mock.calls[0][1]).toMatchObject({
'airi.gen_ai.operation.kind': 'asr',
'gen_ai.provider.name': 'aliyun-nls',
'gen_ai.request.model': 'aliyun/asr-primary',
'http.response.status_code': 502,
'error.type': 'token_error',
})
})
it('throws 503 and records config_not_set when ASR is not configured', async () => {
const envelope = createEnvelopeCrypto({ masterKey: Buffer.alloc(32, 7) })
const record = vi.fn()
const handler = createAudioTranscriptionStreamHandler({
db: {} as Database,
env: {} as Env,
configKV: { getOptional: vi.fn(async () => createRouterConfig()) } as never,
envelopeCrypto: envelope,
providerCatalogService: createProviderCatalogService(),
genAi: { operationDuration: { record } },
resolveAuth,
})
await expect(handler(mockContext())).rejects.toMatchObject({
statusCode: 503,
errorCode: 'CONFIG_NOT_SET',
})
expect(record).toHaveBeenCalledTimes(1)
expect(record.mock.calls[0][1]).toMatchObject({
'airi.gen_ai.operation.kind': 'asr',
'gen_ai.provider.name': 'unknown',
'http.response.status_code': 503,
'error.type': 'config_not_set',
})
})
})

View file

@ -6,14 +6,20 @@ import type { ConfigKVService } from '../../services/adapters/config-kv'
import type { RouterConfig } from '../../services/domain/llm-router/types'
import type { ProviderCatalogService } from '../../services/domain/provider-catalog'
import type { EnvelopeCrypto } from '../../utils/envelope-crypto'
import type { AliyunNlsCredentials, AliyunNlsToken } from './session'
import type { AsrMetricsSink } from './telemetry'
import { createServiceUnavailableError, createUnauthorizedError } from '@proj-airi/http-shared'
import { useLogger } from '@guiiai/logg'
import { createBadGatewayError, createServiceUnavailableError, createUnauthorizedError } from '@proj-airi/http-shared'
import { integer, maxValue, minValue, number, object, optional, pipe, safeParse, string, trim, url } from 'valibot'
import { resolveRequestAuth } from '../../libs/request-auth'
import { createKeyRotator } from '../../services/domain/llm-router/key-rotator'
import { createDashScopeFunAsrStreamResponse, DASHSCOPE_FUN_ASR_DEFAULT_MODEL, DASHSCOPE_FUN_ASR_DEFAULT_SENTENCE_SILENCE_MS, DASHSCOPE_INTL_INFERENCE_WS_URL } from './dashscope-fun-asr-session'
import { createAliyunNlsStreamResponse } from './session'
import { createAliyunNlsStreamResponse, createAliyunNlsToken } from './session'
import { recordAsrOperation } from './telemetry'
const logger = useLogger('audio-transcription-stream').useGlobalConfig()
type AliyunNlsRegion = 'cn-shanghai' | 'cn-shanghai-internal' | 'cn-beijing' | 'cn-beijing-internal' | 'cn-shenzhen' | 'cn-shenzhen-internal'
@ -164,11 +170,11 @@ export async function resolveOfficialAsrRouteFromConfig(input: {
const funAsr = resolveOfficialDashScopeFunAsrCredentials(routerConfig, input.envelopeCrypto, modelName)
if (funAsr)
return { provider: 'dashscope-fun-asr' as const, credentials: funAsr }
return { provider: 'dashscope-fun-asr' as const, modelName, credentials: funAsr }
const nls = resolveOfficialAliyunNlsCredentials(routerConfig, input.envelopeCrypto, modelName)
if (nls)
return { provider: 'aliyun-nls' as const, credentials: nls }
return { provider: 'aliyun-nls' as const, modelName, credentials: nls }
return null
}
@ -191,9 +197,14 @@ export function createAudioTranscriptionStreamHandler(input: {
configKV: ConfigKVService
envelopeCrypto: EnvelopeCrypto
providerCatalogService: ProviderCatalogService
genAi?: AsrMetricsSink | null
resolveAuth?: typeof resolveRequestAuth
createAliyunToken?: (credentials: AliyunNlsCredentials) => Promise<AliyunNlsToken>
}) {
return async function handleAudioTranscriptionStream(c: Context) {
const session = await resolveRequestAuth(
const startedAt = Date.now()
const authenticate = input.resolveAuth ?? resolveRequestAuth
const session = await authenticate(
input.db,
input.env,
c.req.raw.headers,
@ -202,8 +213,16 @@ export function createAudioTranscriptionStreamHandler(input: {
throw createUnauthorizedError()
const asrRoute = await resolveOfficialAsrRouteFromConfig(input)
if (!asrRoute)
if (!asrRoute) {
recordAsrOperation(input.genAi, {
provider: 'unknown',
model: OFFICIAL_ASR_MODEL_NAME,
status: 503,
durationMs: Date.now() - startedAt,
errorType: 'config_not_set',
})
throw createServiceUnavailableError('Official ASR transcription is not configured in the ASR capability catalog', 'CONFIG_NOT_SET')
}
const audioStream = c.req.raw.body
if (!audioStream)
@ -213,12 +232,35 @@ export function createAudioTranscriptionStreamHandler(input: {
return createDashScopeFunAsrStreamResponse({
audioStream: audioStream as ReadableStream<Uint8Array>,
credentials: asrRoute.credentials,
genAi: input.genAi,
})
}
// Acquire the Aliyun NLS token before returning the HTTP 200 SSE header.
// A token failure then returns HTTP 502 instead of a broken 200 stream.
let token: AliyunNlsToken
try {
const createToken = input.createAliyunToken ?? createAliyunNlsToken
token = await createToken(asrRoute.credentials)
}
catch (error) {
logger.withError(error).withFields({ region: asrRoute.credentials.region }).warn('Failed to create Aliyun NLS token before ASR stream start')
recordAsrOperation(input.genAi, {
provider: 'aliyun-nls',
model: asrRoute.modelName,
status: 502,
durationMs: Date.now() - startedAt,
errorType: 'token_error',
})
throw createBadGatewayError('Failed to start official ASR transcription session')
}
return createAliyunNlsStreamResponse({
audioStream: audioStream as ReadableStream<Uint8Array>,
credentials: asrRoute.credentials,
token,
genAi: input.genAi,
modelName: asrRoute.modelName,
})
}
}

View file

@ -16,7 +16,7 @@ interface MockAliyunUpstream {
close: () => Promise<void>
}
async function startMockAliyunUpstream(): Promise<MockAliyunUpstream> {
async function startMockAliyunUpstream(behavior: 'success' | 'task_failed' = 'success'): Promise<MockAliyunUpstream> {
const receivedTextFrames: string[] = []
const receivedBinaryFrames: Buffer[] = []
const httpServer = createServer()
@ -33,6 +33,12 @@ async function startMockAliyunUpstream(): Promise<MockAliyunUpstream> {
receivedTextFrames.push(text)
const parsed = JSON.parse(text) as { header?: { name?: string } }
if (parsed.header?.name === 'StartTranscription') {
if (behavior === 'task_failed') {
ws.send(JSON.stringify({
header: { name: 'TaskFailed', status: 40000001, status_text: 'Invalid token' },
}))
return
}
ws.send(JSON.stringify({
header: { name: 'TranscriptionStarted' },
payload: { session_id: 'mock-session' },
@ -169,4 +175,92 @@ describe('createAliyunNlsStreamResponse', () => {
await vi.waitFor(() => expect(upstream?.activeConnections()).toBe(0))
expect(cancelInput).toHaveBeenCalledOnce()
})
it('records 200 ASR operation metrics on completion and 499 on client cancel', async () => {
upstream = await startMockAliyunUpstream()
const record = vi.fn()
const genAi = { operationDuration: { record } }
const response = createAliyunNlsStreamResponse({
audioStream: streamOf([Buffer.from([1, 2])]),
credentials: { accessKeyId: 'ak', accessKeySecret: 'secret', appKey: 'app', region: 'cn-shanghai' },
token: { token: 'pre-acquired-token', expiresAt: Date.now() + 3600_000 },
websocketBaseURL: upstream.url,
genAi,
modelName: 'aliyun/asr-primary',
})
await readText(response.body!)
expect(record).toHaveBeenCalledTimes(1)
expect(record.mock.calls[0][1]).toMatchObject({
'airi.gen_ai.operation.kind': 'asr',
'gen_ai.provider.name': 'aliyun-nls',
'gen_ai.request.model': 'aliyun/asr-primary',
'http.response.status_code': 200,
})
const cancelResponse = createAliyunNlsStreamResponse({
audioStream: new ReadableStream<Uint8Array>(),
credentials: { accessKeyId: 'ak', accessKeySecret: 'secret', appKey: 'app', region: 'cn-shanghai' },
token: { token: 'pre-acquired-token', expiresAt: Date.now() + 3600_000 },
websocketBaseURL: upstream.url,
genAi,
modelName: 'aliyun/asr-primary',
})
await cancelResponse.body!.getReader().cancel()
expect(record).toHaveBeenCalledTimes(2)
expect(record.mock.calls[1][1]).toMatchObject({
'airi.gen_ai.operation.kind': 'asr',
'gen_ai.provider.name': 'aliyun-nls',
'http.response.status_code': 499,
'error.type': 'client_cancelled',
})
})
it('records 502 task_failed when Aliyun NLS emits TaskFailed', async () => {
upstream = await startMockAliyunUpstream('task_failed')
const record = vi.fn()
const genAi = { operationDuration: { record } }
const response = createAliyunNlsStreamResponse({
audioStream: streamOf([Buffer.from([1, 2])]),
credentials: { accessKeyId: 'ak', accessKeySecret: 'secret', appKey: 'app', region: 'cn-shanghai' },
token: { token: 'bad-token', expiresAt: Date.now() + 3600_000 },
websocketBaseURL: upstream.url,
genAi,
})
await expect(readText(response.body!)).rejects.toThrow('Aliyun NLS task failed: Invalid token')
expect(record).toHaveBeenCalledTimes(1)
expect(record.mock.calls[0][1]).toMatchObject({
'airi.gen_ai.operation.kind': 'asr',
'gen_ai.provider.name': 'aliyun-nls',
'http.response.status_code': 502,
'error.type': 'task_failed',
})
})
it('records 502 token_error when createToken rejects inside the stream', async () => {
const record = vi.fn()
const genAi = { operationDuration: { record } }
const response = createAliyunNlsStreamResponse({
audioStream: streamOf([Buffer.from([1, 2])]),
credentials: { accessKeyId: 'ak', accessKeySecret: 'secret', appKey: 'app', region: 'cn-shanghai' },
createToken: async () => {
throw new Error('nls-meta unreachable')
},
genAi,
})
await expect(readText(response.body!)).rejects.toThrow('nls-meta unreachable')
expect(record).toHaveBeenCalledTimes(1)
expect(record.mock.calls[0][1]).toMatchObject({
'airi.gen_ai.operation.kind': 'asr',
'gen_ai.provider.name': 'aliyun-nls',
'http.response.status_code': 502,
'error.type': 'token_error',
})
})
})

View file

@ -1,20 +1,27 @@
import type { AsrMetricsSink } from './telemetry'
import { createHmac, randomUUID } from 'node:crypto'
import WebSocket from 'ws'
import { merge } from '@moeru/std'
import { useLogger } from '@guiiai/logg'
import { errorMessageFrom, merge } from '@moeru/std'
import { ofetch } from 'ofetch'
import { createAsrSessionTelemetry } from './telemetry'
const logger = useLogger('aliyun-nls-asr').useGlobalConfig()
type AliyunNlsRegion = 'cn-shanghai' | 'cn-shanghai-internal' | 'cn-beijing' | 'cn-beijing-internal' | 'cn-shenzhen' | 'cn-shenzhen-internal'
interface AliyunNlsCredentials {
export interface AliyunNlsCredentials {
accessKeyId: string
accessKeySecret: string
appKey: string
region: AliyunNlsRegion
}
interface AliyunNlsToken {
export interface AliyunNlsToken {
token: string
expiresAt: number
}
@ -32,6 +39,8 @@ interface AliyunNlsStartPayload {
interface AliyunNlsServerEvent {
header?: {
name?: string
status?: number
status_text?: string
}
payload?: {
result?: string
@ -41,9 +50,12 @@ interface AliyunNlsServerEvent {
interface CreateAliyunNlsStreamResponseOptions {
audioStream: ReadableStream<Uint8Array>
credentials: AliyunNlsCredentials
token?: AliyunNlsToken
createToken?: (credentials: AliyunNlsCredentials) => Promise<AliyunNlsToken>
sessionOptions?: AliyunNlsStartPayload
websocketBaseURL?: string
genAi?: AsrMetricsSink | null
modelName?: string
}
const encoder = new TextEncoder()
@ -99,7 +111,10 @@ function aliyunTimestamp(date: Date): string {
return date.toISOString().replace(/\.\d{3}Z$/, 'Z')
}
async function createAliyunNlsToken(credentials: AliyunNlsCredentials): Promise<AliyunNlsToken> {
/**
* Requests a short-lived Aliyun NLS token for a realtime transcription session.
*/
export async function createAliyunNlsToken(credentials: AliyunNlsCredentials): Promise<AliyunNlsToken> {
const params: Record<string, string> = {
AccessKeyId: credentials.accessKeyId,
Action: 'CreateToken',
@ -183,14 +198,37 @@ async function writeAudioToUpstream(
* - A `text/event-stream` response consumable by the shared `streamTranscription` adapter.
*/
export function createAliyunNlsStreamResponse(options: CreateAliyunNlsStreamResponseOptions): Response {
const telemetry = createAsrSessionTelemetry({
genAi: options.genAi,
provider: 'aliyun-nls',
model: options.modelName ?? 'aliyun-nls',
})
let cancelled = false
let finished = false
let started = false
let upstream: WebSocket | undefined
let audioReader: ReadableStreamDefaultReader<Uint8Array> | undefined
const body = new ReadableStream<Uint8Array>({
async start(controller) {
const createToken = options.createToken ?? createAliyunNlsToken
const token = await createToken(options.credentials)
let token: AliyunNlsToken
try {
if (options.token) {
token = options.token
}
else {
const createToken = options.createToken ?? createAliyunNlsToken
token = await createToken(options.credentials)
}
}
catch (error) {
const message = errorMessageFrom(error) ?? 'Failed to create Aliyun NLS token'
logger.withError(error).warn('Aliyun NLS token creation failed inside stream')
telemetry.fail('token_error', message)
finished = true
if (!cancelled)
controller.error(error instanceof Error ? error : new Error(message))
return
}
if (cancelled)
return
const sessionId = randomUUID().replaceAll('-', '')
@ -214,6 +252,7 @@ export function createAliyunNlsStreamResponse(options: CreateAliyunNlsStreamResp
const event = JSON.parse(data.toString()) as AliyunNlsServerEvent
switch (event.header?.name) {
case 'TranscriptionStarted':
started = true
void writeAudioToUpstream(
options.audioStream,
ws,
@ -224,6 +263,9 @@ export function createAliyunNlsStreamResponse(options: CreateAliyunNlsStreamResp
).catch((error) => {
if (cancelled || finished)
return
const message = errorMessageFrom(error) ?? 'Failed to read audio stream'
logger.withError(error).warn('Aliyun NLS audio stream read failed')
telemetry.fail('audio_read_failed', message)
finished = true
controller.error(error)
ws.close(1011, 'audio_read_failed')
@ -238,25 +280,46 @@ export function createAliyunNlsStreamResponse(options: CreateAliyunNlsStreamResp
}
case 'TranscriptionCompleted':
finished = true
telemetry.complete()
void audioReader?.cancel()
controller.close()
ws.close(1000, 'completed')
break
case 'TaskFailed': {
const detail = event.header.status_text || String(event.header.status ?? 'unknown')
const error = new Error(`Aliyun NLS task failed: ${detail}`)
logger.withFields({ status: event.header.status, detail }).warn('Aliyun NLS task failed')
finished = true
telemetry.fail('task_failed', error.message)
void audioReader?.cancel()
controller.error(error)
ws.close(1000, 'task_failed')
break
}
}
})
ws.on('error', (error) => {
logger.withError(error).warn('Aliyun NLS upstream websocket error')
finished = true
telemetry.fail('ws_error', error.message)
void audioReader?.cancel()
if (!cancelled)
controller.error(error)
})
ws.on('close', () => {
ws.on('close', (code) => {
const wasFinished = finished
finished = true
void audioReader?.cancel()
if (cancelled)
return
if (!wasFinished) {
if (!started || (code !== 1000 && code !== 1001))
telemetry.fail('upstream_closed_early', `Aliyun NLS closed with code ${code}`)
else
telemetry.complete()
}
try {
controller.close()
}
@ -265,6 +328,7 @@ export function createAliyunNlsStreamResponse(options: CreateAliyunNlsStreamResp
},
cancel() {
cancelled = true
telemetry.cancel()
if (audioReader)
void audioReader.cancel()
else if (!options.audioStream.locked)

View file

@ -0,0 +1,99 @@
import type { Attributes } from '@opentelemetry/api'
import type { GenAiMetrics } from '../../otel'
import { SpanStatusCode, trace } from '@opentelemetry/api'
import { ATTR_ERROR_TYPE } from '@opentelemetry/semantic-conventions'
import {
ATTR_GEN_AI_PROVIDER_NAME,
ATTR_GEN_AI_REQUEST_MODEL,
} from '@proj-airi/trace-kit/semconv'
import { AIRI_ATTR_GEN_AI_OPERATION_KIND } from '../../utils/observability'
export type AsrProvider = 'aliyun-nls' | 'dashscope-fun-asr' | 'unknown'
export type AsrErrorType
= | 'config_not_set'
| 'token_error'
| 'ws_error'
| 'task_failed'
| 'audio_read_failed'
| 'upstream_closed_early'
| 'client_cancelled'
export type AsrMetricsSink = Pick<GenAiMetrics, 'operationDuration'>
const tracer = trace.getTracer('audio-transcription-stream')
/**
* Records a completed or failed ASR operation on the shared GenAI duration histogram.
*/
export function recordAsrOperation(
genAi: AsrMetricsSink | null | undefined,
input: {
provider: AsrProvider
model: string
status: number
durationMs: number
errorType?: AsrErrorType
},
): void {
if (!genAi)
return
const attrs: Attributes = {
[ATTR_GEN_AI_REQUEST_MODEL]: input.model,
[ATTR_GEN_AI_PROVIDER_NAME]: input.provider,
[AIRI_ATTR_GEN_AI_OPERATION_KIND]: 'asr',
'http.response.status_code': input.status,
}
if (input.status >= 400)
attrs[ATTR_ERROR_TYPE] = input.errorType ?? String(input.status)
genAi.operationDuration.record(Math.max(0, input.durationMs) / 1000, attrs)
}
/**
* Tracks one realtime ASR stream session and records its terminal status once.
*/
export function createAsrSessionTelemetry(input: {
genAi?: AsrMetricsSink | null
provider: AsrProvider
model: string
}) {
const startedAt = Date.now()
const span = tracer.startSpan('llm.gateway.asr', {
attributes: {
[ATTR_GEN_AI_REQUEST_MODEL]: input.model,
[ATTR_GEN_AI_PROVIDER_NAME]: input.provider,
[AIRI_ATTR_GEN_AI_OPERATION_KIND]: 'asr',
},
})
let settled = false
function settle(status: number, errorType?: AsrErrorType, errorMessage?: string): void {
if (settled)
return
settled = true
span.setAttribute('http.response.status_code', status)
if (status >= 500)
span.setStatus({ code: SpanStatusCode.ERROR, message: errorMessage ?? errorType ?? String(status) })
span.end()
recordAsrOperation(input.genAi, {
provider: input.provider,
model: input.model,
status,
durationMs: Date.now() - startedAt,
errorType,
})
}
return {
complete: () => settle(200),
cancel: () => settle(499, 'client_cancelled'),
fail: (errorType: AsrErrorType, message?: string) => settle(502, errorType, message),
}
}

View file

@ -0,0 +1,101 @@
import type { GenAiMetrics } from '../../../otel'
import type { ConfigKVService } from '../../adapters/config-kv'
import type { SpeechBilling } from '../billing/speech-billing'
import type { LlmRouterService } from '../llm-router'
import type { ProviderCatalogService } from '../provider-catalog'
import type { VoicePackService } from '../voice-packs'
import { ATTR_ERROR_TYPE } from '@opentelemetry/semantic-conventions'
import { describe, expect, it, vi } from 'vitest'
import { createOpenAiSpeechService } from './index'
function makeSpeechService(routeTts: LlmRouterService['routeTts']) {
const operationDurationRecord = vi.fn()
const fluxConsumedAdd = vi.fn()
const genAi = Object.assign({} as GenAiMetrics, {
operationDuration: { record: operationDurationRecord },
fluxConsumed: { add: fluxConsumedAdd },
})
const service = createOpenAiSpeechService({
configKV: Object.assign({} as ConfigKVService, {
getOrThrow: vi.fn(async () => 'stepfun/stepaudio-2.5-tts'),
}),
speechBilling: Object.assign({} as SpeechBilling, {
assertCanAfford: vi.fn(async () => {}),
settle: vi.fn(async () => ({ feeFlux: 0 })),
}),
llmRouter: Object.assign({} as LlmRouterService, {
routeTts,
}),
voicePackService: Object.assign({} as VoicePackService, {
findById: vi.fn(async () => null),
findEnabledByVoiceId: vi.fn(async () => null),
}),
providerCatalogService: Object.assign({} as ProviderCatalogService, {
assertTtsModelEnabled: vi.fn(async () => ({ costMultiplier: 1 })),
assertTtsVoiceEnabled: vi.fn(async () => {}),
}),
genAi,
})
return { service, operationDurationRecord }
}
describe('createOpenAiSpeechService telemetry', () => {
// ROOT CAUSE:
//
// When a client cancelled a POST /api/v1/audio/speech turn, routeTts threw
// the non-ApiError abort reason. routerFailure mapped every non-ApiError to
// status 502, so aborted TTS turns polluted gen_ai.client.operation.duration
// with thousands of false 502 failures.
//
// Fix: routerFailure inspects abortSignal?.aborted and records 499, matching
// chat and responses client-disconnect classification.
it('records status 499 instead of 502 when the caller aborts a TTS request', async () => {
const controller = new AbortController()
const { service, operationDurationRecord } = makeSpeechService(vi.fn(async (_req, ctx) => {
if (ctx)
ctx.provider = 'api.stepfun.ai'
controller.abort(new DOMException('Client disconnected', 'AbortError'))
throw controller.signal.reason
}))
await expect(service.handleSpeechRequest({
userId: 'user-1',
body: { model: 'stepfun/stepaudio-2.5-tts', input: 'hello', voice: 'cixingnansheng' },
abortSignal: controller.signal,
})).rejects.toBeDefined()
expect(operationDurationRecord).toHaveBeenCalledTimes(1)
expect(operationDurationRecord.mock.calls[0][1]).toMatchObject({
'gen_ai.request.model': 'stepfun/stepaudio-2.5-tts',
'gen_ai.provider.name': 'api.stepfun.ai',
'airi.gen_ai.operation.kind': 'tts',
'http.response.status_code': 499,
[ATTR_ERROR_TYPE]: '499',
})
})
it('records status 502 when routeTts throws a non-ApiError without client abort', async () => {
const { service, operationDurationRecord } = makeSpeechService(vi.fn(async (_req, ctx) => {
if (ctx)
ctx.provider = 'api.stepfun.ai'
throw new Error('upstream connection reset')
}))
await expect(service.handleSpeechRequest({
userId: 'user-1',
body: { model: 'stepfun/stepaudio-2.5-tts', input: 'hello', voice: 'cixingnansheng' },
})).rejects.toThrow('upstream connection reset')
expect(operationDurationRecord).toHaveBeenCalledTimes(1)
expect(operationDurationRecord.mock.calls[0][1]).toMatchObject({
'gen_ai.provider.name': 'api.stepfun.ai',
'airi.gen_ai.operation.kind': 'tts',
'http.response.status_code': 502,
[ATTR_ERROR_TYPE]: '502',
})
})
})

View file

@ -1,3 +1,5 @@
import type { Attributes } from '@opentelemetry/api'
import type { GenAiMetrics } from '../../../otel'
import type { ConfigKVService } from '../../adapters/config-kv'
import type { SpeechBilling } from '../billing/speech-billing'
@ -7,6 +9,7 @@ import type { VoicePackService } from '../voice-packs'
import { useLogger } from '@guiiai/logg'
import { context, SpanStatusCode, trace } from '@opentelemetry/api'
import { ATTR_ERROR_TYPE } from '@opentelemetry/semantic-conventions'
import { ApiError, createBadRequestError, createPaymentRequiredError } from '@proj-airi/http-shared'
import {
ATTR_GEN_AI_PROVIDER_NAME,
@ -191,8 +194,10 @@ export function createOpenAiSpeechService(deps: OpenAiSpeechServiceDeps) {
}, routeCtx))
}
catch (err) {
const failure = routerFailure(err)
span.setStatus({ code: SpanStatusCode.ERROR, message: failure.message })
const failure = routerFailure(err, input.abortSignal)
span.setAttribute('http.response.status_code', failure.status)
if (failure.status !== 499)
span.setStatus({ code: SpanStatusCode.ERROR, message: failure.message })
span.end()
recordMetrics({
durationMs: Date.now() - startedAt,
@ -265,12 +270,14 @@ export function createOpenAiSpeechService(deps: OpenAiSpeechServiceDeps) {
durationMs: number
fluxConsumed: number
}): void {
const attrs = {
const attrs: Attributes = {
[ATTR_GEN_AI_REQUEST_MODEL]: input.model,
[AIRI_ATTR_GEN_AI_OPERATION_KIND]: 'tts',
[ATTR_GEN_AI_PROVIDER_NAME]: input.provider,
'http.response.status_code': input.status,
}
if (input.status >= 400)
attrs[ATTR_ERROR_TYPE] = String(input.status)
deps.genAi?.operationDuration.record(input.durationMs / 1000, attrs)
deps.genAi?.fluxConsumed.add(input.fluxConsumed, attrs)
}
@ -378,7 +385,17 @@ async function resolveVoicePackRequest(
return pack
}
function routerFailure(error: unknown): { status: number, reason: string, message: string } {
function routerFailure(error: unknown, abortSignal?: AbortSignal): { status: number, reason: string, message: string } {
// Classify caller disconnects as 499 so TTS failure alerts do not count
// client-cancelled speech turns as upstream 502 outages.
if (abortSignal?.aborted) {
return {
status: 499,
reason: 'client_aborted',
message: 'Client aborted TTS request',
}
}
if (error instanceof ApiError) {
return {
status: error.statusCode,