-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
fix(start-static-server-functions): fall back to the server function on a cache miss #8221
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
theRizwan
wants to merge
1
commit into
TanStack:main
Choose a base branch
from
theRizwan:fix/static-server-fn-cache-miss-fallback
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| '@tanstack/start-static-server-functions': patch | ||
| --- | ||
|
|
||
| Fix `staticFunctionMiddleware` failing with `Unexpected token '<', "<!DOCTYPE "... is not valid JSON` when no prerendered cache file exists for a call. The client now treats an unreadable or non-JSON cache response as a miss and invokes the server function instead, and a cache hit is reused from the client cache rather than refetched. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
156 changes: 156 additions & 0 deletions
156
packages/start-static-server-functions/tests/staticFunctionMiddleware.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,156 @@ | ||
| import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' | ||
| import { toJSONAsync } from 'seroval' | ||
|
|
||
| // `getDefaultSerovalPlugins` reads the Start options through an isomorphic | ||
| // function. Uncompiled, that chain resolves to its server implementation and | ||
| // wants a Start context in AsyncLocalStorage, which a browser never has. The | ||
| // adapter list is irrelevant to the cache lookup under test, so stub it out and | ||
| // serialize the fixtures the same way. | ||
| vi.mock('@tanstack/start-client-core', async (importOriginal) => { | ||
| const actual = | ||
| await importOriginal<typeof import('@tanstack/start-client-core')>() | ||
| return { ...actual, getDefaultSerovalPlugins: () => [] } | ||
| }) | ||
|
|
||
| const { staticFunctionMiddleware } = | ||
| await import('../src/staticFunctionMiddleware') | ||
|
|
||
| const clientMiddleware = staticFunctionMiddleware.options.client! | ||
|
|
||
| /** The result the live server function produces when the cache is not used. */ | ||
| const LIVE_RESULT = { result: 'from the server function' } | ||
|
|
||
| /** | ||
| * Each test uses its own `data`, so it hashes to its own cache URL and cannot | ||
| * be served by the module level client cache another test populated. | ||
| */ | ||
| function callClientMiddleware(data: unknown) { | ||
| const next = vi.fn(async () => LIVE_RESULT) | ||
| const promise = clientMiddleware({ | ||
| serverFnMeta: { id: 'test_fn' }, | ||
| data, | ||
| context: {}, | ||
| next, | ||
| } as any) | ||
| return { promise, next } | ||
| } | ||
|
|
||
| function jsonResponse(body: string, status = 200) { | ||
| return new Response(body, { | ||
| status, | ||
| headers: { 'content-type': 'application/json' }, | ||
| }) | ||
| } | ||
|
|
||
| /** What the application's catch-all route serves for a missing cache file. */ | ||
| function htmlShellResponse(status = 200) { | ||
| return new Response('<!DOCTYPE html><html><body></body></html>', { | ||
| status, | ||
| headers: { 'content-type': 'text/html' }, | ||
| }) | ||
| } | ||
|
|
||
| beforeEach(() => { | ||
| vi.stubEnv('NODE_ENV', 'production') | ||
| }) | ||
|
|
||
| afterEach(() => { | ||
| vi.unstubAllEnvs() | ||
| vi.unstubAllGlobals() | ||
| vi.restoreAllMocks() | ||
| }) | ||
|
|
||
| describe('staticFunctionMiddleware client on a cache miss', () => { | ||
| test('falls back to the server function when the HTML shell is served with a 200', async () => { | ||
| vi.stubGlobal( | ||
| 'fetch', | ||
| vi.fn(async () => htmlShellResponse(200)), | ||
| ) | ||
|
|
||
| const { promise, next } = callClientMiddleware({ case: 'html-200' }) | ||
|
|
||
| await expect(promise).resolves.toBe(LIVE_RESULT) | ||
| expect(next).toHaveBeenCalledTimes(1) | ||
| }) | ||
|
|
||
| test('falls back to the server function on a 404', async () => { | ||
| vi.stubGlobal( | ||
| 'fetch', | ||
| vi.fn(async () => htmlShellResponse(404)), | ||
| ) | ||
|
|
||
| const { promise, next } = callClientMiddleware({ case: 'html-404' }) | ||
|
|
||
| await expect(promise).resolves.toBe(LIVE_RESULT) | ||
| expect(next).toHaveBeenCalledTimes(1) | ||
| }) | ||
|
|
||
| test('falls back to the server function when the body is not valid JSON', async () => { | ||
| vi.stubGlobal( | ||
| 'fetch', | ||
| vi.fn(async () => jsonResponse('not json at all')), | ||
| ) | ||
|
|
||
| const { promise, next } = callClientMiddleware({ case: 'bad-json' }) | ||
|
|
||
| await expect(promise).resolves.toBe(LIVE_RESULT) | ||
| expect(next).toHaveBeenCalledTimes(1) | ||
| }) | ||
|
|
||
| test('falls back to the server function when the request fails outright', async () => { | ||
| vi.stubGlobal( | ||
| 'fetch', | ||
| vi.fn(async () => { | ||
| throw new TypeError('Failed to fetch') | ||
| }), | ||
| ) | ||
|
|
||
| const { promise, next } = callClientMiddleware({ case: 'network-error' }) | ||
|
|
||
| await expect(promise).resolves.toBe(LIVE_RESULT) | ||
| expect(next).toHaveBeenCalledTimes(1) | ||
| }) | ||
| }) | ||
|
|
||
| describe('staticFunctionMiddleware client on a cache hit', () => { | ||
| test('returns the prerendered result without calling the server function', async () => { | ||
| const payload = JSON.stringify( | ||
| await toJSONAsync({ | ||
| result: 'from the static cache', | ||
| context: { user: 'sean' }, | ||
| }), | ||
| ) | ||
| const fetchMock = vi.fn(async () => jsonResponse(payload)) | ||
| vi.stubGlobal('fetch', fetchMock) | ||
|
|
||
| const first = callClientMiddleware({ case: 'hit' }) | ||
| await expect(first.promise).resolves.toMatchObject({ | ||
| result: 'from the static cache', | ||
| context: { user: 'sean' }, | ||
| }) | ||
| expect(first.next).not.toHaveBeenCalled() | ||
| expect(fetchMock).toHaveBeenCalledTimes(1) | ||
|
|
||
| // The same call is served from the client cache rather than refetched. | ||
| const second = callClientMiddleware({ case: 'hit' }) | ||
| await expect(second.promise).resolves.toMatchObject({ | ||
| result: 'from the static cache', | ||
| }) | ||
| expect(second.next).not.toHaveBeenCalled() | ||
| expect(fetchMock).toHaveBeenCalledTimes(1) | ||
| }) | ||
| }) | ||
|
|
||
| describe('staticFunctionMiddleware client outside production', () => { | ||
| test('does not request the cache at all', async () => { | ||
| vi.stubEnv('NODE_ENV', 'development') | ||
| const fetchMock = vi.fn(async () => jsonResponse('{}')) | ||
| vi.stubGlobal('fetch', fetchMock) | ||
|
|
||
| const { promise, next } = callClientMiddleware({ case: 'development' }) | ||
|
|
||
| await expect(promise).resolves.toBe(LIVE_RESULT) | ||
| expect(fetchMock).not.toHaveBeenCalled() | ||
| expect(next).toHaveBeenCalledTimes(1) | ||
| }) | ||
| }) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Validate the decoded cache payload before using it as a cache hit.
A cache file can contain valid Seroval JSON for a value other than
StaticCachedResult, such as a serialized string.fromJSONthen succeeds, but the middleware later skipsctx.next()and returnsundefinedforresponse.result. Treat decoded values without ownresultandcontextfields as cache misses. Add a regression test with a valid Seroval payload that decodes to a non-object value.Proposed fix
try { result = fromJSON(await response.json(), { plugins: getDefaultSerovalPlugins(), }) } catch { // The file exists but is not a payload this build can read. return undefined } + + if ( + result === null || + typeof result !== 'object' || + !Object.prototype.hasOwnProperty.call(result, 'result') || + !Object.prototype.hasOwnProperty.call(result, 'context') + ) { + return undefined + } staticClientCache?.set(url, result)📝 Committable suggestion
🤖 Prompt for AI Agents