mirror of
https://github.com/readest/readest.git
synced 2026-11-29 19:02:28 +00:00
fix(tts): make Readest Voice downloads responsive and tell users about quota (#6736)
* fix(tts): make Readest Voice downloads responsive and tell users about quota Chapter downloads looked stuck and quota refusals went unexplained: - Progress counts the sentences cached so far, in any order, and shows the total as soon as a run starts. Before, it counted sentences in reading order, so it froze until the earliest window came back, even when later windows had finished. - Download windows are sized by characters (up to 2000, about two minutes of audio) instead of up to 64 sentences, so progress moves often and work spreads across workers. - A failed run retries on its own up to 3 times (after 10, 20 and 30 s); a quota refusal does not retry. - Preparing a download checks the cache for the whole section in one query and registers its sentences in a few statements, instead of one SQLite round trip per sentence. - Every quota refusal tells the user (at most once per toast), not just the first, and a failed chapter says Quota Exceeded. After a refusal the provider asks the server again a minute later instead of staying refused for the session. - Daily quotas: Plus 500,000 and Pro 1,000,000 characters. - The contract check and warmup accept plain RPC values, which is what the platform proxy returns under next dev. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(tts): do not report audio-less cache rows as cached A row that pack deletion detached (no audio, no pack) is a miss for get; cachedKeys reported it as cached, so a download skipped the sentence and left it to the slower one-sentence fallback. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
4a9cb331a7
commit
d2875c5ac1
25 changed files with 510 additions and 83 deletions
|
|
@ -95,7 +95,7 @@ describe('POST /jobs', () => {
|
|||
lang: 'en-US',
|
||||
segments: body.segments,
|
||||
engines: ['kokoro', 'omnivoice'],
|
||||
quotaLeft: 300 * 1024 - 1_000,
|
||||
quotaLeft: 1_000_000 - 1_000,
|
||||
});
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -106,6 +106,12 @@ describe('POST /api/tts/readest', () => {
|
|||
expect(await res.json()).toEqual({ ok: true });
|
||||
});
|
||||
|
||||
it('accepts a plain value, as the next dev platform proxy answers RPC calls', async () => {
|
||||
m.service.warmup.mockReturnValueOnce(undefined);
|
||||
const res = await POST(req('POST', { warmup: true }));
|
||||
expect(await res.json()).toEqual({ ok: true });
|
||||
});
|
||||
|
||||
it('is gated like GET', async () => {
|
||||
m.getSubscriptionPlan.mockReturnValue('free');
|
||||
expect((await POST(req('POST', { warmup: true }))).status).toBe(403);
|
||||
|
|
|
|||
|
|
@ -182,8 +182,8 @@ describe('window validation', () => {
|
|||
|
||||
describe('quota and admission', () => {
|
||||
it('counts the uncharged download jobs of the user against the quota', async () => {
|
||||
m.getCurrentUsage.mockResolvedValue(50 * 1024);
|
||||
m.service.admitWindow.mockResolvedValue({ acquired: true, pendingChars: 50 * 1024 });
|
||||
m.getCurrentUsage.mockResolvedValue(250_000);
|
||||
m.service.admitWindow.mockResolvedValue({ acquired: true, pendingChars: 250_000 });
|
||||
const res = await POST(post(listen(seg('s0', 'a'.repeat(200)))));
|
||||
expect(res.status).toBe(429);
|
||||
expect(await res.json()).toEqual({ error: 'DAILY_QUOTA_EXCEEDED' });
|
||||
|
|
@ -191,7 +191,7 @@ describe('quota and admission', () => {
|
|||
});
|
||||
|
||||
it('429s when the window would exceed the daily quota, and gives the slot back', async () => {
|
||||
m.getCurrentUsage.mockResolvedValue(100 * 1024 - 100);
|
||||
m.getCurrentUsage.mockResolvedValue(500_000 - 100);
|
||||
const res = await POST(post(listen(seg('s0', 'a'.repeat(200)))));
|
||||
expect(res.status).toBe(429);
|
||||
expect(await res.json()).toEqual({ error: 'DAILY_QUOTA_EXCEEDED' });
|
||||
|
|
|
|||
|
|
@ -126,6 +126,19 @@ describe('TTSChaptersView', () => {
|
|||
expect(downloads.downloadChapter).toHaveBeenCalledWith(chapters[1]);
|
||||
});
|
||||
|
||||
test('a chapter that ran out of daily quota says so', () => {
|
||||
const item = { ...makeItem('b', 'failed'), error: 'DAILY_QUOTA_EXCEEDED' };
|
||||
render(
|
||||
<TTSChaptersView
|
||||
downloads={makeDownloads(withItems([item]))}
|
||||
activeSectionIndex={null}
|
||||
isEink={false}
|
||||
/>,
|
||||
);
|
||||
expect(screen.getByText('Quota Exceeded')).toBeTruthy();
|
||||
expect(screen.queryByText('Download failed')).toBeNull();
|
||||
});
|
||||
|
||||
test('download all skips when every chapter is complete', () => {
|
||||
const downloads = makeDownloads({ statusOf: vi.fn().mockReturnValue('complete') });
|
||||
render(<TTSChaptersView downloads={downloads} activeSectionIndex={null} isEink={false} />);
|
||||
|
|
|
|||
|
|
@ -43,6 +43,12 @@ describe('getVoiceService', () => {
|
|||
expect(await (await load()).getVoiceService()).toBeNull();
|
||||
});
|
||||
|
||||
it('accepts a plain value, as the next dev platform proxy answers RPC calls', async () => {
|
||||
const service = { contractVersion: vi.fn().mockReturnValue(1) };
|
||||
m.env = { READEST_VOICE: service };
|
||||
expect(await (await load()).getVoiceService()).toBe(service);
|
||||
});
|
||||
|
||||
it('checks again after a failed version call', async () => {
|
||||
const service = {
|
||||
contractVersion: vi.fn().mockRejectedValueOnce(new Error('down')).mockResolvedValue(1),
|
||||
|
|
|
|||
|
|
@ -326,13 +326,14 @@ describe('BufferedTTSClient with a windowed provider', () => {
|
|||
const prefetch = vi.fn();
|
||||
const client = await start(makeProvider({ prefetch }));
|
||||
const signal = new AbortController().signal;
|
||||
await client.prefetchSentences(
|
||||
const windowed = await client.prefetchSentences(
|
||||
[
|
||||
{ lang: 'en', text: 'A.' },
|
||||
{ lang: 'en', text: 'B.' },
|
||||
],
|
||||
signal,
|
||||
);
|
||||
expect(windowed).toBe(true);
|
||||
expect(prefetch).toHaveBeenCalledWith(
|
||||
[
|
||||
{ lang: 'en', text: 'A.', voice: 'v1', pitch: 1 },
|
||||
|
|
|
|||
|
|
@ -238,6 +238,27 @@ describe('CachingProvider.prefetch', () => {
|
|||
});
|
||||
});
|
||||
|
||||
test('checks a whole download against the cache in one lookup', async () => {
|
||||
const { inner, deliver } = windowed();
|
||||
const store = Object.assign(new MemoryStore(), {
|
||||
cachedKeys: vi.fn(async (keys: string[]) => new Set(keys.filter((k) => store.map.has(k)))),
|
||||
});
|
||||
const provider = new CachingProvider(inner, store);
|
||||
const cached = provider.synthesize(req('b'), signal());
|
||||
await flush();
|
||||
deliver('b');
|
||||
await cached;
|
||||
store.get.mockClear();
|
||||
const s = signal();
|
||||
provider.prefetch!([req('a'), req('b'), req('c')], 'download', s);
|
||||
await flush();
|
||||
expect(store.cachedKeys).toHaveBeenCalledTimes(1);
|
||||
expect(inner.prefetch).toHaveBeenCalledWith([req('a'), req('c')], 'download', s, undefined);
|
||||
// Handed off before any per-sentence read (only the fills read after).
|
||||
const forwarded = vi.mocked(inner.prefetch!).mock.invocationCallOrder[0]!;
|
||||
expect(store.get.mock.invocationCallOrder.every((order) => order > forwarded)).toBe(true);
|
||||
});
|
||||
|
||||
test('persists a delivered sentence without a later synthesize call', async () => {
|
||||
const { inner, deliver } = windowed();
|
||||
const store = new MemoryStore();
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import { TTSDownloadManager } from '@/services/tts/ttsDownloadManager';
|
|||
import type { TTSController } from '@/services/tts/TTSController';
|
||||
import type { DownloadChapter } from '@/services/tts/downloadChapters';
|
||||
import type { SectionDownloadProgress } from '@/services/tts/TTSDownloader';
|
||||
import { SpeechSynthesisFatalError } from '@/services/tts/providers/types';
|
||||
|
||||
const QUEUE_KEY = 'readest_tts_download_queue';
|
||||
|
||||
|
|
@ -117,12 +118,75 @@ describe('TTSDownloadManager', () => {
|
|||
expect(downloader.download.mock.calls[1]![0]).toEqual([0]);
|
||||
});
|
||||
|
||||
test('retries a failed chapter 3 times, waiting longer each time, then shows it failed', async () => {
|
||||
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
|
||||
try {
|
||||
const { downloader, controller } = makeController();
|
||||
downloader.download.mockRejectedValue(new Error('offline'));
|
||||
const manager = new TTSDownloadManager();
|
||||
manager.attachController('book', () => controller);
|
||||
manager.queueChapter('book', chapter('a', 0, 1));
|
||||
const item = () => useTTSDownloadStore.getState().itemForChapter('book', 'a');
|
||||
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(downloader.download).toHaveBeenCalledTimes(1);
|
||||
expect(item()?.status).toBe('pending');
|
||||
await vi.advanceTimersByTimeAsync(9_999);
|
||||
expect(downloader.download).toHaveBeenCalledTimes(1);
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
expect(downloader.download).toHaveBeenCalledTimes(2);
|
||||
await vi.advanceTimersByTimeAsync(20_000);
|
||||
expect(downloader.download).toHaveBeenCalledTimes(3);
|
||||
await vi.advanceTimersByTimeAsync(30_000);
|
||||
expect(downloader.download).toHaveBeenCalledTimes(4);
|
||||
expect(item()).toMatchObject({ status: 'failed', error: 'offline' });
|
||||
await vi.advanceTimersByTimeAsync(60_000);
|
||||
expect(downloader.download).toHaveBeenCalledTimes(4);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
test('a failure that would only repeat (quota) is not retried', async () => {
|
||||
const { downloader, controller } = makeController();
|
||||
downloader.download.mockRejectedValue(new SpeechSynthesisFatalError('DAILY_QUOTA_EXCEEDED'));
|
||||
const manager = new TTSDownloadManager();
|
||||
manager.attachController('book', () => controller);
|
||||
manager.queueChapter('book', chapter('a', 0, 1));
|
||||
|
||||
await vi.waitFor(() =>
|
||||
expect(useTTSDownloadStore.getState().itemForChapter('book', 'a')).toMatchObject({
|
||||
status: 'failed',
|
||||
error: 'DAILY_QUOTA_EXCEEDED',
|
||||
}),
|
||||
);
|
||||
expect(downloader.download).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test('cancelling a chapter waiting to retry drops it for good', async () => {
|
||||
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
|
||||
try {
|
||||
const { downloader, controller } = makeController();
|
||||
downloader.download.mockRejectedValue(new Error('offline'));
|
||||
const manager = new TTSDownloadManager();
|
||||
manager.attachController('book', () => controller);
|
||||
manager.queueChapter('book', chapter('a', 0, 1));
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
manager.cancelItem('book:a');
|
||||
await vi.advanceTimersByTimeAsync(60_000);
|
||||
expect(downloader.download).toHaveBeenCalledTimes(1);
|
||||
expect(useTTSDownloadStore.getState().itemForChapter('book', 'a')).toBeUndefined();
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
test('a failed chapter can be retried by queueing it again', async () => {
|
||||
const { downloader, controller, packed } = makeController();
|
||||
let calls = 0;
|
||||
downloader.download.mockImplementation(async (sections: number[]) => {
|
||||
calls++;
|
||||
if (calls === 1) throw new Error('offline');
|
||||
if (calls === 1) throw new SpeechSynthesisFatalError('DAILY_QUOTA_EXCEEDED');
|
||||
for (const section of sections) packed.add(section);
|
||||
return { completed: [...sections], skipped: [], synthesized: 0 };
|
||||
});
|
||||
|
|
@ -284,8 +348,12 @@ describe('TTSDownloadManager', () => {
|
|||
manager.attachController('book', () => controller);
|
||||
manager.queueChapter('book', chapter('a', 0, 1));
|
||||
|
||||
// The failed run is set to run again.
|
||||
await vi.waitFor(() =>
|
||||
expect(useTTSDownloadStore.getState().itemForChapter('book', 'a')?.status).toBe('failed'),
|
||||
expect(useTTSDownloadStore.getState().itemForChapter('book', 'a')).toMatchObject({
|
||||
status: 'pending',
|
||||
retries: 1,
|
||||
}),
|
||||
);
|
||||
expect(cancelDownloadSections).not.toHaveBeenCalled();
|
||||
});
|
||||
|
|
@ -391,17 +459,22 @@ describe('TTSDownloadManager', () => {
|
|||
);
|
||||
});
|
||||
|
||||
test('keeps an incomplete resolved download as failed so it can be retried', async () => {
|
||||
const { downloader, controller, cancelDownloadSections } = makeController();
|
||||
downloader.download.mockResolvedValue({ completed: [], skipped: [0], synthesized: 0 });
|
||||
const manager = new TTSDownloadManager();
|
||||
manager.attachController('book', () => controller);
|
||||
manager.queueChapter('book', chapter('a', 0, 1));
|
||||
test('keeps an incomplete resolved download as failed after its retries', async () => {
|
||||
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
|
||||
try {
|
||||
const { downloader, controller, cancelDownloadSections } = makeController();
|
||||
downloader.download.mockResolvedValue({ completed: [], skipped: [0], synthesized: 0 });
|
||||
const manager = new TTSDownloadManager();
|
||||
manager.attachController('book', () => controller);
|
||||
manager.queueChapter('book', chapter('a', 0, 1));
|
||||
|
||||
await vi.waitFor(() =>
|
||||
expect(useTTSDownloadStore.getState().itemForChapter('book', 'a')?.status).toBe('failed'),
|
||||
);
|
||||
expect(cancelDownloadSections).toHaveBeenCalledWith([0]);
|
||||
await vi.advanceTimersByTimeAsync(60_000);
|
||||
expect(downloader.download).toHaveBeenCalledTimes(4);
|
||||
expect(useTTSDownloadStore.getState().itemForChapter('book', 'a')?.status).toBe('failed');
|
||||
expect(cancelDownloadSections).toHaveBeenCalledWith([0]);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
test('repairs a pinned section whose durable pack is missing', async () => {
|
||||
|
|
|
|||
|
|
@ -56,7 +56,7 @@ describe('TTSDownloader', () => {
|
|||
expect(warmer.manifests).toEqual([{ section: 2, labels: ['0:s0', '0:s1', '0:s2'] }]);
|
||||
expect(warmer.warmed.map((w) => w.text)).toEqual(['a', 'b', 'c']);
|
||||
expect(warmer.compacts).toBe(1);
|
||||
expect(progress).toEqual(['1/3', '2/3', '3/3']);
|
||||
expect(progress).toEqual(['0/3', '1/3', '2/3', '3/3']);
|
||||
expect(result.completed).toEqual([2]);
|
||||
});
|
||||
|
||||
|
|
@ -128,6 +128,7 @@ describe('TTSDownloader', () => {
|
|||
const order: string[] = [];
|
||||
const prefetchSentences = vi.fn(async (sentences: { lang: string; text: string }[]) => {
|
||||
order.push(`prefetch:${sentences.map((s) => s.text).join(',')}`);
|
||||
return true;
|
||||
});
|
||||
vi.mocked(warmer.warmSentence).mockImplementation(async (_s, _o, _l, text) => {
|
||||
order.push(`warm:${text}`);
|
||||
|
|
@ -149,6 +150,47 @@ describe('TTSDownloader', () => {
|
|||
);
|
||||
});
|
||||
|
||||
test('counts the sentences of a windowed warmer as they arrive, in any order', async () => {
|
||||
enumerated[0] = [sentence(0, 'A.'), sentence(1, 'B.'), sentence(2, 'C.')];
|
||||
const arrive = new Map<string, (ok: boolean) => void>();
|
||||
vi.mocked(warmer.warmSentence).mockImplementation(
|
||||
(_s, _o, _l, text) => new Promise((resolve) => arrive.set(text, resolve)),
|
||||
);
|
||||
const prefetchSentences = vi.fn(async () => true);
|
||||
const progress: string[] = [];
|
||||
const done = new TTSDownloader(enumerator, { ...warmer, prefetchSentences }).download(
|
||||
[0],
|
||||
(p) => progress.push(`${p.done}/${p.total} ${p.synthesized}`),
|
||||
);
|
||||
const flush = () => new Promise((r) => setTimeout(r, 0));
|
||||
await flush();
|
||||
// The total shows at once, before any sentence arrives.
|
||||
expect(progress).toEqual(['0/3 0']);
|
||||
// Every sentence is waited on at once: a later window may finish first.
|
||||
expect([...arrive.keys()]).toEqual(['A.', 'B.', 'C.']);
|
||||
arrive.get('C.')!(true);
|
||||
await flush();
|
||||
expect(progress).toEqual(['0/3 0', '1/3 1']);
|
||||
// A sentence that failed is not in the cache: progress counts cached ones.
|
||||
arrive.get('A.')!(false);
|
||||
arrive.get('B.')!(true);
|
||||
const result = await done;
|
||||
expect(progress).toEqual(['0/3 0', '1/3 1', '2/3 2']);
|
||||
expect(result).toEqual({ completed: [], skipped: [0], synthesized: 2 });
|
||||
});
|
||||
|
||||
test('a fatal synthesis failure (quota) ends a windowed download too', async () => {
|
||||
const { SpeechSynthesisFatalError } = await import('@/services/tts/providers/types');
|
||||
enumerated[0] = [sentence(0, 'A.'), sentence(1, 'B.')];
|
||||
vi.mocked(warmer.warmSentence).mockRejectedValue(
|
||||
new SpeechSynthesisFatalError('DAILY_QUOTA_EXCEEDED'),
|
||||
);
|
||||
const prefetchSentences = vi.fn(async () => true);
|
||||
await expect(
|
||||
new TTSDownloader(enumerator, { ...warmer, prefetchSentences }).download([0]),
|
||||
).rejects.toThrow('DAILY_QUOTA_EXCEEDED');
|
||||
});
|
||||
|
||||
test('a fatal synthesis failure (quota) ends the whole download', async () => {
|
||||
const { SpeechSynthesisFatalError } = await import('@/services/tts/providers/types');
|
||||
enumerated[0] = [sentence(0, 'A.'), sentence(1, 'B.')];
|
||||
|
|
|
|||
|
|
@ -471,6 +471,55 @@ describe('errors', () => {
|
|||
expect(m.fetchWithAuth.mock.calls.filter(([, i]) => i.method === 'POST')).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('tells the user again when a later request is refused for quota', async () => {
|
||||
vi.useFakeTimers({ toFake: ['Date'] });
|
||||
try {
|
||||
const quota = vi.fn();
|
||||
events.addEventListener('tts-quota-exceeded', quota);
|
||||
m.fetchWithAuth.mockImplementation(async (_url: string, init: RequestInit) => {
|
||||
if (init.method === 'POST') throw new Error('DAILY_QUOTA_EXCEEDED');
|
||||
return Response.json({ voices: VOICES });
|
||||
});
|
||||
const signal = new AbortController().signal;
|
||||
await expect(provider.synthesize(req('A.'), signal)).rejects.toThrow();
|
||||
await expect(provider.synthesize(req('B.'), signal)).rejects.toThrow();
|
||||
// One toast for a burst of refusals (a download refuses many at once).
|
||||
expect(quota).toHaveBeenCalledTimes(1);
|
||||
// Play pressed again later: refused without a request, but not silently.
|
||||
vi.setSystemTime(Date.now() + 10_000);
|
||||
await expect(provider.synthesize(req('C.'), signal)).rejects.toThrow();
|
||||
expect(quota).toHaveBeenCalledTimes(2);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('asks the server again a minute after a quota rejection (retry, upgrade, new day)', async () => {
|
||||
vi.useFakeTimers({ toFake: ['Date'] });
|
||||
try {
|
||||
m.fetchWithAuth.mockImplementation(async (_url: string, init: RequestInit) => {
|
||||
if (init.method === 'POST') throw new Error('DAILY_QUOTA_EXCEEDED');
|
||||
return Response.json({ voices: VOICES });
|
||||
});
|
||||
const signal = new AbortController().signal;
|
||||
await expect(provider.synthesize(req('A.'), signal)).rejects.toBeInstanceOf(
|
||||
SpeechSynthesisFatalError,
|
||||
);
|
||||
await expect(provider.synthesize(req('B.'), signal)).rejects.toBeInstanceOf(
|
||||
SpeechSynthesisFatalError,
|
||||
);
|
||||
const posts = () => m.fetchWithAuth.mock.calls.filter(([, i]) => i.method === 'POST');
|
||||
expect(posts()).toHaveLength(1);
|
||||
vi.setSystemTime(Date.now() + 60_000);
|
||||
await expect(provider.synthesize(req('C.'), signal)).rejects.toBeInstanceOf(
|
||||
SpeechSynthesisFatalError,
|
||||
);
|
||||
expect(posts()).toHaveLength(2);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
'UNKNOWN_VOICE',
|
||||
'VOICE_TIER_REQUIRED',
|
||||
|
|
@ -536,16 +585,24 @@ describe('download jobs', () => {
|
|||
});
|
||||
const all = () => jobs!;
|
||||
|
||||
it('submits windows of up to 64 sentences as jobs, four at a time', async () => {
|
||||
provider.prefetch(reqs(300), 'download', new AbortController().signal);
|
||||
await flush();
|
||||
expect(all().map((j) => j.body.segments.length)).toEqual([64, 64, 64, 64]);
|
||||
it('submits jobs of up to 2000 characters, four at a time', async () => {
|
||||
// 900-character sentences: two fit in a window, a third would not.
|
||||
const long = Array.from({ length: 10 }, (_, i) => req(`${'a'.repeat(898)}${i}.`));
|
||||
provider.prefetch(long, 'download', new AbortController().signal);
|
||||
await flush(6);
|
||||
expect(all().map((j) => j.body.segments.length)).toEqual([2, 2, 2, 2]);
|
||||
expect(all()[0]!.body).toMatchObject({ lane: 'download', lang: 'en-US' });
|
||||
expect(windows).toHaveLength(0);
|
||||
|
||||
all()[1]!.complete();
|
||||
await flush();
|
||||
expect(all().map((j) => j.body.segments.length)).toEqual([64, 64, 64, 64, 44]);
|
||||
expect(all().map((j) => j.body.segments.length)).toEqual([2, 2, 2, 2, 2]);
|
||||
});
|
||||
|
||||
it('caps a job at the 64 sentences a window may hold', async () => {
|
||||
provider.prefetch(reqs(100), 'download', new AbortController().signal);
|
||||
await flush(6);
|
||||
expect(all().map((j) => j.body.segments.length)).toEqual([64, 36]);
|
||||
});
|
||||
|
||||
it('resolves sentences from the result once the job is done, polling meanwhile', async () => {
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { beforeEach, describe, expect, test } from 'vitest';
|
||||
import { beforeEach, describe, expect, test, vi } from 'vitest';
|
||||
|
||||
import { NodeDatabaseService } from '@/services/database/nodeDatabaseService';
|
||||
import { SqliteTTSCacheStore } from '@/services/tts/providers/sqliteCacheStore';
|
||||
|
|
@ -23,6 +23,43 @@ describe('SqliteTTSCacheStore', () => {
|
|||
return new SqliteTTSCacheStore(db, { budgetBytes, now: () => now++ });
|
||||
};
|
||||
|
||||
test('registers a long section in a few statements, keeping recorded keys', async () => {
|
||||
const store = makeStore(1024 * 1024);
|
||||
const marks = Array.from({ length: 300 }, (_, i) => `0:s${i}`);
|
||||
await store.registerSectionMarks(4, marks);
|
||||
await store.put('key7', entry(8));
|
||||
await store.recordMarkKey(4, 7, 'key7');
|
||||
// Each statement is a round trip to the database worker: a chapter
|
||||
// must not cost one per sentence.
|
||||
const execute = vi.spyOn(db, 'execute');
|
||||
await store.registerSectionMarks(4, [...marks.slice(0, 250), 'changed']);
|
||||
expect(execute.mock.calls.length).toBeLessThanOrEqual(5);
|
||||
const status = (await store.getSectionStatuses()).get(4);
|
||||
expect(status).toMatchObject({ total: 251, recorded: 1 });
|
||||
});
|
||||
|
||||
test('tells which keys are cached in one query, however many', async () => {
|
||||
const store = makeStore(1024 * 1024);
|
||||
await store.put('a', entry(8));
|
||||
await store.put('b', entry(8));
|
||||
const keys = ['a', 'b', 'c', ...Array.from({ length: 1500 }, (_, i) => `k${i}`)];
|
||||
const select = vi.spyOn(db, 'select');
|
||||
expect(await store.cachedKeys(keys)).toEqual(new Set(['a', 'b']));
|
||||
expect(select.mock.calls.length).toBeLessThanOrEqual(3);
|
||||
});
|
||||
|
||||
test('does not report an entry its deleted pack left without audio', async () => {
|
||||
const store = makeStore(1024 * 1024);
|
||||
await store.put('kept', entry(8));
|
||||
// What pack deletion leaves when no other pack holds the key.
|
||||
await db.execute(
|
||||
`INSERT INTO entries (key, audio, pack_id, boundaries, size, created_at, accessed_at)
|
||||
VALUES ('detached', NULL, NULL, '[]', 0, 1, 1)`,
|
||||
);
|
||||
expect(await store.get('detached')).toBeNull();
|
||||
expect(await store.cachedKeys(['kept', 'detached'])).toEqual(new Set(['kept']));
|
||||
});
|
||||
|
||||
test('round-trips audio, boundaries, and duration', async () => {
|
||||
const store = makeStore(1024 * 1024);
|
||||
await store.put('key1', entry(64, 7), { provider: 'edge-tts', voice: 'v1' });
|
||||
|
|
|
|||
|
|
@ -15,8 +15,8 @@ describe('getTTSQuota', () => {
|
|||
afterEach(() => vi.unstubAllEnvs());
|
||||
|
||||
it('returns per-plan daily character quotas', () => {
|
||||
expect(getTTSQuota('plus')).toBe(100 * 1024);
|
||||
expect(getTTSQuota('pro')).toBe(300 * 1024);
|
||||
expect(getTTSQuota('plus')).toBe(500_000);
|
||||
expect(getTTSQuota('pro')).toBe(1_000_000);
|
||||
expect(getTTSQuota('free')).toBe(0);
|
||||
expect(getTTSQuota('purchase')).toBe(0);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -18,8 +18,10 @@ export async function POST(request: NextRequest) {
|
|||
const body = (await request.json().catch(() => null)) as { warmup?: unknown } | null;
|
||||
if (body?.warmup !== true) return errorResponse('INVALID_INPUT', 400);
|
||||
// Best effort: the voice picker does not wait on it.
|
||||
await gate.ctx.service.warmup().catch((error) => {
|
||||
try {
|
||||
await gate.ctx.service.warmup();
|
||||
} catch (error) {
|
||||
console.warn('Readest Voice warmup failed:', error);
|
||||
});
|
||||
}
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import clsx from 'clsx';
|
|||
import { MdGraphicEq } from 'react-icons/md';
|
||||
import { useTranslation } from '@/hooks/useTranslation';
|
||||
import { formatBytes } from '@/utils/book';
|
||||
import { DAILY_QUOTA_EXCEEDED } from '@/services/tts/providers/types';
|
||||
import DownloadBadge from './DownloadBadge';
|
||||
import type { UseTTSDownloadsResult } from '@/app/reader/hooks/useTTSDownloads';
|
||||
|
||||
|
|
@ -113,7 +114,9 @@ const TTSChaptersView: React.FC<TTSChaptersViewProps> = ({
|
|||
: item?.status === 'pending'
|
||||
? _('Waiting…')
|
||||
: item?.status === 'failed'
|
||||
? _('Download failed')
|
||||
? item.error === DAILY_QUOTA_EXCEEDED
|
||||
? _('Quota Exceeded')
|
||||
: _('Download failed')
|
||||
: status === 'complete'
|
||||
? _('Downloaded')
|
||||
: status === 'partial'
|
||||
|
|
|
|||
|
|
@ -91,7 +91,9 @@ export interface ReadestVoiceService {
|
|||
let verified: Promise<boolean> | null = null;
|
||||
|
||||
const checkContract = (service: ReadestVoiceService): Promise<boolean> =>
|
||||
(verified ??= service.contractVersion().then(
|
||||
// Promise.resolve: under next dev the platform proxy answers RPC calls
|
||||
// with plain values.
|
||||
(verified ??= Promise.resolve(service.contractVersion()).then(
|
||||
(version) => {
|
||||
if (version === CONTRACT_VERSION) return true;
|
||||
console.error(
|
||||
|
|
|
|||
|
|
@ -1041,8 +1041,8 @@ export const DEFAULT_DAILY_TRANSLATION_QUOTA: UserDailyTranslationQuota = {
|
|||
|
||||
export const DEFAULT_DAILY_TTS_QUOTA: UserDailyTTSQuota = {
|
||||
free: 0,
|
||||
plus: 100 * 1024,
|
||||
pro: 300 * 1024,
|
||||
plus: 500_000,
|
||||
pro: 1_000_000,
|
||||
purchase: 0,
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -717,17 +717,19 @@ export class BufferedTTSClient implements TTSClient {
|
|||
|
||||
// Chapter downloads: hand a windowed provider the whole section on the
|
||||
// download lane (cached sentences are filtered out by CachingProvider).
|
||||
// Whether it did: its sentences then arrive in windows, in any order.
|
||||
async prefetchSentences(
|
||||
sentences: { lang: string; text: string }[],
|
||||
signal?: AbortSignal,
|
||||
): Promise<void> {
|
||||
if (!this.provider.prefetch) return;
|
||||
): Promise<boolean> {
|
||||
if (!this.provider.prefetch) return false;
|
||||
const reqs: SpeechSynthesisRequest[] = [];
|
||||
for (const { lang, text } of sentences) {
|
||||
const voice = await this.getVoiceIdFromLang(lang);
|
||||
reqs.push({ lang, text, voice, pitch: this.#pitch });
|
||||
}
|
||||
this.provider.prefetch(reqs, 'download', signal ?? new AbortController().signal);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Synthesize one sentence into the cache (a hit is a no-op) and record its
|
||||
|
|
|
|||
|
|
@ -46,12 +46,12 @@ export interface CacheWarmer {
|
|||
compactCache(): Promise<void>;
|
||||
// Windowed engines: announce a whole section up front so it synthesizes in
|
||||
// a few large requests; warmSentence then picks each sentence up as it
|
||||
// arrives. A fatal failure (e.g. quota) thrown by warmSentence ends the
|
||||
// download.
|
||||
// arrives. Resolves whether the section was handed off. A fatal failure
|
||||
// (e.g. quota) thrown by warmSentence ends the download.
|
||||
prefetchSentences?(
|
||||
sentences: { lang: string; text: string }[],
|
||||
signal?: AbortSignal,
|
||||
): Promise<void>;
|
||||
): Promise<boolean>;
|
||||
}
|
||||
|
||||
export interface SectionDownloadProgress {
|
||||
|
|
@ -96,12 +96,15 @@ export class TTSDownloader {
|
|||
continue;
|
||||
}
|
||||
|
||||
// The total shows at once; preparing the section can take a while.
|
||||
onProgress?.({ sectionIndex, total: sentences.length, done: 0, synthesized: 0 });
|
||||
|
||||
await this.#warmer.registerSectionManifest(
|
||||
sectionIndex,
|
||||
sentences.map((s) => s.label),
|
||||
);
|
||||
|
||||
await this.#warmer.prefetchSentences?.(
|
||||
const windowed = await this.#warmer.prefetchSentences?.(
|
||||
sentences.map(({ lang, text }) => ({ lang, text })),
|
||||
signal,
|
||||
);
|
||||
|
|
@ -109,21 +112,56 @@ export class TTSDownloader {
|
|||
let synthesized = 0;
|
||||
let failed = false;
|
||||
let aborted = false;
|
||||
for (let done = 0; done < sentences.length; done++) {
|
||||
if (signal?.aborted) {
|
||||
aborted = true;
|
||||
break;
|
||||
if (windowed) {
|
||||
// Windows run several at a time and may finish in any order: wait on
|
||||
// every sentence at once and count each as it lands in the cache, so
|
||||
// progress moves as soon as any window is done.
|
||||
const results = await Promise.all(
|
||||
sentences.map(async (s) => {
|
||||
const ok = await this.#warmer.warmSentence(
|
||||
sectionIndex,
|
||||
s.ordinal,
|
||||
s.lang,
|
||||
s.text,
|
||||
signal,
|
||||
);
|
||||
if (ok) {
|
||||
synthesized++;
|
||||
onProgress?.({
|
||||
sectionIndex,
|
||||
total: sentences.length,
|
||||
done: synthesized,
|
||||
synthesized,
|
||||
});
|
||||
}
|
||||
return ok;
|
||||
}),
|
||||
);
|
||||
aborted = !!signal?.aborted;
|
||||
failed = results.includes(false);
|
||||
} else {
|
||||
for (let done = 0; done < sentences.length; done++) {
|
||||
if (signal?.aborted) {
|
||||
aborted = true;
|
||||
break;
|
||||
}
|
||||
const s = sentences[done]!;
|
||||
const ok = await this.#warmer.warmSentence(
|
||||
sectionIndex,
|
||||
s.ordinal,
|
||||
s.lang,
|
||||
s.text,
|
||||
signal,
|
||||
);
|
||||
if (ok) synthesized++;
|
||||
else failed = true;
|
||||
onProgress?.({
|
||||
sectionIndex,
|
||||
total: sentences.length,
|
||||
done: done + 1,
|
||||
synthesized,
|
||||
});
|
||||
}
|
||||
const s = sentences[done]!;
|
||||
const ok = await this.#warmer.warmSentence(sectionIndex, s.ordinal, s.lang, s.text, signal);
|
||||
if (ok) synthesized++;
|
||||
else failed = true;
|
||||
onProgress?.({
|
||||
sectionIndex,
|
||||
total: sentences.length,
|
||||
done: done + 1,
|
||||
synthesized,
|
||||
});
|
||||
}
|
||||
|
||||
// Compact whatever completed. A section left partial by an abort or an
|
||||
|
|
|
|||
|
|
@ -198,6 +198,11 @@ export class BookTTSCacheStore implements TTSCacheStore {
|
|||
return opened ? opened.store.get(key) : null;
|
||||
}
|
||||
|
||||
async cachedKeys(keys: string[]): Promise<Set<string>> {
|
||||
const opened = await this.#open();
|
||||
return opened ? opened.store.cachedKeys(keys) : new Set();
|
||||
}
|
||||
|
||||
async put(
|
||||
key: string,
|
||||
entry: TTSCacheEntry,
|
||||
|
|
|
|||
|
|
@ -28,6 +28,9 @@ export interface TTSCacheStore {
|
|||
// Open the backing store ahead of the first lookup (no-op if it cannot yet).
|
||||
open?(): Promise<void>;
|
||||
get(key: string): Promise<TTSCacheEntry | null>;
|
||||
// Which of these keys are cached, in one lookup (a download checks a whole
|
||||
// section at once).
|
||||
cachedKeys?(keys: string[]): Promise<Set<string>>;
|
||||
put(
|
||||
key: string,
|
||||
entry: TTSCacheEntry,
|
||||
|
|
@ -153,6 +156,14 @@ export class CachingProvider implements SpeechProvider {
|
|||
): Promise<void> {
|
||||
const uncached: SpeechSynthesisRequest[] = [];
|
||||
const toFill: SpeechSynthesisRequest[] = [];
|
||||
// A caller that needs no cached audio back (a download) checks the whole
|
||||
// batch in one lookup instead of reading each sentence.
|
||||
const cachedKeys =
|
||||
this.#store.cachedKeys && !options?.onDelivered
|
||||
? await this.#store
|
||||
.cachedKeys(reqs.map((req) => computeTTSCacheKey(this.#inner.id, req)))
|
||||
.catch(() => new Set<string>()) // Unreadable store: treat as uncached.
|
||||
: null;
|
||||
for (const req of reqs) {
|
||||
const key = computeTTSCacheKey(this.#inner.id, req);
|
||||
// Already being filled: still forwarded, so the provider can raise a
|
||||
|
|
@ -161,15 +172,19 @@ export class CachingProvider implements SpeechProvider {
|
|||
uncached.push(req);
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
const cached = this.#recent.get(key) ?? (await this.#store.get(key));
|
||||
if (cached) {
|
||||
this.#remember(key, cached);
|
||||
options?.onDelivered?.(req, { audio: cached.audio, boundaries: cached.boundaries });
|
||||
continue;
|
||||
if (cachedKeys) {
|
||||
if (this.#recent.has(key) || cachedKeys.has(key)) continue;
|
||||
} else {
|
||||
try {
|
||||
const cached = this.#recent.get(key) ?? (await this.#store.get(key));
|
||||
if (cached) {
|
||||
this.#remember(key, cached);
|
||||
options?.onDelivered?.(req, { audio: cached.audio, boundaries: cached.boundaries });
|
||||
continue;
|
||||
}
|
||||
} catch {
|
||||
// Unreadable store: treat as uncached.
|
||||
}
|
||||
} catch {
|
||||
// Unreadable store: treat as uncached.
|
||||
}
|
||||
uncached.push(req);
|
||||
toFill.push(req);
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ import { readNDJSON } from '@/utils/ndjson';
|
|||
import { estimateSentenceSeconds } from '../ttsDuration';
|
||||
import type { TTSVoice } from '../types';
|
||||
import {
|
||||
DAILY_QUOTA_EXCEEDED,
|
||||
type PrefetchOptions,
|
||||
type SpeechProvider,
|
||||
SpeechSynthesisFatalError,
|
||||
|
|
@ -26,26 +27,33 @@ import {
|
|||
// current paragraph is waiting on fill a window before background preloads
|
||||
// of later paragraphs, never mixing languages. A window frees the lane as
|
||||
// soon as its last sentence arrives.
|
||||
// - download: chapter downloads, up to 64 sentences per window, submitted as
|
||||
// durable jobs that any worker may run (/api/tts/readest/jobs), up to four
|
||||
// at a time, and collected when done. A server without jobs (off Workers)
|
||||
// gets streamed windows instead, one at a time, like listening.
|
||||
// - download: chapter downloads, in windows of up to 2000 characters (about
|
||||
// two minutes of audio, so progress moves often and work spreads across
|
||||
// workers), submitted as durable jobs that any worker may run
|
||||
// (/api/tts/readest/jobs), up to four at a time, and collected when done.
|
||||
// A server without jobs (off Workers) gets streamed windows instead, one
|
||||
// at a time, like listening.
|
||||
// A sentence stays requested while any caller that asked for it is still
|
||||
// interested; once every such signal is aborted it is withdrawn, and a window
|
||||
// nobody wants any more is aborted, which cancels its GPU job server-side.
|
||||
|
||||
export const DAILY_QUOTA_EXCEEDED = 'DAILY_QUOTA_EXCEEDED';
|
||||
|
||||
const LISTEN_WINDOW_SIZES = [1, 4, 8];
|
||||
const LISTEN_WINDOW_CHARS = 2000;
|
||||
const LISTEN_WINDOW_SEC = 20;
|
||||
// A window of background preloads only: nobody waits on it, so it may carry
|
||||
// more audio, amortizing the per-request overhead and batching on the GPU.
|
||||
const LISTEN_BACKGROUND_WINDOW_SEC = 60;
|
||||
// The most sentences a download window may hold (the route's limit).
|
||||
const DOWNLOAD_WINDOW_SENTENCES = 64;
|
||||
const DOWNLOAD_WINDOW_CHARS = 12000;
|
||||
const DOWNLOAD_WINDOW_CHARS = 2000;
|
||||
const DOWNLOAD_JOBS = 4;
|
||||
const BUSY_RETRY_MS = 5000;
|
||||
// After a quota refusal, ask the server again no sooner than this: a retry,
|
||||
// an upgrade or a new day may have made room.
|
||||
const QUOTA_RECHECK_MS = 60_000;
|
||||
// Refusals within this long of the last notice (a toast's lifetime) are one
|
||||
// notice: a download refuses many sentences at once.
|
||||
const QUOTA_NOTICE_MS = 5_000;
|
||||
// Route codes that will fail again for the same sentences.
|
||||
const PERMANENT_CODES = new Set(['UNKNOWN_VOICE', 'VOICE_TIER_REQUIRED', 'INVALID_INPUT']);
|
||||
// Job codes worth submitting the window again for: another device of the user
|
||||
|
|
@ -114,7 +122,9 @@ export class ReadestVoiceProvider implements SpeechProvider {
|
|||
|
||||
readonly #events: EventTarget | undefined;
|
||||
#voices: Promise<TTSVoice[]> | null = null;
|
||||
#quotaExhausted = false;
|
||||
// When the server last refused for quota (0: not refused).
|
||||
#quotaExhaustedAt = 0;
|
||||
#quotaNoticeAt = 0;
|
||||
#warmupFired = false;
|
||||
// Whether the server runs download jobs (null: not known yet, so one
|
||||
// download goes out at a time); without them downloads stream.
|
||||
|
|
@ -142,7 +152,7 @@ export class ReadestVoiceProvider implements SpeechProvider {
|
|||
|
||||
async init(): Promise<boolean> {
|
||||
// A new session (or day) may have fresh quota.
|
||||
this.#quotaExhausted = false;
|
||||
this.#quotaExhaustedAt = 0;
|
||||
const voices = await this.getAllVoices();
|
||||
this.#voices = null; // the next init asks again (plan or catalog may change)
|
||||
return voices.length > 0;
|
||||
|
|
@ -164,7 +174,8 @@ export class ReadestVoiceProvider implements SpeechProvider {
|
|||
signal: AbortSignal,
|
||||
options?: PrefetchOptions,
|
||||
): Promise<SpeechSynthesisResult> {
|
||||
if (this.#quotaExhausted) {
|
||||
if (this.#quotaExhausted()) {
|
||||
this.#noticeQuota();
|
||||
return Promise.reject(new SpeechSynthesisFatalError(DAILY_QUOTA_EXCEEDED));
|
||||
}
|
||||
// No Readest voice for this sentence's language: skip it rather than read
|
||||
|
|
@ -204,7 +215,7 @@ export class ReadestVoiceProvider implements SpeechProvider {
|
|||
signal: AbortSignal,
|
||||
options?: PrefetchOptions,
|
||||
): void {
|
||||
if (this.#quotaExhausted || signal.aborted) return;
|
||||
if (this.#quotaExhausted() || signal.aborted) return;
|
||||
const background = lane === 'listen' && !!options?.background;
|
||||
const onDelivered = options?.onDelivered;
|
||||
for (const req of reqs) {
|
||||
|
|
@ -512,13 +523,23 @@ export class ReadestVoiceProvider implements SpeechProvider {
|
|||
}
|
||||
}
|
||||
|
||||
// Every further request would be refused too: fail everything and tell the
|
||||
// user once. init() (a new session) clears it.
|
||||
#quotaExhausted() {
|
||||
return Date.now() - this.#quotaExhaustedAt < QUOTA_RECHECK_MS;
|
||||
}
|
||||
|
||||
// Tells the user why a request was refused (tts-quota-exceeded), once per
|
||||
// burst of refusals.
|
||||
#noticeQuota() {
|
||||
if (Date.now() - this.#quotaNoticeAt < QUOTA_NOTICE_MS) return;
|
||||
this.#quotaNoticeAt = Date.now();
|
||||
this.#events?.dispatchEvent(new CustomEvent('tts-quota-exceeded'));
|
||||
}
|
||||
|
||||
// Further requests would be refused too for a while: fail everything and
|
||||
// tell the user. init() (a new session) clears it.
|
||||
#exhaustQuota() {
|
||||
if (!this.#quotaExhausted) {
|
||||
this.#quotaExhausted = true;
|
||||
this.#events?.dispatchEvent(new CustomEvent('tts-quota-exceeded'));
|
||||
}
|
||||
this.#noticeQuota();
|
||||
this.#quotaExhaustedAt = Date.now();
|
||||
const fatal = new SpeechSynthesisFatalError(DAILY_QUOTA_EXCEEDED);
|
||||
for (const lane of Object.values(this.#lanes)) {
|
||||
lane.queue = [];
|
||||
|
|
|
|||
|
|
@ -159,6 +159,8 @@ const SCHEMA = [
|
|||
|
||||
// Batch accessed_at updates: reads must not each cost a synchronous write.
|
||||
const TOUCH_FLUSH_LIMIT = 64;
|
||||
// Rows per multi-row statement, under SQLite's oldest 999-parameter limit.
|
||||
const BATCH_ROWS = 300;
|
||||
|
||||
// importPack stores synced packs under a fingerprint prefixed with this, so a
|
||||
// pack adopted from another device never equals the local manifest
|
||||
|
|
@ -295,6 +297,25 @@ export class SqliteTTSCacheStore implements TTSCacheStore {
|
|||
}
|
||||
}
|
||||
|
||||
// Which of these keys have audio cached, in a few queries (a download
|
||||
// checks a whole section at once).
|
||||
async cachedKeys(keys: string[]): Promise<Set<string>> {
|
||||
await this.#ensureSchema();
|
||||
const cached = new Set<string>();
|
||||
for (let start = 0; start < keys.length; start += BATCH_ROWS * 3) {
|
||||
const batch = keys.slice(start, start + BATCH_ROWS * 3);
|
||||
const rows = await this.#db.select<DatabaseRow & { key: string }>(
|
||||
// A row a deleted pack left without audio (and without a pack) is a miss.
|
||||
`SELECT key FROM entries
|
||||
WHERE key IN (${batch.map(() => '?').join(', ')})
|
||||
AND (audio IS NOT NULL OR pack_id IS NOT NULL)`,
|
||||
batch,
|
||||
);
|
||||
for (const row of rows) cached.add(row.key);
|
||||
}
|
||||
return cached;
|
||||
}
|
||||
|
||||
async put(
|
||||
key: string,
|
||||
entry: TTSCacheEntry,
|
||||
|
|
@ -347,11 +368,14 @@ export class SqliteTTSCacheStore implements TTSCacheStore {
|
|||
// (section, ordinal) primary key. UPSERT keeps each ordinal unique and
|
||||
// preserves a key already recorded for an unchanged mark; a trailing
|
||||
// DELETE trims ordinals left over from a shorter new manifest.
|
||||
for (let i = 0; i < marks.length; i++) {
|
||||
// Many rows per statement: each is a round trip to the database worker.
|
||||
for (let start = 0; start < marks.length; start += BATCH_ROWS) {
|
||||
const batch = marks.slice(start, start + BATCH_ROWS);
|
||||
await this.#db.execute(
|
||||
`INSERT INTO manifest_marks (section, ordinal, mark, key) VALUES (?, ?, ?, NULL)
|
||||
`INSERT INTO manifest_marks (section, ordinal, mark, key)
|
||||
VALUES ${batch.map(() => '(?, ?, ?, NULL)').join(', ')}
|
||||
ON CONFLICT(section, ordinal) DO UPDATE SET mark = excluded.mark`,
|
||||
[section, i, marks[i]!],
|
||||
batch.flatMap((mark, i) => [section, start + i, mark]),
|
||||
);
|
||||
}
|
||||
await this.#db.execute('DELETE FROM manifest_marks WHERE section = ? AND ordinal >= ?', [
|
||||
|
|
|
|||
|
|
@ -51,6 +51,9 @@ export class SpeechSynthesisFatalError extends Error {
|
|||
}
|
||||
}
|
||||
|
||||
// The fatal error's message when the daily synthesis quota is used up.
|
||||
export const DAILY_QUOTA_EXCEEDED = 'DAILY_QUOTA_EXCEEDED';
|
||||
|
||||
// Who a prefetch serves: live listening or a chapter download. Windowed
|
||||
// providers admit and size the two differently.
|
||||
export type TTSLane = 'listen' | 'download';
|
||||
|
|
|
|||
|
|
@ -13,11 +13,16 @@
|
|||
import type { TTSDownloadItem } from '@/store/ttsDownloadStore';
|
||||
import { useTTSDownloadStore } from '@/store/ttsDownloadStore';
|
||||
import type { DownloadChapter } from './downloadChapters';
|
||||
import { SpeechSynthesisFatalError } from './providers/types';
|
||||
import type { TTSController } from './TTSController';
|
||||
import type { SectionDownloadProgress } from './TTSDownloader';
|
||||
|
||||
const QUEUE_KEY = 'readest_tts_download_queue';
|
||||
const QUEUE_SCHEMA_VERSION = 1;
|
||||
// A failed run (offline, server hiccup) runs again on its own, after 10, 20
|
||||
// and 30 s; each run only synthesizes what is still missing.
|
||||
const MAX_RETRIES = 3;
|
||||
const RETRY_DELAY_MS = 10_000;
|
||||
|
||||
interface PersistedQueueData {
|
||||
schemaVersion?: number;
|
||||
|
|
@ -41,6 +46,8 @@ export class TTSDownloadManager {
|
|||
#controllers = new Map<string, () => TTSController | null>();
|
||||
#activeDownloads = new Map<string, ActiveDownload>();
|
||||
#unsettledDownloads = new Map<string, Set<ActiveDownload>>();
|
||||
// Items waiting out their retry delay.
|
||||
#retryWaits = new Map<string, ReturnType<typeof setTimeout>>();
|
||||
#isProcessing = false;
|
||||
#loaded = false;
|
||||
|
||||
|
|
@ -98,6 +105,7 @@ export class TTSDownloadManager {
|
|||
// attempt inert, even if the same deterministic row ID is queued again.
|
||||
this.#activeDownloads.delete(id);
|
||||
if (active) void this.#cancelActive(active);
|
||||
this.#clearRetryWait(id);
|
||||
useTTSDownloadStore.getState().removeItem(id);
|
||||
this.persist();
|
||||
}
|
||||
|
|
@ -116,6 +124,7 @@ export class TTSDownloadManager {
|
|||
void this.#cancelActive(active);
|
||||
}
|
||||
for (const item of store.itemsForBook(bookHash)) {
|
||||
this.#clearRetryWait(item.id);
|
||||
store.removeItem(item.id);
|
||||
}
|
||||
this.persist();
|
||||
|
|
@ -147,6 +156,7 @@ export class TTSDownloadManager {
|
|||
.filter(
|
||||
(item) =>
|
||||
item.status === 'pending' &&
|
||||
!this.#retryWaits.has(item.id) &&
|
||||
!parkedBooks.has(item.bookHash) &&
|
||||
this.#controllers.has(item.bookHash),
|
||||
)
|
||||
|
|
@ -215,7 +225,7 @@ export class TTSDownloadManager {
|
|||
const finish = (error?: string) => {
|
||||
if (!isCurrent()) return;
|
||||
this.#activeDownloads.delete(item.id);
|
||||
if (error) store.setFailed(item.id, error);
|
||||
if (error) this.#fail(item.id, error, true);
|
||||
else store.removeItem(item.id);
|
||||
this.persist();
|
||||
};
|
||||
|
|
@ -280,10 +290,10 @@ export class TTSDownloadManager {
|
|||
await this.#cancelActive(active);
|
||||
if (this.#activeDownloads.get(item.id) !== active) return true;
|
||||
this.#activeDownloads.delete(item.id);
|
||||
store.setFailed(item.id, err instanceof Error ? err.message : String(err));
|
||||
this.#failWith(item.id, err);
|
||||
this.persist();
|
||||
} else if (useTTSDownloadStore.getState().items[item.id] === current) {
|
||||
store.setFailed(item.id, err instanceof Error ? err.message : String(err));
|
||||
this.#failWith(item.id, err);
|
||||
this.persist();
|
||||
}
|
||||
} finally {
|
||||
|
|
@ -297,6 +307,35 @@ export class TTSDownloadManager {
|
|||
return true;
|
||||
}
|
||||
|
||||
#failWith(id: string, err: unknown): void {
|
||||
// A fatal failure (quota) would only fail again.
|
||||
const retryable = !(err instanceof SpeechSynthesisFatalError);
|
||||
this.#fail(id, err instanceof Error ? err.message : String(err), retryable);
|
||||
}
|
||||
|
||||
#fail(id: string, error: string, retryable: boolean): void {
|
||||
const store = useTTSDownloadStore.getState();
|
||||
const retries = store.items[id]?.retries ?? 0;
|
||||
if (!retryable || retries >= MAX_RETRIES) {
|
||||
store.setFailed(id, error);
|
||||
return;
|
||||
}
|
||||
store.setRetrying(id);
|
||||
const wait = setTimeout(
|
||||
() => {
|
||||
this.#retryWaits.delete(id);
|
||||
void this.processQueue();
|
||||
},
|
||||
RETRY_DELAY_MS * (retries + 1),
|
||||
);
|
||||
this.#retryWaits.set(id, wait);
|
||||
}
|
||||
|
||||
#clearRetryWait(id: string): void {
|
||||
clearTimeout(this.#retryWaits.get(id));
|
||||
this.#retryWaits.delete(id);
|
||||
}
|
||||
|
||||
#cancelActive(active: ActiveDownload): Promise<void> {
|
||||
if (!active.cleanup) {
|
||||
const release = () => active.controller.cancelDownloadSections(active.sections);
|
||||
|
|
|
|||
|
|
@ -29,6 +29,8 @@ export interface TTSDownloadItem {
|
|||
done: number;
|
||||
total: number;
|
||||
error?: string;
|
||||
// Automatic re-runs after a failed run (see ttsDownloadManager).
|
||||
retries?: number;
|
||||
createdAt: number;
|
||||
startedAt?: number;
|
||||
priority: number; // Lower = processed first ('Download all' batches win).
|
||||
|
|
@ -42,6 +44,8 @@ interface TTSDownloadState {
|
|||
setInProgress: (id: string) => void;
|
||||
updateProgress: (id: string, done: number, total: number) => void;
|
||||
setFailed: (id: string, error?: string) => void;
|
||||
// Back to pending for another run, counting the retry.
|
||||
setRetrying: (id: string) => void;
|
||||
|
||||
itemsForBook: (bookHash: string) => TTSDownloadItem[];
|
||||
itemForChapter: (bookHash: string, chapterKey: string) => TTSDownloadItem | undefined;
|
||||
|
|
@ -116,6 +120,19 @@ export const useTTSDownloadStore = create<TTSDownloadState>((set, get) => ({
|
|||
});
|
||||
},
|
||||
|
||||
setRetrying: (id) => {
|
||||
set((state) => {
|
||||
const item = state.items[id];
|
||||
if (!item) return state;
|
||||
return {
|
||||
items: {
|
||||
...state.items,
|
||||
[id]: { ...item, status: 'pending', retries: (item.retries ?? 0) + 1 },
|
||||
},
|
||||
};
|
||||
});
|
||||
},
|
||||
|
||||
itemsForBook: (bookHash) => Object.values(get().items).filter((i) => i.bookHash === bookHash),
|
||||
|
||||
itemForChapter: (bookHash, chapterKey) => get().items[`${bookHash}:${chapterKey}`],
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue