Unverified Commit 55e7e190 authored by Sebastian "Sebbie" Silbermann's avatar Sebastian "Sebbie" Silbermann Committed by GitHub

[test] Cover the prerender worker-thread backend with an addon we control (#97543)

`experimental.workerThreads` decides whether static generation runs in
real worker threads or forked child processes, and a native addon
declared with `NODE_MODULE` can only be loaded once per process. That is
why the flag defaults to false (#9199) and why the static export worker
was fixed to respect it rather than hardcoding threads on (#25063).
Nothing tested it: the only suite that tried, `firebase-grpc`, had its
assertion skipped since 2019, and modern `firebase` ships no native
module at all, so its remaining test asserted only that a build
succeeds.

This adds a `single-context-addon` fixture, deliberately declared with
`NODE_MODULE`, and a production suite asserting both directions: the
build succeeds by default and fails with "Module did not self-register"
once worker threads are enabled. The fixture loads the addon from
`next.config.js` as well as from the page, because that failure only
happens on a second `dlopen` within one process, so an addon loaded only
inside the worker would register there and the build would pass.

A third case documents a bug rather than intended behaviour. `next
build` runs Turbopack in a worker thread and that worker re-evaluates
`next.config.js`, so requiring a non-context-aware addon from the config
breaks the build even with `experimental.workerThreads` off. Webpack and
rspack are unaffected, since their build workers are forked child
processes. Isolated with an unguarded `require` and default flags,
Turbopack exits 1 with "Module did not self-register" where webpack
exits 0. It is the same class of failure #9199 and #25063 fixed, in a
worker those PRs did not touch. The assertion is branched on the bundler
and carries a note to drop the branch once Turbopack stops evaluating
the config on a worker thread. The `isMainThread` guard in the fixture's
config keeps the first two cases pointed at the static generation worker
instead.

A development suite covers the other direction, asserting that
evaluating a route does not put such an addon on one of the threads
`next dev` uses regardless of the flag, so it would catch a change that
moved route evaluation onto the dev validation pool. The expectation is
the same with and without Cache Components; both were checked by logging
the thread id from the page's module scope, and the route is evaluated
on the main thread either way.

`firebase-grpc` is removed, since it covered the same flag with a
skipped assertion and a vacuous one.
parent 33af645b
...@@ -29,6 +29,8 @@ const customJestConfig = { ...@@ -29,6 +29,8 @@ const customJestConfig = {
// Jest does not normalize/resolve paths in modulePathIgnorePatterns so we can't // Jest does not normalize/resolve paths in modulePathIgnorePatterns so we can't
// prefix with <rootDir>/../ like we do in roots. // prefix with <rootDir>/../ like we do in roots.
'packages/next/src/compiled/', 'packages/next/src/compiled/',
'<rootDir>/development/app-dir/non-context-aware-addon/bindings',
'<rootDir>/development/app-dir/non-context-aware-addon/single-context-addon',
'<rootDir>/development/app-dir/ssr-in-rsc/internal-pkg/', '<rootDir>/development/app-dir/ssr-in-rsc/internal-pkg/',
'<rootDir>/e2e/app-dir/self-importing-package/internal-pkg', '<rootDir>/e2e/app-dir/self-importing-package/internal-pkg',
'<rootDir>/e2e/app-dir/self-importing-package-monorepo/internal-pkg', '<rootDir>/e2e/app-dir/self-importing-package-monorepo/internal-pkg',
...@@ -39,6 +41,8 @@ const customJestConfig = { ...@@ -39,6 +41,8 @@ const customJestConfig = {
'<rootDir>/e2e/prerender-native-module/native-addon', '<rootDir>/e2e/prerender-native-module/native-addon',
'<rootDir>/e2e/prerender-native-module/native-addon-wrapper', '<rootDir>/e2e/prerender-native-module/native-addon-wrapper',
'<rootDir>/e2e/transpile-packages-typescript-foreign/pkg', '<rootDir>/e2e/transpile-packages-typescript-foreign/pkg',
'<rootDir>/production/prerender-worker-threads/bindings',
'<rootDir>/production/prerender-worker-threads/single-context-addon',
'<rootDir>/production/standalone-mode/tracing-side-effects-false/foo', '<rootDir>/production/standalone-mode/tracing-side-effects-false/foo',
'<rootDir>/production/standalone-mode/tracing-static-files/foo', '<rootDir>/production/standalone-mode/tracing-static-files/foo',
'<rootDir>/production/standalone-mode/tracing-unparsable/foo', '<rootDir>/production/standalone-mode/tracing-unparsable/foo',
......
...@@ -15,3 +15,4 @@ turbopack-test-junit-report/ ...@@ -15,3 +15,4 @@ turbopack-test-junit-report/
# inside each test's throwaway install directory, so this only catches builds # inside each test's throwaway install directory, so this only catches builds
# someone runs in place while iterating on a fixture. # someone runs in place while iterating on a fixture.
**/native-addon/build/ **/native-addon/build/
**/single-context-addon/build/
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import addon from 'single-context-addon'
// `CONTEXT_AWARE` comes from the compiled binary, so rendering it proves the addon
// really loaded rather than resolving to an empty module.
export default function Page() {
return <p id="context-aware">{String(addon.CONTEXT_AWARE)}</p>
}
// A minimal stand-in for the `bindings` npm package, reproducing only the part
// both bundlers model: locate the calling package's root by walking up for a
// `package.json`, then load the compiled binary from `build/Release`.
//
// Neither bundler evaluates this file. `@vercel/nft` maps the `bindings`
// specifier to its own bundled copy, and Turbopack maps it to
// `WellKnownFunctionKind::NodeBindings`; both then resolve the binary's path
// themselves. `build/Release/<name>` is node-gyp's default output location and
// is on both of their candidate lists, so this agrees with what they trace.
const fs = require('fs')
const path = require('path')
function getCallerFile() {
const { prepareStackTrace } = Error
try {
Error.prepareStackTrace = (_error, stack) => stack
for (const frame of new Error().stack) {
const fileName = frame.getFileName()
if (typeof fileName === 'string' && fileName !== __filename) {
return fileName
}
}
} finally {
Error.prepareStackTrace = prepareStackTrace
}
throw new Error('bindings: could not determine the calling file')
}
function getPackageRoot(file) {
let dir = path.dirname(file)
while (!fs.existsSync(path.join(dir, 'package.json'))) {
const parent = path.dirname(dir)
if (parent === dir) {
throw new Error(`bindings: found no package.json above ${file}`)
}
dir = parent
}
return dir
}
module.exports = function bindings(name) {
const binary = path.join(
getPackageRoot(getCallerFile()),
'build',
'Release',
name
)
if (!fs.existsSync(binary)) {
throw new Error(
`bindings: ${binary} does not exist. The fixture addon is compiled by ` +
`node-gyp during install, which requires the package to be listed in ` +
`the test's pnpm.onlyBuiltDependencies.`
)
}
// Deliberately not wrapped. A non-context-aware addon fails on this line with
// Node's own `ERR_DLOPEN_FAILED` / "Module did not self-register", and the
// worker-thread tests assert on that message.
return require(binary)
}
{
"name": "bindings",
"version": "1.0.0",
"description": "Minimal stand-in for the bindings npm package, for tests",
"main": "index.js"
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
// The addon resolves and loads a compiled binary at runtime, so it has to stay
// external rather than being bundled into the server build.
serverExternalPackages: ['single-context-addon'],
}
module.exports = nextConfig
import { nextTestSetup } from 'e2e-utils'
// A native addon declared with `NODE_MODULE` rather than `NODE_MODULE_INIT` can
// only be loaded once per process, so loading it on a second thread of that
// process fails with `ERR_DLOPEN_FAILED` / "Module did not self-register".
//
// `next dev` runs some work on worker threads regardless of
// `experimental.workerThreads`: the dev validation pool hardcodes
// `enableWorkerThreads: true`. This asserts that evaluating a route still does not
// put such an addon on one of those threads, so it would catch a change that moved
// route evaluation onto that pool.
//
// The expectation is the same with and without Cache Components. Both were checked
// by logging `isMainThread` from the page's module scope: the route is evaluated on
// the main thread either way, so there is nothing to fork on here.
describe('non-context-aware addon in development', () => {
const { next } = nextTestSetup({
files: __dirname,
// `bindings` is a direct dependency rather than one of the addon, and both use
// `file:` so pnpm copies them into the virtual store. See the comments in
// test/production/prerender-worker-threads for why neither is `link:`.
dependencies: require('./package.json').dependencies,
})
it('should render a route that loads a non-context-aware addon', async () => {
const $ = await next.render$('/')
// `false` is the value the non-context-aware binary exports, so reading it back
// confirms the addon was loaded rather than stubbed out.
expect($('#context-aware').text()).toBe('false')
expect(next.cliOutput).not.toContain('Module did not self-register')
})
})
{
"dependencies": {
"single-context-addon": "file:single-context-addon",
"bindings": "file:bindings"
}
}
# `single-context-addon` is compiled by node-gyp during install, and pnpm does
# not run a dependency's build scripts unless they are approved here. The repo
# root uses the same key for the one package it allows to build.
allowBuilds:
single-context-addon: true
// A deliberately non-context-aware addon. `NODE_MODULE` registers once per
// process, so loading it on the main thread and then again on a worker thread
// fails: the second `dlopen` returns the cached handle, the module constructor
// does not run again, and Node reports
//
// Error [ERR_DLOPEN_FAILED]: Module did not self-register: '<path>'.
//
// which is the failure PR #9199 and PR #25063 both worked around by keeping
// worker threads off by default. Do not port this to Node-API or
// `NODE_MODULE_INIT`: either would make it context-aware and the tests that
// depend on it would silently start passing for the wrong reason.
#include <node.h>
namespace {
void Init(v8::Local<v8::Object> exports) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::Local<v8::Context> context = isolate->GetCurrentContext();
exports
->Set(context,
v8::String::NewFromUtf8(isolate, "CONTEXT_AWARE").ToLocalChecked(),
v8::Boolean::New(isolate, false))
.Check();
}
} // namespace
NODE_MODULE(NODE_GYP_MODULE_NAME, Init)
{
"targets": [
{
"target_name": "single_context_addon",
"sources": ["addon.cc"]
}
]
}
module.exports = require('bindings')('single_context_addon.node')
{
"name": "single-context-addon",
"version": "1.0.0",
"description": "Non-context-aware native addon fixture, compiled by node-gyp",
"main": "index.js"
}
import { nextTestSetup } from 'e2e-utils'
describe('Building Firebase', () => {
const { next } = nextTestSetup({
files: __dirname,
skipStart: true,
dependencies: {
firebase: 'latest',
},
})
// TODO: investigate re-enabling this test in node 12 environment
it.skip('Throws an error when building with firebase dependency with worker_threads', async () => {
await next.patchFile(
'next.config.js',
`module.exports = { experimental: { workerThreads: true } }`
)
await next.build()
expect(next.cliOutput).toMatch(/Build error occurred/)
expect(next.cliOutput).toMatch(
/grpc_node\.node\. Module did not self-register\./
)
})
it('Throws no error when building with firebase dependency without worker_threads', async () => {
await next.build()
expect(next.cliOutput).not.toMatch(/Build error occurred/)
expect(next.cliOutput).not.toMatch(
/grpc_node\.node\. Module did not self-register\./
)
})
})
import 'firebase/firestore'
export default () => <div>Firebase</div>
import 'firebase/firestore'
export default () => <div>Firebase</div>
// A minimal stand-in for the `bindings` npm package, reproducing only the part
// both bundlers model: locate the calling package's root by walking up for a
// `package.json`, then load the compiled binary from `build/Release`.
//
// Neither bundler evaluates this file. `@vercel/nft` maps the `bindings`
// specifier to its own bundled copy, and Turbopack maps it to
// `WellKnownFunctionKind::NodeBindings`; both then resolve the binary's path
// themselves. `build/Release/<name>` is node-gyp's default output location and
// is on both of their candidate lists, so this agrees with what they trace.
const fs = require('fs')
const path = require('path')
function getCallerFile() {
const { prepareStackTrace } = Error
try {
Error.prepareStackTrace = (_error, stack) => stack
for (const frame of new Error().stack) {
const fileName = frame.getFileName()
if (typeof fileName === 'string' && fileName !== __filename) {
return fileName
}
}
} finally {
Error.prepareStackTrace = prepareStackTrace
}
throw new Error('bindings: could not determine the calling file')
}
function getPackageRoot(file) {
let dir = path.dirname(file)
while (!fs.existsSync(path.join(dir, 'package.json'))) {
const parent = path.dirname(dir)
if (parent === dir) {
throw new Error(`bindings: found no package.json above ${file}`)
}
dir = parent
}
return dir
}
module.exports = function bindings(name) {
const binary = path.join(
getPackageRoot(getCallerFile()),
'build',
'Release',
name
)
if (!fs.existsSync(binary)) {
throw new Error(
`bindings: ${binary} does not exist. The fixture addon is compiled by ` +
`node-gyp during install, which requires the package to be listed in ` +
`the test's pnpm.onlyBuiltDependencies.`
)
}
// Deliberately not wrapped. A non-context-aware addon fails on this line with
// Node's own `ERR_DLOPEN_FAILED` / "Module did not self-register", and the
// worker-thread tests assert on that message.
return require(binary)
}
{
"name": "bindings",
"version": "1.0.0",
"description": "Minimal stand-in for the bindings npm package, for tests",
"main": "index.js"
}
const { isMainThread } = require('node:worker_threads')
// Loading the addon here puts it in the main build process, so the load the page
// performs inside the static generation worker is the *second* one. Both matter:
// "Module did not self-register" only happens on a second `dlopen` of the same
// file in one process, so an addon only ever loaded inside the worker would
// register there and the build would succeed.
//
// The `isMainThread` guard keeps the first two cases pointed at the static
// generation worker. `next build` also runs Turbopack in a worker thread that
// re-evaluates this file, and loading the addon there too fails the build before
// static generation is reached. The last case in the suite covers that separately.
if (isMainThread) {
require('single-context-addon')
}
module.exports = {}
{
"dependencies": {
"single-context-addon": "file:single-context-addon",
"bindings": "file:bindings"
}
}
import addon from 'single-context-addon'
export const getStaticProps = () => {
// Runs inside the static generation worker, which is the second place the addon
// gets loaded. `next.config.js` already loaded it in the main process.
return {
props: {
contextAware: addon.CONTEXT_AWARE,
},
}
}
export default function Page(props) {
return <p id="props">{JSON.stringify(props)}</p>
}
# `single-context-addon` is compiled by node-gyp during install, and pnpm does
# not run a dependency's build scripts unless they are approved here. The repo
# root uses the same key for the one package it allows to build.
allowBuilds:
single-context-addon: true
import { nextTestSetup } from 'e2e-utils'
const UNGUARDED_CONFIG = `require('single-context-addon')
module.exports = {}
`
// A native addon declared with `NODE_MODULE` rather than `NODE_MODULE_INIT` can
// only be loaded once per process, so a second `dlopen` on another thread of the
// same process fails with `ERR_DLOPEN_FAILED` / "Module did not self-register".
//
// `experimental.workerThreads` decides whether static generation runs in real
// worker threads or in forked child processes. Forks get a fresh process and load
// the addon cleanly; threads share the build process and do not. That is why the
// flag defaults to false (PR #9199) and why the static export worker was fixed to
// respect it instead of hardcoding threads on (PR #25063).
describe('prerender worker threads', () => {
const { next, isTurbopack } = nextTestSetup({
files: __dirname,
skipStart: true,
// `bindings` is a direct dependency rather than one of the addon. The addon
// resolves it by walking up from the virtual store, and declaring it on the
// addon would make it a non-registry transitive dependency, which
// `blockExoticSubdeps` rejects.
//
// These use `file:` rather than `link:` so pnpm copies them into the virtual
// store. A linked package resolves to a path inside the app, which the bundler
// treats as app code and tries to bundle, and `bindings` contains a `require`
// it cannot resolve statically.
dependencies: require('./package.json').dependencies,
})
it('should prerender a page using a non-context-aware addon by default', async () => {
const { exitCode, cliOutput } = await next.build()
expect(cliOutput).not.toContain('Module did not self-register')
expect(exitCode).toBe(0)
})
it('should fail to prerender that page when worker threads are enabled', async () => {
await next.patchFile(
'next.config.js',
`const { isMainThread } = require('node:worker_threads')
if (isMainThread) { require('single-context-addon') }
module.exports = { experimental: { workerThreads: true } }
`
)
const { exitCode, cliOutput } = await next.build()
expect(cliOutput).toContain('Module did not self-register')
expect(cliOutput).toContain('single_context_addon.node')
expect(exitCode).not.toBe(0)
})
// This documents a bug rather than intended behavior. `next build` runs Turbopack
// in a worker thread (`enableWorkerThreads: true` is hardcoded in
// packages/next/src/build/turbopack-build/index.ts) and that worker re-evaluates
// `next.config.js`, so requiring a non-context-aware addon from the config breaks
// the build even though `experimental.workerThreads` is off. It is the same class
// of failure PR #9199 and PR #25063 fixed, in a worker those PRs did not touch.
//
// Webpack is unaffected, because its build worker is a forked child process.
//
// When Turbopack stops evaluating the config on a worker thread, this test will
// fail: drop the branch and assert the webpack outcome for both bundlers.
it('should currently fail under Turbopack when the config loads the addon', async () => {
await next.patchFile('next.config.js', UNGUARDED_CONFIG)
const { exitCode, cliOutput } = await next.build()
if (isTurbopack) {
expect(cliOutput).toContain('Module did not self-register')
expect(exitCode).not.toBe(0)
} else {
expect(cliOutput).not.toContain('Module did not self-register')
expect(exitCode).toBe(0)
}
})
})
// A deliberately non-context-aware addon. `NODE_MODULE` registers once per
// process, so loading it on the main thread and then again on a worker thread
// fails: the second `dlopen` returns the cached handle, the module constructor
// does not run again, and Node reports
//
// Error [ERR_DLOPEN_FAILED]: Module did not self-register: '<path>'.
//
// which is the failure PR #9199 and PR #25063 both worked around by keeping
// worker threads off by default. Do not port this to Node-API or
// `NODE_MODULE_INIT`: either would make it context-aware and the tests that
// depend on it would silently start passing for the wrong reason.
#include <node.h>
namespace {
void Init(v8::Local<v8::Object> exports) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::Local<v8::Context> context = isolate->GetCurrentContext();
exports
->Set(context,
v8::String::NewFromUtf8(isolate, "CONTEXT_AWARE").ToLocalChecked(),
v8::Boolean::New(isolate, false))
.Check();
}
} // namespace
NODE_MODULE(NODE_GYP_MODULE_NAME, Init)
{
"targets": [
{
"target_name": "single_context_addon",
"sources": ["addon.cc"]
}
]
}
module.exports = require('bindings')('single_context_addon.node')
{
"name": "single-context-addon",
"version": "1.0.0",
"description": "Non-context-aware native addon fixture, compiled by node-gyp",
"main": "index.js"
}
...@@ -16103,17 +16103,6 @@ ...@@ -16103,17 +16103,6 @@
"flakey": [], "flakey": [],
"runtimeError": false "runtimeError": false
}, },
"test/integration/firebase-grpc/test/index.test.ts": {
"passed": [
"Building Firebase production mode Throws no error when building with firebase dependency without worker_threads"
],
"failed": [],
"pending": [
"Building Firebase production mode Throws an error when building with firebase dependency with worker_threads"
],
"flakey": [],
"runtimeError": false
},
"test/integration/future/test/index.test.ts": { "test/integration/future/test/index.test.ts": {
"passed": [ "passed": [
"excludeDefaultMomentLocales production mode should load momentjs" "excludeDefaultMomentLocales production mode should load momentjs"
...@@ -18557,16 +18557,6 @@ ...@@ -18557,16 +18557,6 @@
"flakey": [], "flakey": [],
"runtimeError": false "runtimeError": false
}, },
"test/integration/firebase-grpc/test/index.test.ts": {
"passed": [],
"failed": [],
"pending": [
"Building Firebase production mode Throws an error when building with firebase dependency with worker_threads",
"Building Firebase production mode Throws no error when building with firebase dependency without worker_threads"
],
"flakey": [],
"runtimeError": false
},
"test/integration/future/test/index.test.ts": { "test/integration/future/test/index.test.ts": {
"passed": [], "passed": [],
"failed": [], "failed": [],
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