agora-appbuilder-core 4.1.30-beta.2 → 4.1.31-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -6,13 +6,23 @@ import {PropsContext, useLocalUid} from '../../../agora-rn-uikit';
6
6
  import {logger, LogSource} from '../../logger/AppBuilderLogger';
7
7
  import getUniqueID from '../../utils/getUniqueID';
8
8
  import {buildSTTRequestBody, type STTMethod} from './sttRequestBody';
9
- import {ensureSTTSessionId} from './sttSessionId';
9
+ import {
10
+ ensureSTTSessionId,
11
+ rotateSTTSessionId,
12
+ wasSTTSessionIdFreshlyCreated,
13
+ markSTTSessionIdUsed,
14
+ } from './sttSessionId';
10
15
  import {TRANSCRIPT_JOURNEY} from './transcriptJourney';
11
16
 
12
17
  export interface STTAPIResponse {
13
18
  success: boolean;
14
19
  data?: any;
15
20
  httpStatus?: number;
21
+ // session_id that was sent on this request. Included so callers can
22
+ // emit the id in their own Datadog breadcrumbs without having to
23
+ // re-read the coordinator cache (which may have rotated between the
24
+ // request leaving and the caller reading).
25
+ sessionId?: string;
16
26
  error?: {
17
27
  message: string;
18
28
  code?: number;
@@ -32,6 +42,25 @@ const getStartRetryDelay = (botUid: number) =>
32
42
  const shouldRetryStart = (result: STTAPIResponse) =>
33
43
  result.httpStatus === 429 || result.error?.code === 610;
34
44
 
45
+ const shouldRotateSessionId = (result: STTAPIResponse) =>
46
+ result.error?.code === 631;
47
+
48
+ // Status values returned by /v1/stt-transcript that mean the session_id
49
+ // has moved past 'active' in the backend's ledger and should not be reused
50
+ // for a new startv7. See managed-service `storage/postgres/stt.go` status
51
+ // enum: STARTED/INPROGRESS are active; the remaining states below are
52
+ // stopped or processing artifacts and cannot resume live transcription.
53
+ const ENDED_STT_STATUSES = new Set<string>([
54
+ 'COMPLETED',
55
+ 'FAILED',
56
+ 'ARTIFACTS_PENDING',
57
+ 'PROCESSING',
58
+ ]);
59
+ // Bound the optional lookup to the latest 50 sessions. Older entries can be
60
+ // missed, so startv7's 631 response remains the authoritative fallback.
61
+ const PREFLIGHT_PAGE_LIMIT = 50;
62
+ const PREFLIGHT_TIMEOUT_MS = 3000;
63
+
35
64
  interface IuseSTTAPI {
36
65
  start: (
37
66
  botUid: number,
@@ -77,9 +106,20 @@ const useSTTAPI = (): IuseSTTAPI => {
77
106
  method: STTMethod,
78
107
  botUid: number,
79
108
  translationConfig?: LanguageTranslationConfig,
109
+ attempt?: number,
80
110
  ): Promise<STTAPIResponse> => {
81
111
  const requestId = getUniqueID();
82
112
  const startReqTs = Date.now();
113
+ const channelName = rtcPropsRef?.current?.channel || '';
114
+ let sessionId: string | undefined;
115
+ const requestContext = () => ({
116
+ channelName,
117
+ sessionId: sessionId ?? null,
118
+ botUid,
119
+ method,
120
+ attempt: attempt ?? null,
121
+ requestId,
122
+ });
83
123
 
84
124
  try {
85
125
  // Calculate which user this bot belongs to
@@ -99,6 +139,19 @@ const useSTTAPI = (): IuseSTTAPI => {
99
139
  resolveSessionId: ensureSTTSessionId,
100
140
  });
101
141
 
142
+ sessionId = requestBody.session_id;
143
+ if (method === 'startv7') {
144
+ logger.log(
145
+ LogSource.NetworkRest,
146
+ 'stt',
147
+ `${TRANSCRIPT_JOURNEY} STT start attempt`,
148
+ {
149
+ ...requestContext(),
150
+ isFreshlyCreated: wasSTTSessionIdFreshlyCreated(channelName),
151
+ },
152
+ );
153
+ }
154
+
102
155
  console.log(
103
156
  `${TRANSCRIPT_JOURNEY} [STT_BOT_SUBSCRIPTION] ${method.toUpperCase()} - Bot UID: ${botUid} will subscribe to User UID: ${ownerUid}`,
104
157
  {
@@ -108,6 +161,9 @@ const useSTTAPI = (): IuseSTTAPI => {
108
161
  translationConfig: translationConfig ?? null,
109
162
  },
110
163
  );
164
+ if (method === 'startv7' && sessionId) {
165
+ markSTTSessionIdUsed(channelName, sessionId);
166
+ }
111
167
  const response = await fetch(`${STT_API_URL}/${method}`, {
112
168
  method: 'POST',
113
169
  headers: {
@@ -152,7 +208,7 @@ const useSTTAPI = (): IuseSTTAPI => {
152
208
  {
153
209
  responseData: res ?? null,
154
210
  httpStatus,
155
- requestId,
211
+ ...requestContext(),
156
212
  startReqTs,
157
213
  endReqTs,
158
214
  latency,
@@ -161,6 +217,7 @@ const useSTTAPI = (): IuseSTTAPI => {
161
217
 
162
218
  return {
163
219
  success: false,
220
+ sessionId,
164
221
  httpStatus,
165
222
  error: {
166
223
  message,
@@ -177,7 +234,7 @@ const useSTTAPI = (): IuseSTTAPI => {
177
234
  {
178
235
  responseData: res ?? null,
179
236
  httpStatus,
180
- requestId,
237
+ ...requestContext(),
181
238
  startReqTs,
182
239
  endReqTs,
183
240
  latency,
@@ -186,6 +243,7 @@ const useSTTAPI = (): IuseSTTAPI => {
186
243
 
187
244
  return {
188
245
  success: true,
246
+ sessionId,
189
247
  httpStatus,
190
248
  data: res,
191
249
  };
@@ -198,7 +256,7 @@ const useSTTAPI = (): IuseSTTAPI => {
198
256
  `${TRANSCRIPT_JOURNEY} STT API Failure - Called ${method}`,
199
257
  error ?? null,
200
258
  {
201
- requestId,
259
+ ...requestContext(),
202
260
  startReqTs,
203
261
  endReqTs,
204
262
  latency,
@@ -207,6 +265,7 @@ const useSTTAPI = (): IuseSTTAPI => {
207
265
 
208
266
  return {
209
267
  success: false,
268
+ sessionId,
210
269
  error: {
211
270
  message: error?.message || 'Unknown error occurred',
212
271
  code: error?.code,
@@ -215,21 +274,204 @@ const useSTTAPI = (): IuseSTTAPI => {
215
274
  }
216
275
  };
217
276
 
277
+ const preflightSessionStatus = async (
278
+ passphrase: string,
279
+ channelName: string,
280
+ sessionId: string,
281
+ ): Promise<void> => {
282
+ if (!passphrase || !channelName || !sessionId) {
283
+ return;
284
+ }
285
+ const url = `${$config.BACKEND_ENDPOINT}/v1/stt-transcript`;
286
+ const body = JSON.stringify({
287
+ passphrase,
288
+ limit: PREFLIGHT_PAGE_LIMIT,
289
+ page: 1,
290
+ });
291
+ const controller = new AbortController();
292
+ const timeout = setTimeout(() => controller.abort(), PREFLIGHT_TIMEOUT_MS);
293
+ try {
294
+ let response: Response;
295
+ try {
296
+ response = await fetch(url, {
297
+ method: 'POST',
298
+ signal: controller.signal,
299
+ headers: {
300
+ 'Content-Type': 'application/json',
301
+ authorization: tokenRef?.current
302
+ ? `Bearer ${tokenRef?.current}`
303
+ : '',
304
+ },
305
+ body,
306
+ });
307
+ } catch (fetchError) {
308
+ logger.warn(
309
+ LogSource.NetworkRest,
310
+ 'stt',
311
+ `${TRANSCRIPT_JOURNEY} STT session pre-flight network error`,
312
+ fetchError ?? null,
313
+ );
314
+ return;
315
+ }
316
+ if (!response.ok) {
317
+ logger.warn(
318
+ LogSource.NetworkRest,
319
+ 'stt',
320
+ `${TRANSCRIPT_JOURNEY} STT session pre-flight non-OK response`,
321
+ {httpStatus: response.status},
322
+ );
323
+ return;
324
+ }
325
+ let data: {stts?: Array<{session_id?: string; status?: string}>};
326
+ try {
327
+ data = await response.json();
328
+ } catch (parseError) {
329
+ logger.warn(
330
+ LogSource.NetworkRest,
331
+ 'stt',
332
+ `${TRANSCRIPT_JOURNEY} STT session pre-flight body parse error`,
333
+ parseError ?? null,
334
+ );
335
+ return;
336
+ }
337
+ const match = Array.isArray(data?.stts)
338
+ ? data.stts.find(
339
+ entry =>
340
+ entry?.session_id === sessionId &&
341
+ typeof entry.status === 'string' &&
342
+ ENDED_STT_STATUSES.has(entry.status),
343
+ )
344
+ : undefined;
345
+ if (!match) {
346
+ return; // No evidence of staleness on this page; startv7 still validates.
347
+ }
348
+ logger.log(
349
+ LogSource.NetworkRest,
350
+ 'stt',
351
+ `${TRANSCRIPT_JOURNEY} STT session pre-flight detected stale id; rotating`,
352
+ {
353
+ channelName,
354
+ staleSessionId: sessionId,
355
+ beStatus: match.status,
356
+ },
357
+ );
358
+ try {
359
+ await rotateSTTSessionId(channelName, sessionId);
360
+ } catch (rotateError) {
361
+ logger.error(
362
+ LogSource.NetworkRest,
363
+ 'stt',
364
+ `${TRANSCRIPT_JOURNEY} STT session pre-flight rotation failed`,
365
+ rotateError as any,
366
+ );
367
+ }
368
+ } finally {
369
+ clearTimeout(timeout);
370
+ }
371
+ };
372
+
218
373
  const start = async (
219
374
  botUid: number,
220
375
  translationConfig: LanguageTranslationConfig,
221
376
  ): Promise<STTAPIResponse> => {
222
377
  const retryDelayMs = getStartRetryDelay(botUid);
378
+ const channelName = rtcPropsRef?.current?.channel || '';
379
+ const passphrase =
380
+ roomIdRef?.current?.host || roomIdRef?.current?.attendee || '';
223
381
  let result: STTAPIResponse;
382
+ let rotatedOnce = false;
383
+ let requestAttempt = 0;
384
+
385
+ // Pre-flight: if we are about to send a session_id that already existed
386
+ // in RTM channel metadata (not one we just minted), check with the
387
+ // backend whether it has moved past 'active' in the ledger. If so, we
388
+ // rotate here to avoid a guaranteed-to-fail startv7 round-trip.
389
+ if (channelName && passphrase) {
390
+ try {
391
+ const cachedSessionId = await ensureSTTSessionId(channelName);
392
+ const isFreshlyCreated = wasSTTSessionIdFreshlyCreated(channelName);
393
+ if (cachedSessionId && !isFreshlyCreated) {
394
+ await preflightSessionStatus(
395
+ passphrase,
396
+ channelName,
397
+ cachedSessionId,
398
+ );
399
+ }
400
+ } catch (preflightError) {
401
+ logger.warn(
402
+ LogSource.NetworkRest,
403
+ 'stt',
404
+ `${TRANSCRIPT_JOURNEY} STT session pre-flight skipped`,
405
+ preflightError ?? null,
406
+ );
407
+ }
408
+ }
224
409
 
225
410
  for (let attempt = 1; attempt <= STT_START_MAX_ATTEMPTS; attempt += 1) {
226
- result = await apiCall('startv7', botUid, translationConfig);
411
+ requestAttempt += 1;
412
+ result = await apiCall(
413
+ 'startv7',
414
+ botUid,
415
+ translationConfig,
416
+ requestAttempt,
417
+ );
418
+
419
+ if (result.success) {
420
+ return result;
421
+ }
227
422
 
228
423
  if (
229
- result.success ||
230
- !shouldRetryStart(result) ||
231
- attempt === STT_START_MAX_ATTEMPTS
424
+ shouldRotateSessionId(result) &&
425
+ !rotatedOnce &&
426
+ channelName &&
427
+ result.sessionId
232
428
  ) {
429
+ const staleSessionId = result.sessionId;
430
+ logger.log(
431
+ LogSource.NetworkRest,
432
+ 'stt',
433
+ `${TRANSCRIPT_JOURNEY} Rotating STT session ID after terminal-reuse error`,
434
+ {
435
+ attempt: requestAttempt,
436
+ channelName,
437
+ botUid,
438
+ httpStatus: result.httpStatus ?? null,
439
+ errorCode: result.error?.code ?? null,
440
+ staleSessionId: staleSessionId ?? null,
441
+ },
442
+ );
443
+ try {
444
+ const newSessionId = await rotateSTTSessionId(
445
+ channelName,
446
+ staleSessionId,
447
+ );
448
+ logger.log(
449
+ LogSource.NetworkRest,
450
+ 'stt',
451
+ `${TRANSCRIPT_JOURNEY} STT session ID rotated; retrying start`,
452
+ {
453
+ attempt: requestAttempt,
454
+ channelName,
455
+ botUid,
456
+ staleSessionId: staleSessionId ?? null,
457
+ newSessionId,
458
+ },
459
+ );
460
+ rotatedOnce = true;
461
+ attempt -= 1; // Always send a start after rotation, even at the retry limit.
462
+ continue;
463
+ } catch (rotateError) {
464
+ logger.error(
465
+ LogSource.NetworkRest,
466
+ 'stt',
467
+ `${TRANSCRIPT_JOURNEY} Failed to rotate STT session ID`,
468
+ rotateError as any,
469
+ );
470
+ return result;
471
+ }
472
+ }
473
+
474
+ if (!shouldRetryStart(result) || attempt === STT_START_MAX_ATTEMPTS) {
233
475
  return result;
234
476
  }
235
477
 
@@ -238,9 +480,11 @@ const useSTTAPI = (): IuseSTTAPI => {
238
480
  'stt',
239
481
  `${TRANSCRIPT_JOURNEY} Retrying STT start after transient failure`,
240
482
  {
241
- attempt,
483
+ attempt: requestAttempt,
242
484
  maxAttempts: STT_START_MAX_ATTEMPTS,
243
485
  retryDelayMs,
486
+ channelName,
487
+ sessionId: result.sessionId ?? null,
244
488
  botUid,
245
489
  httpStatus: result.httpStatus ?? null,
246
490
  errorCode: result.error?.code ?? null,