Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(docsite): warm site search before the first keystroke (#9426)

Cindy Zhangc25607cab48c
diff --git a/apps/docsite/src/__tests__/search-warmup-route.test.ts b/apps/docsite/src/__tests__/search-warmup-route.test.ts
new file mode 100644
index 0000000000..6dab2e8d1c
--- /dev/null
+++ b/apps/docsite/src/__tests__/search-warmup-route.test.ts
@@ -0,0 +1,24 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file The search API's warm-up: it loads the search and is never cached, so
+ * it reaches, and warms, a server.
+ */
+
+import {describe, expect, it} from 'vitest';
+import {GET} from '../app/api/search/route';
+import {SEARCH_WARMUP_URL} from '../lib/searchWarmup';
+
+describe('GET /api/search?warm=1', () => {
+ it('answers 204, uncached, after loading the search', async () => {
+ const response = await GET(new Request(`http://site${SEARCH_WARMUP_URL}`));
+ expect(response.status).toBe(204);
+ expect(response.headers.get('Cache-Control')).toBe('no-store');
+ expect(await response.text()).toBe('');
+ }, 120_000);
+
+ it('leaves a request without a query rejected', async () => {
+ const response = await GET(new Request('http://site/api/search'));
+ expect(response.status).toBe(400);
+ });
+});
diff --git a/apps/docsite/src/__tests__/search-warmup.test.ts b/apps/docsite/src/__tests__/search-warmup.test.ts
new file mode 100644
index 0000000000..704753aa2a
--- /dev/null
+++ b/apps/docsite/src/__tests__/search-warmup.test.ts
@@ -0,0 +1,258 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+// @vitest-environment jsdom
+
+/**
+ * @file Search is warmed before the first keystroke, at most once per tab per
+ * interval. The API's side is in search-warmup-route.test.ts.
+ */
+
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {SERVER_WAIT_MS, createCliSearchSource} from '../lib/cliSearchSource';
+import {
+ SEARCH_WARMUP_INTERVAL_MS,
+ SEARCH_WARMUP_URL,
+ resetSearchWarmup,
+ runningSearchWarmup,
+ warmSearch,
+ whenIdle,
+} from '../lib/searchWarmup';
+
+describe('warmSearch', () => {
+ beforeEach(() => resetSearchWarmup());
+
+ it('sends one uncached warm-up request', () => {
+ const fetchWarmup = vi.fn(() => Promise.resolve());
+ expect(warmSearch(fetchWarmup, 1_000)).toBe(true);
+ expect(fetchWarmup).toHaveBeenCalledTimes(1);
+ expect(fetchWarmup).toHaveBeenCalledWith(SEARCH_WARMUP_URL, {
+ cache: 'no-store',
+ });
+ });
+
+ it('sends nothing again within the interval, however often it is asked', () => {
+ const fetchWarmup = vi.fn(() => Promise.resolve());
+ warmSearch(fetchWarmup, 1_000);
+ for (let i = 0; i < 20; i++) {
+ expect(warmSearch(fetchWarmup, 1_000 + i * 1_000)).toBe(false);
+ }
+ expect(fetchWarmup).toHaveBeenCalledTimes(1);
+ });
+
+ it('warms again once the interval has passed', () => {
+ const fetchWarmup = vi.fn(() => Promise.resolve());
+ warmSearch(fetchWarmup, 1_000);
+ expect(warmSearch(fetchWarmup, 1_000 + SEARCH_WARMUP_INTERVAL_MS)).toBe(
+ true,
+ );
+ expect(fetchWarmup).toHaveBeenCalledTimes(2);
+ });
+
+ it('keeps throttling across a reload of the tab', () => {
+ const fetchWarmup = vi.fn(() => Promise.resolve());
+ warmSearch(fetchWarmup, 1_000);
+ // A reload loses module state; the tab's sessionStorage keeps the time.
+ expect(window.sessionStorage.length).toBe(1);
+ expect(warmSearch(fetchWarmup, 2_000)).toBe(false);
+ });
+
+ it('never throws when the request fails', async () => {
+ const rejecting = vi.fn(() => Promise.reject(new Error('offline')));
+ expect(warmSearch(rejecting, 1_000)).toBe(true);
+ await Promise.resolve();
+ resetSearchWarmup();
+ const throwing = vi.fn(() => {
+ throw new Error('no fetch');
+ });
+ expect(() => warmSearch(throwing, 1_000)).not.toThrow();
+ });
+});
+
+describe('whenIdle', () => {
+ afterEach(() => vi.useRealTimers());
+
+ it('runs the task after the fallback delay without an idle callback, and can be cancelled', () => {
+ vi.useFakeTimers();
+ const task = vi.fn();
+ whenIdle(task, 2_000);
+ vi.advanceTimersByTime(1_999);
+ expect(task).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(1);
+ expect(task).toHaveBeenCalledTimes(1);
+
+ const cancelled = vi.fn();
+ const cancel = whenIdle(cancelled, 2_000);
+ cancel();
+ vi.advanceTimersByTime(5_000);
+ expect(cancelled).not.toHaveBeenCalled();
+ });
+});
+
+/** A warm-up request the test answers when it chooses. */
+function heldWarmup() {
+ let answer: () => void = () => {};
+ const fetchWarmup = vi.fn(
+ () =>
+ new Promise<void>(resolve => {
+ answer = resolve;
+ }),
+ );
+ return {fetchWarmup, answer: () => answer()};
+}
+
+const flush = async () => {
+ for (let i = 0; i < 10; i++) {
+ await Promise.resolve();
+ }
+};
+
+describe('runningSearchWarmup', () => {
+ beforeEach(() => resetSearchWarmup());
+
+ it('is null when no warm-up is running, and settles when one answers', async () => {
+ expect(runningSearchWarmup()).toBeNull();
+ const warmup = heldWarmup();
+ warmSearch(warmup.fetchWarmup, 1_000);
+ const running = runningSearchWarmup();
+ expect(running).not.toBeNull();
+ warmup.answer();
+ await running;
+ expect(runningSearchWarmup()).toBeNull();
+ });
+
+ it('settles, never rejects, when the warm-up fails', async () => {
+ warmSearch(() => Promise.reject(new Error('offline')), 1_000);
+ await expect(runningSearchWarmup()).resolves.toBeUndefined();
+ });
+});
+
+/** A search fetch whose answers the test releases one by one. */
+function heldSearch() {
+ const pending: {
+ url: string;
+ init: RequestInit;
+ answer: (results: {href: string; name: string}[]) => void;
+ }[] = [];
+ const fetchSearch = vi.fn(
+ (url: string, init: RequestInit) =>
+ new Promise<Response>(resolve => {
+ pending.push({
+ url,
+ init,
+ answer: results =>
+ resolve(
+ Response.json({
+ data: {
+ results: results.map(result => ({
+ domain: 'component',
+ ...result,
+ })),
+ },
+ }),
+ ),
+ });
+ }),
+ );
+ return {fetchSearch, pending};
+}
+
+const APP_SHELL = [{href: '/components/app-shell', name: 'AppShell'}];
+const wait = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
+
+describe('one search request at a time', () => {
+ beforeEach(() => resetSearchWarmup());
+
+ it('sends a query typed during the warm-up when the warm-up answers', async () => {
+ const warmup = heldWarmup();
+ warmSearch(warmup.fetchWarmup, 1_000);
+ const search = heldSearch();
+ const source = createCliSearchSource(search.fetchSearch);
+ const results = source.search('app shell');
+ await wait(300);
+ expect(search.pending).toHaveLength(0);
+
+ warmup.answer();
+ await flush();
+ expect(search.pending.map(request => request.url)).toEqual([
+ '/api/search?q=app%20shell',
+ ]);
+ search.pending[0].answer(APP_SHELL);
+ expect((await results).map(item => item.label)).toEqual(['AppShell']);
+ });
+
+ it('sends only the newest query once the request before it answers', async () => {
+ const search = heldSearch();
+ const source = createCliSearchSource(search.fetchSearch, () => null);
+ const app = source.search('app');
+ await wait(200);
+ expect(search.pending).toHaveLength(1);
+
+ // Typed while "app" is on the server: these wait, and only the newest goes.
+ const appS = source.search('app s');
+ await wait(200);
+ const appShell = source.search('app shell');
+ await wait(200);
+ expect(search.pending).toHaveLength(1);
+ expect(await appS).toEqual([]);
+
+ search.pending[0].answer([{href: '/components/app', name: 'App'}]);
+ // A replaced query's answer is never shown.
+ expect(await app).toEqual([]);
+ await flush();
+ expect(search.pending.map(request => request.url)).toEqual([
+ '/api/search?q=app',
+ '/api/search?q=app%20shell',
+ ]);
+ search.pending[1].answer(APP_SHELL);
+ expect((await appShell).map(item => item.label)).toEqual(['AppShell']);
+ });
+
+ it('does not cancel a request already on the server when a query replaces it', async () => {
+ const search = heldSearch();
+ const source = createCliSearchSource(search.fetchSearch, () => null);
+ void source.search('app');
+ await wait(200);
+ void source.search('app shell');
+ expect(search.pending[0].init.signal).toBeUndefined();
+ });
+
+ it('sends the query anyway when the request before it never answers', async () => {
+ vi.useFakeTimers();
+ try {
+ warmSearch(heldWarmup().fetchWarmup, 1_000);
+ const search = heldSearch();
+ const source = createCliSearchSource(search.fetchSearch);
+ void source.search('app shell');
+ await vi.advanceTimersByTimeAsync(120 + SERVER_WAIT_MS - 10);
+ expect(search.pending).toHaveLength(0);
+ await vi.advanceTimersByTimeAsync(20);
+ expect(search.pending).toHaveLength(1);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('sends one request when the server is free', async () => {
+ const search = heldSearch();
+ const source = createCliSearchSource(search.fetchSearch, () => null);
+ const results = source.search('button');
+ await wait(200);
+ search.pending[0].answer([{href: '/components/button', name: 'Button'}]);
+ expect((await results).map(item => item.label)).toEqual(['Button']);
+ expect(search.pending).toHaveLength(1);
+ });
+
+ it('sends nothing for a query replaced while it waits', async () => {
+ const warmup = heldWarmup();
+ warmSearch(warmup.fetchWarmup, 1_000);
+ const search = heldSearch();
+ const source = createCliSearchSource(search.fetchSearch);
+ const stale = source.search('app');
+ await wait(200);
+ source.cancel?.();
+ expect(await stale).toEqual([]);
+ warmup.answer();
+ await flush();
+ expect(search.pending).toHaveLength(0);
+ });
+});
diff --git a/apps/docsite/src/__tests__/shared-top-nav-search.test.tsx b/apps/docsite/src/__tests__/shared-top-nav-search.test.tsx
index 5e638c52aa..1e9869724f 100644
--- a/apps/docsite/src/__tests__/shared-top-nav-search.test.tsx
+++ b/apps/docsite/src/__tests__/shared-top-nav-search.test.tsx
@@ -4,9 +4,15 @@
import type {ReactNode} from 'react';
import {useLayoutEffect, useRef} from 'react';
-import {render, screen, waitFor} from '@testing-library/react';
+import {cleanup, render, screen, waitFor} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
-import {describe, expect, it, vi} from 'vitest';
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {SEARCH_WARMUP_URL, resetSearchWarmup} from '../lib/searchWarmup';
+
+const fetchSpy = vi.fn((_url: string, _init?: RequestInit) =>
+ Promise.resolve(new Response(null, {status: 204})),
+);
+vi.stubGlobal('fetch', fetchSpy);
vi.mock('next/navigation', () => ({
usePathname: () => '/templates',
@@ -43,16 +49,25 @@ vi.mock('@astryxdesign/core/Button', () => ({
Button: ({
label,
onClick,
+ onPointerEnter,
+ onFocus,
href,
}: {
label: string;
onClick?: () => void;
+ onPointerEnter?: () => void;
+ onFocus?: () => void;
href?: string;
}) =>
href ? (
<a href={href}>{label}</a>
) : (
- <button onClick={onClick}>{label}</button>
+ <button
+ onClick={onClick}
+ onPointerEnter={onPointerEnter}
+ onFocus={onFocus}>
+ {label}
+ </button>
),
}));
@@ -112,7 +127,37 @@ vi.mock('../components/SearchPalette', () => ({
import {SharedTopNav} from '../components/SharedTopNav';
+const warmups = () =>
+ fetchSpy.mock.calls.filter(([url]) => url === SEARCH_WARMUP_URL);
+
describe('SharedTopNav search lifecycle', () => {
+ beforeEach(() => {
+ fetchSpy.mockClear();
+ resetSearchWarmup();
+ });
+ afterEach(cleanup);
+
+ it('starts the search server before the first keystroke, once', async () => {
+ const user = userEvent.setup();
+ render(<SharedTopNav />);
+ const trigger = screen.getByRole('button', {name: 'Search'});
+
+ await user.hover(trigger);
+ expect(warmups()).toHaveLength(1);
+ expect(warmups()[0][1]).toEqual({cache: 'no-store'});
+
+ // Hovering again, focusing and opening do not send it again.
+ await user.unhover(trigger);
+ await user.hover(trigger);
+ await user.click(trigger);
+ expect(warmups()).toHaveLength(1);
+ });
+
+ it('starts the search server once the page is idle, with no interaction', async () => {
+ render(<SharedTopNav />);
+ await waitFor(() => expect(warmups()).toHaveLength(1), {timeout: 3_000});
+ });
+
it('keeps Search mounted through close so focus returns to its trigger', async () => {
const user = userEvent.setup();
render(<SharedTopNav />);
diff --git a/apps/docsite/src/app/api/search/route.ts b/apps/docsite/src/app/api/search/route.ts
index eaa88eebb0..f3c670c37a 100644
--- a/apps/docsite/src/app/api/search/route.ts
+++ b/apps/docsite/src/app/api/search/route.ts
@@ -11,6 +11,10 @@
* `@astryxdesign/cli/api`, the function behind `astryx search --json`, in this
* site's project, so the panel gives the CLI's results in the CLI's order and
* every change to the CLI's search reaches the site. Nothing here ranks.
+ *
+ * GET /api/search?warm=1 answers 204 after loading the CLI's search in this
+ * server, so a reader's first query does not wait for a cold start
+ * (lib/searchWarmup.ts sends it before the first keystroke).
*/
import {search} from '@astryxdesign/cli/api';
@@ -43,8 +47,21 @@ const LIMIT = 20;
/** Longest query the API accepts. */
const MAX_QUERY = 200;
+/** The query a warm-up runs: any query loads the CLI and gathers its catalog. */
+const WARMUP_QUERY = 'button';
+
export async function GET(request: Request): Promise<Response> {
- const query = new URL(request.url).searchParams.get('q')?.trim() ?? '';
+ const params = new URL(request.url).searchParams;
+ if (params.has('warm')) {
+ // Gather now, in this server, so the reader's first query only ranks.
+ // Never cached: a cached answer would not reach, and so not warm, a server.
+ await search(WARMUP_QUERY, {cwd: process.cwd(), limit: 1});
+ return new Response(null, {
+ status: 204,
+ headers: {'Cache-Control': 'no-store'},
+ });
+ }
+ const query = params.get('q')?.trim() ?? '';
if (query === '' || query.length > MAX_QUERY) {
return Response.json(
{error: `q must be 1 to ${MAX_QUERY} characters`},
diff --git a/apps/docsite/src/components/SharedTopNav.tsx b/apps/docsite/src/components/SharedTopNav.tsx
index ce7333b484..acce8b942f 100644
--- a/apps/docsite/src/components/SharedTopNav.tsx
+++ b/apps/docsite/src/components/SharedTopNav.tsx
@@ -24,11 +24,33 @@ import {AstryxIcon} from './logos';
import {useThemeMode} from '../app/providers';
import {trackSearch, trackClickCta} from '../lib/analytics';
import {useAppShellHeaderHeight} from '../lib/useAppShellHeaderHeight';
+import {warmSearch, whenIdle} from '../lib/searchWarmup';
+
+type SearchPaletteModule = typeof import('./SearchPalette');
+let searchPaletteModule: Promise<SearchPaletteModule> | undefined;
+
+/** The palette's code, requested once; a failed load is tried again. */
+function loadSearchPalette(): Promise<SearchPaletteModule> {
+ searchPaletteModule ??= import('./SearchPalette').catch(error => {
+ searchPaletteModule = undefined;
+ throw error;
+ });
+ return searchPaletteModule;
+}
const LazySearchPalette = lazy(() =>
- import('./SearchPalette').then(module => ({default: module.SearchPalette})),
+ loadSearchPalette().then(module => ({default: module.SearchPalette})),
);
+/**
+ * Get search ready before the reader types: start the search server (throttled
+ * per tab) and load the palette's code, so the first query waits for neither.
+ */
+function prepareSearch() {
+ warmSearch();
+ loadSearchPalette().catch(() => {});
+}
+
const GitHubIcon = ({
width = 20,
height = 20,
@@ -138,6 +160,7 @@ export function SharedTopNav() {
) {
event.preventDefault();
trackSearch({target: 'open'});
+ prepareSearch();
setHasLoadedSearch(true);
setIsSearchOpen(true);
}
@@ -147,6 +170,14 @@ export function SharedTopNav() {
return () => document.removeEventListener('keydown', onKeyDown);
}, []);
+ // Synchronizes with the browser's idle scheduler: most readers open Search
+ // seconds after a page loads, so once the page is idle, get search ready and
+ // their first query does not wait on a cold start. Cleanup cancels the idle
+ // callback. The warm-up request itself belongs to the tab, not this nav
+ // (lib/searchWarmup.ts throttles it per tab), so a StrictMode replay or a
+ // remount sends no second request.
+ useEffect(() => whenIdle(prepareSearch), []);
+
// Determine active nav item
const getActiveItem = () => {
if (
@@ -219,8 +250,11 @@ export function SharedTopNav() {
variant="ghost"
isIconOnly
icon={<Search size={20} />}
+ onPointerEnter={prepareSearch}
+ onFocus={prepareSearch}
onClick={() => {
trackSearch({target: 'open'});
+ prepareSearch();
setHasLoadedSearch(true);
setIsSearchOpen(true);
}}
diff --git a/apps/docsite/src/lib/cliSearchSource.ts b/apps/docsite/src/lib/cliSearchSource.ts
index 92c00bed14..ecbdb4eaae 100644
--- a/apps/docsite/src/lib/cliSearchSource.ts
+++ b/apps/docsite/src/lib/cliSearchSource.ts
@@ -3,7 +3,8 @@
/**
* @file The search panel's source: each query goes to the site's search API
* (app/api/search/route.ts), which runs `astryx search`, and its results come
- * back in the CLI's order.
+ * back in the CLI's order. The page sends one search request at a time (the
+ * warm-up counts as one), and only the newest query once the server is free.
* @position Consumed by SearchPalette.tsx.
*
* Items carry no `group`, since CommandPalette orders grouped items by group
@@ -12,6 +13,7 @@
import type {SearchSource, SearchableItem} from '@astryxdesign/core/Typeahead';
import type {SiteSearchResult} from './cliSearchTypes';
+import {runningSearchWarmup} from './searchWarmup';
export interface CliSearchItem extends SearchableItem<SiteSearchResult> {
id: string;
@@ -78,15 +80,25 @@ export function toSearchItem(
/** How long typing must pause before a query is sent. */
const DEBOUNCE_MS = 120;
+/**
+ * The longest a query waits for the request before it (or the warm-up):
+ * longer than a cold start, so a request that never answers holds nothing for
+ * good.
+ */
+export const SERVER_WAIT_MS = 10_000;
+
/**
* A SearchSource that answers with `astryx search`, through the site's API.
* @param fetchSearch - Fetches one query's response; the site passes `fetch`.
+ * @param runningWarmup - The page's running warm-up (lib/searchWarmup.ts), or
+ * null.
*/
export function createCliSearchSource(
fetchSearch: (url: string, init: RequestInit) => Promise<Response> = (
url,
init,
) => fetch(url, init),
+ runningWarmup: () => Promise<void> | null = runningSearchWarmup,
): SearchSource<CliSearchItem> & {
item(id: string): CliSearchItem | undefined;
} {
@@ -94,6 +106,32 @@ export function createCliSearchSource(
let shown = new Map<string, CliSearchItem>();
let inFlight: AbortController | null = null;
+ // The request the server is working on, settled or not.
+ let serverBusy: Promise<unknown> = Promise.resolve();
+
+ /**
+ * Send one query when the server is free. A search server is blocked while
+ * it works on a request (and for seconds while it starts), so the host
+ * sends a request that arrives meanwhile to another server, which may start
+ * cold. So the page keeps one request at a time: a query waits for the
+ * request before it and for a running warm-up, at most SERVER_WAIT_MS. A
+ * request already sent is not cancelled when a newer query replaces it: the
+ * server finishes it anyway, and the newer query waits for it.
+ */
+ async function sendQuery(
+ url: string,
+ signal: AbortSignal,
+ ): Promise<Response> {
+ const warmup = runningWarmup();
+ await whenSettled(
+ warmup ? Promise.all([serverBusy, warmup]) : serverBusy,
+ signal,
+ );
+ const request = fetchSearch(url, {});
+ serverBusy = request.catch(() => {});
+ return (await whenSettled(request, signal, false)) as Response;
+ }
+
return {
bootstrap() {
return [];
@@ -113,9 +151,9 @@ export function createCliSearchSource(
reject(controller.signal.reason);
});
});
- const response = await fetchSearch(
+ const response = await sendQuery(
`/api/search?q=${encodeURIComponent(query)}`,
- {signal: controller.signal},
+ controller.signal,
);
if (!response.ok) {
throw new Error(`search: HTTP ${response.status}`);
@@ -123,13 +161,17 @@ export function createCliSearchSource(
const body = (await response.json()) as {
data: {results: SiteSearchResult[]};
};
+ // A newer query replaced this one while its answer was read.
+ controller.signal.throwIfAborted();
// Two results can open the same place on the site (a topic and the
// page that shows it): the panel lists each place once, at its
// first result, keeping the CLI's order.
const opened = new Set<string>();
const items = body.data.results
.filter(result => {
- if (opened.has(result.href)) return false;
+ if (opened.has(result.href)) {
+ return false;
+ }
opened.add(result.href);
return true;
})
@@ -152,3 +194,34 @@ export function createCliSearchSource(
},
};
}
+
+/**
+ * `work`'s outcome, or a rejection with `signal`'s reason once it aborts.
+ * With `capped`, resolve after SERVER_WAIT_MS at the latest.
+ */
+function whenSettled<T>(
+ work: Promise<T>,
+ signal: AbortSignal,
+ capped = true,
+): Promise<T | undefined> {
+ return new Promise((resolve, reject) => {
+ const timer = capped
+ ? setTimeout(() => finish(() => resolve(undefined)), SERVER_WAIT_MS)
+ : undefined;
+ const onAbort = () => finish(() => reject(signal.reason));
+ function finish(settle: () => void) {
+ clearTimeout(timer);
+ signal.removeEventListener('abort', onAbort);
+ settle();
+ }
+ if (signal.aborted) {
+ onAbort();
+ return;
+ }
+ signal.addEventListener('abort', onAbort, {once: true});
+ work.then(
+ value => finish(() => resolve(value)),
+ error => finish(() => reject(error)),
+ );
+ });
+}
diff --git a/apps/docsite/src/lib/searchWarmup.ts b/apps/docsite/src/lib/searchWarmup.ts
new file mode 100644
index 0000000000..8b3ec1c74f
--- /dev/null
+++ b/apps/docsite/src/lib/searchWarmup.ts
@@ -0,0 +1,132 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Gets the site's search ready before the first keystroke.
+ * @input A moment the reader may be about to search: the page went idle after
+ * loading, the pointer or focus reached the Search button, or the palette
+ * opened.
+ * @output At most one warm-up request to the search API (app/api/search) per
+ * tab every few minutes, and while it runs, a promise that settles when it
+ * answers (runningSearchWarmup).
+ * @position Called by SharedTopNav.tsx.
+ *
+ * The site's search runs the CLI's `search()` on the server (spec:AST-033
+ * DEC-8). A server that has not answered for a while starts cold: it loads the
+ * CLI and gathers its catalog, which takes seconds, and the reader's first
+ * query used to wait for all of it. A warm-up request does that work while the
+ * reader is still reading or reaching for Search, so their first query only
+ * ranks. Warm-ups are throttled per tab (sessionStorage survives reloads and
+ * client navigation) so hovering or reopening Search never sends a request
+ * each time.
+ *
+ * While the warm-up runs, its server is starting and cannot take requests, so
+ * the host would start another cold server for a query sent then. The search
+ * source (lib/cliSearchSource.ts) holds a query until the running warm-up
+ * answers (runningSearchWarmup), and keeps one request at a time after that.
+ */
+
+/** The request that loads the search server without running a query. */
+export const SEARCH_WARMUP_URL = '/api/search?warm=1';
+
+/**
+ * How long a warm-up keeps counting: shorter than the time an idle server is
+ * kept, so a reader who comes back to Search later warms it again.
+ */
+export const SEARCH_WARMUP_INTERVAL_MS = 4 * 60 * 1000;
+
+const STORAGE_KEY = 'astryx-docsite:search-warmed-at';
+
+/** The last warm-up in this tab when sessionStorage is unavailable. */
+let lastWarmedAt = Number.NEGATIVE_INFINITY;
+
+/** The warm-up this page sent, until it answers. */
+let running: Promise<void> | null = null;
+
+function readWarmedAt(): number {
+ try {
+ const stored = window.sessionStorage.getItem(STORAGE_KEY);
+ if (stored != null) {
+ const at = Number(stored);
+ if (Number.isFinite(at)) {
+ return Math.max(at, lastWarmedAt);
+ }
+ }
+ } catch {
+ // Storage can be denied; the in-memory time still throttles this page.
+ }
+ return lastWarmedAt;
+}
+
+function writeWarmedAt(at: number): void {
+ lastWarmedAt = at;
+ try {
+ window.sessionStorage.setItem(STORAGE_KEY, String(at));
+ } catch {
+ // See readWarmedAt.
+ }
+}
+
+/**
+ * Send one warm-up request unless this tab sent one in the last
+ * SEARCH_WARMUP_INTERVAL_MS. Never throws, and never waits for the answer.
+ * @returns Whether a request was sent.
+ */
+export function warmSearch(
+ fetchWarmup: (url: string, init: RequestInit) => Promise<unknown> = (
+ url,
+ init,
+ ) => fetch(url, init),
+ now: number = Date.now(),
+): boolean {
+ if (now - readWarmedAt() < SEARCH_WARMUP_INTERVAL_MS) {
+ return false;
+ }
+ writeWarmedAt(now);
+ let request: Promise<unknown>;
+ try {
+ request = fetchWarmup(SEARCH_WARMUP_URL, {cache: 'no-store'});
+ } catch {
+ // A failed warm-up only means the first query starts the server itself.
+ return true;
+ }
+ const settled: Promise<void> = Promise.resolve(request).then(
+ () => {},
+ () => {},
+ );
+ running = settled;
+ settled.then(() => {
+ if (running === settled) {
+ running = null;
+ }
+ });
+ return true;
+}
+
+/** The warm-up this page sent, until it answers (never rejects); otherwise null. */
+export function runningSearchWarmup(): Promise<void> | null {
+ return running;
+}
+
+/** Forget the last warm-up. For tests. */
+export function resetSearchWarmup(): void {
+ lastWarmedAt = Number.NEGATIVE_INFINITY;
+ running = null;
+ try {
+ window.sessionStorage.removeItem(STORAGE_KEY);
+ } catch {
+ // See readWarmedAt.
+ }
+}
+
+/**
+ * Run `task` once the page is idle after loading, or after `fallbackMs` where
+ * the browser has no idle callback. Returns a cancel function.
+ */
+export function whenIdle(task: () => void, fallbackMs = 2000): () => void {
+ if (typeof window.requestIdleCallback === 'function') {
+ const handle = window.requestIdleCallback(task, {timeout: fallbackMs * 2});
+ return () => window.cancelIdleCallback(handle);
+ }
+ const handle = window.setTimeout(task, fallbackMs);
+ return () => window.clearTimeout(handle);
+}