Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion apps/web/src/features/recipes/RecipeCreatePage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1180,7 +1180,10 @@ function RecipeEditPage({ id }: { id: string }) {
(signal: AbortSignal) => getRecipe(id, signal),
[id],
);
const query = useRecipeQuery(id, load, { refreshOnMutation: false });
const query = useRecipeQuery(id, load, {
refreshOnMutation: false,
refreshWhenStale: false,
});
// Each state sets its own title; RecipeEditor sets "Edit <title>".
if (query.loading || query.error)
return (
Expand Down
15 changes: 12 additions & 3 deletions apps/web/src/features/recipes/recipeQueryCache.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
const TTL_MS = 30_000;
/** How long fetched recipe data counts as fresh (cache and refresh-on-focus). */
export const RECIPE_FRESHNESS_MS = 30_000;
const TTL_MS = RECIPE_FRESHNESS_MS;
const MAX_ENTRIES = 40;
const entries = new Map<string, { data: unknown; expires: number }>();
let generation = 0;
Expand All @@ -8,18 +10,25 @@ export function clearRecipeQueryCache() {
generation += 1;
}

/** Drops one entry so the next read fetches from the API. */
export function forgetRecipeCache(key: string) {
entries.delete(key);
}

export function recipeCacheGeneration() {
return generation;
}

export function readRecipeCache<T>(key: string): { data: T } | undefined {
export function readRecipeCache<T>(
key: string,
): { data: T; fetchedAt: number } | undefined {
const entry = entries.get(key);
if (!entry) return;
if (entry.expires <= Date.now()) {
entries.delete(key);
return;
}
return { data: entry.data as T };
return { data: entry.data as T, fetchedAt: entry.expires - TTL_MS };
}

export function writeRecipeCache(key: string, data: unknown, started: number) {
Expand Down
77 changes: 77 additions & 0 deletions apps/web/src/features/recipes/useRecipeQuery.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -136,3 +136,80 @@ it('invalidates cached pages after a mutation while they are unmounted', async (
await waitFor(() => expect(second.result.current.data).toBe('after'));
expect(load).toHaveBeenCalledTimes(2);
});
it('refreshes stale data in the background when the page regains focus', async () => {
const now = vi.spyOn(Date, 'now');
now.mockReturnValue(1_000_000);
const load = vi
.fn<(_: AbortSignal) => Promise<string>>()
.mockResolvedValueOnce('first')
.mockResolvedValueOnce('fresh');
const { result } = renderHook(() => useRecipeQuery('freshness', load));
await waitFor(() => expect(result.current.data).toBe('first'));

// Returning after 10 s: still fresh, no request.
now.mockReturnValue(1_010_000);
act(() => window.dispatchEvent(new Event('focus')));
expect(load).toHaveBeenCalledTimes(1);

// After 31 s the data is stale: refetch, keeping the old data meanwhile.
now.mockReturnValue(1_031_000);
act(() => window.dispatchEvent(new Event('focus')));
expect(result.current.data).toBe('first');
await waitFor(() => expect(result.current.data).toBe('fresh'));
expect(load).toHaveBeenCalledTimes(2);
now.mockRestore();
});
it('never refreshes on focus when refreshWhenStale is off (forms)', async () => {
const now = vi.spyOn(Date, 'now');
now.mockReturnValue(2_000_000);
const load = vi.fn(async () => 'form data');
const { result } = renderHook(() =>
useRecipeQuery('editor', load, { refreshWhenStale: false }),
);
await waitFor(() => expect(result.current.data).toBe('form data'));
now.mockReturnValue(2_100_000);
act(() => window.dispatchEvent(new Event('focus')));
expect(load).toHaveBeenCalledTimes(1);
now.mockRestore();
});
it('retries a failed background refresh the next time the page regains focus', async () => {
const now = vi.spyOn(Date, 'now');
now.mockReturnValue(3_000_000);
let fail!: (error: Error) => void;
const load = vi
.fn<(_: AbortSignal) => Promise<string>>()
.mockResolvedValueOnce('first')
.mockImplementationOnce(
() =>
new Promise((_resolve, reject) => {
fail = reject;
}),
)
.mockResolvedValueOnce('fresh');
const { result } = renderHook(() => useRecipeQuery('retry-stale', load));
await waitFor(() => expect(result.current.data).toBe('first'));

// Stale: one refresh starts. focus and visibilitychange often fire
// together; the second event must not start another request.
now.mockReturnValue(3_031_000);
act(() => {
window.dispatchEvent(new Event('focus'));
document.dispatchEvent(new Event('visibilitychange'));
});
expect(load).toHaveBeenCalledTimes(2);
act(() => window.dispatchEvent(new Event('focus')));
expect(load).toHaveBeenCalledTimes(2);

// The refresh fails: old data stays, the failure is reported.
await act(async () => fail(new Error('offline')));
await waitFor(() => expect(result.current.refreshError).toBeTruthy());
expect(result.current.data).toBe('first');

// Returning again shortly after still counts as stale and retries.
now.mockReturnValue(3_032_000);
act(() => window.dispatchEvent(new Event('focus')));
expect(load).toHaveBeenCalledTimes(3);
await waitFor(() => expect(result.current.data).toBe('fresh'));
expect(result.current.refreshError).toBeUndefined();
now.mockRestore();
});
67 changes: 57 additions & 10 deletions apps/web/src/features/recipes/useRecipeQuery.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { useEffect, useState } from 'react';
import { useEffect, useRef, useState } from 'react';
import { useAppStore } from '../../store';
import { recipeErrorMessage, useRecipeChanges } from './recipeApi';
import {
readRecipeCache,
writeRecipeCache,
recipeCacheGeneration,
clearRecipeQueryCache,
forgetRecipeCache,
RECIPE_FRESHNESS_MS,
} from './recipeQueryCache';

useAppStore.subscribe((state, previous) => {
Expand All @@ -23,16 +25,34 @@ useRecipeChanges.subscribe((state, previous) => {
export function useRecipeQuery<T>(
key: string,
load: (signal: AbortSignal) => Promise<T>,
{ refreshOnMutation = true } = {},
{
refreshOnMutation = true,
// Refetch stale data when the user comes back to a long-open page.
// Off for forms (the editor), which must never replace typed input.
refreshWhenStale = true,
} = {},
) {
const userId = useAppStore((state) => state.currentUser?.id);
const sessionStatus = useAppStore((state) => state.sessionStatus);
const revision = useRecipeChanges((state) =>
refreshOnMutation ? state.revision : 0,
);
const [attempt, setAttempt] = useState(0);
// Bumped when the page regains focus with stale data (see below).
const [freshnessCheck, setFreshnessCheck] = useState(0);
// When the shown data was fetched. Only set when a request succeeds, so a
// failed refresh leaves the data stale and the next return retries it.
const fetchedAt = useRef(0);
// True from a freshness refresh until its request settles, so focus and
// visibilitychange (often fired together) do not start it twice.
const refreshInFlight = useRef(false);
const identity = JSON.stringify([key, userId]);
const requestKey = JSON.stringify([identity, revision, attempt]);
const requestKey = JSON.stringify([
identity,
revision,
attempt,
freshnessCheck,
]);
const waiting = sessionStatus === 'restoring';
const [state, setState] = useState<{
identity: string;
Expand All @@ -53,23 +73,50 @@ export function useRecipeQuery<T>(
(data) => {
if (!controller.signal.aborted) {
if (!cached) writeRecipeCache(identity, data, generation);
fetchedAt.current = cached ? cached.fetchedAt : Date.now();
refreshInFlight.current = false;
setState({ identity, key: requestKey, hasData: true, data });
}
},
(error: unknown) => {
if (!controller.signal.aborted)
setState((previous) => ({
...(previous.identity === identity ? previous : { hasData: false }),
identity,
key: requestKey,
error: recipeErrorMessage(error),
}));
if (controller.signal.aborted) return;
refreshInFlight.current = false;
setState((previous) => ({
...(previous.identity === identity ? previous : { hasData: false }),
identity,
key: requestKey,
error: recipeErrorMessage(error),
}));
},
);
return () => controller.abort();
}, [identity, requestKey, load, waiting, attempt]);
const current = !waiting && state.identity === identity ? state : undefined;
const hasData = current?.hasData ?? false;

/*
* A page left open (e.g. in a background tab) is refreshed when the user
* returns to it, if its data is older than RECIPE_FRESHNESS_MS. The
* refresh runs in the background: the shown data stays until new data
* arrives (`refreshing`), and failures appear as `refreshError`.
*/
useEffect(() => {
if (!refreshWhenStale || !hasData) return;
function refreshIfStale() {
if (document.visibilityState === 'hidden') return;
if (refreshInFlight.current) return;
if (Date.now() - fetchedAt.current < RECIPE_FRESHNESS_MS) return;
forgetRecipeCache(identity);
refreshInFlight.current = true;
setFreshnessCheck((value) => value + 1);
}
window.addEventListener('focus', refreshIfStale);
document.addEventListener('visibilitychange', refreshIfStale);
return () => {
window.removeEventListener('focus', refreshIfStale);
document.removeEventListener('visibilitychange', refreshIfStale);
};
}, [refreshWhenStale, hasData, identity]);
return {
data: hasData ? current?.data : undefined,
error: !hasData && current?.key === requestKey ? current.error : undefined,
Expand Down