重试机制
This commit is contained in:
@@ -327,6 +327,24 @@ function findTocLabelByHref(items: TocItem[], currentHref: string): string {
|
|||||||
return '';
|
return '';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function fetchJsonWithRetry<T>(url: string, init?: RequestInit, retries = 2): Promise<T> {
|
||||||
|
let lastError: unknown;
|
||||||
|
for (let attempt = 0; attempt <= retries; attempt += 1) {
|
||||||
|
try {
|
||||||
|
const res = await fetch(url, init);
|
||||||
|
const json = await res.json();
|
||||||
|
if (!res.ok) throw new Error(json.error || `请求失败: ${res.status}`);
|
||||||
|
return json as T;
|
||||||
|
} catch (error) {
|
||||||
|
lastError = error;
|
||||||
|
if (attempt < retries) {
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 300 * (attempt + 1)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw lastError instanceof Error ? lastError : new Error('请求失败');
|
||||||
|
}
|
||||||
|
|
||||||
async function downloadBookWithProgress(
|
async function downloadBookWithProgress(
|
||||||
manifest: Pick<BookReadManifest, 'book' | 'format' | 'acquisitionHref'>,
|
manifest: Pick<BookReadManifest, 'book' | 'format' | 'acquisitionHref'>,
|
||||||
onProgress: (received: number, total: number | null) => void
|
onProgress: (received: number, total: number | null) => void
|
||||||
@@ -492,10 +510,8 @@ function ChapterReader({ manifest }: { manifest: BookReadManifest }) {
|
|||||||
setLoading(true);
|
setLoading(true);
|
||||||
setError('');
|
setError('');
|
||||||
const url = manifest.chaptersUrl || `/api/books/read/chapters?sourceId=${encodeURIComponent(manifest.book.sourceId)}&bookId=${encodeURIComponent(manifest.book.id)}`;
|
const url = manifest.chaptersUrl || `/api/books/read/chapters?sourceId=${encodeURIComponent(manifest.book.sourceId)}&bookId=${encodeURIComponent(manifest.book.id)}`;
|
||||||
fetch(url, { cache: 'no-store' })
|
fetchJsonWithRetry<{ chapters?: BookChapter[] }>(url, { cache: 'no-store' })
|
||||||
.then(async (res) => {
|
.then((json) => {
|
||||||
const json = await res.json();
|
|
||||||
if (!res.ok) throw new Error(json.error || '获取目录失败');
|
|
||||||
if (cancelled) return;
|
if (cancelled) return;
|
||||||
const list = (json.chapters || []) as BookChapter[];
|
const list = (json.chapters || []) as BookChapter[];
|
||||||
setChapters(list);
|
setChapters(list);
|
||||||
@@ -520,10 +536,8 @@ function ChapterReader({ manifest }: { manifest: BookReadManifest }) {
|
|||||||
scrollRef.current?.scrollTo({ top: 0, behavior: 'auto' });
|
scrollRef.current?.scrollTo({ top: 0, behavior: 'auto' });
|
||||||
const params = new URLSearchParams({ sourceId: manifest.book.sourceId, href: item.href });
|
const params = new URLSearchParams({ sourceId: manifest.book.sourceId, href: item.href });
|
||||||
if (manifest.acquisitionHref) params.set('tocHref', manifest.acquisitionHref);
|
if (manifest.acquisitionHref) params.set('tocHref', manifest.acquisitionHref);
|
||||||
fetch(`/api/books/read/chapter?${params.toString()}`, { cache: 'no-store' })
|
fetchJsonWithRetry<BookChapterContent>(`/api/books/read/chapter?${params.toString()}`, { cache: 'no-store' })
|
||||||
.then(async (res) => {
|
.then((json) => {
|
||||||
const json = await res.json();
|
|
||||||
if (!res.ok) throw new Error(json.error || '获取章节失败');
|
|
||||||
setChapter({ ...(json as BookChapterContent), title: (json as BookChapterContent).title || item.title });
|
setChapter({ ...(json as BookChapterContent), title: (json as BookChapterContent).title || item.title });
|
||||||
const progressPercent = chapters.length > 0 ? Math.round(((currentIndex + 1) / chapters.length) * 100) : 0;
|
const progressPercent = chapters.length > 0 ? Math.round(((currentIndex + 1) / chapters.length) * 100) : 0;
|
||||||
const record: BookReadRecord = {
|
const record: BookReadRecord = {
|
||||||
|
|||||||
+24
-13
@@ -373,6 +373,10 @@ function normalizeConfiguredLegadoSource(item: any, index: number): BookSource |
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function wait(ms: number) {
|
||||||
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||||
|
}
|
||||||
|
|
||||||
async function fetchText(source: BookSource, url: string): Promise<string> {
|
async function fetchText(source: BookSource, url: string): Promise<string> {
|
||||||
const safe = await validateProxyUrlServerSide(url);
|
const safe = await validateProxyUrlServerSide(url);
|
||||||
if (!safe) throw new Error('书源地址未通过安全校验');
|
if (!safe) throw new Error('书源地址未通过安全校验');
|
||||||
@@ -381,20 +385,27 @@ async function fetchText(source: BookSource, url: string): Promise<string> {
|
|||||||
const { cacheTTL } = await resolveLegadoConfig();
|
const { cacheTTL } = await resolveLegadoConfig();
|
||||||
if (cached && cached.expiresAt > Date.now()) return cached.data;
|
if (cached && cached.expiresAt > Date.now()) return cached.data;
|
||||||
|
|
||||||
const controller = new AbortController();
|
let lastError: unknown;
|
||||||
const timeout = setTimeout(() => controller.abort(), DEFAULT_TIMEOUT_MS);
|
for (let attempt = 0; attempt < 3; attempt += 1) {
|
||||||
try {
|
const controller = new AbortController();
|
||||||
const response = await fetch(url, { headers: buildHeaders(source), signal: controller.signal, cache: 'no-store' });
|
const timeout = setTimeout(() => controller.abort(), DEFAULT_TIMEOUT_MS);
|
||||||
if (!response.ok) throw new Error(`请求失败: ${response.status}`);
|
try {
|
||||||
const contentLength = Number(response.headers.get('content-length') || '0');
|
const response = await fetch(url, { headers: buildHeaders(source), signal: controller.signal, cache: 'no-store' });
|
||||||
if (contentLength > MAX_TEXT_BYTES) throw new Error('响应内容过大');
|
if (!response.ok) throw new Error(`请求失败: ${response.status}`);
|
||||||
const text = await response.text();
|
const contentLength = Number(response.headers.get('content-length') || '0');
|
||||||
if (text.length > MAX_TEXT_BYTES) throw new Error('响应内容过大');
|
if (contentLength > MAX_TEXT_BYTES) throw new Error('响应内容过大');
|
||||||
textCache.set(cacheKey, { data: text, expiresAt: Date.now() + cacheTTL });
|
const text = await response.text();
|
||||||
return text;
|
if (text.length > MAX_TEXT_BYTES) throw new Error('响应内容过大');
|
||||||
} finally {
|
textCache.set(cacheKey, { data: text, expiresAt: Date.now() + cacheTTL });
|
||||||
clearTimeout(timeout);
|
return text;
|
||||||
|
} catch (error) {
|
||||||
|
lastError = error;
|
||||||
|
if (attempt < 2) await wait(300 * (attempt + 1));
|
||||||
|
} finally {
|
||||||
|
clearTimeout(timeout);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
throw lastError instanceof Error ? lastError : new Error('请求失败');
|
||||||
}
|
}
|
||||||
|
|
||||||
async function getSourceById(sourceId: string): Promise<BookSource> {
|
async function getSourceById(sourceId: string): Promise<BookSource> {
|
||||||
|
|||||||
Reference in New Issue
Block a user