Unverified Commit c784c6f0 authored by Janka Uryga's avatar Janka Uryga Committed by GitHub

Always apply render preparations after running an action (#77898)

This PR centralizes some logic that we always want to run after
executing a server action into `executeActionAndPrepareForRender`. This
fixes some issues where we were only executing revalidates, setting
draft mode, and synchronizing mutated cookies for fetch actions, but not
MPA actions.

I've also moved the logic for `addRevalidationHeader` to the one place
where it makes sense -- after executing a fetch action. This header is
only used by the client router and only makes sense to add if we
actually executed an action, so e.g. calling it for each possible error
type was unnecessary.
parent 2341019f
...@@ -501,20 +501,6 @@ export async function handleAction({ ...@@ -501,20 +501,6 @@ export async function handleAction({
let temporaryReferences: TemporaryReferenceSet | undefined let temporaryReferences: TemporaryReferenceSet | undefined
const finalizeAndGenerateFlight: GenerateFlight = (...args) => {
// When we switch to the render phase, cookies() will return
// `workUnitStore.cookies` instead of `workUnitStore.userspaceMutableCookies`.
// We want the render to see any cookie writes that we performed during the action,
// so we need to update the immutable cookies to reflect the changes.
synchronizeMutableCookies(requestStore)
// The server action might have toggled draft mode, so we need to reflect
// that in the work store to be up-to-date for subsequent rendering.
workStore.isDraftMode = requestStore.draftMode.isEnabled
return generateFlight(...args)
}
// When running actions the default is no-store, you can still `cache: 'force-cache'` // When running actions the default is no-store, you can still `cache: 'force-cache'`
workStore.fetchCache = 'default-no-store' workStore.fetchCache = 'default-no-store'
...@@ -566,7 +552,6 @@ export async function handleAction({ ...@@ -566,7 +552,6 @@ export async function handleAction({
if (isFetchAction) { if (isFetchAction) {
res.statusCode = 500 res.statusCode = 500
await executeRevalidates(workStore)
const promise = Promise.reject(error) const promise = Promise.reject(error)
try { try {
...@@ -581,10 +566,10 @@ export async function handleAction({ ...@@ -581,10 +566,10 @@ export async function handleAction({
return { return {
type: 'done', type: 'done',
result: await finalizeAndGenerateFlight(req, ctx, requestStore, { result: await generateFlight(req, ctx, requestStore, {
actionResult: promise, actionResult: promise,
// if the page was not revalidated, we can skip the rendering the flight tree // We didn't execute an action, so no revalidations could have occurred. We can skip rendering the page.
skipFlight: !workStore.pathWasRevalidated, skipFlight: true,
temporaryReferences, temporaryReferences,
}), }),
} }
...@@ -672,16 +657,13 @@ export async function handleAction({ ...@@ -672,16 +657,13 @@ export async function handleAction({
// Only warn if it's a server action, otherwise skip for other post requests // Only warn if it's a server action, otherwise skip for other post requests
warnBadServerActionRequest() warnBadServerActionRequest()
let actionReturnedState: unknown const actionReturnedState =
requestStore.phase = 'action' await executeActionAndPrepareForRender(
try { action as () => Promise<unknown>,
actionReturnedState = await workUnitAsyncStorage.run( [],
requestStore, workStore,
action requestStore
) )
} finally {
requestStore.phase = 'render'
}
formState = await decodeFormState( formState = await decodeFormState(
actionReturnedState, actionReturnedState,
...@@ -846,16 +828,13 @@ export async function handleAction({ ...@@ -846,16 +828,13 @@ export async function handleAction({
// Only warn if it's a server action, otherwise skip for other post requests // Only warn if it's a server action, otherwise skip for other post requests
warnBadServerActionRequest() warnBadServerActionRequest()
let actionReturnedState: unknown const actionReturnedState =
requestStore.phase = 'action' await executeActionAndPrepareForRender(
try { action as () => Promise<unknown>,
actionReturnedState = await workUnitAsyncStorage.run( [],
requestStore, workStore,
action requestStore
) )
} finally {
requestStore.phase = 'render'
}
formState = await decodeFormState( formState = await decodeFormState(
actionReturnedState, actionReturnedState,
...@@ -938,22 +917,18 @@ export async function handleAction({ ...@@ -938,22 +917,18 @@ export async function handleAction({
actionId! actionId!
] ]
let returnVal: unknown const returnVal = await executeActionAndPrepareForRender(
requestStore.phase = 'action' actionHandler,
try { boundActionArguments,
returnVal = await workUnitAsyncStorage.run(requestStore, () => workStore,
actionHandler.apply(null, boundActionArguments) requestStore
) ).finally(() => {
} finally { addRevalidationHeader(res, { workStore, requestStore })
requestStore.phase = 'render' })
}
// For form actions, we need to continue rendering the page. // For form actions, we need to continue rendering the page.
if (isFetchAction) { if (isFetchAction) {
await executeRevalidates(workStore) actionResult = await generateFlight(req, ctx, requestStore, {
addRevalidationHeader(res, { workStore, requestStore })
actionResult = await finalizeAndGenerateFlight(req, ctx, requestStore, {
actionResult: Promise.resolve(returnVal), actionResult: Promise.resolve(returnVal),
// if the page was not revalidated, or if the action was forwarded from another worker, we can skip the rendering the flight tree // if the page was not revalidated, or if the action was forwarded from another worker, we can skip the rendering the flight tree
skipFlight: !workStore.pathWasRevalidated || actionWasForwarded, skipFlight: !workStore.pathWasRevalidated || actionWasForwarded,
...@@ -972,9 +947,6 @@ export async function handleAction({ ...@@ -972,9 +947,6 @@ export async function handleAction({
const redirectUrl = getURLFromRedirectError(err) const redirectUrl = getURLFromRedirectError(err)
const redirectType = getRedirectTypeFromError(err) const redirectType = getRedirectTypeFromError(err)
await executeRevalidates(workStore)
addRevalidationHeader(res, { workStore, requestStore })
// if it's a fetch action, we'll set the status code for logging/debugging purposes // if it's a fetch action, we'll set the status code for logging/debugging purposes
// but we won't set a Location header, as the redirect will be handled by the client router // but we won't set a Location header, as the redirect will be handled by the client router
res.statusCode = RedirectStatusCode.SeeOther res.statusCode = RedirectStatusCode.SeeOther
...@@ -1002,9 +974,6 @@ export async function handleAction({ ...@@ -1002,9 +974,6 @@ export async function handleAction({
} else if (isHTTPAccessFallbackError(err)) { } else if (isHTTPAccessFallbackError(err)) {
res.statusCode = getAccessFallbackHTTPStatus(err) res.statusCode = getAccessFallbackHTTPStatus(err)
await executeRevalidates(workStore)
addRevalidationHeader(res, { workStore, requestStore })
if (isFetchAction) { if (isFetchAction) {
const promise = Promise.reject(err) const promise = Promise.reject(err)
try { try {
...@@ -1018,7 +987,7 @@ export async function handleAction({ ...@@ -1018,7 +987,7 @@ export async function handleAction({
} }
return { return {
type: 'done', type: 'done',
result: await finalizeAndGenerateFlight(req, ctx, requestStore, { result: await generateFlight(req, ctx, requestStore, {
skipFlight: false, skipFlight: false,
actionResult: promise, actionResult: promise,
temporaryReferences, temporaryReferences,
...@@ -1035,7 +1004,6 @@ export async function handleAction({ ...@@ -1035,7 +1004,6 @@ export async function handleAction({
// so that we can respond with a 413 to requests that break the body size limit // so that we can respond with a 413 to requests that break the body size limit
// (but if we do that, we also need to make sure that whatever handles the non-fetch error path below does the same) // (but if we do that, we also need to make sure that whatever handles the non-fetch error path below does the same)
res.statusCode = 500 res.statusCode = 500
await executeRevalidates(workStore)
const promise = Promise.reject(err) const promise = Promise.reject(err)
try { try {
// we need to await the promise to trigger the rejection early // we need to await the promise to trigger the rejection early
...@@ -1062,6 +1030,38 @@ export async function handleAction({ ...@@ -1062,6 +1030,38 @@ export async function handleAction({
} }
} }
async function executeActionAndPrepareForRender<
TFn extends (...args: any[]) => Promise<any>,
>(
action: TFn,
args: Parameters<TFn>,
workStore: WorkStore,
requestStore: RequestStore
): Promise<Awaited<ReturnType<TFn>>> {
requestStore.phase = 'action'
try {
return await workUnitAsyncStorage.run(requestStore, () =>
action.apply(null, args)
)
} finally {
requestStore.phase = 'render'
// When we switch to the render phase, cookies() will return
// `workUnitStore.cookies` instead of `workUnitStore.userspaceMutableCookies`.
// We want the render to see any cookie writes that we performed during the action,
// so we need to update the immutable cookies to reflect the changes.
synchronizeMutableCookies(requestStore)
// The server action might have toggled draft mode, so we need to reflect
// that in the work store to be up-to-date for subsequent rendering.
workStore.isDraftMode = requestStore.draftMode.isEnabled
// If the action called revalidateTag/revalidatePath, then that might affect data used by the subsequent render,
// so we need to make sure all revalidations are applied before that
await executeRevalidates(workStore)
}
}
/** /**
* Attempts to find the module ID for the action from the module map. When this fails, it could be a deployment skew where * Attempts to find the module ID for the action from the module map. When this fails, it could be a deployment skew where
* the action came from a different deployment. It could also simply be an invalid POST request that is not a server action. * the action came from a different deployment. It could also simply be an invalid POST request that is not a server action.
......
...@@ -740,8 +740,30 @@ describe('use-cache', () => { ...@@ -740,8 +740,30 @@ describe('use-cache', () => {
expect(text).toBe('This page could not be found.') expect(text).toBe('This page could not be found.')
}) })
it('should not read nor write cached data when draft mode is enabled', async () => { it.each([
const browser = await next.browser('/draft-mode') { description: 'js enabled', disableJavaScript: false },
{ description: 'js disabled', disableJavaScript: true },
])(
'should not read nor write cached data when draft mode is enabled: $description',
async ({ disableJavaScript }) => {
const browser = await next.browser('/draft-mode', {
// This test relies on a server action to set draft mode.
// To ensure that it works for both fetch actions and MPA actions,
// we test it with javascript disabled too.
// (this is because of a bug where draft mode status was not correctly propagated to the workStore for MPA actions)
disableJavaScript,
})
const refreshAfterServerAction = async () => {
if (disableJavaScript) {
// browser.refresh() seems to automatically resubmit POST requests,
// so if we submitted an MPA action, it'll trigger the action again,
// which in this case will toggle draftMode again.
await browser.get(new URL('/draft-mode', next.url).href)
} else {
await browser.refresh()
}
}
expect(await browser.elementByCss('button#toggle').text()).toBe( expect(await browser.elementByCss('button#toggle').text()).toBe(
'Enable Draft Mode' 'Enable Draft Mode'
...@@ -791,7 +813,7 @@ describe('use-cache', () => { ...@@ -791,7 +813,7 @@ describe('use-cache', () => {
expect(newTopLevelValue).not.toBe(initialTopLevelValue) expect(newTopLevelValue).not.toBe(initialTopLevelValue)
expect(newClosureValue).not.toBe(initialClosureValue) expect(newClosureValue).not.toBe(initialClosureValue)
await browser.refresh() await refreshAfterServerAction()
expect(await browser.elementById('top-level').text()).not.toBe( expect(await browser.elementById('top-level').text()).not.toBe(
newTopLevelValue newTopLevelValue
...@@ -820,7 +842,9 @@ describe('use-cache', () => { ...@@ -820,7 +842,9 @@ describe('use-cache', () => {
// returned again. // returned again.
console.log(await browser.elementById('top-level').text()) console.log(await browser.elementById('top-level').text())
await browser.refresh()
await refreshAfterServerAction()
console.log(await browser.elementById('top-level').text()) console.log(await browser.elementById('top-level').text())
expect(await browser.elementById('top-level').text()).toBe( expect(await browser.elementById('top-level').text()).toBe(
...@@ -829,7 +853,8 @@ describe('use-cache', () => { ...@@ -829,7 +853,8 @@ describe('use-cache', () => {
expect(await browser.elementById('closure').text()).toBe( expect(await browser.elementById('closure').text()).toBe(
initialClosureValue initialClosureValue
) )
}) }
)
if (isNextDev) { if (isNextDev) {
it('should not have unhandled rejection of Request data promises when use cache is enabled without dynamicIO', async () => { it('should not have unhandled rejection of Request data promises when use cache is enabled without dynamicIO', async () => {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment