fix(mobile): harden recorder, queue, context, and screen async lifecycles
This commit is contained in:
parent
3f9e412257
commit
bd3c1a98d9
25 changed files with 2279 additions and 68 deletions
316
apps/mobile-rn/__tests__/queue-and-history-races.test.ts
Normal file
316
apps/mobile-rn/__tests__/queue-and-history-races.test.ts
Normal file
|
|
@ -0,0 +1,316 @@
|
|||
import React from 'react'
|
||||
import { act, create, type ReactTestRenderer } from 'react-test-renderer'
|
||||
import AsyncStorage from '@react-native-async-storage/async-storage'
|
||||
import { FileSystem } from 'react-native-file-access'
|
||||
import {
|
||||
AudioPipelineError,
|
||||
type AudioPipelineResult,
|
||||
type LocalAudioInput,
|
||||
} from '../src/features/import/audio-import-types'
|
||||
import type { HistoryListEntry, HistoryPageResult } from '../src/features/history/history-service'
|
||||
|
||||
const START_MS = 1_700_000_000_000
|
||||
const USER_A = '11111111-1111-4111-8111-111111111111'
|
||||
const USER_B = '22222222-2222-4222-8222-222222222222'
|
||||
|
||||
const mockProcessAudioInput = jest.fn<Promise<AudioPipelineResult>, [LocalAudioInput, unknown]>()
|
||||
const mockListHistoryPage = jest.fn<Promise<HistoryPageResult>, [unknown]>()
|
||||
const mockLoadHistoryCache = jest.fn()
|
||||
const mockUpdateHistoryRevisionSafe = jest.fn()
|
||||
let mockAuthUser: { id: string } | null = null
|
||||
|
||||
jest.mock('../src/lib/supabase', () => ({
|
||||
supabase: {
|
||||
channel: jest.fn(),
|
||||
removeChannel: jest.fn(async () => 'ok'),
|
||||
},
|
||||
}))
|
||||
jest.mock('../src/lib/auth-context', () => ({
|
||||
useAuth: () => ({ user: mockAuthUser }),
|
||||
}))
|
||||
jest.mock('../src/features/import/audio-transcription-service', () => ({
|
||||
processAudioInput: (input: LocalAudioInput, options: unknown) => mockProcessAudioInput(input, options),
|
||||
}))
|
||||
jest.mock('../src/features/meetings/meetings-service', () => ({
|
||||
failMeetingRecording: jest.fn(async () => undefined),
|
||||
markMeetingProcessingFailure: jest.fn(async () => undefined),
|
||||
queueMeetingRecording: jest.fn(async () => undefined),
|
||||
}))
|
||||
jest.mock('../src/features/history/history-service', () => ({
|
||||
...jest.requireActual('../src/features/history/history-service'),
|
||||
listHistoryPage: (options: unknown) => mockListHistoryPage(options),
|
||||
subscribeToHistory: () => ({ unsubscribe: async () => undefined }),
|
||||
updateHistoryRevisionSafe: (...args: unknown[]) => mockUpdateHistoryRevisionSafe(...args),
|
||||
}))
|
||||
jest.mock('../src/features/history/history-cache', () => ({
|
||||
...jest.requireActual('../src/features/history/history-cache'),
|
||||
loadHistoryCache: (...args: unknown[]) => mockLoadHistoryCache(...args),
|
||||
saveHistoryCache: jest.fn(async () => undefined),
|
||||
clearHistoryCache: jest.fn(async () => undefined),
|
||||
}))
|
||||
|
||||
import {
|
||||
clearQueuedAudioForUser,
|
||||
durableQueueTestContract,
|
||||
processQueuedAudioNow,
|
||||
QueuedAudioPendingError,
|
||||
resumeQueuedAudioForUser,
|
||||
retainQueuedAudioOnlyForUser,
|
||||
retryQueuedAudio,
|
||||
type DurableQueueItem,
|
||||
} from '../src/features/recording/durable-processing-queue'
|
||||
import { useHistorySync } from '../src/features/history/use-history-sync'
|
||||
|
||||
const mockFileSystem = FileSystem as typeof FileSystem & { filesystem: Map<string, string> }
|
||||
|
||||
function makeQueueItem(
|
||||
userId: string,
|
||||
suffix: string,
|
||||
overrides: Partial<DurableQueueItem> = {},
|
||||
): DurableQueueItem {
|
||||
const path = `${durableQueueTestContract.queueDirectory}/queued-${suffix}.wav`
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
id: suffix,
|
||||
userId,
|
||||
meetingId: null,
|
||||
path,
|
||||
uri: `file://${path}`,
|
||||
fileName: `${suffix}.wav`,
|
||||
mimeType: 'audio/wav',
|
||||
sizeBytes: 128,
|
||||
durationMs: 1_000,
|
||||
source: 'recording',
|
||||
languageCode: 'ko',
|
||||
status: 'pending',
|
||||
phase: null,
|
||||
attempts: 0,
|
||||
uploadedBytes: 0,
|
||||
nextAttemptAtMs: START_MS,
|
||||
lastErrorCode: null,
|
||||
lastErrorMessage: null,
|
||||
createdAtMs: START_MS,
|
||||
updatedAtMs: START_MS,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function makeHistoryEntry(id: string, userId = USER_A): HistoryListEntry {
|
||||
return {
|
||||
id,
|
||||
user_id: userId,
|
||||
title: `entry ${id}`,
|
||||
original_text: `text ${id}`,
|
||||
polished_text: null,
|
||||
focused_app: null,
|
||||
focused_app_name: null,
|
||||
focused_app_window_title: null,
|
||||
mode: 'dictation',
|
||||
status: 'completed',
|
||||
error_code: null,
|
||||
audio_storage_key: null,
|
||||
duration: 2,
|
||||
detected_language: 'ko',
|
||||
mic_device: null,
|
||||
word_count: 1,
|
||||
stt_model: 'whisper',
|
||||
llm_model: null,
|
||||
stt_latency_ms: null,
|
||||
llm_latency_ms: null,
|
||||
app_version: '1.0.0',
|
||||
summary_text: null,
|
||||
is_favorite: false,
|
||||
revision: 1,
|
||||
created_at: '2026-08-21T00:00:00.000Z',
|
||||
updated_at: '2026-08-21T00:00:00.000Z',
|
||||
activeJob: null,
|
||||
}
|
||||
}
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve: (value: T) => void = () => undefined
|
||||
let reject: (reason?: unknown) => void = () => undefined
|
||||
const promise = new Promise<T>((res, rej) => {
|
||||
resolve = res
|
||||
reject = rej
|
||||
})
|
||||
return { promise, resolve, reject }
|
||||
}
|
||||
|
||||
async function flushMicrotasks(): Promise<void> {
|
||||
for (let index = 0; index < 8; index += 1) await Promise.resolve()
|
||||
}
|
||||
|
||||
describe('durable queue and history sync race guards', () => {
|
||||
let activeRenderer: ReactTestRenderer | null = null
|
||||
|
||||
beforeEach(async () => {
|
||||
jest.useFakeTimers({ now: START_MS })
|
||||
await AsyncStorage.clear()
|
||||
mockFileSystem.filesystem.clear()
|
||||
mockProcessAudioInput.mockReset()
|
||||
mockListHistoryPage.mockReset()
|
||||
mockLoadHistoryCache.mockReset()
|
||||
mockUpdateHistoryRevisionSafe.mockReset()
|
||||
mockAuthUser = null
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
if (activeRenderer !== null) {
|
||||
const target = activeRenderer
|
||||
activeRenderer = null
|
||||
act(() => target.unmount())
|
||||
}
|
||||
await clearQueuedAudioForUser(USER_A).catch(() => undefined)
|
||||
await clearQueuedAudioForUser(USER_B).catch(() => undefined)
|
||||
await resumeQueuedAudioForUser(USER_A).catch(() => undefined)
|
||||
await resumeQueuedAudioForUser(USER_B).catch(() => undefined)
|
||||
jest.clearAllTimers()
|
||||
jest.useRealTimers()
|
||||
})
|
||||
|
||||
test('durableQueue_정지된사용자의재시도실패시_스케줄러를재예약하지않음', async () => {
|
||||
const item = makeQueueItem(USER_A, 'aaaa0001')
|
||||
mockFileSystem.filesystem.set(item.path, 'audio-bytes')
|
||||
await AsyncStorage.setItem(durableQueueTestContract.storageKey, JSON.stringify([item]))
|
||||
|
||||
const runGate = deferred<AudioPipelineResult>()
|
||||
mockProcessAudioInput.mockImplementationOnce(() => runGate.promise)
|
||||
|
||||
const processing = processQueuedAudioNow(USER_A, item.id).catch((err: unknown) => err)
|
||||
await flushMicrotasks()
|
||||
|
||||
await retainQueuedAudioOnlyForUser(USER_A)
|
||||
|
||||
runGate.reject(new AudioPipelineError('upload', 'network temporarily offline'))
|
||||
const caught = await processing
|
||||
expect(caught).toBeInstanceOf(QueuedAudioPendingError)
|
||||
expect(jest.getTimerCount()).toBe(0)
|
||||
|
||||
await jest.advanceTimersByTimeAsync(120_000)
|
||||
await flushMicrotasks()
|
||||
|
||||
// While USER_A remains suspended after retainQueuedAudioOnlyForUser, no retry run fires.
|
||||
expect(mockProcessAudioInput).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
test('durableQueue_정지또는정리단계항목재시도시_running이나cleanup상태를덮어쓰지않음', async () => {
|
||||
const cleaningItem = makeQueueItem(USER_A, 'aaaa0002', {
|
||||
status: 'cleanup',
|
||||
phase: 'saving',
|
||||
})
|
||||
const runningItem = makeQueueItem(USER_A, 'aaaa0003', {
|
||||
status: 'running',
|
||||
phase: 'transcribing',
|
||||
})
|
||||
mockFileSystem.filesystem.set(cleaningItem.path, 'audio-bytes')
|
||||
mockFileSystem.filesystem.set(runningItem.path, 'audio-bytes')
|
||||
await AsyncStorage.setItem(
|
||||
durableQueueTestContract.storageKey,
|
||||
JSON.stringify([cleaningItem, runningItem]),
|
||||
)
|
||||
mockProcessAudioInput.mockResolvedValue({
|
||||
historyId: null,
|
||||
audioFileId: 'audio-file',
|
||||
meetingId: null,
|
||||
processingJobId: null,
|
||||
transcript: 'done',
|
||||
provider: 'test',
|
||||
language: 'ko',
|
||||
durationSeconds: 1,
|
||||
deduplicated: false,
|
||||
})
|
||||
|
||||
// Hold resume at readQueue or reject nothing — instead inspect status change before resume consumes running.
|
||||
await retryQueuedAudio(USER_A, cleaningItem.id)
|
||||
const afterCleanupRetry = durableQueueTestContract.parseQueue(
|
||||
await AsyncStorage.getItem(durableQueueTestContract.storageKey),
|
||||
)
|
||||
const cleanupState = afterCleanupRetry.find((candidate) => candidate.id === cleaningItem.id)
|
||||
// cleanup item must not be downgraded to retry and re-transcribed.
|
||||
expect(mockProcessAudioInput).not.toHaveBeenCalled()
|
||||
expect(cleanupState).toBeUndefined()
|
||||
|
||||
await retryQueuedAudio(USER_A, runningItem.id)
|
||||
const afterRunningRetry = durableQueueTestContract.parseQueue(
|
||||
await AsyncStorage.getItem(durableQueueTestContract.storageKey),
|
||||
)
|
||||
expect(afterRunningRetry.find((candidate) => candidate.id === runningItem.id)?.status).toBe('running')
|
||||
})
|
||||
|
||||
test('useHistorySync_오프라인캐시조회중새요청이나언마운트시_오래된캐시로덮어쓰지않음', async () => {
|
||||
jest.useRealTimers()
|
||||
let latestState: ReturnType<typeof useHistorySync> | null = null
|
||||
function Probe(): null {
|
||||
latestState = useHistorySync()
|
||||
return null
|
||||
}
|
||||
|
||||
const firstOfflineCache = deferred<{ savedAt: string; entries: HistoryListEntry[] } | null>()
|
||||
mockAuthUser = { id: USER_A }
|
||||
mockListHistoryPage
|
||||
.mockRejectedValueOnce(new TypeError('Network request failed'))
|
||||
.mockResolvedValueOnce({
|
||||
entries: [makeHistoryEntry('fresh-entry', USER_B)],
|
||||
nextCursor: null,
|
||||
})
|
||||
mockLoadHistoryCache.mockReturnValueOnce(firstOfflineCache.promise)
|
||||
|
||||
let renderer!: ReactTestRenderer
|
||||
await act(async () => {
|
||||
renderer = create(React.createElement(Probe))
|
||||
activeRenderer = renderer
|
||||
await flushMicrotasks()
|
||||
})
|
||||
|
||||
// Switch user while USER_A's offline cache load is still pending.
|
||||
mockAuthUser = { id: USER_B }
|
||||
await act(async () => {
|
||||
renderer.update(React.createElement(Probe))
|
||||
await flushMicrotasks()
|
||||
})
|
||||
expect(latestState?.entries.map((item) => item.id)).toEqual(['fresh-entry'])
|
||||
|
||||
// Now USER_A's stalled offline cache finishes.
|
||||
await act(async () => {
|
||||
firstOfflineCache.resolve({
|
||||
savedAt: '2026-08-21T00:00:00.000Z',
|
||||
entries: [makeHistoryEntry('stale-user-a-cache', USER_A)],
|
||||
})
|
||||
await flushMicrotasks()
|
||||
})
|
||||
|
||||
expect(latestState?.entries.map((item) => item.id)).toEqual(['fresh-entry'])
|
||||
expect(latestState?.offline).toBe(false)
|
||||
|
||||
// Now test toggleFavorite resolving after user switch does not pollute USER_B's entries.
|
||||
const favGate = deferred<HistoryListEntry>()
|
||||
mockUpdateHistoryRevisionSafe.mockReturnValueOnce(favGate.promise)
|
||||
const staleEntry = makeHistoryEntry('shared-like-entry', USER_A)
|
||||
let pendingToggle: Promise<unknown> = Promise.resolve()
|
||||
act(() => {
|
||||
pendingToggle = latestState!.toggleFavorite(staleEntry).catch(() => undefined)
|
||||
})
|
||||
|
||||
mockAuthUser = { id: USER_A }
|
||||
mockListHistoryPage.mockResolvedValueOnce({
|
||||
entries: [makeHistoryEntry('shared-like-entry', USER_A)],
|
||||
nextCursor: null,
|
||||
})
|
||||
await act(async () => {
|
||||
renderer.update(React.createElement(Probe))
|
||||
await flushMicrotasks()
|
||||
})
|
||||
expect(latestState?.entries[0]?.is_favorite).toBe(false)
|
||||
|
||||
await act(async () => {
|
||||
favGate.resolve({ ...staleEntry, is_favorite: true, revision: 2 })
|
||||
await pendingToggle
|
||||
await flushMicrotasks()
|
||||
})
|
||||
|
||||
expect(latestState?.entries[0]?.is_favorite).toBe(false)
|
||||
activeRenderer = null
|
||||
act(() => renderer.unmount())
|
||||
})
|
||||
})
|
||||
Loading…
Add table
Add a link
Reference in a new issue