Unverified Commit 663488cf authored by Janka Uryga's avatar Janka Uryga Committed by GitHub

unstable_after: support nested unstable_after calls (#65950)

Adds support for nested `unstable_after()`.

This pattern previously threw a "Not supported yet" error, but works
now:

```js
function MyComponent() {
  after(() => asyncWork());
  return <div>...</div>
}

async function asyncWork() {
  after(() => { /* look ma, nesting!*/ })
  // more stuff...
}
```

### Implementation notes
Switched `AfterContext` to use a proper promise queue
([`p-queue`](https://www.npmjs.com/package/p-queue)) instead of plain a
callback array to support adding more callbacks as we execute (i.e. from
nested `after`s). Used a package because I didn't want to reinvent the
wheel here.

As a nice bonus, `p-queue` lets us limit the concurrency of running
tasks if we're worried about resource consumption. **This PR doesn't do
that**, but it's very easy to add. That could be controlled via
`process.env.NEXT_AFTER_MAX_CONCURRENT_TASKS`, a next.config.js option
(`unstable_after: { maxConcurrentTasks: 5 }`), or something like that.
parent a1420124
...@@ -271,6 +271,7 @@ ...@@ -271,6 +271,7 @@
"ora": "4.0.4", "ora": "4.0.4",
"os-browserify": "0.3.0", "os-browserify": "0.3.0",
"p-limit": "3.1.0", "p-limit": "3.1.0",
"p-queue": "6.6.2",
"path-browserify": "1.0.1", "path-browserify": "1.0.1",
"path-to-regexp": "6.1.0", "path-to-regexp": "6.1.0",
"picomatch": "4.0.1", "picomatch": "4.0.1",
......
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
(()=>{"use strict";var e={993:e=>{var t=Object.prototype.hasOwnProperty,n="~";function Events(){}if(Object.create){Events.prototype=Object.create(null);if(!(new Events).__proto__)n=false}function EE(e,t,n){this.fn=e;this.context=t;this.once=n||false}function addListener(e,t,r,i,s){if(typeof r!=="function"){throw new TypeError("The listener must be a function")}var o=new EE(r,i||e,s),u=n?n+t:t;if(!e._events[u])e._events[u]=o,e._eventsCount++;else if(!e._events[u].fn)e._events[u].push(o);else e._events[u]=[e._events[u],o];return e}function clearEvent(e,t){if(--e._eventsCount===0)e._events=new Events;else delete e._events[t]}function EventEmitter(){this._events=new Events;this._eventsCount=0}EventEmitter.prototype.eventNames=function eventNames(){var e=[],r,i;if(this._eventsCount===0)return e;for(i in r=this._events){if(t.call(r,i))e.push(n?i.slice(1):i)}if(Object.getOwnPropertySymbols){return e.concat(Object.getOwnPropertySymbols(r))}return e};EventEmitter.prototype.listeners=function listeners(e){var t=n?n+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var i=0,s=r.length,o=new Array(s);i<s;i++){o[i]=r[i].fn}return o};EventEmitter.prototype.listenerCount=function listenerCount(e){var t=n?n+e:e,r=this._events[t];if(!r)return 0;if(r.fn)return 1;return r.length};EventEmitter.prototype.emit=function emit(e,t,r,i,s,o){var u=n?n+e:e;if(!this._events[u])return false;var a=this._events[u],l=arguments.length,c,h;if(a.fn){if(a.once)this.removeListener(e,a.fn,undefined,true);switch(l){case 1:return a.fn.call(a.context),true;case 2:return a.fn.call(a.context,t),true;case 3:return a.fn.call(a.context,t,r),true;case 4:return a.fn.call(a.context,t,r,i),true;case 5:return a.fn.call(a.context,t,r,i,s),true;case 6:return a.fn.call(a.context,t,r,i,s,o),true}for(h=1,c=new Array(l-1);h<l;h++){c[h-1]=arguments[h]}a.fn.apply(a.context,c)}else{var _=a.length,f;for(h=0;h<_;h++){if(a[h].once)this.removeListener(e,a[h].fn,undefined,true);switch(l){case 1:a[h].fn.call(a[h].context);break;case 2:a[h].fn.call(a[h].context,t);break;case 3:a[h].fn.call(a[h].context,t,r);break;case 4:a[h].fn.call(a[h].context,t,r,i);break;default:if(!c)for(f=1,c=new Array(l-1);f<l;f++){c[f-1]=arguments[f]}a[h].fn.apply(a[h].context,c)}}}return true};EventEmitter.prototype.on=function on(e,t,n){return addListener(this,e,t,n,false)};EventEmitter.prototype.once=function once(e,t,n){return addListener(this,e,t,n,true)};EventEmitter.prototype.removeListener=function removeListener(e,t,r,i){var s=n?n+e:e;if(!this._events[s])return this;if(!t){clearEvent(this,s);return this}var o=this._events[s];if(o.fn){if(o.fn===t&&(!i||o.once)&&(!r||o.context===r)){clearEvent(this,s)}}else{for(var u=0,a=[],l=o.length;u<l;u++){if(o[u].fn!==t||i&&!o[u].once||r&&o[u].context!==r){a.push(o[u])}}if(a.length)this._events[s]=a.length===1?a[0]:a;else clearEvent(this,s)}return this};EventEmitter.prototype.removeAllListeners=function removeAllListeners(e){var t;if(e){t=n?n+e:e;if(this._events[t])clearEvent(this,t)}else{this._events=new Events;this._eventsCount=0}return this};EventEmitter.prototype.off=EventEmitter.prototype.removeListener;EventEmitter.prototype.addListener=EventEmitter.prototype.on;EventEmitter.prefixed=n;EventEmitter.EventEmitter=EventEmitter;if(true){e.exports=EventEmitter}},213:e=>{e.exports=(e,t)=>{t=t||(()=>{});return e.then((e=>new Promise((e=>{e(t())})).then((()=>e))),(e=>new Promise((e=>{e(t())})).then((()=>{throw e}))))}},574:(e,t)=>{Object.defineProperty(t,"__esModule",{value:true});function lowerBound(e,t,n){let r=0;let i=e.length;while(i>0){const s=i/2|0;let o=r+s;if(n(e[o],t)<=0){r=++o;i-=s+1}else{i=s}}return r}t["default"]=lowerBound},821:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:true});const r=n(574);class PriorityQueue{constructor(){this._queue=[]}enqueue(e,t){t=Object.assign({priority:0},t);const n={priority:t.priority,run:e};if(this.size&&this._queue[this.size-1].priority>=t.priority){this._queue.push(n);return}const i=r.default(this._queue,n,((e,t)=>t.priority-e.priority));this._queue.splice(i,0,n)}dequeue(){const e=this._queue.shift();return e===null||e===void 0?void 0:e.run}filter(e){return this._queue.filter((t=>t.priority===e.priority)).map((e=>e.run))}get size(){return this._queue.length}}t["default"]=PriorityQueue},816:(e,t,n)=>{const r=n(213);class TimeoutError extends Error{constructor(e){super(e);this.name="TimeoutError"}}const pTimeout=(e,t,n)=>new Promise(((i,s)=>{if(typeof t!=="number"||t<0){throw new TypeError("Expected `milliseconds` to be a positive number")}if(t===Infinity){i(e);return}const o=setTimeout((()=>{if(typeof n==="function"){try{i(n())}catch(e){s(e)}return}const r=typeof n==="string"?n:`Promise timed out after ${t} milliseconds`;const o=n instanceof Error?n:new TimeoutError(r);if(typeof e.cancel==="function"){e.cancel()}s(o)}),t);r(e.then(i,s),(()=>{clearTimeout(o)}))}));e.exports=pTimeout;e.exports["default"]=pTimeout;e.exports.TimeoutError=TimeoutError}};var t={};function __nccwpck_require__(n){var r=t[n];if(r!==undefined){return r.exports}var i=t[n]={exports:{}};var s=true;try{e[n](i,i.exports,__nccwpck_require__);s=false}finally{if(s)delete t[n]}return i.exports}if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var n={};(()=>{var e=n;Object.defineProperty(e,"__esModule",{value:true});const t=__nccwpck_require__(993);const r=__nccwpck_require__(816);const i=__nccwpck_require__(821);const empty=()=>{};const s=new r.TimeoutError;class PQueue extends t{constructor(e){var t,n,r,s;super();this._intervalCount=0;this._intervalEnd=0;this._pendingCount=0;this._resolveEmpty=empty;this._resolveIdle=empty;e=Object.assign({carryoverConcurrencyCount:false,intervalCap:Infinity,interval:0,concurrency:Infinity,autoStart:true,queueClass:i.default},e);if(!(typeof e.intervalCap==="number"&&e.intervalCap>=1)){throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(n=(t=e.intervalCap)===null||t===void 0?void 0:t.toString())!==null&&n!==void 0?n:""}\` (${typeof e.intervalCap})`)}if(e.interval===undefined||!(Number.isFinite(e.interval)&&e.interval>=0)){throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(s=(r=e.interval)===null||r===void 0?void 0:r.toString())!==null&&s!==void 0?s:""}\` (${typeof e.interval})`)}this._carryoverConcurrencyCount=e.carryoverConcurrencyCount;this._isIntervalIgnored=e.intervalCap===Infinity||e.interval===0;this._intervalCap=e.intervalCap;this._interval=e.interval;this._queue=new e.queueClass;this._queueClass=e.queueClass;this.concurrency=e.concurrency;this._timeout=e.timeout;this._throwOnTimeout=e.throwOnTimeout===true;this._isPaused=e.autoStart===false}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount<this._intervalCap}get _doesConcurrentAllowAnother(){return this._pendingCount<this._concurrency}_next(){this._pendingCount--;this._tryToStartAnother();this.emit("next")}_resolvePromises(){this._resolveEmpty();this._resolveEmpty=empty;if(this._pendingCount===0){this._resolveIdle();this._resolveIdle=empty;this.emit("idle")}}_onResumeInterval(){this._onInterval();this._initializeIntervalIfNeeded();this._timeoutId=undefined}_isIntervalPaused(){const e=Date.now();if(this._intervalId===undefined){const t=this._intervalEnd-e;if(t<0){this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0}else{if(this._timeoutId===undefined){this._timeoutId=setTimeout((()=>{this._onResumeInterval()}),t)}return true}}return false}_tryToStartAnother(){if(this._queue.size===0){if(this._intervalId){clearInterval(this._intervalId)}this._intervalId=undefined;this._resolvePromises();return false}if(!this._isPaused){const e=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){const t=this._queue.dequeue();if(!t){return false}this.emit("active");t();if(e){this._initializeIntervalIfNeeded()}return true}}return false}_initializeIntervalIfNeeded(){if(this._isIntervalIgnored||this._intervalId!==undefined){return}this._intervalId=setInterval((()=>{this._onInterval()}),this._interval);this._intervalEnd=Date.now()+this._interval}_onInterval(){if(this._intervalCount===0&&this._pendingCount===0&&this._intervalId){clearInterval(this._intervalId);this._intervalId=undefined}this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0;this._processQueue()}_processQueue(){while(this._tryToStartAnother()){}}get concurrency(){return this._concurrency}set concurrency(e){if(!(typeof e==="number"&&e>=1)){throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`)}this._concurrency=e;this._processQueue()}async add(e,t={}){return new Promise(((n,i)=>{const run=async()=>{this._pendingCount++;this._intervalCount++;try{const o=this._timeout===undefined&&t.timeout===undefined?e():r.default(Promise.resolve(e()),t.timeout===undefined?this._timeout:t.timeout,(()=>{if(t.throwOnTimeout===undefined?this._throwOnTimeout:t.throwOnTimeout){i(s)}return undefined}));n(await o)}catch(e){i(e)}this._next()};this._queue.enqueue(run,t);this._tryToStartAnother();this.emit("add")}))}async addAll(e,t){return Promise.all(e.map((async e=>this.add(e,t))))}start(){if(!this._isPaused){return this}this._isPaused=false;this._processQueue();return this}pause(){this._isPaused=true}clear(){this._queue=new this._queueClass}async onEmpty(){if(this._queue.size===0){return}return new Promise((e=>{const t=this._resolveEmpty;this._resolveEmpty=()=>{t();e()}}))}async onIdle(){if(this._pendingCount===0&&this._queue.size===0){return}return new Promise((e=>{const t=this._resolveIdle;this._resolveIdle=()=>{t();e()}}))}get size(){return this._queue.size}sizeBy(e){return this._queue.filter(e).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(e){this._timeout=e}}e["default"]=PQueue})();module.exports=n})();
\ No newline at end of file
{"name":"p-queue","main":"index.js","license":"MIT"}
...@@ -246,6 +246,67 @@ describe('createAfterContext', () => { ...@@ -246,6 +246,67 @@ describe('createAfterContext', () => {
expect(results).toEqual([undefined]) expect(results).toEqual([undefined])
}) })
it('runs after() callbacks added within an after()', async () => {
const waitUntilPromises: Promise<unknown>[] = []
const waitUntil = jest.fn((promise) => waitUntilPromises.push(promise))
let onCloseCallback: (() => void) | undefined = undefined
const onClose = jest.fn((cb) => {
onCloseCallback = cb
})
const afterContext = createAfterContext({
waitUntil,
onClose,
cacheScope: undefined,
})
const requestStore = createMockRequestStore(afterContext)
const run = createRun(afterContext, requestStore)
// ==================================
const promise1 = new DetachedPromise<string>()
const afterCallback1 = jest.fn(async () => {
await promise1.promise
after(afterCallback2)
})
const promise2 = new DetachedPromise<string>()
const afterCallback2 = jest.fn(() => promise2.promise)
await run(async () => {
after(afterCallback1)
expect(onClose).toHaveBeenCalledTimes(1)
expect(waitUntil).toHaveBeenCalledTimes(1) // just runCallbacksOnClose
})
expect(onClose).toHaveBeenCalledTimes(1)
expect(afterCallback1).not.toHaveBeenCalled()
expect(afterCallback2).not.toHaveBeenCalled()
// the response is done.
onCloseCallback!()
await Promise.resolve(null)
expect(afterCallback1).toHaveBeenCalledTimes(1)
expect(afterCallback2).toHaveBeenCalledTimes(0)
expect(waitUntil).toHaveBeenCalledTimes(1)
promise1.resolve('1')
await Promise.resolve(null)
expect(afterCallback1).toHaveBeenCalledTimes(1)
expect(afterCallback2).toHaveBeenCalledTimes(1)
expect(waitUntil).toHaveBeenCalledTimes(1)
promise2.resolve('2')
const results = await Promise.all(waitUntilPromises)
expect(results).toEqual([
undefined, // callbacks all get collected into a big void promise
])
})
it('does not hang forever if onClose failed', async () => { it('does not hang forever if onClose failed', async () => {
const waitUntilPromises: Promise<unknown>[] = [] const waitUntilPromises: Promise<unknown>[] = []
const waitUntil = jest.fn((promise) => waitUntilPromises.push(promise)) const waitUntil = jest.fn((promise) => waitUntilPromises.push(promise))
......
import PromiseQueue from 'next/dist/compiled/p-queue'
import { import {
requestAsyncStorage, requestAsyncStorage,
type RequestStore, type RequestStore,
...@@ -30,12 +31,16 @@ export class AfterContextImpl implements AfterContext { ...@@ -30,12 +31,16 @@ export class AfterContextImpl implements AfterContext {
private requestStore: RequestStore | undefined private requestStore: RequestStore | undefined
private afterCallbacks: AfterCallback[] = [] private runCallbacksOnClosePromise: Promise<void> | undefined
private callbackQueue: PromiseQueue
constructor({ waitUntil, onClose, cacheScope }: AfterContextOpts) { constructor({ waitUntil, onClose, cacheScope }: AfterContextOpts) {
this.waitUntil = waitUntil this.waitUntil = waitUntil
this.onClose = onClose this.onClose = onClose
this.cacheScope = cacheScope this.cacheScope = cacheScope
this.callbackQueue = new PromiseQueue()
this.callbackQueue.pause()
} }
public run<T>(requestStore: RequestStore, callback: () => T): T { public run<T>(requestStore: RequestStore, callback: () => T): T {
...@@ -79,10 +84,26 @@ export class AfterContextImpl implements AfterContext { ...@@ -79,10 +84,26 @@ export class AfterContextImpl implements AfterContext {
'unstable_after: Missing `onClose` implementation' 'unstable_after: Missing `onClose` implementation'
) )
} }
if (this.afterCallbacks.length === 0) {
this.waitUntil(this.runCallbacksOnClose()) // this should only happen once.
if (!this.runCallbacksOnClosePromise) {
this.runCallbacksOnClosePromise = this.runCallbacksOnClose()
this.waitUntil(this.runCallbacksOnClosePromise)
}
const wrappedCallback = async () => {
try {
await callback()
} catch (err) {
// TODO(after): this is fine for now, but will need better intergration with our error reporting.
console.error(
'An error occurred in a function passed to `unstable_after()`:',
err
)
}
} }
this.afterCallbacks.push(callback)
this.callbackQueue.add(wrappedCallback)
} }
private async runCallbacksOnClose() { private async runCallbacksOnClose() {
...@@ -91,24 +112,11 @@ export class AfterContextImpl implements AfterContext { ...@@ -91,24 +112,11 @@ export class AfterContextImpl implements AfterContext {
} }
private async runCallbacks(requestStore: RequestStore): Promise<void> { private async runCallbacks(requestStore: RequestStore): Promise<void> {
if (this.afterCallbacks.length === 0) return if (this.callbackQueue.size === 0) return
const runCallbacksImpl = async () => { const runCallbacksImpl = async () => {
// TODO(after): we should consider limiting the parallelism here via something like `p-queue`. this.callbackQueue.start()
// (having a queue will also be needed for after-within-after, so this'd solve two problems at once). return this.callbackQueue.onIdle()
await Promise.all(
this.afterCallbacks.map(async (afterCallback) => {
try {
await afterCallback()
} catch (err) {
// TODO(after): this is fine for now, but will need better intergration with our error reporting.
console.error(
'An error occurred in a function passed to `unstable_after()`:',
err
)
}
})
)
} }
const readonlyRequestStore: RequestStore = const readonlyRequestStore: RequestStore =
...@@ -148,19 +156,7 @@ function wrapRequestStoreForAfterCallbacks( ...@@ -148,19 +156,7 @@ function wrapRequestStoreForAfterCallbacks(
mutableCookies: new ResponseCookies(new Headers()), mutableCookies: new ResponseCookies(new Headers()),
assetPrefix: requestStore.assetPrefix, assetPrefix: requestStore.assetPrefix,
reactLoadableManifest: requestStore.reactLoadableManifest, reactLoadableManifest: requestStore.reactLoadableManifest,
afterContext: requestStore.afterContext,
afterContext: {
after: () => {
throw new Error(
'Calling `unstable_after()` from within `unstable_after()` is not supported yet.'
)
},
run: () => {
throw new InvariantError(
'unstable_after: Cannot call `AfterContext.run()` from within an `unstable_after()` callback'
)
},
},
} }
} }
......
...@@ -646,6 +646,15 @@ export async function ncc_p_limit(task, opts) { ...@@ -646,6 +646,15 @@ export async function ncc_p_limit(task, opts) {
.target('src/compiled/p-limit') .target('src/compiled/p-limit')
} }
// eslint-disable-next-line camelcase
externals['p-queue'] = 'next/dist/compiled/p-queue'
export async function ncc_p_queue(task, opts) {
await task
.source(relative(__dirname, require.resolve('p-queue')))
.ncc({ packageName: 'p-queue', externals })
.target('src/compiled/p-queue')
}
// eslint-disable-next-line camelcase // eslint-disable-next-line camelcase
externals['raw-body'] = 'next/dist/compiled/raw-body' externals['raw-body'] = 'next/dist/compiled/raw-body'
export async function ncc_raw_body(task, opts) { export async function ncc_raw_body(task, opts) {
...@@ -2171,6 +2180,7 @@ export async function ncc(task, opts) { ...@@ -2171,6 +2180,7 @@ export async function ncc(task, opts) {
'ncc_node_html_parser', 'ncc_node_html_parser',
'ncc_napirs_triples', 'ncc_napirs_triples',
'ncc_p_limit', 'ncc_p_limit',
'ncc_p_queue',
'ncc_raw_body', 'ncc_raw_body',
'ncc_image_size', 'ncc_image_size',
'ncc_hapi_accept', 'ncc_hapi_accept',
......
...@@ -79,6 +79,11 @@ declare module 'next/dist/compiled/p-limit' { ...@@ -79,6 +79,11 @@ declare module 'next/dist/compiled/p-limit' {
export = m export = m
} }
declare module 'next/dist/compiled/p-queue' {
import m from 'p-queue'
export = m
}
declare module 'next/dist/compiled/raw-body' { declare module 'next/dist/compiled/raw-body' {
import m from 'raw-body' import m from 'raw-body'
export = m export = m
......
...@@ -1279,6 +1279,9 @@ importers: ...@@ -1279,6 +1279,9 @@ importers:
p-limit: p-limit:
specifier: 3.1.0 specifier: 3.1.0
version: 3.1.0 version: 3.1.0
p-queue:
specifier: 6.6.2
version: 6.6.2
path-browserify: path-browserify:
specifier: 1.0.1 specifier: 1.0.1
version: 1.0.1 version: 1.0.1
...@@ -9845,6 +9848,7 @@ packages: ...@@ -9845,6 +9848,7 @@ packages:
/color-name@1.1.4: /color-name@1.1.4:
resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==} resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==}
requiresBuild: true
/color-string@1.5.4: /color-string@1.5.4:
resolution: {integrity: sha512-57yF5yt8Xa3czSEW1jfQDE79Idk0+AkN/4KWad6tbdxUmAs3MvjxlWSWD4deYytcRfoZ9nhKyFl1kj5tBvidbw==} resolution: {integrity: sha512-57yF5yt8Xa3czSEW1jfQDE79Idk0+AkN/4KWad6tbdxUmAs3MvjxlWSWD4deYytcRfoZ9nhKyFl1kj5tBvidbw==}
...@@ -22754,6 +22758,7 @@ packages: ...@@ -22754,6 +22758,7 @@ packages:
/simple-swizzle@0.2.2: /simple-swizzle@0.2.2:
resolution: {integrity: sha512-JA//kQgZtbuY83m+xT+tXJkmJncGMTFT+C+g2h2R9uxkYIrE2yy9sgmcLhCnw57/WSD+Eh3J97FPEDFnbXnDUg==} resolution: {integrity: sha512-JA//kQgZtbuY83m+xT+tXJkmJncGMTFT+C+g2h2R9uxkYIrE2yy9sgmcLhCnw57/WSD+Eh3J97FPEDFnbXnDUg==}
requiresBuild: true
dependencies: dependencies:
is-arrayish: 0.3.2 is-arrayish: 0.3.2
......
import { unstable_after as after } from 'next/server'
import { cache } from 'react'
import { cliLog } from '../../utils/log'
import { headers } from 'next/headers'
const thing = cache(() => Symbol('cache me please'))
export default function Index({ params }) {
const hostFromRender = headers().get('host')
const valueFromRender = thing()
after(async () => {
const hostFromAfter = headers().get('host')
const valueFromAfter = thing()
cliLog({
source: '[page] /nested-after (after #1)',
assertions: {
'cache() works in after()': valueFromRender === valueFromAfter,
'headers() works in after()': hostFromRender === hostFromAfter,
},
})
after(() => {
const hostFromAfter = headers().get('host')
const valueFromAfter = thing()
cliLog({
source: '[page] /nested-after (after #2)',
assertions: {
'cache() works in after()': valueFromRender === valueFromAfter,
'headers() works in after()': hostFromRender === hostFromAfter,
},
})
})
await new Promise((resolve) => setTimeout(resolve, 500))
after(() => {
const hostFromAfter = headers().get('host')
const valueFromAfter = thing()
cliLog({
source: '[page] /nested-after (after #3)',
assertions: {
'cache() works in after()': valueFromRender === valueFromAfter,
'headers() works in after()': hostFromRender === hostFromAfter,
},
})
})
})
return <div>Page with nested after()</div>
}
...@@ -104,6 +104,22 @@ describe.each(runtimes)('unstable_after() in %s runtime', (runtimeValue) => { ...@@ -104,6 +104,22 @@ describe.each(runtimes)('unstable_after() in %s runtime', (runtimeValue) => {
// TODO: server seems to close before the response fully returns? // TODO: server seems to close before the response fully returns?
}) })
it('runs callbacks from nested unstable_after calls', async () => {
await next.browser('/nested-after')
await retry(() => {
for (const id of [1, 2, 3]) {
expect(getLogs()).toContainEqual({
source: `[page] /nested-after (after #${id})`,
assertions: {
'cache() works in after()': true,
'headers() works in after()': true,
},
})
}
})
})
describe('interrupted RSC renders', () => { describe('interrupted RSC renders', () => {
it('runs callbacks if redirect() was called', async () => { it('runs callbacks if redirect() was called', async () => {
await next.browser('/interrupted/calls-redirect') await next.browser('/interrupted/calls-redirect')
......
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