From 82f835395e37c5b66411146294187fc410859f4b Mon Sep 17 00:00:00 2001 From: YangObscurity Date: Thu, 26 Nov 2026 14:18:56 +0800 Subject: [PATCH 1/7] fix(search): send same-origin session credentials and surface load/retry states --- site/docs/.vitepress/i18n/en.ts | 3 + site/docs/.vitepress/i18n/zh-CN.ts | 3 + .../.vitepress/theme/search/SearchHost.vue | 43 ++++-- site/docs/.vitepress/theme/search/engine.ts | 128 +++++++++++++++--- .../theme/slots/default/SearchPanel.vue | 50 ++++++- site/docs/.vitepress/theme/slots/registry.ts | 9 +- .../datasheet/components/SearchPanel.vue | 49 ++++++- site/tests/e2e/search.spec.ts | 28 ++++ site/tests/unit/search-index.test.ts | 77 +++++++++++ 9 files changed, 355 insertions(+), 35 deletions(-) diff --git a/site/docs/.vitepress/i18n/en.ts b/site/docs/.vitepress/i18n/en.ts index 985588d..7155b05 100644 --- a/site/docs/.vitepress/i18n/en.ts +++ b/site/docs/.vitepress/i18n/en.ts @@ -34,6 +34,9 @@ export const en: Messages = { 'search.metaCountTime': '{count} hits, {ms} ms', 'search.loadingBar': 'Loading body index ({loaded} / {total} MB), showing title and heading matches first', 'search.loadingIdle': 'Loading body index ({loaded} / {total} MB)…', + 'search.loadingTitles': 'Loading lecture index…', + 'search.loadError': 'Could not load the search index (your session may have expired). Sign in again or retry.', + 'search.retry': 'Retry', 'search.groupCount': '{count}', 'search.lectureNo': 'L{n}', 'search.groupSite': 'Overview', diff --git a/site/docs/.vitepress/i18n/zh-CN.ts b/site/docs/.vitepress/i18n/zh-CN.ts index 133e893..e2e00cc 100644 --- a/site/docs/.vitepress/i18n/zh-CN.ts +++ b/site/docs/.vitepress/i18n/zh-CN.ts @@ -40,6 +40,9 @@ export const zhCN = { 'search.metaCountTime': '{count} 条,{ms} ms', 'search.loadingBar': '正文索引载入中({loaded} / {total} MB),以下先按讲名与小节标题给出结果', 'search.loadingIdle': '正文索引载入中({loaded} / {total} MB)…', + 'search.loadingTitles': '正在载入讲义索引…', + 'search.loadError': '讲义索引载入失败(可能登录会话已过期或网络异常),请重新登录后重试', + 'search.retry': '重试加载', 'search.groupCount': '{count} 条', 'search.lectureNo': '第{n}讲', 'search.groupSite': '站点页面', diff --git a/site/docs/.vitepress/theme/search/SearchHost.vue b/site/docs/.vitepress/theme/search/SearchHost.vue index 6caa70f..57c6bc4 100644 --- a/site/docs/.vitepress/theme/search/SearchHost.vue +++ b/site/docs/.vitepress/theme/search/SearchHost.vue @@ -74,6 +74,8 @@ const engine = new LectureSearchEngine({ conceptBadge: t('search.conceptBadge'), loadingBar: (loaded, total) => t('search.loadingBar', { loaded, total }), loadingIdle: (loaded, total) => t('search.loadingIdle', { loaded, total }), + loadingTitles: t('search.loadingTitles'), + loadError: t('search.loadError'), statusLabel: (status) => { if (status === 'completed') return t('sidebar.status.completed') if (status === 'in_progress') return t('sidebar.status.inProgress') @@ -110,12 +112,12 @@ function openSearch(): void { // spec board 04.2: on a group or lecture page the default scope is "this group" scope.value = currentGroupId.value ? 'group' : 'all' isOpen.value = true - loadIndex() + loadIndex(true) } -function loadIndex(): void { - engine.ensureLoaded(activeLocale.value, currentGroupId.value).catch(() => { - // the title index could not be fetched: the panel stays usable (empty) and the next open retries +function loadIndex(forceRetry = false): void { + engine.ensureLoaded(activeLocale.value, currentGroupId.value, { forceRetry }).catch(() => { + // Error status is surfaced cleanly via getLoadState / emptyState='error'; next open/retry will re-fetch }) } @@ -137,13 +139,17 @@ function openHit(hit: SearchHitView): void { function setQuery(next: string): void { query.value = next activeIndex.value = 0 - if (isOpen.value) loadIndex() + if (isOpen.value) loadIndex(false) } function setScope(next: 'all' | 'group'): void { scope.value = next activeIndex.value = 0 if (next === 'group') engine.prioritizeGroup(activeLocale.value, currentGroupId.value) + const st = engine.getLoadState(activeLocale.value, query.value.trim().length > 0) + if (st.phase === 'error' || st.phase === 'partial-error' || st.phase === 'idle') { + loadIndex(true) + } } function handleDialogKeyDown(ev: KeyboardEvent): void { @@ -221,13 +227,22 @@ function handleGlobalKeyDown(ev: KeyboardEvent): void { const panelProps = computed(() => { void revision.value const hasQuery = query.value.trim().length > 0 + const loadState = engine.getLoadState(activeLocale.value, hasQuery) const groups: readonly SearchGroupSectionView[] = searchResult.value.groups - const metaText = hasQuery - ? t('search.metaCountTime', { count: searchResult.value.totalHits, ms: searchResult.value.elapsedMs }) - : '' - const emptyState = hasQuery - ? (groups.length === 0 ? 'no-results' : null) - : 'idle' + const indexUnavailable = loadState.phase === 'loading-titles' || loadState.phase === 'error' + const metaText = + hasQuery && !indexUnavailable + ? t('search.metaCountTime', { count: searchResult.value.totalHits, ms: searchResult.value.elapsedMs }) + : '' + const emptyState: SearchPanelProps['emptyState'] = groups.length > 0 + ? null + : loadState.phase === 'error' + ? 'error' + : loadState.phase === 'loading-titles' && hasQuery + ? 'loading' + : hasQuery + ? 'no-results' + : 'idle' return { query: query.value, @@ -237,7 +252,7 @@ const panelProps = computed(() => { groups, activeIndex: activeIndex.value, metaText, - loadState: engine.getLoadState(activeLocale.value, hasQuery), + loadState, emptyState, labels: { dialogLabel: t('search.dialogLabel'), @@ -249,6 +264,9 @@ const panelProps = computed(() => { scopeGroup: t('search.scopeGroup', { id: currentGroupId.value ?? '' }), noResults: t('search.noResults'), idleHint: t('search.idleHint'), + loadingTitles: t('search.loadingTitles'), + loadError: t('search.loadError'), + retry: t('search.retry'), footerSelect: t('search.footerSelect'), footerOpen: t('search.footerOpen'), footerClose: t('search.footerClose'), @@ -261,6 +279,7 @@ const panelProps = computed(() => { }, onOpen: openHit, onClose: closeSearch, + onRetry: () => loadIndex(true), onKeyDown: handleDialogKeyDown, } }) diff --git a/site/docs/.vitepress/theme/search/engine.ts b/site/docs/.vitepress/theme/search/engine.ts index eefeb60..e2dbbb1 100644 --- a/site/docs/.vitepress/theme/search/engine.ts +++ b/site/docs/.vitepress/theme/search/engine.ts @@ -56,18 +56,21 @@ interface ShardQueueItem { meta: ShardMeta url: string credentials: RequestCredentials + cache: RequestCache } export interface LocaleIndexState { locale: string titleLoaded: boolean titleLoading: Promise | null + loadError: boolean groups: TitleIndexGroup[] groupOrder: Map docsByUrl: Map titleDocs: ClientTitleDoc[] sectionsByShard: Map pendingShards: ShardQueueItem[] + failedShardsByKey: Map loadedShardKeys: Set failedShardKeys: Set inFlightBytes: Map @@ -142,11 +145,12 @@ export async function fetchCompressedShard( credentials: RequestCredentials, fetchFn: typeof fetch, onProgress: (bytesReceived: number) => void, + cache: RequestCache = 'default', ): Promise { const res = await fetchFn(url, { credentials, redirect: 'manual', - cache: credentials === 'same-origin' ? 'no-store' : 'default', + cache, }) if (res.status !== 200) return null @@ -199,6 +203,8 @@ export interface SearchEngineOptions { conceptBadge?: string loadingBar: (loadedMb: string, totalMb: string) => string loadingIdle: (loadedMb: string, totalMb: string) => string + loadingTitles?: string + loadError?: string statusLabel: (status: ProgressStatus) => string } fetchFn?: typeof fetch @@ -236,12 +242,14 @@ export class LectureSearchEngine { locale, titleLoaded: false, titleLoading: null, + loadError: false, groups: [], groupOrder: new Map(), docsByUrl: new Map(), titleDocs: [], sectionsByShard: new Map(), pendingShards: [], + failedShardsByKey: new Map(), loadedShardKeys: new Set(), failedShardKeys: new Set(), inFlightBytes: new Map(), @@ -321,6 +329,7 @@ export class LectureSearchEngine { manifest: SearchManifestFile, urlPrefix: string, credentials: RequestCredentials, + cache: RequestCache, ): void { for (const shard of manifest.shards) { const key = `${bucketKey}:${shard.shardId}` @@ -332,11 +341,23 @@ export class LectureSearchEngine { meta: shard, url: `${urlPrefix}/${shard.url}`.replace(/\/{2,}/g, '/'), credentials, + cache, }) st.totalShardBytes += shard.bytes } } + private requeueFailedShards(st: LocaleIndexState): void { + if (st.failedShardsByKey.size === 0) return + for (const [key, item] of st.failedShardsByKey) { + st.failedShardKeys.delete(key) + if (!st.loadedShardKeys.has(key) && !st.pendingShards.some((p) => p.key === key)) { + st.pendingShards.push(item) + } + } + st.failedShardsByKey.clear() + } + private prioritizeShards(st: LocaleIndexState, preferGroupId: string | null): void { if (!preferGroupId) return st.pendingShards.sort((a, b) => { @@ -346,26 +367,38 @@ export class LectureSearchEngine { }) } - async ensureLoaded(locale: string, preferGroupId: string | null): Promise { + async ensureLoaded(locale: string, preferGroupId: string | null, opts?: { forceRetry?: boolean }): Promise { const st = this.getOrCreateState(locale) const basePrefix = this.opts.base.replace(/\/$/, '') + const forceRetry = Boolean(opts?.forceRetry) - if (!st.titleLoading) { + if (forceRetry && st.loadError && !st.titleLoaded) { + st.loadError = false + } + + if (!st.titleLoading && !st.titleLoaded && !st.loadError) { st.titleLoading = (async () => { const publicBase = `${basePrefix}/search/${locale}` + // Send same-origin cookies so gateway/forward-auth deployments (e.g. Authelia) authorize search JSON & shards, + // and prevent cross-origin login redirects from turning into unhandled CORS/CSP errors via `redirect: 'manual'`. const [manifestRes, titleRes] = await Promise.all([ - this.fetchImpl(`${publicBase}/manifest.json`, { credentials: 'omit' }), - this.fetchImpl(`${publicBase}/titles.json`, { credentials: 'omit' }), + this.fetchImpl(`${publicBase}/manifest.json`, { credentials: 'same-origin', redirect: 'manual' }), + this.fetchImpl(`${publicBase}/titles.json`, { credentials: 'same-origin', redirect: 'manual' }), ]) - if (titleRes.ok) { - const titleData = (await titleRes.json()) as TitleIndexFile - this.mergeTitleIndex(st, titleData, this.opts.base) + if (titleRes.status !== 200) { + throw new Error(`Search title index returned status ${titleRes.status}`) } - if (manifestRes.ok) { - const manifest = (await manifestRes.json()) as SearchManifestFile - this.enqueueShards(st, 'public', manifest, publicBase, 'omit') + if (manifestRes.status !== 200) { + throw new Error(`Search manifest returned status ${manifestRes.status}`) } + const [titleData, manifest] = await Promise.all([ + titleRes.json() as Promise, + manifestRes.json() as Promise, + ]) + this.mergeTitleIndex(st, titleData, this.opts.base) + this.enqueueShards(st, 'public', manifest, publicBase, 'same-origin', 'default') st.titleLoaded = true + st.loadError = false this.opts.onStateChange?.() // Only request /_access// when restricted tiers are configured on this build @@ -386,7 +419,7 @@ export class LectureSearchEngine { } if (tManRes.status === 200) { const tMan = (await tManRes.json()) as SearchManifestFile - this.enqueueShards(st, `tier:${tier.id}`, tMan, tierBase, 'same-origin') + this.enqueueShards(st, `tier:${tier.id}`, tMan, tierBase, 'same-origin', 'no-store') } } catch { // Fail closed when tier endpoints do not resolve @@ -396,15 +429,23 @@ export class LectureSearchEngine { this.opts.onStateChange?.() } })() + this.opts.onStateChange?.() } + if (!st.titleLoading) return + try { await st.titleLoading } catch (err) { st.titleLoading = null st.titleLoaded = false + st.loadError = true + this.opts.onStateChange?.() throw err } + if (forceRetry) { + this.requeueFailedShards(st) + } this.prioritizeShards(st, preferGroupId) void this.pumpShards(st, preferGroupId) } @@ -434,6 +475,7 @@ export class LectureSearchEngine { st.inFlightBytes.set(item.key, Math.min(bytes, item.meta.bytes)) this.opts.onStateChange?.() }, + item.cache, ) st.inFlightBytes.delete(item.key) if (payload) { @@ -459,15 +501,17 @@ export class LectureSearchEngine { } st.sectionsByShard.set(item.key, parsedSections) st.loadedShardKeys.add(item.key) + st.failedShardKeys.delete(item.key) + st.failedShardsByKey.delete(item.key) st.finishedBytes.set(item.key, item.meta.bytes) } else { st.failedShardKeys.add(item.key) - st.finishedBytes.set(item.key, item.meta.bytes) + st.failedShardsByKey.set(item.key, item) } } catch { st.inFlightBytes.delete(item.key) st.failedShardKeys.add(item.key) - st.finishedBytes.set(item.key, item.meta.bytes) + st.failedShardsByKey.set(item.key, item) } this.opts.onStateChange?.() } @@ -488,17 +532,60 @@ export class LectureSearchEngine { getLoadState(locale: string, hasQuery: boolean): SearchLoadState { const st = this.states.get(locale) - if (!st || !st.titleLoaded) { - return { loading: false, loadedBytes: 0, totalBytes: 0, percent: 0, label: '' } + if (!st) { + return { loading: false, loadedBytes: 0, totalBytes: 0, percent: 0, label: '', phase: 'idle' } } - const pending = st.pendingShards.length + st.inFlightBytes.size > 0 - if (!pending || st.totalShardBytes === 0) { - return { loading: false, loadedBytes: st.totalShardBytes, totalBytes: st.totalShardBytes, percent: 100, label: '' } + if (!st.titleLoaded) { + if (st.loadError) { + return { + loading: false, + loadedBytes: 0, + totalBytes: 0, + percent: 0, + label: this.opts.labels.loadError ?? '', + phase: 'error', + error: true, + } + } + if (st.titleLoading) { + return { + loading: true, + loadedBytes: 0, + totalBytes: 0, + percent: 0, + label: this.opts.labels.loadingTitles ?? '', + phase: 'loading-titles', + } + } + return { loading: false, loadedBytes: 0, totalBytes: 0, percent: 0, label: '', phase: 'idle' } } + const pending = st.pendingShards.length + st.inFlightBytes.size > 0 let loaded = 0 for (const v of st.finishedBytes.values()) loaded += v for (const v of st.inFlightBytes.values()) loaded += v const capped = Math.min(loaded, st.totalShardBytes) + if (!pending || st.totalShardBytes === 0) { + if (st.failedShardKeys.size > 0) { + return { + loading: false, + loadedBytes: capped, + totalBytes: st.totalShardBytes, + percent: st.totalShardBytes > 0 ? Math.min(99, Math.round((capped / st.totalShardBytes) * 100)) : 0, + label: this.opts.labels.loadError ?? '', + phase: 'partial-error', + error: true, + failedShards: st.failedShardKeys.size, + } + } + return { + loading: false, + loadedBytes: st.totalShardBytes, + totalBytes: st.totalShardBytes, + percent: 100, + label: '', + phase: 'ready', + } + } const percent = Math.min(99, Math.max(0, Math.round((capped / st.totalShardBytes) * 100))) const toMb = (b: number) => (b / (1024 * 1024)).toFixed(1) const label = hasQuery @@ -510,6 +597,7 @@ export class LectureSearchEngine { totalBytes: st.totalShardBytes, percent, label, + phase: 'loading-shards', } } @@ -637,7 +725,7 @@ export class LectureSearchEngine { const titleDoc = st.docsByUrl.get(sec.url) if (!matchesScope(titleDoc, sec.groupId)) continue - const combinedLower = `${sec.textLower} ${sec.crumb.toLowerCase()} ${sec.displayTitle.toLowerCase()} ${sec.code.toLowerCase()}` + const combinedLower = `${sec.textLower} ${sec.crumb.toLowerCase()} ${sec.displayTitle.toLowerCase()} ${titleDoc?.fullTitle.toLowerCase() ?? ''} ${sec.groupId.toLowerCase()} ${sec.groupTitle.toLowerCase()} ${sec.code.toLowerCase()}` let ok = true let inBodyCount = 0 for (const t of termsLower) { diff --git a/site/docs/.vitepress/theme/slots/default/SearchPanel.vue b/site/docs/.vitepress/theme/slots/default/SearchPanel.vue index c7b7075..e5befab 100644 --- a/site/docs/.vitepress/theme/slots/default/SearchPanel.vue +++ b/site/docs/.vitepress/theme/slots/default/SearchPanel.vue @@ -122,6 +122,17 @@ watch( +
+ {{ loadState.label }} + +
{{ labels.scopeLabel }} @@ -148,7 +159,16 @@ watch(
-
+
+

{{ labels.loadError || loadState.label }}

+ +
+
+ {{ labels.loadingTitles || loadState.label }} +
+
{{ labels.noResults }}
@@ -374,6 +394,34 @@ watch( color: var(--lec-text-muted); } +.sp-load--error { + display: flex; + align-items: center; + justify-content: space-between; + gap: var(--lec-space-2); +} + +.sp-empty-msg { + margin: 0 0 var(--lec-space-2); +} + +.sp-retry-btn { + border: var(--lec-line-hair) solid var(--lec-border); + border-radius: var(--lec-radius-1); + background: var(--lec-bg); + color: var(--lec-text); + font: inherit; + font-size: 12px; + padding: 4px 12px; + cursor: pointer; +} + +.sp-retry-btn:hover, +.sp-retry-btn:focus-visible { + border-color: var(--lec-accent); + color: var(--lec-accent); +} + .sp-grp h4 { display: flex; align-items: center; diff --git a/site/docs/.vitepress/theme/slots/registry.ts b/site/docs/.vitepress/theme/slots/registry.ts index f97529e..147200e 100644 --- a/site/docs/.vitepress/theme/slots/registry.ts +++ b/site/docs/.vitepress/theme/slots/registry.ts @@ -433,6 +433,9 @@ export interface SearchLoadState { totalBytes: number percent: number label: string + phase?: 'idle' | 'loading-titles' | 'loading-shards' | 'ready' | 'partial-error' | 'error' + error?: boolean + failedShards?: number } export interface SearchPanelProps { @@ -444,7 +447,7 @@ export interface SearchPanelProps { activeIndex: number metaText: string loadState: SearchLoadState - emptyState: 'idle' | 'no-results' | null + emptyState: 'idle' | 'no-results' | 'loading' | 'error' | null labels: { dialogLabel: string placeholder: string @@ -455,6 +458,9 @@ export interface SearchPanelProps { scopeGroup: string noResults: string idleHint: string + loadingTitles?: string + loadError?: string + retry?: string footerSelect: string footerOpen: string footerClose: string @@ -465,6 +471,7 @@ export interface SearchPanelProps { onHighlight: (index: number) => void onOpen: (hit: SearchHitView) => void onClose: () => void + onRetry?: () => void onKeyDown: (ev: KeyboardEvent) => void } diff --git a/site/docs/.vitepress/themes/datasheet/components/SearchPanel.vue b/site/docs/.vitepress/themes/datasheet/components/SearchPanel.vue index be0d817..c59a2ec 100644 --- a/site/docs/.vitepress/themes/datasheet/components/SearchPanel.vue +++ b/site/docs/.vitepress/themes/datasheet/components/SearchPanel.vue @@ -117,6 +117,17 @@ watch(
+
+ {{ loadState.label }} + +
{{ labels.scopeLabel }} @@ -143,7 +154,16 @@ watch(
-
+
+

{{ labels.loadError || loadState.label }}

+ +
+
+ {{ labels.loadingTitles || loadState.label }} +
+
{{ labels.noResults }}
@@ -372,6 +392,33 @@ watch( color: var(--lec-text-muted); } +.sp-load--error { + display: flex; + align-items: center; + justify-content: space-between; + gap: var(--lec-space-2); +} + +.sp-empty-msg { + margin: 0 0 var(--lec-space-2); +} + +.sp-retry-btn { + border: var(--lec-line-hair) solid var(--lec-border); + border-radius: var(--lec-radius-1); + background: var(--lec-surface); + color: var(--lec-text); + font-family: var(--lec-font-mono); + font-size: 12px; + padding: 4px 12px; + cursor: pointer; +} + +.sp-retry-btn:hover, +.sp-retry-btn:focus-visible { + border-color: var(--lec-text); +} + .sp-grp h4 { display: flex; align-items: center; diff --git a/site/tests/e2e/search.spec.ts b/site/tests/e2e/search.spec.ts index c25b9eb..a4a496f 100644 --- a/site/tests/e2e/search.spec.ts +++ b/site/tests/e2e/search.spec.ts @@ -162,6 +162,34 @@ for (const [theme, expectedImpl] of SKINS) { expect(pageErrors).toEqual([]) }) + test('shows honest error and recovers on retry when search index requires session auth / fails', async ({ page, pageErrors }) => { + await useTheme(page, theme, 'light') + let blockSearch = true + await page.route('**/search/**', async (route) => { + if (blockSearch) { + await route.fulfill({ status: 401, contentType: 'text/plain', body: 'auth required' }) + return + } + await route.continue() + }) + + await gotoAndSettle(page, '/mea/L03') + await page.keyboard.press('ControlOrMeta+k') + + const input = page.locator('#lec-search-input') + await input.fill('误差') + await expect(page.locator('.sp-empty--error')).toBeVisible({ timeout: 10_000 }) + await expect(page.locator('.sp-empty--error')).not.toContainText('未找到相关内容') + await expect(page.locator('.sp-scope .meta')).toHaveCount(0) + + blockSearch = false + await page.locator('.sp-retry-btn').click() + await expect(page.locator('.sp-hit').first()).toBeVisible({ timeout: 15_000 }) + await expect(page.locator('.sp-scope .meta')).toContainText(/\d+\s*条/) + await page.unroute('**/search/**') + expect(pageErrors).toEqual([]) + }) + test('focus trap: Tab and Shift+Tab stay inside search dialog; Esc closes and returns focus to opener button', async ({ page, pageErrors }) => { await useTheme(page, theme, 'light') await gotoAndSettle(page, '/mea/L03') diff --git a/site/tests/unit/search-index.test.ts b/site/tests/unit/search-index.test.ts index 489a160..9078bd9 100644 --- a/site/tests/unit/search-index.test.ts +++ b/site/tests/unit/search-index.test.ts @@ -439,4 +439,81 @@ describe('client LectureSearchEngine: instant title results, progress, scope and expect(rows).toBeLessThan(5) // five matching sections, capped per lecture expect(res.totalHits).toBe(rows) }) + + it('sends same-origin credentials for gateway auth, enters error state on redirect/non-200 instead of false empty results, and recovers on retry', async () => { + const titlePayload: TitleIndexFile = { + v: 1, + locale: 'root', + groups: [{ id: 'LR', dir: 'lr', title: '文献精读', catSlot: 1 }], + pages: [[0, 6, 'LR-L06', '/lr/L06', '第6讲 · TEEN 协议解析', [[2, '协议核心思想']]]], + } + const shardRaw = Buffer.from( + JSON.stringify({ + v: 1, + shardId: 'lr', + groupId: 'LR', + pages: ['/lr/L06'], + sections: [[0, 's1', ['协议核心思想'], '协议采用双阈值节能机制。']], + }), + 'utf8', + ) + const shard = zlib.deflateRawSync(shardRaw, { level: 9 }) + const manifestPayload: SearchManifestFile = { + v: 1, + locale: 'root', + titleFile: 'titles.json', + titleBytes: Buffer.byteLength(JSON.stringify(titlePayload)), + totalShardBytes: shard.byteLength, + totalRawShardBytes: shardRaw.byteLength, + shards: [{ shardId: 'lr', groupId: 'LR', url: 'shards/lr.sz', bytes: shard.byteLength, rawBytes: shardRaw.byteLength, pageCount: 1 }], + } + + let authed = false + const seenInits: Array<{ url: string; credentials?: RequestCredentials; redirect?: RequestRedirect }> = [] + const fetchFn: typeof fetch = async (input, init) => { + const url = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url + seenInits.push({ url, credentials: init?.credentials, redirect: init?.redirect }) + if (!authed) { + return { status: 0, ok: false, type: 'opaqueredirect' } as unknown as Response + } + if (url.endsWith('/manifest.json')) return new Response(JSON.stringify(manifestPayload), { status: 200 }) + if (url.endsWith('/titles.json')) return new Response(JSON.stringify(titlePayload), { status: 200 }) + if (url.endsWith('/shards/lr.sz')) return new Response(new Uint8Array(shard), { status: 200 }) + return new Response('not found', { status: 404 }) + } + + const engine = new LectureSearchEngine({ + base: '/', + localeKeys: ['en'], + siteData: () => ({ themeConfig: { lectureAccess: { inlineTier: 'public', tiers: [] } } }), + statusOf: () => 'not_started', + labels: { + lectureNo: (n) => `第${n}讲`, + groupCount: (n) => `${n} 条`, + groupSite: '站点页面', + loadingBar: (l, t) => `loading ${l}/${t}`, + loadingIdle: (l, t) => `idle ${l}/${t}`, + loadingTitles: 'loading titles', + loadError: 'index load failed', + statusLabel: (s) => s, + }, + fetchFn, + }) + + await expect(engine.ensureLoaded('root', 'LR')).rejects.toThrow() + expect(seenInits.every((r) => r.credentials === 'same-origin' && r.redirect === 'manual')).toBe(true) + expect(engine.getLoadState('root', true)).toMatchObject({ loading: false, error: true, phase: 'error', label: 'index load failed' }) + expect(engine.query('root', '协议', 'all', 'LR').totalHits).toBe(0) + + // Without forceRetry, typing doesn't spam requests; reopening with forceRetry recovers cleanly + await engine.ensureLoaded('root', 'LR') + expect(engine.getLoadState('root', true).phase).toBe('error') + + authed = true + await engine.ensureLoaded('root', 'LR', { forceRetry: true }) + await vi.waitFor(() => expect(engine.getLoadState('root', true).loading).toBe(false), { timeout: 10_000, interval: 10 }) + expect(seenInits.every((r) => r.credentials === 'same-origin' && r.redirect === 'manual')).toBe(true) + expect(engine.getLoadState('root', true)).toMatchObject({ loading: false, phase: 'ready', percent: 100 }) + expect(engine.query('root', '协议', 'all', 'LR').totalHits).toBeGreaterThan(0) + }) }) From 713717de9a675ab0541a64b097c1b73cee882872 Mon Sep 17 00:00:00 2001 From: YangObscurity Date: Thu, 26 Nov 2026 17:52:25 +0800 Subject: [PATCH 2/7] fix(search): harden manifest failure isolation, v1 slot compat, ARIA, and retry focus --- .../.vitepress/theme/search/SearchHost.vue | 23 +- site/docs/.vitepress/theme/search/engine.ts | 219 +++++++++++++----- .../theme/slots/default/SearchPanel.vue | 39 +++- site/docs/.vitepress/theme/slots/registry.ts | 2 +- .../datasheet/components/SearchPanel.vue | 39 +++- site/tests/e2e/search.spec.ts | 7 +- site/tests/unit/search-index.test.ts | 84 +++++++ 7 files changed, 313 insertions(+), 100 deletions(-) diff --git a/site/docs/.vitepress/theme/search/SearchHost.vue b/site/docs/.vitepress/theme/search/SearchHost.vue index 57c6bc4..0ba5c65 100644 --- a/site/docs/.vitepress/theme/search/SearchHost.vue +++ b/site/docs/.vitepress/theme/search/SearchHost.vue @@ -74,8 +74,8 @@ const engine = new LectureSearchEngine({ conceptBadge: t('search.conceptBadge'), loadingBar: (loaded, total) => t('search.loadingBar', { loaded, total }), loadingIdle: (loaded, total) => t('search.loadingIdle', { loaded, total }), - loadingTitles: t('search.loadingTitles'), - loadError: t('search.loadError'), + loadingTitles: () => t('search.loadingTitles'), + loadError: () => t('search.loadError'), statusLabel: (status) => { if (status === 'completed') return t('sidebar.status.completed') if (status === 'in_progress') return t('sidebar.status.inProgress') @@ -147,7 +147,7 @@ function setScope(next: 'all' | 'group'): void { activeIndex.value = 0 if (next === 'group') engine.prioritizeGroup(activeLocale.value, currentGroupId.value) const st = engine.getLoadState(activeLocale.value, query.value.trim().length > 0) - if (st.phase === 'error' || st.phase === 'partial-error' || st.phase === 'idle') { + if (st.phase === 'error' || st.phase === 'idle') { loadIndex(true) } } @@ -229,20 +229,19 @@ const panelProps = computed(() => { const hasQuery = query.value.trim().length > 0 const loadState = engine.getLoadState(activeLocale.value, hasQuery) const groups: readonly SearchGroupSectionView[] = searchResult.value.groups - const indexUnavailable = loadState.phase === 'loading-titles' || loadState.phase === 'error' + const suppressMeta = + loadState.phase === 'loading-titles' || + loadState.phase === 'error' || + (Boolean(loadState.error) && groups.length === 0) const metaText = - hasQuery && !indexUnavailable + hasQuery && !suppressMeta ? t('search.metaCountTime', { count: searchResult.value.totalHits, ms: searchResult.value.elapsedMs }) : '' const emptyState: SearchPanelProps['emptyState'] = groups.length > 0 ? null - : loadState.phase === 'error' - ? 'error' - : loadState.phase === 'loading-titles' && hasQuery - ? 'loading' - : hasQuery - ? 'no-results' - : 'idle' + : hasQuery + ? 'no-results' + : 'idle' return { query: query.value, diff --git a/site/docs/.vitepress/theme/search/engine.ts b/site/docs/.vitepress/theme/search/engine.ts index e2dbbb1..9c14303 100644 --- a/site/docs/.vitepress/theme/search/engine.ts +++ b/site/docs/.vitepress/theme/search/engine.ts @@ -63,6 +63,9 @@ export interface LocaleIndexState { locale: string titleLoaded: boolean titleLoading: Promise | null + manifestLoaded: boolean + manifestLoading: Promise | null + accessLoaded: boolean loadError: boolean groups: TitleIndexGroup[] groupOrder: Map @@ -190,6 +193,12 @@ export async function fetchCompressedShard( return JSON.parse(text) as ShardPayload } +export type SearchLabelValue = string | (() => string) + +function resolveDynamicLabel(val?: SearchLabelValue): string { + return typeof val === 'function' ? val() : (val ?? '') +} + export interface SearchEngineOptions { base: string localeKeys: readonly string[] @@ -203,8 +212,8 @@ export interface SearchEngineOptions { conceptBadge?: string loadingBar: (loadedMb: string, totalMb: string) => string loadingIdle: (loadedMb: string, totalMb: string) => string - loadingTitles?: string - loadError?: string + loadingTitles?: SearchLabelValue + loadError?: SearchLabelValue statusLabel: (status: ProgressStatus) => string } fetchFn?: typeof fetch @@ -242,6 +251,9 @@ export class LectureSearchEngine { locale, titleLoaded: false, titleLoading: null, + manifestLoaded: false, + manifestLoading: null, + accessLoaded: false, loadError: false, groups: [], groupOrder: new Map(), @@ -367,82 +379,140 @@ export class LectureSearchEngine { }) } + private async loadAccessTiers(st: LocaleIndexState, basePrefix: string): Promise { + if (st.accessLoaded) return + st.accessLoaded = true + const accessCfg = lectureAccessOf(this.opts.siteData()) + if (!accessCfg || accessCfg.tiers.length === 0) return + + const access = await getAccess().catch(() => null) + await Promise.all( + (access?.tiers ?? []).map(async (tier) => { + const tierBase = `${basePrefix}${tierBasePath(tier.id)}/search/${st.locale}` + try { + const [tManRes, tTitleRes] = await Promise.all([ + this.fetchImpl(`${tierBase}/manifest.json`, { credentials: 'same-origin', redirect: 'manual', cache: 'no-store' }), + this.fetchImpl(`${tierBase}/titles.json`, { credentials: 'same-origin', redirect: 'manual', cache: 'no-store' }), + ]) + if (tTitleRes.status === 200) { + const tTitleData = (await tTitleRes.json()) as TitleIndexFile + this.mergeTitleIndex(st, tTitleData, this.opts.base) + } + if (tManRes.status === 200) { + const tMan = (await tManRes.json()) as SearchManifestFile + this.enqueueShards(st, `tier:${tier.id}`, tMan, tierBase, 'same-origin', 'no-store') + } + } catch { + // Fail closed when tier endpoints do not resolve + } + }), + ) + this.opts.onStateChange?.() + } + + private async fetchAndEnqueueManifest( + st: LocaleIndexState, + publicBase: string, + prefetched?: Promise<{ res?: Response; err?: unknown }>, + ): Promise { + if (st.manifestLoaded) return + if (!st.manifestLoading) { + st.manifestLoading = (async () => { + try { + let manifestRes: Response + if (prefetched) { + const settled = await prefetched + if (!settled.res) throw (settled.err ?? new Error('Search manifest fetch failed')) + manifestRes = settled.res + } else { + manifestRes = await this.fetchImpl(`${publicBase}/manifest.json`, { credentials: 'same-origin', redirect: 'manual' }) + } + if (manifestRes.status !== 200) { + throw new Error(`Search manifest returned status ${manifestRes.status}`) + } + const manifest = (await manifestRes.json()) as SearchManifestFile + this.enqueueShards(st, 'public', manifest, publicBase, 'same-origin', 'default') + st.manifestLoaded = true + st.loadError = false + } catch { + st.manifestLoaded = false + st.loadError = true + } finally { + st.manifestLoading = null + this.opts.onStateChange?.() + } + })() + this.opts.onStateChange?.() + } + await st.manifestLoading + } + async ensureLoaded(locale: string, preferGroupId: string | null, opts?: { forceRetry?: boolean }): Promise { const st = this.getOrCreateState(locale) const basePrefix = this.opts.base.replace(/\/$/, '') + const publicBase = `${basePrefix}/search/${locale}` const forceRetry = Boolean(opts?.forceRetry) - if (forceRetry && st.loadError && !st.titleLoaded) { + if (forceRetry && st.loadError) { st.loadError = false } if (!st.titleLoading && !st.titleLoaded && !st.loadError) { st.titleLoading = (async () => { - const publicBase = `${basePrefix}/search/${locale}` - // Send same-origin cookies so gateway/forward-auth deployments (e.g. Authelia) authorize search JSON & shards, - // and prevent cross-origin login redirects from turning into unhandled CORS/CSP errors via `redirect: 'manual'`. - const [manifestRes, titleRes] = await Promise.all([ - this.fetchImpl(`${publicBase}/manifest.json`, { credentials: 'same-origin', redirect: 'manual' }), - this.fetchImpl(`${publicBase}/titles.json`, { credentials: 'same-origin', redirect: 'manual' }), - ]) - if (titleRes.status !== 200) { - throw new Error(`Search title index returned status ${titleRes.status}`) - } - if (manifestRes.status !== 200) { - throw new Error(`Search manifest returned status ${manifestRes.status}`) - } - const [titleData, manifest] = await Promise.all([ - titleRes.json() as Promise, - manifestRes.json() as Promise, - ]) - this.mergeTitleIndex(st, titleData, this.opts.base) - this.enqueueShards(st, 'public', manifest, publicBase, 'same-origin', 'default') - st.titleLoaded = true - st.loadError = false - this.opts.onStateChange?.() - - // Only request /_access// when restricted tiers are configured on this build - const accessCfg = lectureAccessOf(this.opts.siteData()) - if (accessCfg && accessCfg.tiers.length > 0) { - const access = await getAccess().catch(() => null) - await Promise.all( - (access?.tiers ?? []).map(async (tier) => { - const tierBase = `${basePrefix}${tierBasePath(tier.id)}/search/${locale}` - try { - const [tManRes, tTitleRes] = await Promise.all([ - this.fetchImpl(`${tierBase}/manifest.json`, { credentials: 'same-origin', redirect: 'manual', cache: 'no-store' }), - this.fetchImpl(`${tierBase}/titles.json`, { credentials: 'same-origin', redirect: 'manual', cache: 'no-store' }), - ]) - if (tTitleRes.status === 200) { - const tTitleData = (await tTitleRes.json()) as TitleIndexFile - this.mergeTitleIndex(st, tTitleData, this.opts.base) - } - if (tManRes.status === 200) { - const tMan = (await tManRes.json()) as SearchManifestFile - this.enqueueShards(st, `tier:${tier.id}`, tMan, tierBase, 'same-origin', 'no-store') - } - } catch { - // Fail closed when tier endpoints do not resolve - } - }), + try { + // Send same-origin cookies so gateway/forward-auth deployments (e.g. Authelia) authorize search JSON & shards, + // and prevent cross-origin login redirects from turning into unhandled CORS/CSP errors via `redirect: 'manual'`. + // Attach settlement handler on manifest fetch immediately so a titles failure never leaks an unhandled rejection. + const manifestSettled = this.fetchImpl(`${publicBase}/manifest.json`, { credentials: 'same-origin', redirect: 'manual' }).then( + (res): { res?: Response; err?: unknown } => ({ res }), + (err): { res?: Response; err?: unknown } => ({ err }), ) + const titleRes = await this.fetchImpl(`${publicBase}/titles.json`, { credentials: 'same-origin', redirect: 'manual' }) + if (titleRes.status !== 200) { + void manifestSettled + throw new Error(`Search title index returned status ${titleRes.status}`) + } + const titleData = (await titleRes.json()) as TitleIndexFile + this.mergeTitleIndex(st, titleData, this.opts.base) + st.titleLoaded = true + st.loadError = false this.opts.onStateChange?.() + + // Isolate manifest + access-tier loading so a manifest error never blocks already-loaded title search. + await Promise.all([ + this.fetchAndEnqueueManifest(st, publicBase, manifestSettled), + this.loadAccessTiers(st, basePrefix), + ]) + } finally { + st.titleLoading = null } })() this.opts.onStateChange?.() } - if (!st.titleLoading) return - - try { - await st.titleLoading - } catch (err) { - st.titleLoading = null - st.titleLoaded = false - st.loadError = true - this.opts.onStateChange?.() - throw err + if (st.titleLoading) { + const pendingTitles = st.titleLoading + try { + await pendingTitles + } catch (err) { + st.titleLoaded = false + st.loadError = true + this.opts.onStateChange?.() + throw err + } + } else if (st.titleLoaded) { + if (forceRetry && !st.manifestLoaded) { + await this.fetchAndEnqueueManifest(st, publicBase) + } else if (!st.manifestLoaded && !st.manifestLoading) { + return + } + if (st.manifestLoading) { + await st.manifestLoading + } + } else { + return } + if (forceRetry) { this.requeueFailedShards(st) } @@ -542,7 +612,7 @@ export class LectureSearchEngine { loadedBytes: 0, totalBytes: 0, percent: 0, - label: this.opts.labels.loadError ?? '', + label: resolveDynamicLabel(this.opts.labels.loadError), phase: 'error', error: true, } @@ -553,12 +623,35 @@ export class LectureSearchEngine { loadedBytes: 0, totalBytes: 0, percent: 0, - label: this.opts.labels.loadingTitles ?? '', + label: resolveDynamicLabel(this.opts.labels.loadingTitles), phase: 'loading-titles', } } return { loading: false, loadedBytes: 0, totalBytes: 0, percent: 0, label: '', phase: 'idle' } } + if (!st.manifestLoaded) { + if (st.manifestLoading) { + return { + loading: true, + loadedBytes: 0, + totalBytes: 0, + percent: 0, + label: resolveDynamicLabel(this.opts.labels.loadingTitles), + phase: 'loading-shards', + } + } + if (st.loadError) { + return { + loading: false, + loadedBytes: 0, + totalBytes: 0, + percent: 0, + label: resolveDynamicLabel(this.opts.labels.loadError), + phase: 'partial-error', + error: true, + } + } + } const pending = st.pendingShards.length + st.inFlightBytes.size > 0 let loaded = 0 for (const v of st.finishedBytes.values()) loaded += v @@ -571,7 +664,7 @@ export class LectureSearchEngine { loadedBytes: capped, totalBytes: st.totalShardBytes, percent: st.totalShardBytes > 0 ? Math.min(99, Math.round((capped / st.totalShardBytes) * 100)) : 0, - label: this.opts.labels.loadError ?? '', + label: resolveDynamicLabel(this.opts.labels.loadError), phase: 'partial-error', error: true, failedShards: st.failedShardKeys.size, diff --git a/site/docs/.vitepress/theme/slots/default/SearchPanel.vue b/site/docs/.vitepress/theme/slots/default/SearchPanel.vue index e5befab..a3b9d6e 100644 --- a/site/docs/.vitepress/theme/slots/default/SearchPanel.vue +++ b/site/docs/.vitepress/theme/slots/default/SearchPanel.vue @@ -4,7 +4,7 @@ * * Pure drawing & event forwarding component: all state, index loading, filtering and navigation live in `theme/search/`. */ -import { nextTick, onMounted, ref, watch } from 'vue' +import { computed, nextTick, onMounted, ref, watch } from 'vue' import type { SearchGroupSectionView, SearchHitView, SearchPanelProps } from '../registry.ts' const props = defineProps() @@ -12,6 +12,21 @@ const props = defineProps() const inputRef = ref(null) const optionRefs = ref>(new Map()) +const isIndexError = computed( + () => props.loadState.phase === 'error' || props.loadState.phase === 'partial-error' || Boolean(props.loadState.error), +) +const showErrorEmpty = computed(() => props.groups.length === 0 && isIndexError.value) +const showLoadingEmpty = computed( + () => !showErrorEmpty.value && props.groups.length === 0 && props.loadState.phase === 'loading-titles' && props.query.trim().length > 0, +) + +function handleRetry(): void { + props.onRetry?.() + void nextTick(() => { + inputRef.value?.focus() + }) +} + function setOptionRef(index: number, el: unknown): void { if (el instanceof HTMLElement) optionRefs.value.set(index, el) else optionRefs.value.delete(index) @@ -86,8 +101,8 @@ watch( spellcheck="false" role="combobox" aria-autocomplete="list" - aria-expanded="true" - aria-controls="lec-search-listbox" + :aria-expanded="groups.length > 0" + :aria-controls="groups.length > 0 ? 'lec-search-listbox' : undefined" :aria-activedescendant="activeIndex >= 0 ? optionId(activeIndex) : undefined" :aria-label="labels.placeholder" :placeholder="labels.placeholder" @@ -123,13 +138,13 @@ watch(
{{ loadState.label }} -
@@ -158,14 +173,14 @@ watch( {{ metaText }}
-
-
+
+

{{ labels.loadError || loadState.label }}

-
-
+
{{ labels.loadingTitles || loadState.label }}
@@ -175,7 +190,8 @@ watch( {{ labels.idleHint }}
-
+
+

{{ groupHeading(grp) }} {{ grp.countLabel }} @@ -215,7 +231,8 @@ watch( -

+
+
diff --git a/site/docs/.vitepress/theme/slots/registry.ts b/site/docs/.vitepress/theme/slots/registry.ts index 147200e..570381e 100644 --- a/site/docs/.vitepress/theme/slots/registry.ts +++ b/site/docs/.vitepress/theme/slots/registry.ts @@ -447,7 +447,7 @@ export interface SearchPanelProps { activeIndex: number metaText: string loadState: SearchLoadState - emptyState: 'idle' | 'no-results' | 'loading' | 'error' | null + emptyState: 'idle' | 'no-results' | null labels: { dialogLabel: string placeholder: string diff --git a/site/docs/.vitepress/themes/datasheet/components/SearchPanel.vue b/site/docs/.vitepress/themes/datasheet/components/SearchPanel.vue index c59a2ec..66c3437 100644 --- a/site/docs/.vitepress/themes/datasheet/components/SearchPanel.vue +++ b/site/docs/.vitepress/themes/datasheet/components/SearchPanel.vue @@ -8,7 +8,7 @@ * - monospace lecture code (`G05-L19`) column * - selected hit accented by a 3 px left bar; match highlights marked by thick underline without background tint */ -import { nextTick, onMounted, ref, watch } from 'vue' +import { computed, nextTick, onMounted, ref, watch } from 'vue' import type { SearchGroupSectionView, SearchHitView, SearchPanelProps } from '../../../theme/slots/registry.ts' const props = defineProps() @@ -16,6 +16,21 @@ const props = defineProps() const inputRef = ref(null) const optionRefs = ref>(new Map()) +const isIndexError = computed( + () => props.loadState.phase === 'error' || props.loadState.phase === 'partial-error' || Boolean(props.loadState.error), +) +const showErrorEmpty = computed(() => props.groups.length === 0 && isIndexError.value) +const showLoadingEmpty = computed( + () => !showErrorEmpty.value && props.groups.length === 0 && props.loadState.phase === 'loading-titles' && props.query.trim().length > 0, +) + +function handleRetry(): void { + props.onRetry?.() + void nextTick(() => { + inputRef.value?.focus() + }) +} + function setOptionRef(index: number, el: unknown): void { if (el instanceof HTMLElement) optionRefs.value.set(index, el) else optionRefs.value.delete(index) @@ -81,8 +96,8 @@ watch( spellcheck="false" role="combobox" aria-autocomplete="list" - aria-expanded="true" - aria-controls="lec-search-listbox" + :aria-expanded="groups.length > 0" + :aria-controls="groups.length > 0 ? 'lec-search-listbox' : undefined" :aria-activedescendant="activeIndex >= 0 ? optionId(activeIndex) : undefined" :aria-label="labels.placeholder" :placeholder="labels.placeholder" @@ -118,13 +133,13 @@ watch(
{{ loadState.label }} -
@@ -153,14 +168,14 @@ watch( {{ metaText }}
-
-
+
+

{{ labels.loadError || loadState.label }}

-
-
+
{{ labels.loadingTitles || loadState.label }}
@@ -170,7 +185,8 @@ watch( {{ labels.idleHint }}
-
+
+

{{ grp.groupId === 'CONCEPTS' || grp.groupId === 'SITE' ? grp.groupTitle : `${grp.groupId} ${grp.groupTitle}` }} {{ grp.countLabel }} @@ -210,7 +226,8 @@ watch( -

+
+
diff --git a/site/tests/e2e/search.spec.ts b/site/tests/e2e/search.spec.ts index a4a496f..7f6e5cc 100644 --- a/site/tests/e2e/search.spec.ts +++ b/site/tests/e2e/search.spec.ts @@ -165,7 +165,7 @@ for (const [theme, expectedImpl] of SKINS) { test('shows honest error and recovers on retry when search index requires session auth / fails', async ({ page, pageErrors }) => { await useTheme(page, theme, 'light') let blockSearch = true - await page.route('**/search/**', async (route) => { + await page.route('**/search/**/*.{json,sz}', async (route) => { if (blockSearch) { await route.fulfill({ status: 401, contentType: 'text/plain', body: 'auth required' }) return @@ -180,13 +180,16 @@ for (const [theme, expectedImpl] of SKINS) { await input.fill('误差') await expect(page.locator('.sp-empty--error')).toBeVisible({ timeout: 10_000 }) await expect(page.locator('.sp-empty--error')).not.toContainText('未找到相关内容') + await expect(page.locator('#lec-search-listbox')).toHaveCount(0) await expect(page.locator('.sp-scope .meta')).toHaveCount(0) + await expect(page.locator('.sp-retry-btn')).toHaveCount(1) blockSearch = false await page.locator('.sp-retry-btn').click() + await expect(input).toBeFocused() await expect(page.locator('.sp-hit').first()).toBeVisible({ timeout: 15_000 }) await expect(page.locator('.sp-scope .meta')).toContainText(/\d+\s*条/) - await page.unroute('**/search/**') + await page.unroute('**/search/**/*.{json,sz}') expect(pageErrors).toEqual([]) }) diff --git a/site/tests/unit/search-index.test.ts b/site/tests/unit/search-index.test.ts index 9078bd9..2c8d849 100644 --- a/site/tests/unit/search-index.test.ts +++ b/site/tests/unit/search-index.test.ts @@ -516,4 +516,88 @@ describe('client LectureSearchEngine: instant title results, progress, scope and expect(engine.getLoadState('root', true)).toMatchObject({ loading: false, phase: 'ready', percent: 100 }) expect(engine.query('root', '协议', 'all', 'LR').totalHits).toBeGreaterThan(0) }) + + it('keeps title search usable if manifest.json fails, evaluates dynamic locale labels lazily, and recovers manifest on forceRetry', async () => { + const titlePayload: TitleIndexFile = { + v: 1, + locale: 'root', + groups: [{ id: 'LR', dir: 'lr', title: '文献精读', catSlot: 1 }], + pages: [[0, 6, 'LR-L06', '/lr/L06', '第6讲 · TEEN 协议解析', [[2, '协议核心思想']]]], + } + const shardRaw = Buffer.from( + JSON.stringify({ + v: 1, + shardId: 'lr', + groupId: 'LR', + pages: ['/lr/L06'], + sections: [[0, 's1', ['协议核心思想'], '协议采用双阈值节能机制。']], + }), + 'utf8', + ) + const shard = zlib.deflateRawSync(shardRaw, { level: 9 }) + const manifestPayload: SearchManifestFile = { + v: 1, + locale: 'root', + titleFile: 'titles.json', + titleBytes: Buffer.byteLength(JSON.stringify(titlePayload)), + totalShardBytes: shard.byteLength, + totalRawShardBytes: shardRaw.byteLength, + shards: [{ shardId: 'lr', groupId: 'LR', url: 'shards/lr.sz', bytes: shard.byteLength, rawBytes: shardRaw.byteLength, pageCount: 1 }], + } + + let manifestOk = false + let currentLang = 'zh' + const fetchFn: typeof fetch = async (input) => { + const url = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url + if (url.endsWith('/titles.json')) return new Response(JSON.stringify(titlePayload), { status: 200 }) + if (url.endsWith('/manifest.json')) { + return manifestOk ? new Response(JSON.stringify(manifestPayload), { status: 200 }) : new Response('err', { status: 500 }) + } + if (url.endsWith('/shards/lr.sz')) return new Response(new Uint8Array(shard), { status: 200 }) + return new Response('not found', { status: 404 }) + } + + const engine = new LectureSearchEngine({ + base: '/', + localeKeys: ['en'], + siteData: () => ({ themeConfig: { lectureAccess: { inlineTier: 'public', tiers: [] } } }), + statusOf: () => 'not_started', + labels: { + lectureNo: (n) => `第${n}讲`, + groupCount: (n) => `${n} 条`, + groupSite: '站点页面', + loadingBar: (l, t) => `loading ${l}/${t}`, + loadingIdle: (l, t) => `idle ${l}/${t}`, + loadingTitles: () => (currentLang === 'zh' ? '正在加载' : 'Loading index'), + loadError: () => (currentLang === 'zh' ? '加载失败' : 'Index failed'), + statusLabel: (s) => s, + }, + fetchFn, + }) + + // Manifest 500 must NOT block title search + await engine.ensureLoaded('root', 'LR') + expect(engine.query('root', '协议', 'all', 'LR').totalHits).toBeGreaterThan(0) + expect(engine.query('root', '双阈值', 'all', 'LR').totalHits).toBe(0) + expect(engine.getLoadState('root', true)).toMatchObject({ + loading: false, + error: true, + phase: 'partial-error', + label: '加载失败', + }) + + // Runtime locale switch reflects in getLoadState without reconstructing engine + currentLang = 'en' + expect(engine.getLoadState('root', true).label).toBe('Index failed') + + // Non-retry query calls don't spam failed manifest, forceRetry recovers shards + await engine.ensureLoaded('root', 'LR') + expect(engine.getLoadState('root', true).phase).toBe('partial-error') + + manifestOk = true + await engine.ensureLoaded('root', 'LR', { forceRetry: true }) + await vi.waitFor(() => expect(engine.getLoadState('root', true).loading).toBe(false), { timeout: 10_000, interval: 10 }) + expect(engine.getLoadState('root', true)).toMatchObject({ loading: false, phase: 'ready', percent: 100 }) + expect(engine.query('root', '双阈值', 'all', 'LR').totalHits).toBe(1) + }) }) From b440ba532e7b9b7ec46a769eac51c860f92a1c36 Mon Sep 17 00:00:00 2001 From: YangObscurity Date: Thu, 26 Nov 2026 18:53:42 +0800 Subject: [PATCH 3/7] fix(search): track authorized tier retry state and show shard-loading status --- .../.vitepress/theme/search/SearchHost.vue | 2 +- site/docs/.vitepress/theme/search/engine.ts | 135 ++++++++++++++---- .../theme/slots/default/SearchPanel.vue | 4 +- .../datasheet/components/SearchPanel.vue | 4 +- site/tests/e2e/search.spec.ts | 8 +- site/tests/unit/search-index.test.ts | 112 +++++++++++++++ 6 files changed, 228 insertions(+), 37 deletions(-) diff --git a/site/docs/.vitepress/theme/search/SearchHost.vue b/site/docs/.vitepress/theme/search/SearchHost.vue index 0ba5c65..c5376be 100644 --- a/site/docs/.vitepress/theme/search/SearchHost.vue +++ b/site/docs/.vitepress/theme/search/SearchHost.vue @@ -232,7 +232,7 @@ const panelProps = computed(() => { const suppressMeta = loadState.phase === 'loading-titles' || loadState.phase === 'error' || - (Boolean(loadState.error) && groups.length === 0) + (groups.length === 0 && (Boolean(loadState.error) || loadState.loading)) const metaText = hasQuery && !suppressMeta ? t('search.metaCountTime', { count: searchResult.value.totalHits, ms: searchResult.value.elapsedMs }) diff --git a/site/docs/.vitepress/theme/search/engine.ts b/site/docs/.vitepress/theme/search/engine.ts index 9c14303..24debe8 100644 --- a/site/docs/.vitepress/theme/search/engine.ts +++ b/site/docs/.vitepress/theme/search/engine.ts @@ -65,7 +65,11 @@ export interface LocaleIndexState { titleLoading: Promise | null manifestLoaded: boolean manifestLoading: Promise | null - accessLoaded: boolean + accessLoading: Promise | null + accessFetchError: boolean + tierTitlesLoaded: Set + tierManifestsLoaded: Set + failedTierIds: Set loadError: boolean groups: TitleIndexGroup[] groupOrder: Map @@ -253,7 +257,11 @@ export class LectureSearchEngine { titleLoading: null, manifestLoaded: false, manifestLoading: null, - accessLoaded: false, + accessLoading: null, + accessFetchError: false, + tierTitlesLoaded: new Set(), + tierManifestsLoaded: new Set(), + failedTierIds: new Set(), loadError: false, groups: [], groupOrder: new Map(), @@ -380,34 +388,90 @@ export class LectureSearchEngine { } private async loadAccessTiers(st: LocaleIndexState, basePrefix: string): Promise { - if (st.accessLoaded) return - st.accessLoaded = true const accessCfg = lectureAccessOf(this.opts.siteData()) if (!accessCfg || accessCfg.tiers.length === 0) return - const access = await getAccess().catch(() => null) - await Promise.all( - (access?.tiers ?? []).map(async (tier) => { - const tierBase = `${basePrefix}${tierBasePath(tier.id)}/search/${st.locale}` + if (st.accessLoading) { + await st.accessLoading + return + } + + st.accessLoading = (async () => { + try { + let access: Awaited> try { - const [tManRes, tTitleRes] = await Promise.all([ - this.fetchImpl(`${tierBase}/manifest.json`, { credentials: 'same-origin', redirect: 'manual', cache: 'no-store' }), - this.fetchImpl(`${tierBase}/titles.json`, { credentials: 'same-origin', redirect: 'manual', cache: 'no-store' }), - ]) - if (tTitleRes.status === 200) { - const tTitleData = (await tTitleRes.json()) as TitleIndexFile - this.mergeTitleIndex(st, tTitleData, this.opts.base) - } - if (tManRes.status === 200) { - const tMan = (await tManRes.json()) as SearchManifestFile - this.enqueueShards(st, `tier:${tier.id}`, tMan, tierBase, 'same-origin', 'no-store') - } + access = await getAccess() + st.accessFetchError = false } catch { - // Fail closed when tier endpoints do not resolve + st.accessFetchError = true + return } - }), - ) + + await Promise.all( + (access?.tiers ?? []).map(async (tier) => { + const needTitle = !st.tierTitlesLoaded.has(tier.id) + const needManifest = !st.tierManifestsLoaded.has(tier.id) + if (!needTitle && !needManifest) { + st.failedTierIds.delete(tier.id) + return + } + + const tierBase = `${basePrefix}${tierBasePath(tier.id)}/search/${st.locale}` + let tierFailed = false + const [tManSettled, tTitleSettled] = await Promise.all([ + needManifest + ? this.fetchImpl(`${tierBase}/manifest.json`, { credentials: 'same-origin', redirect: 'manual', cache: 'no-store' }).then( + (res): { res?: Response; err?: unknown } => ({ res }), + (err): { res?: Response; err?: unknown } => ({ err }), + ) + : Promise.resolve(null), + needTitle + ? this.fetchImpl(`${tierBase}/titles.json`, { credentials: 'same-origin', redirect: 'manual', cache: 'no-store' }).then( + (res): { res?: Response; err?: unknown } => ({ res }), + (err): { res?: Response; err?: unknown } => ({ err }), + ) + : Promise.resolve(null), + ]) + + if (needTitle) { + try { + if (!tTitleSettled || !tTitleSettled.res || tTitleSettled.res.status !== 200) { + tierFailed = true + } else { + const tTitleData = (await tTitleSettled.res.json()) as TitleIndexFile + this.mergeTitleIndex(st, tTitleData, this.opts.base) + st.tierTitlesLoaded.add(tier.id) + } + } catch { + tierFailed = true + } + } + + if (needManifest) { + try { + if (!tManSettled || !tManSettled.res || tManSettled.res.status !== 200) { + tierFailed = true + } else { + const tMan = (await tManSettled.res.json()) as SearchManifestFile + this.enqueueShards(st, `tier:${tier.id}`, tMan, tierBase, 'same-origin', 'no-store') + st.tierManifestsLoaded.add(tier.id) + } + } catch { + tierFailed = true + } + } + + if (tierFailed) st.failedTierIds.add(tier.id) + else st.failedTierIds.delete(tier.id) + }), + ) + } finally { + st.accessLoading = null + this.opts.onStateChange?.() + } + })() this.opts.onStateChange?.() + await st.accessLoading } private async fetchAndEnqueueManifest( @@ -501,13 +565,21 @@ export class LectureSearchEngine { throw err } } else if (st.titleLoaded) { + const retryTasks: Array> = [] if (forceRetry && !st.manifestLoaded) { - await this.fetchAndEnqueueManifest(st, publicBase) - } else if (!st.manifestLoaded && !st.manifestLoading) { - return + retryTasks.push(this.fetchAndEnqueueManifest(st, publicBase)) + } else if (st.manifestLoading) { + retryTasks.push(st.manifestLoading) } - if (st.manifestLoading) { - await st.manifestLoading + if (forceRetry && (st.failedTierIds.size > 0 || st.accessFetchError)) { + retryTasks.push(this.loadAccessTiers(st, basePrefix)) + } else if (st.accessLoading) { + retryTasks.push(st.accessLoading) + } + if (retryTasks.length > 0) { + await Promise.all(retryTasks) + } else if (!st.manifestLoaded && !st.manifestLoading && st.failedTierIds.size === 0 && !st.accessFetchError) { + return } } else { return @@ -653,12 +725,13 @@ export class LectureSearchEngine { } } const pending = st.pendingShards.length + st.inFlightBytes.size > 0 + const failedTierCount = st.failedTierIds.size + (st.accessFetchError ? 1 : 0) let loaded = 0 for (const v of st.finishedBytes.values()) loaded += v for (const v of st.inFlightBytes.values()) loaded += v const capped = Math.min(loaded, st.totalShardBytes) - if (!pending || st.totalShardBytes === 0) { - if (st.failedShardKeys.size > 0) { + if ((!pending && !st.accessLoading && !st.manifestLoading) || (st.totalShardBytes === 0 && !st.accessLoading && !st.manifestLoading)) { + if (st.failedShardKeys.size > 0 || failedTierCount > 0) { return { loading: false, loadedBytes: capped, @@ -667,7 +740,7 @@ export class LectureSearchEngine { label: resolveDynamicLabel(this.opts.labels.loadError), phase: 'partial-error', error: true, - failedShards: st.failedShardKeys.size, + failedShards: st.failedShardKeys.size + failedTierCount, } } return { diff --git a/site/docs/.vitepress/theme/slots/default/SearchPanel.vue b/site/docs/.vitepress/theme/slots/default/SearchPanel.vue index a3b9d6e..e61ea38 100644 --- a/site/docs/.vitepress/theme/slots/default/SearchPanel.vue +++ b/site/docs/.vitepress/theme/slots/default/SearchPanel.vue @@ -17,7 +17,7 @@ const isIndexError = computed( ) const showErrorEmpty = computed(() => props.groups.length === 0 && isIndexError.value) const showLoadingEmpty = computed( - () => !showErrorEmpty.value && props.groups.length === 0 && props.loadState.phase === 'loading-titles' && props.query.trim().length > 0, + () => !showErrorEmpty.value && props.groups.length === 0 && props.loadState.loading && props.query.trim().length > 0, ) function handleRetry(): void { @@ -181,7 +181,7 @@ watch(
- {{ labels.loadingTitles || loadState.label }} + {{ loadState.phase === 'loading-shards' ? (loadState.label || labels.loadingTitles) : (labels.loadingTitles || loadState.label) }}
{{ labels.noResults }} diff --git a/site/docs/.vitepress/themes/datasheet/components/SearchPanel.vue b/site/docs/.vitepress/themes/datasheet/components/SearchPanel.vue index 66c3437..ebc8fb9 100644 --- a/site/docs/.vitepress/themes/datasheet/components/SearchPanel.vue +++ b/site/docs/.vitepress/themes/datasheet/components/SearchPanel.vue @@ -21,7 +21,7 @@ const isIndexError = computed( ) const showErrorEmpty = computed(() => props.groups.length === 0 && isIndexError.value) const showLoadingEmpty = computed( - () => !showErrorEmpty.value && props.groups.length === 0 && props.loadState.phase === 'loading-titles' && props.query.trim().length > 0, + () => !showErrorEmpty.value && props.groups.length === 0 && props.loadState.loading && props.query.trim().length > 0, ) function handleRetry(): void { @@ -176,7 +176,7 @@ watch(
- {{ labels.loadingTitles || loadState.label }} + {{ loadState.phase === 'loading-shards' ? (loadState.label || labels.loadingTitles) : (labels.loadingTitles || loadState.label) }}
{{ labels.noResults }} diff --git a/site/tests/e2e/search.spec.ts b/site/tests/e2e/search.spec.ts index 7f6e5cc..03125ce 100644 --- a/site/tests/e2e/search.spec.ts +++ b/site/tests/e2e/search.spec.ts @@ -151,9 +151,15 @@ for (const [theme, expectedImpl] of SKINS) { expect(panelBox!.x + panelBox!.width).toBeLessThanOrEqual(390.5) await page.setViewportSize({ width: 1280, height: 800 }) - // Release shards -> progress bar clears and body snippets hydrate + // Typing a query with 0 title hits while shards are still delayed must show loading state instead of false "no results" + await input.fill('仅等待分片完成_loading_check') + await expect(page.locator('.sp-empty--loading')).toBeVisible() + await expect(page.locator('.sp-res')).not.toContainText('未找到相关内容') + + // Release shards -> progress bar clears, no-results shows after loading finishes, and body snippets hydrate releaseShards() await expect(loadBar).toBeHidden({ timeout: 20_000 }) + await expect(page.locator('.sp-res .sp-empty')).toContainText('未找到相关内容') await input.fill('标准差') await expect(page.locator('.sp-hit .snip').first()).toBeVisible({ timeout: 10_000 }) await expect(page.locator('.sp-hit mark').first()).toBeVisible() diff --git a/site/tests/unit/search-index.test.ts b/site/tests/unit/search-index.test.ts index 2c8d849..4021850 100644 --- a/site/tests/unit/search-index.test.ts +++ b/site/tests/unit/search-index.test.ts @@ -21,6 +21,7 @@ import { } from '../../docs/.vitepress/search/format.ts' import { buildSearchArtifacts, SearchBudgetError, writeSearchArtifacts } from '../../docs/.vitepress/search/indexBuilder.ts' import { extractSearchablePage } from '../../docs/.vitepress/search/markdown.ts' +import { configureAccess } from '../../docs/.vitepress/theme/access/store.ts' import { LectureSearchEngine, buildSnippet, splitHighlightParts } from '../../docs/.vitepress/theme/search/engine.ts' const tmpDirs: string[] = [] @@ -600,4 +601,115 @@ describe('client LectureSearchEngine: instant title results, progress, scope and expect(engine.getLoadState('root', true)).toMatchObject({ loading: false, phase: 'ready', percent: 100 }) expect(engine.query('root', '双阈值', 'all', 'LR').totalHits).toBe(1) }) + + it('tracks authorized restricted tier failures and retries only missing tier metadata on forceRetry', async () => { + const publicTitles: TitleIndexFile = { + v: 1, + locale: 'root', + groups: [{ id: 'G01', dir: 'g01', title: '公开组', catSlot: 1 }], + pages: [[0, 1, 'G01-L01', '/g01/L01', '第1讲 · 公开导论', [[2, '公开概述']]]], + } + const vipTitles: TitleIndexFile = { + v: 1, + locale: 'root', + groups: [{ id: 'VIP', dir: 'vip', title: '进阶组', catSlot: 2 }], + pages: [[0, 1, 'VIP-L01', '/vip/L01', '第1讲 · VIP 专题', [[2, '高阶技巧']]]], + } + const pubShardRaw = Buffer.from(JSON.stringify({ v: 1, shardId: 'g01', groupId: 'G01', pages: ['/g01/L01'], sections: [] }), 'utf8') + const pubShard = zlib.deflateRawSync(pubShardRaw, { level: 9 }) + const vipShardRaw = Buffer.from( + JSON.stringify({ + v: 1, + shardId: 'vip', + groupId: 'VIP', + pages: ['/vip/L01'], + sections: [[0, 's1', ['高阶技巧'], '隐藏正文关键字只存在于 VIP 分片。']], + }), + 'utf8', + ) + const vipShard = zlib.deflateRawSync(vipShardRaw, { level: 9 }) + + const pubManifest: SearchManifestFile = { + v: 1, + locale: 'root', + titleFile: 'titles.json', + titleBytes: 10, + totalShardBytes: pubShard.byteLength, + totalRawShardBytes: pubShardRaw.byteLength, + shards: [{ shardId: 'g01', groupId: 'G01', url: 'shards/g01.sz', bytes: pubShard.byteLength, rawBytes: pubShardRaw.byteLength, pageCount: 1 }], + } + const vipManifest: SearchManifestFile = { + v: 1, + locale: 'root', + titleFile: 'titles.json', + titleBytes: 10, + totalShardBytes: vipShard.byteLength, + totalRawShardBytes: vipShardRaw.byteLength, + shards: [{ shardId: 'vip', groupId: 'VIP', url: 'shards/vip.sz', bytes: vipShard.byteLength, rawBytes: vipShardRaw.byteLength, pageCount: 1 }], + } + + let vipSearchOk = false + let vipRequests = 0 + const siteObj = { themeConfig: { lectureAccess: { inlineTier: 'public', tiers: ['vip'] } } } + const fetchFn: typeof fetch = async (input) => { + const url = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url + if (url.endsWith('/_access/vip/site-data.json')) { + return new Response( + JSON.stringify({ version: 1, tier: 'vip', groups: [], totals: { lectures: 1, charts: 0 }, locales: {} }), + { status: 200 }, + ) + } + if (url.includes('/_access/vip/search/')) { + vipRequests++ + if (!vipSearchOk) return new Response('unavailable', { status: 503 }) + if (url.endsWith('/titles.json')) return new Response(JSON.stringify(vipTitles), { status: 200 }) + if (url.endsWith('/manifest.json')) return new Response(JSON.stringify(vipManifest), { status: 200 }) + if (url.endsWith('/shards/vip.sz')) return new Response(new Uint8Array(vipShard), { status: 200 }) + } + if (url.endsWith('/search/root/titles.json')) return new Response(JSON.stringify(publicTitles), { status: 200 }) + if (url.endsWith('/search/root/manifest.json')) return new Response(JSON.stringify(pubManifest), { status: 200 }) + if (url.endsWith('/shards/g01.sz')) return new Response(new Uint8Array(pubShard), { status: 200 }) + return new Response('not found', { status: 404 }) + } + + configureAccess({ siteData: { value: siteObj }, withBase: (p) => p, fetch: fetchFn }) + try { + const engine = new LectureSearchEngine({ + base: '/', + localeKeys: ['en'], + siteData: () => siteObj, + statusOf: () => 'not_started', + labels: { + lectureNo: (n) => `第${n}讲`, + groupCount: (n) => `${n} 条`, + groupSite: '概览', + loadingBar: (l, t) => `loading ${l}/${t}`, + loadingIdle: (l, t) => `idle ${l}/${t}`, + loadError: '部分索引加载失败', + statusLabel: (s) => s, + }, + fetchFn, + }) + + await engine.ensureLoaded('root', null) + await vi.waitFor(() => expect(engine.getLoadState('root', true).loading).toBe(false), { timeout: 10_000, interval: 10 }) + expect(engine.query('root', '公开导论', 'all', null).totalHits).toBe(1) + expect(engine.query('root', 'VIP', 'all', null).totalHits).toBe(0) + expect(engine.getLoadState('root', true)).toMatchObject({ loading: false, error: true, phase: 'partial-error' }) + + const callsAfterFail = vipRequests + // Typing / normal ensureLoaded does not spam failed tier + await engine.ensureLoaded('root', null) + expect(vipRequests).toBe(callsAfterFail) + + vipSearchOk = true + await engine.ensureLoaded('root', null, { forceRetry: true }) + await vi.waitFor(() => expect(engine.getLoadState('root', true).loading).toBe(false), { timeout: 10_000, interval: 10 }) + expect(engine.getLoadState('root', true)).toMatchObject({ loading: false, phase: 'ready', percent: 100 }) + expect(engine.query('root', '高阶技巧', 'all', null).totalHits).toBeGreaterThanOrEqual(1) + expect(engine.query('root', '隐藏正文关键字', 'all', null).totalHits).toBe(1) + } finally { + configureAccess({ siteData: { value: {} }, withBase: (p) => p }) + } + }) }) From 4698700e142c61e6a436bb9321a7d7a1d8d705cd Mon Sep 17 00:00:00 2001 From: YangObscurity Date: Thu, 26 Nov 2026 19:11:30 +0800 Subject: [PATCH 4/7] fix(search): expose transient tier check errors, defer un-titled shards, and prune stale tier failures --- site/docs/.vitepress/theme/access/resolve.ts | 36 +++-- site/docs/.vitepress/theme/search/engine.ts | 43 ++++-- site/tests/unit/search-index.test.ts | 138 ++++++++++++++++++- 3 files changed, 192 insertions(+), 25 deletions(-) diff --git a/site/docs/.vitepress/theme/access/resolve.ts b/site/docs/.vitepress/theme/access/resolve.ts index 7f5ca5d..b17917a 100644 --- a/site/docs/.vitepress/theme/access/resolve.ts +++ b/site/docs/.vitepress/theme/access/resolve.ts @@ -30,6 +30,8 @@ export interface ReadableTier { export interface AccessResult { /** The tiers the gateway let through, in the order of `lectureAccess.tiers`. */ tiers: ReadableTier[] + /** Tiers whose `site-data.json` check encountered a transient network/5xx fault (not normal 401/403 denial). */ + failedTiers?: string[] } export const EMPTY_ACCESS: AccessResult = { tiers: [] } @@ -39,31 +41,45 @@ export function tierUrl(deps: Pick, tier: string, file: return deps.withBase(`${tierBasePath(tier)}/${file}`) } +async function fetchTierJsonWithStatus( + deps: Pick, + url: string, +): Promise<{ json: unknown | undefined; transientError: boolean }> { + try { + const res = await deps.fetch(url, { redirect: 'manual', credentials: 'same-origin', cache: 'no-store' }) + if (res.status >= 500) return { json: undefined, transientError: true } + if (res.status !== 200) return { json: undefined, transientError: false } + return { json: (await res.json()) as unknown, transientError: false } + } catch (err) { + // Only treat network/fetch rejections as transient errors (syntax/HTML parse failure is an auth redirect body). + const isSyntax = err instanceof SyntaxError + return { json: undefined, transientError: !isSyntax } + } +} + /** * GET a file of a tier. The answer counts only on a 200 whose body is JSON: a redirect (`redirect: 'manual'` gives an * opaque redirect with status 0), 401 / 403, any other status, a network error and a body that is not JSON all give * `undefined`. */ export async function fetchTierJson(deps: Pick, url: string): Promise { - try { - const res = await deps.fetch(url, { redirect: 'manual', credentials: 'same-origin', cache: 'no-store' }) - if (res.status !== 200) return undefined - return (await res.json()) as unknown - } catch { - return undefined - } + return (await fetchTierJsonWithStatus(deps, url)).json } /** Ask the gateway which restricted tiers the reader may read. No restricted tier configured: no request at all. */ export async function resolveAccess(lectureAccess: LectureAccess | undefined, deps: AccessDeps): Promise { const ids = lectureAccess?.tiers ?? [] if (ids.length === 0) return EMPTY_ACCESS - const slices = await Promise.all(ids.map(async (id) => ({ id, json: await fetchTierJson(deps, tierUrl(deps, id, 'site-data.json')) }))) + const slices = await Promise.all( + ids.map(async (id) => ({ id, ...(await fetchTierJsonWithStatus(deps, tierUrl(deps, id, 'site-data.json'))) })), + ) const tiers: ReadableTier[] = [] - for (const { id, json } of slices) { + const failedTiers: string[] = [] + for (const { id, json, transientError } of slices) { if (isTierSlice(json) && json.tier === id) tiers.push({ id, slice: json }) + else if (transientError) failedTiers.push(id) } - return { tiers } + return failedTiers.length > 0 ? { tiers, failedTiers } : { tiers } } /** The nodes of the `graph.json` of each readable tier (a tier whose file does not arrive or is not an array adds nothing). */ diff --git a/site/docs/.vitepress/theme/search/engine.ts b/site/docs/.vitepress/theme/search/engine.ts index 24debe8..bde9537 100644 --- a/site/docs/.vitepress/theme/search/engine.ts +++ b/site/docs/.vitepress/theme/search/engine.ts @@ -7,7 +7,7 @@ */ import { inflateTitleHeadings, stripLectureTitlePrefix, type SearchManifestFile, type ShardMeta, type ShardPayload, type TitleIndexFile, type TitleIndexGroup } from '../../search/format.ts' import { tierBasePath } from '../../access/tiers.ts' -import { lectureAccessOf, getAccess } from '../access/store.ts' +import { lectureAccessOf, getAccess, invalidateAccess } from '../access/store.ts' import { parseLecture } from '../core/route.ts' import type { ProgressStatus } from '../progress/types.ts' import type { SearchGroupSectionView, SearchHighlightPart, SearchHitView, SearchLoadState } from '../slots/registry.ts' @@ -387,7 +387,7 @@ export class LectureSearchEngine { }) } - private async loadAccessTiers(st: LocaleIndexState, basePrefix: string): Promise { + private async loadAccessTiers(st: LocaleIndexState, basePrefix: string, forceRetry = false): Promise { const accessCfg = lectureAccessOf(this.opts.siteData()) if (!accessCfg || accessCfg.tiers.length === 0) return @@ -401,14 +401,24 @@ export class LectureSearchEngine { let access: Awaited> try { access = await getAccess() - st.accessFetchError = false + if (forceRetry && (st.accessFetchError || (access.failedTiers?.length ?? 0) > 0)) { + invalidateAccess() + access = await getAccess() + } + st.accessFetchError = (access.failedTiers?.length ?? 0) > 0 } catch { st.accessFetchError = true return } + const tiers = access?.tiers ?? [] + const readableIds = new Set(tiers.map((t) => t.id)) + for (const oldId of st.failedTierIds) { + if (!readableIds.has(oldId)) st.failedTierIds.delete(oldId) + } + await Promise.all( - (access?.tiers ?? []).map(async (tier) => { + tiers.map(async (tier) => { const needTitle = !st.tierTitlesLoaded.has(tier.id) const needManifest = !st.tierManifestsLoaded.has(tier.id) if (!needTitle && !needManifest) { @@ -447,17 +457,22 @@ export class LectureSearchEngine { } } + // Never mark manifest/shards loaded while this tier's titles failed, or pumpShards skips all sections without docs. if (needManifest) { - try { - if (!tManSettled || !tManSettled.res || tManSettled.res.status !== 200) { + if (!st.tierTitlesLoaded.has(tier.id)) { + tierFailed = true + } else { + try { + if (!tManSettled || !tManSettled.res || tManSettled.res.status !== 200) { + tierFailed = true + } else { + const tMan = (await tManSettled.res.json()) as SearchManifestFile + this.enqueueShards(st, `tier:${tier.id}`, tMan, tierBase, 'same-origin', 'no-store') + st.tierManifestsLoaded.add(tier.id) + } + } catch { tierFailed = true - } else { - const tMan = (await tManSettled.res.json()) as SearchManifestFile - this.enqueueShards(st, `tier:${tier.id}`, tMan, tierBase, 'same-origin', 'no-store') - st.tierManifestsLoaded.add(tier.id) } - } catch { - tierFailed = true } } @@ -545,7 +560,7 @@ export class LectureSearchEngine { // Isolate manifest + access-tier loading so a manifest error never blocks already-loaded title search. await Promise.all([ this.fetchAndEnqueueManifest(st, publicBase, manifestSettled), - this.loadAccessTiers(st, basePrefix), + this.loadAccessTiers(st, basePrefix, forceRetry), ]) } finally { st.titleLoading = null @@ -572,7 +587,7 @@ export class LectureSearchEngine { retryTasks.push(st.manifestLoading) } if (forceRetry && (st.failedTierIds.size > 0 || st.accessFetchError)) { - retryTasks.push(this.loadAccessTiers(st, basePrefix)) + retryTasks.push(this.loadAccessTiers(st, basePrefix, true)) } else if (st.accessLoading) { retryTasks.push(st.accessLoading) } diff --git a/site/tests/unit/search-index.test.ts b/site/tests/unit/search-index.test.ts index 4021850..34c3761 100644 --- a/site/tests/unit/search-index.test.ts +++ b/site/tests/unit/search-index.test.ts @@ -21,7 +21,7 @@ import { } from '../../docs/.vitepress/search/format.ts' import { buildSearchArtifacts, SearchBudgetError, writeSearchArtifacts } from '../../docs/.vitepress/search/indexBuilder.ts' import { extractSearchablePage } from '../../docs/.vitepress/search/markdown.ts' -import { configureAccess } from '../../docs/.vitepress/theme/access/store.ts' +import { configureAccess, invalidateAccess } from '../../docs/.vitepress/theme/access/store.ts' import { LectureSearchEngine, buildSnippet, splitHighlightParts } from '../../docs/.vitepress/theme/search/engine.ts' const tmpDirs: string[] = [] @@ -712,4 +712,140 @@ describe('client LectureSearchEngine: instant title results, progress, scope and configureAccess({ siteData: { value: {} }, withBase: (p) => p }) } }) + + it('defers tier shards when tier titles fail, clears stale tier errors on downgrade, and retries site-data 503 via forceRetry', async () => { + const publicTitles: TitleIndexFile = { + v: 1, + locale: 'root', + groups: [{ id: 'G01', dir: 'g01', title: '公开组', catSlot: 1 }], + pages: [[0, 1, 'G01-L01', '/g01/L01', '第1讲 · 公开导论', [[2, '公开概述']]]], + } + const vipTitles: TitleIndexFile = { + v: 1, + locale: 'root', + groups: [{ id: 'VIP', dir: 'vip', title: '进阶组', catSlot: 2 }], + pages: [[0, 1, 'VIP-L01', '/vip/L01', '第1讲 · VIP 专题', [[2, '高阶技巧']]]], + } + const pubShardRaw = Buffer.from(JSON.stringify({ v: 1, shardId: 'g01', groupId: 'G01', pages: ['/g01/L01'], sections: [] }), 'utf8') + const pubShard = zlib.deflateRawSync(pubShardRaw, { level: 9 }) + const vipShardRaw = Buffer.from( + JSON.stringify({ + v: 1, + shardId: 'vip', + groupId: 'VIP', + pages: ['/vip/L01'], + sections: [[0, 's1', ['高阶技巧'], '仅 VIP 分片独有正文字段。']], + }), + 'utf8', + ) + const vipShard = zlib.deflateRawSync(vipShardRaw, { level: 9 }) + + const pubManifest: SearchManifestFile = { + v: 1, + locale: 'root', + titleFile: 'titles.json', + titleBytes: 10, + totalShardBytes: pubShard.byteLength, + totalRawShardBytes: pubShardRaw.byteLength, + shards: [{ shardId: 'g01', groupId: 'G01', url: 'shards/g01.sz', bytes: pubShard.byteLength, rawBytes: pubShardRaw.byteLength, pageCount: 1 }], + } + const vipManifest: SearchManifestFile = { + v: 1, + locale: 'root', + titleFile: 'titles.json', + titleBytes: 10, + totalShardBytes: vipShard.byteLength, + totalRawShardBytes: vipShardRaw.byteLength, + shards: [{ shardId: 'vip', groupId: 'VIP', url: 'shards/vip.sz', bytes: vipShard.byteLength, rawBytes: vipShardRaw.byteLength, pageCount: 1 }], + } + + let siteDataStatus = 503 + let vipTitlesStatus = 503 + const siteObj = { themeConfig: { lectureAccess: { inlineTier: 'public', tiers: ['vip'] } } } + const fetchFn: typeof fetch = async (input) => { + const url = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url + if (url.endsWith('/_access/vip/site-data.json')) { + if (siteDataStatus !== 200) return new Response('err', { status: siteDataStatus }) + return new Response(JSON.stringify({ version: 1, tier: 'vip', groups: [], totals: { lectures: 1, charts: 0 }, locales: {} }), { status: 200 }) + } + if (url.endsWith('/_access/vip/search/root/titles.json')) { + return vipTitlesStatus === 200 ? new Response(JSON.stringify(vipTitles), { status: 200 }) : new Response('err', { status: vipTitlesStatus }) + } + if (url.endsWith('/_access/vip/search/root/manifest.json')) return new Response(JSON.stringify(vipManifest), { status: 200 }) + if (url.endsWith('/_access/vip/search/root/shards/vip.sz')) return new Response(new Uint8Array(vipShard), { status: 200 }) + if (url.endsWith('/search/root/titles.json')) return new Response(JSON.stringify(publicTitles), { status: 200 }) + if (url.endsWith('/search/root/manifest.json')) return new Response(JSON.stringify(pubManifest), { status: 200 }) + if (url.endsWith('/shards/g01.sz')) return new Response(new Uint8Array(pubShard), { status: 200 }) + return new Response('not found', { status: 404 }) + } + + configureAccess({ siteData: { value: siteObj }, withBase: (p) => p, fetch: fetchFn }) + try { + const engine = new LectureSearchEngine({ + base: '/', + localeKeys: ['en'], + siteData: () => siteObj, + statusOf: () => 'not_started', + labels: { + lectureNo: (n) => `第${n}讲`, + groupCount: (n) => `${n} 条`, + groupSite: '概览', + loadingBar: (l, t) => `loading ${l}/${t}`, + loadingIdle: (l, t) => `idle ${l}/${t}`, + loadError: '部分索引加载失败', + statusLabel: (s) => s, + }, + fetchFn, + }) + + // 1. Transient 503 on site-data.json must surface partial-error (not ready) + await engine.ensureLoaded('root', null) + await vi.waitFor(() => expect(engine.getLoadState('root', true).loading).toBe(false), { timeout: 10_000, interval: 10 }) + expect(engine.getLoadState('root', true)).toMatchObject({ loading: false, error: true, phase: 'partial-error' }) + + // 2. Retry resolves site-data.json -> 200, while vip titles.json still 503 & manifest 200: + // shards must NOT be consumed/marked loaded without titles! + siteDataStatus = 200 + await engine.ensureLoaded('root', null, { forceRetry: true }) + await vi.waitFor(() => expect(engine.getLoadState('root', true).loading).toBe(false), { timeout: 10_000, interval: 10 }) + expect(engine.getLoadState('root', true)).toMatchObject({ loading: false, error: true, phase: 'partial-error' }) + expect(engine.query('root', '独有正文字段', 'all', null).totalHits).toBe(0) + + // 3. When vip titles.json recovers -> deferred manifest & shards enqueue and index vip body cleanly! + vipTitlesStatus = 200 + await engine.ensureLoaded('root', null, { forceRetry: true }) + await vi.waitFor(() => expect(engine.getLoadState('root', true).loading).toBe(false), { timeout: 10_000, interval: 10 }) + expect(engine.getLoadState('root', true)).toMatchObject({ loading: false, phase: 'ready', percent: 100 }) + expect(engine.query('root', '独有正文字段', 'all', null).totalHits).toBe(1) + + // 4. Separate instance: failed tier cleared cleanly if user later loses access (403) + vipTitlesStatus = 503 + const engine2 = new LectureSearchEngine({ + base: '/', + localeKeys: ['en'], + siteData: () => siteObj, + statusOf: () => 'not_started', + labels: { + lectureNo: (n) => `第${n}讲`, + groupCount: (n) => `${n} 条`, + groupSite: '概览', + loadingBar: (l, t) => `loading ${l}/${t}`, + loadingIdle: (l, t) => `idle ${l}/${t}`, + loadError: '部分索引加载失败', + statusLabel: (s) => s, + }, + fetchFn, + }) + await engine2.ensureLoaded('root', null) + await vi.waitFor(() => expect(engine2.getLoadState('root', true).loading).toBe(false), { timeout: 10_000, interval: 10 }) + expect(engine2.getLoadState('root', true)).toMatchObject({ loading: false, error: true, phase: 'partial-error' }) + siteDataStatus = 403 + invalidateAccess() + await engine2.ensureLoaded('root', null, { forceRetry: true }) + await vi.waitFor(() => expect(engine2.getLoadState('root', true).loading).toBe(false), { timeout: 10_000, interval: 10 }) + expect(engine2.getLoadState('root', true)).toMatchObject({ loading: false, phase: 'ready', percent: 100 }) + } finally { + configureAccess({ siteData: { value: {} }, withBase: (p) => p }) + } + }) }) From 85f087afe46d3b57aa780764ed277159097e0ee3 Mon Sep 17 00:00:00 2001 From: YangObscurity Date: Thu, 26 Nov 2026 19:30:02 +0800 Subject: [PATCH 5/7] fix(search): evict revoked tier index entries and invalidate cached access on tier failure --- site/docs/.vitepress/theme/search/engine.ts | 42 ++++++++++++++++++--- site/tests/unit/search-index.test.ts | 26 ++++++++++--- 2 files changed, 58 insertions(+), 10 deletions(-) diff --git a/site/docs/.vitepress/theme/search/engine.ts b/site/docs/.vitepress/theme/search/engine.ts index bde9537..3d85fb4 100644 --- a/site/docs/.vitepress/theme/search/engine.ts +++ b/site/docs/.vitepress/theme/search/engine.ts @@ -13,6 +13,7 @@ import type { ProgressStatus } from '../progress/types.ts' import type { SearchGroupSectionView, SearchHighlightPart, SearchHitView, SearchLoadState } from '../slots/registry.ts' export interface ClientTitleDoc { + tierId?: string groupId: string groupTitle: string catSlot: number @@ -82,6 +83,7 @@ export interface LocaleIndexState { failedShardKeys: Set inFlightBytes: Map finishedBytes: Map + shardBytesByKey: Map totalShardBytes: number shardsPumpPromise: Promise | null } @@ -274,6 +276,7 @@ export class LectureSearchEngine { failedShardKeys: new Set(), inFlightBytes: new Map(), finishedBytes: new Map(), + shardBytesByKey: new Map(), totalShardBytes: 0, shardsPumpPromise: null, } @@ -282,7 +285,7 @@ export class LectureSearchEngine { return st } - private mergeTitleIndex(st: LocaleIndexState, payload: TitleIndexFile, base: string): void { + private mergeTitleIndex(st: LocaleIndexState, payload: TitleIndexFile, base: string, tierId = 'public'): void { const localGroups = payload.groups for (const g of localGroups) { if (!st.groupOrder.has(g.id)) { @@ -316,6 +319,7 @@ export class LectureSearchEngine { }) const doc: ClientTitleDoc = { + tierId, groupId: grp.id, groupTitle: this.resolveGroupTitle(grp), catSlot: grp.catSlot, @@ -363,10 +367,37 @@ export class LectureSearchEngine { credentials, cache, }) + st.shardBytesByKey.set(key, shard.bytes) st.totalShardBytes += shard.bytes } } + private evictTierData(st: LocaleIndexState, tierId: string): void { + st.failedTierIds.delete(tierId) + st.tierTitlesLoaded.delete(tierId) + st.tierManifestsLoaded.delete(tierId) + st.titleDocs = st.titleDocs.filter((doc) => { + if (doc.tierId === tierId) { + st.docsByUrl.delete(doc.url) + return false + } + return true + }) + const prefix = `tier:${tierId}:` + st.pendingShards = st.pendingShards.filter((item) => !item.key.startsWith(prefix)) + for (const [key, bytes] of st.shardBytesByKey) { + if (!key.startsWith(prefix)) continue + st.totalShardBytes = Math.max(0, st.totalShardBytes - bytes) + st.shardBytesByKey.delete(key) + st.sectionsByShard.delete(key) + st.loadedShardKeys.delete(key) + st.failedShardKeys.delete(key) + st.failedShardsByKey.delete(key) + st.inFlightBytes.delete(key) + st.finishedBytes.delete(key) + } + } + private requeueFailedShards(st: LocaleIndexState): void { if (st.failedShardsByKey.size === 0) return for (const [key, item] of st.failedShardsByKey) { @@ -401,7 +432,7 @@ export class LectureSearchEngine { let access: Awaited> try { access = await getAccess() - if (forceRetry && (st.accessFetchError || (access.failedTiers?.length ?? 0) > 0)) { + if (forceRetry && (st.accessFetchError || st.failedTierIds.size > 0 || (access.failedTiers?.length ?? 0) > 0)) { invalidateAccess() access = await getAccess() } @@ -413,8 +444,9 @@ export class LectureSearchEngine { const tiers = access?.tiers ?? [] const readableIds = new Set(tiers.map((t) => t.id)) - for (const oldId of st.failedTierIds) { - if (!readableIds.has(oldId)) st.failedTierIds.delete(oldId) + const knownTiers = new Set([...st.tierTitlesLoaded, ...st.tierManifestsLoaded, ...st.failedTierIds]) + for (const oldId of knownTiers) { + if (!readableIds.has(oldId)) this.evictTierData(st, oldId) } await Promise.all( @@ -449,7 +481,7 @@ export class LectureSearchEngine { tierFailed = true } else { const tTitleData = (await tTitleSettled.res.json()) as TitleIndexFile - this.mergeTitleIndex(st, tTitleData, this.opts.base) + this.mergeTitleIndex(st, tTitleData, this.opts.base, tier.id) st.tierTitlesLoaded.add(tier.id) } } catch { diff --git a/site/tests/unit/search-index.test.ts b/site/tests/unit/search-index.test.ts index 34c3761..23127a2 100644 --- a/site/tests/unit/search-index.test.ts +++ b/site/tests/unit/search-index.test.ts @@ -21,7 +21,7 @@ import { } from '../../docs/.vitepress/search/format.ts' import { buildSearchArtifacts, SearchBudgetError, writeSearchArtifacts } from '../../docs/.vitepress/search/indexBuilder.ts' import { extractSearchablePage } from '../../docs/.vitepress/search/markdown.ts' -import { configureAccess, invalidateAccess } from '../../docs/.vitepress/theme/access/store.ts' +import { configureAccess } from '../../docs/.vitepress/theme/access/store.ts' import { LectureSearchEngine, buildSnippet, splitHighlightParts } from '../../docs/.vitepress/theme/search/engine.ts' const tmpDirs: string[] = [] @@ -818,8 +818,19 @@ describe('client LectureSearchEngine: instant title results, progress, scope and expect(engine.getLoadState('root', true)).toMatchObject({ loading: false, phase: 'ready', percent: 100 }) expect(engine.query('root', '独有正文字段', 'all', null).totalHits).toBe(1) - // 4. Separate instance: failed tier cleared cleanly if user later loses access (403) - vipTitlesStatus = 503 + // 4. Separate instance: already-loaded tier titles must be evicted and access cache re-validated when + // user later loses access (403) without manual invalidateAccess(). + vipTitlesStatus = 200 + let vipManifestStatus = 503 + siteDataStatus = 200 + const fetchFnRevoke: typeof fetch = async (input) => { + const url = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url + if (url.endsWith('/_access/vip/search/root/manifest.json') && vipManifestStatus !== 200) { + return new Response('err', { status: vipManifestStatus }) + } + return fetchFn(input) + } + configureAccess({ siteData: { value: siteObj }, withBase: (p) => p, fetch: fetchFnRevoke }) const engine2 = new LectureSearchEngine({ base: '/', localeKeys: ['en'], @@ -834,16 +845,21 @@ describe('client LectureSearchEngine: instant title results, progress, scope and loadError: '部分索引加载失败', statusLabel: (s) => s, }, - fetchFn, + fetchFn: fetchFnRevoke, }) await engine2.ensureLoaded('root', null) await vi.waitFor(() => expect(engine2.getLoadState('root', true).loading).toBe(false), { timeout: 10_000, interval: 10 }) expect(engine2.getLoadState('root', true)).toMatchObject({ loading: false, error: true, phase: 'partial-error' }) + expect(engine2.query('root', 'VIP', 'all', null).totalHits).toBe(1) + + // Gateway now denies vip (403); forceRetry automatically invalidates cached access, clears error, AND evicts cached vip titles! siteDataStatus = 403 - invalidateAccess() + vipManifestStatus = 403 await engine2.ensureLoaded('root', null, { forceRetry: true }) await vi.waitFor(() => expect(engine2.getLoadState('root', true).loading).toBe(false), { timeout: 10_000, interval: 10 }) expect(engine2.getLoadState('root', true)).toMatchObject({ loading: false, phase: 'ready', percent: 100 }) + expect(engine2.query('root', 'VIP', 'all', null).totalHits).toBe(0) + expect(engine2.query('root', '公开导论', 'all', null).totalHits).toBe(1) } finally { configureAccess({ siteData: { value: {} }, withBase: (p) => p }) } From 82f8df57ef4435a4799d5388efa154715412d174 Mon Sep 17 00:00:00 2001 From: YangObscurity Date: Thu, 26 Nov 2026 19:49:23 +0800 Subject: [PATCH 6/7] fix(search): guard evicted in-flight shards via tierEpoch and avoid NaN percent --- site/docs/.vitepress/theme/search/engine.ts | 46 ++++++-- site/tests/unit/search-index.test.ts | 118 +++++++++++++++++++- 2 files changed, 154 insertions(+), 10 deletions(-) diff --git a/site/docs/.vitepress/theme/search/engine.ts b/site/docs/.vitepress/theme/search/engine.ts index 3d85fb4..3b33b85 100644 --- a/site/docs/.vitepress/theme/search/engine.ts +++ b/site/docs/.vitepress/theme/search/engine.ts @@ -7,7 +7,7 @@ */ import { inflateTitleHeadings, stripLectureTitlePrefix, type SearchManifestFile, type ShardMeta, type ShardPayload, type TitleIndexFile, type TitleIndexGroup } from '../../search/format.ts' import { tierBasePath } from '../../access/tiers.ts' -import { lectureAccessOf, getAccess, invalidateAccess } from '../access/store.ts' +import { lectureAccessOf, getAccess, invalidateAccess, accessVersion } from '../access/store.ts' import { parseLecture } from '../core/route.ts' import type { ProgressStatus } from '../progress/types.ts' import type { SearchGroupSectionView, SearchHighlightPart, SearchHitView, SearchLoadState } from '../slots/registry.ts' @@ -53,6 +53,8 @@ export interface ClientBodySection { interface ShardQueueItem { key: string + tierId?: string + tierEpoch: number locale: string meta: ShardMeta url: string @@ -68,6 +70,8 @@ export interface LocaleIndexState { manifestLoading: Promise | null accessLoading: Promise | null accessFetchError: boolean + lastAccessVersion: number + tierEpoch: Map tierTitlesLoaded: Set tierManifestsLoaded: Set failedTierIds: Set @@ -261,6 +265,8 @@ export class LectureSearchEngine { manifestLoading: null, accessLoading: null, accessFetchError: false, + lastAccessVersion: -1, + tierEpoch: new Map(), tierTitlesLoaded: new Set(), tierManifestsLoaded: new Set(), failedTierIds: new Set(), @@ -355,12 +361,16 @@ export class LectureSearchEngine { credentials: RequestCredentials, cache: RequestCache, ): void { + const tierId = bucketKey.startsWith('tier:') ? bucketKey.slice('tier:'.length) : undefined + const tierEpoch = tierId ? (st.tierEpoch.get(tierId) ?? 0) : 0 for (const shard of manifest.shards) { const key = `${bucketKey}:${shard.shardId}` if (st.loadedShardKeys.has(key) || st.failedShardKeys.has(key)) continue if (st.pendingShards.some((p) => p.key === key)) continue st.pendingShards.push({ key, + tierId, + tierEpoch, locale: st.locale, meta: shard, url: `${urlPrefix}/${shard.url}`.replace(/\/{2,}/g, '/'), @@ -372,7 +382,12 @@ export class LectureSearchEngine { } } + private isStaleShard(st: LocaleIndexState, item: ShardQueueItem): boolean { + return Boolean(item.tierId && (st.tierEpoch.get(item.tierId) ?? 0) !== item.tierEpoch) + } + private evictTierData(st: LocaleIndexState, tierId: string): void { + st.tierEpoch.set(tierId, (st.tierEpoch.get(tierId) ?? 0) + 1) st.failedTierIds.delete(tierId) st.tierTitlesLoaded.delete(tierId) st.tierManifestsLoaded.delete(tierId) @@ -437,6 +452,7 @@ export class LectureSearchEngine { access = await getAccess() } st.accessFetchError = (access.failedTiers?.length ?? 0) > 0 + st.lastAccessVersion = accessVersion() } catch { st.accessFetchError = true return @@ -618,8 +634,8 @@ export class LectureSearchEngine { } else if (st.manifestLoading) { retryTasks.push(st.manifestLoading) } - if (forceRetry && (st.failedTierIds.size > 0 || st.accessFetchError)) { - retryTasks.push(this.loadAccessTiers(st, basePrefix, true)) + if (forceRetry || st.lastAccessVersion !== accessVersion()) { + retryTasks.push(this.loadAccessTiers(st, basePrefix, forceRetry)) } else if (st.accessLoading) { retryTasks.push(st.accessLoading) } @@ -661,12 +677,17 @@ export class LectureSearchEngine { item.credentials, this.fetchImpl, (bytes) => { + if (this.isStaleShard(st, item)) return st.inFlightBytes.set(item.key, Math.min(bytes, item.meta.bytes)) this.opts.onStateChange?.() }, item.cache, ) st.inFlightBytes.delete(item.key) + if (this.isStaleShard(st, item)) { + this.opts.onStateChange?.() + continue + } if (payload) { const parsedSections: ClientBodySection[] = [] for (const [pIdx, anchor, pathSegs, text] of payload.sections) { @@ -699,8 +720,10 @@ export class LectureSearchEngine { } } catch { st.inFlightBytes.delete(item.key) - st.failedShardKeys.add(item.key) - st.failedShardsByKey.set(item.key, item) + if (!this.isStaleShard(st, item)) { + st.failedShardKeys.add(item.key) + st.failedShardsByKey.set(item.key, item) + } } this.opts.onStateChange?.() } @@ -799,11 +822,16 @@ export class LectureSearchEngine { phase: 'ready', } } - const percent = Math.min(99, Math.max(0, Math.round((capped / st.totalShardBytes) * 100))) + const percent = + st.totalShardBytes > 0 ? Math.min(99, Math.max(0, Math.round((capped / st.totalShardBytes) * 100))) : 0 const toMb = (b: number) => (b / (1024 * 1024)).toFixed(1) - const label = hasQuery - ? this.opts.labels.loadingBar(toMb(capped), toMb(st.totalShardBytes)) - : this.opts.labels.loadingIdle(toMb(capped), toMb(st.totalShardBytes)) + const label = + st.totalShardBytes === 0 + ? resolveDynamicLabel(this.opts.labels.loadingTitles) || + (hasQuery ? this.opts.labels.loadingBar(toMb(capped), toMb(st.totalShardBytes)) : this.opts.labels.loadingIdle(toMb(capped), toMb(st.totalShardBytes))) + : hasQuery + ? this.opts.labels.loadingBar(toMb(capped), toMb(st.totalShardBytes)) + : this.opts.labels.loadingIdle(toMb(capped), toMb(st.totalShardBytes)) return { loading: true, loadedBytes: capped, diff --git a/site/tests/unit/search-index.test.ts b/site/tests/unit/search-index.test.ts index 23127a2..20cda37 100644 --- a/site/tests/unit/search-index.test.ts +++ b/site/tests/unit/search-index.test.ts @@ -22,7 +22,7 @@ import { import { buildSearchArtifacts, SearchBudgetError, writeSearchArtifacts } from '../../docs/.vitepress/search/indexBuilder.ts' import { extractSearchablePage } from '../../docs/.vitepress/search/markdown.ts' import { configureAccess } from '../../docs/.vitepress/theme/access/store.ts' -import { LectureSearchEngine, buildSnippet, splitHighlightParts } from '../../docs/.vitepress/theme/search/engine.ts' +import { LectureSearchEngine, buildSnippet, splitHighlightParts, type LocaleIndexState } from '../../docs/.vitepress/theme/search/engine.ts' const tmpDirs: string[] = [] @@ -864,4 +864,120 @@ describe('client LectureSearchEngine: instant title results, progress, scope and configureAccess({ siteData: { value: {} }, withBase: (p) => p }) } }) + + it('returns finite percent=0 when public manifest is empty while access tiers are loading, and ignores in-flight evicted shards', async () => { + const publicTitles: TitleIndexFile = { + v: 1, + locale: 'root', + groups: [{ id: 'G01', dir: 'g01', title: '公开组', catSlot: 1 }], + pages: [[0, 1, 'G01-L01', '/g01/L01', '第1讲 · 公开导论', []]], + } + const emptyManifest: SearchManifestFile = { + v: 1, + locale: 'root', + titleFile: 'titles.json', + titleBytes: 10, + totalShardBytes: 0, + totalRawShardBytes: 0, + shards: [], + } + const vipTitles: TitleIndexFile = { + v: 1, + locale: 'root', + groups: [{ id: 'VIP', dir: 'vip', title: '进阶组', catSlot: 2 }], + pages: [[0, 1, 'VIP-L01', '/vip/L01', '第1讲 · 竞态测试', []]], + } + const vipShardRaw = Buffer.from( + JSON.stringify({ v: 1, shardId: 'vip', groupId: 'VIP', pages: ['/vip/L01'], sections: [[0, 's1', ['节'], '竞态恢复内容']] }), + 'utf8', + ) + const vipShard = zlib.deflateRawSync(vipShardRaw, { level: 9 }) + const vipManifest: SearchManifestFile = { + v: 1, + locale: 'root', + titleFile: 'titles.json', + titleBytes: 10, + totalShardBytes: vipShard.byteLength, + totalRawShardBytes: vipShardRaw.byteLength, + shards: [{ shardId: 'vip', groupId: 'VIP', url: 'shards/vip.sz', bytes: vipShard.byteLength, rawBytes: vipShardRaw.byteLength, pageCount: 1 }], + } + + let releaseSiteData!: () => void + const siteDataGate = new Promise((r) => { + releaseSiteData = r + }) + let releaseShard!: () => void + const shardGate = new Promise((r) => { + releaseShard = r + }) + let shardCalls = 0 + const siteObj = { themeConfig: { lectureAccess: { inlineTier: 'public', tiers: ['vip'] } } } + const fetchFn: typeof fetch = async (input) => { + const url = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url + if (url.endsWith('/_access/vip/site-data.json')) { + await siteDataGate + return new Response(JSON.stringify({ version: 1, tier: 'vip', groups: [], totals: { lectures: 1, charts: 0 }, locales: {} }), { status: 200 }) + } + if (url.endsWith('/_access/vip/search/root/titles.json')) return new Response(JSON.stringify(vipTitles), { status: 200 }) + if (url.endsWith('/_access/vip/search/root/manifest.json')) return new Response(JSON.stringify(vipManifest), { status: 200 }) + if (url.endsWith('/_access/vip/search/root/shards/vip.sz')) { + shardCalls++ + if (shardCalls === 1) { + await shardGate + return new Response('revoked', { status: 403 }) + } + return new Response(new Uint8Array(vipShard), { status: 200 }) + } + if (url.endsWith('/search/root/titles.json')) return new Response(JSON.stringify(publicTitles), { status: 200 }) + if (url.endsWith('/search/root/manifest.json')) return new Response(JSON.stringify(emptyManifest), { status: 200 }) + return new Response('not found', { status: 404 }) + } + + configureAccess({ siteData: { value: siteObj }, withBase: (p) => p, fetch: fetchFn }) + try { + const engine = new LectureSearchEngine({ + base: '/', + localeKeys: ['en'], + siteData: () => siteObj, + statusOf: () => 'not_started', + labels: { + lectureNo: (n) => `第${n}讲`, + groupCount: (n) => `${n} 条`, + groupSite: '概览', + loadingBar: (l, t) => `loading ${l}/${t}`, + loadingIdle: (l, t) => `idle ${l}/${t}`, + loadingTitles: '正在加载搜索索引…', + statusLabel: (s) => s, + }, + fetchFn, + }) + + const p = engine.ensureLoaded('root', null) + await vi.waitFor(() => expect(engine.getLoadState('root', true).phase).toBe('loading-shards'), { timeout: 5_000, interval: 5 }) + const loadingWithEmptyManifest = engine.getLoadState('root', true) + expect(Number.isNaN(loadingWithEmptyManifest.percent)).toBe(false) + expect(loadingWithEmptyManifest.percent).toBe(0) + + releaseSiteData() + await p + // Wait for first shard request to enter flight + await vi.waitFor(() => expect(shardCalls).toBe(1), { timeout: 5_000, interval: 5 }) + // Evict vip while shard #1 is still in flight + const st = (engine as unknown as { states: Map }).states.get('root')! + ;(engine as unknown as { evictTierData(s: LocaleIndexState, id: string): void }).evictTierData(st, 'vip') + + releaseShard() + await vi.waitFor(() => expect(st.shardsPumpPromise).toBeNull(), { timeout: 5_000, interval: 5 }) + // Stale failure from evicted epoch must NOT pollute failedShardKeys or loadedShardKeys + expect(st.failedShardKeys.has('tier:vip:vip')).toBe(false) + expect(st.loadedShardKeys.has('tier:vip:vip')).toBe(false) + + // Re-loading vip after eviction works cleanly without stale key skip or poison + await engine.ensureLoaded('root', null, { forceRetry: true }) + await vi.waitFor(() => expect(engine.getLoadState('root', true).loading).toBe(false), { timeout: 5_000, interval: 5 }) + expect(engine.query('root', '竞态恢复内容', 'all', null).totalHits).toBe(1) + } finally { + configureAccess({ siteData: { value: {} }, withBase: (p) => p }) + } + }) }) From 62c221c8d3966182e95a14cecbf853a2efe27cb0 Mon Sep 17 00:00:00 2001 From: YangObscurity Date: Thu, 26 Nov 2026 20:05:46 +0800 Subject: [PATCH 7/7] fix(search): ensure getAccess result and accessVersion pair across concurrent swaps --- site/docs/.vitepress/theme/search/engine.ts | 16 +++- site/tests/unit/search-index.test.ts | 85 ++++++++++++++++++++- 2 files changed, 98 insertions(+), 3 deletions(-) diff --git a/site/docs/.vitepress/theme/search/engine.ts b/site/docs/.vitepress/theme/search/engine.ts index 3b33b85..365af56 100644 --- a/site/docs/.vitepress/theme/search/engine.ts +++ b/site/docs/.vitepress/theme/search/engine.ts @@ -7,7 +7,7 @@ */ import { inflateTitleHeadings, stripLectureTitlePrefix, type SearchManifestFile, type ShardMeta, type ShardPayload, type TitleIndexFile, type TitleIndexGroup } from '../../search/format.ts' import { tierBasePath } from '../../access/tiers.ts' -import { lectureAccessOf, getAccess, invalidateAccess, accessVersion } from '../access/store.ts' +import { lectureAccessOf, getAccess, invalidateAccess, accessVersion, currentAccess } from '../access/store.ts' import { parseLecture } from '../core/route.ts' import type { ProgressStatus } from '../progress/types.ts' import type { SearchGroupSectionView, SearchHighlightPart, SearchHitView, SearchLoadState } from '../slots/registry.ts' @@ -445,15 +445,27 @@ export class LectureSearchEngine { st.accessLoading = (async () => { try { let access: Awaited> + let resolvedVersion = -1 try { access = await getAccess() if (forceRetry && (st.accessFetchError || st.failedTierIds.size > 0 || (access.failedTiers?.length ?? 0) > 0)) { invalidateAccess() access = await getAccess() } + // Ensure `access` and `accessVersion()` belong to the same non-superseded resolution across session swaps. + for (let attempt = 0; attempt < 4 && access !== currentAccess(); attempt++) { + access = await getAccess() + } + if (access !== currentAccess()) { + st.lastAccessVersion = -1 + st.accessFetchError = true + return + } + resolvedVersion = accessVersion() st.accessFetchError = (access.failedTiers?.length ?? 0) > 0 - st.lastAccessVersion = accessVersion() + st.lastAccessVersion = resolvedVersion } catch { + st.lastAccessVersion = -1 st.accessFetchError = true return } diff --git a/site/tests/unit/search-index.test.ts b/site/tests/unit/search-index.test.ts index 20cda37..629f3cd 100644 --- a/site/tests/unit/search-index.test.ts +++ b/site/tests/unit/search-index.test.ts @@ -21,7 +21,7 @@ import { } from '../../docs/.vitepress/search/format.ts' import { buildSearchArtifacts, SearchBudgetError, writeSearchArtifacts } from '../../docs/.vitepress/search/indexBuilder.ts' import { extractSearchablePage } from '../../docs/.vitepress/search/markdown.ts' -import { configureAccess } from '../../docs/.vitepress/theme/access/store.ts' +import { configureAccess, getAccess, invalidateAccess } from '../../docs/.vitepress/theme/access/store.ts' import { LectureSearchEngine, buildSnippet, splitHighlightParts, type LocaleIndexState } from '../../docs/.vitepress/theme/search/engine.ts' const tmpDirs: string[] = [] @@ -980,4 +980,87 @@ describe('client LectureSearchEngine: instant title results, progress, scope and configureAccess({ siteData: { value: {} }, withBase: (p) => p }) } }) + + it('discards superseded getAccess() results on concurrent session switch and pairs lastAccessVersion with currentAccess', async () => { + const publicTitles: TitleIndexFile = { + v: 1, + locale: 'root', + groups: [{ id: 'G01', dir: 'g01', title: '公开组', catSlot: 1 }], + pages: [[0, 1, 'G01-L01', '/g01/L01', '第1讲 · 公开导论', []]], + } + const emptyManifest: SearchManifestFile = { + v: 1, + locale: 'root', + titleFile: 'titles.json', + titleBytes: 10, + totalShardBytes: 0, + totalRawShardBytes: 0, + shards: [], + } + const vipTitles: TitleIndexFile = { + v: 1, + locale: 'root', + groups: [{ id: 'VIP', dir: 'vip', title: '进阶组', catSlot: 2 }], + pages: [[0, 1, 'VIP-L01', '/vip/L01', '第1讲 · 越权旧结果', []]], + } + + let releaseFirstSiteData!: () => void + const firstSiteDataGate = new Promise((r) => { + releaseFirstSiteData = r + }) + let siteDataCalls = 0 + const siteObj = { themeConfig: { lectureAccess: { inlineTier: 'public', tiers: ['vip'] } } } + const fetchFn: typeof fetch = async (input) => { + const url = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url + if (url.endsWith('/_access/vip/site-data.json')) { + const call = ++siteDataCalls + if (call === 1) { + await firstSiteDataGate + return new Response(JSON.stringify({ version: 1, tier: 'vip', groups: [], totals: { lectures: 1, charts: 0 }, locales: {} }), { status: 200 }) + } + return new Response('denied', { status: 403 }) + } + if (url.endsWith('/_access/vip/search/root/titles.json')) return new Response(JSON.stringify(vipTitles), { status: 200 }) + if (url.endsWith('/_access/vip/search/root/manifest.json')) return new Response(JSON.stringify(emptyManifest), { status: 200 }) + if (url.endsWith('/search/root/titles.json')) return new Response(JSON.stringify(publicTitles), { status: 200 }) + if (url.endsWith('/search/root/manifest.json')) return new Response(JSON.stringify(emptyManifest), { status: 200 }) + return new Response('not found', { status: 404 }) + } + + configureAccess({ siteData: { value: siteObj }, withBase: (p) => p, fetch: fetchFn }) + try { + const engine = new LectureSearchEngine({ + base: '/', + localeKeys: ['en'], + siteData: () => siteObj, + statusOf: () => 'not_started', + labels: { + lectureNo: (n) => `第${n}讲`, + groupCount: (n) => `${n} 条`, + groupSite: '概览', + loadingBar: (l, t) => `loading ${l}/${t}`, + loadingIdle: (l, t) => `idle ${l}/${t}`, + loadingTitles: '正在加载搜索索引…', + statusLabel: (s) => s, + }, + fetchFn, + }) + + const p = engine.ensureLoaded('root', null) + await vi.waitFor(() => expect(siteDataCalls).toBe(1), { timeout: 5_000, interval: 5 }) + + // Mid-flight session downgrade: newer getAccess() starts and resolves 403 BEFORE call #1 resolves 200 + invalidateAccess() + await getAccess() + expect(siteDataCalls).toBe(2) + + releaseFirstSiteData() + await p + expect(engine.query('root', '越权旧结果', 'all', null).totalHits).toBe(0) + expect(engine.query('root', '公开导论', 'all', null).totalHits).toBe(1) + expect(engine.getLoadState('root', true).phase).toBe('ready') + } finally { + configureAccess({ siteData: { value: {} }, withBase: (p) => p }) + } + }) })