Unverified Commit 1f933ce9 authored by Sebastian "Sebbie" Silbermann's avatar Sebastian "Sebbie" Silbermann Committed by GitHub

[test] Replace the `turbopack-reports` `sqlite3` dependency with a local addon fixture (#97541)

The suite installed `sqlite3` only to get a package that locates its
compiled binary through `require('bindings')(...)`, which is the shape
turbopack issue 5913 was about. It now carries its own `native-addon`
and `bindings` packages instead, both installed as relative `file:`
dependencies, with node-gyp compiling the addon during install.

The addon is compiled rather than stubbed because the assertion reads a
value off the loaded binary, so a real `process.dlopen()` has to happen.
Compiling at install time also keeps the binary matched to whichever
Node ABI is running, which a checked-in binary could not do, since a
non-context-aware addon cannot use Node-API and is therefore ABI-locked.
The page now renders the addon's constant, so a module that resolved to
nothing fails the test instead of passing quietly.

Both packages are `file:` rather than `link:` dependencies. A linked
package resolves to a path inside the app, which the bundler then treats
as app code and tries to bundle, and `bindings` contains a `require` it
cannot resolve statically. `serverExternalPackages` is needed because
the app router bundles `node_modules` by default, and `sqlite3` only
avoided that by being on the built-in list in
`server-external-packages.jsonc`.

The fixture packages are registered in `modulePathIgnorePatterns`,
following the entries already there. Jest is configured with
`throwOnModuleCollision`, so a package name appearing twice outside
`node_modules` aborts the whole test run, and the layers above add more
copies of `bindings`.
parent c4d33a5c
......@@ -33,6 +33,8 @@ const customJestConfig = {
'<rootDir>/e2e/app-dir/self-importing-package/internal-pkg',
'<rootDir>/e2e/app-dir/self-importing-package-monorepo/internal-pkg',
'<rootDir>/e2e/app-dir/server-source-maps/fixtures/default/internal-pkg',
'<rootDir>/e2e/app-dir/turbopack-reports/bindings',
'<rootDir>/e2e/app-dir/turbopack-reports/native-addon',
'<rootDir>/e2e/transpile-packages-typescript-foreign/pkg',
'<rootDir>/production/standalone-mode/tracing-side-effects-false/foo',
'<rootDir>/production/standalone-mode/tracing-static-files/foo',
......
......@@ -10,3 +10,8 @@ development/**/tsconfig.json
rspack-test-junit-report/
test-junit-report/
turbopack-test-junit-report/
# node-gyp output from the compiled native addon fixtures. The addons are built
# inside each test's throwaway install directory, so this only catches builds
# someone runs in place while iterating on a fixture.
**/native-addon/build/
# Deploy builds install with npm, which symlinks a `file:` directory dependency by
# default. A symlink resolves back into the app, so the server build stops treating
# the package as external and bundles it, and `bindings` cannot survive that: it
# locates its binary from the calling file's path, which becomes a path inside
# `.next` once bundled.
#
# `install-links` makes npm pack the dependency into `node_modules` instead. It only
# takes effect when the dependency is specified without a leading `./`, which is why
# `package.json` says `file:native-addon` rather than `file:./native-addon`.
#
# pnpm ignores this setting and copies the directory into its virtual store either
# way, so the local install is unaffected.
install-links=true
import nativeAddon from 'native-addon'
// Regression test for turbopack issue 5913: a package that locates and loads its
// compiled binary through `require('bindings')(...)` used to break the build.
//
// `CONTEXT_AWARE` comes from the compiled addon itself, so rendering it proves the
// binary was really loaded. A resolution that produced an empty module would
// render nothing here rather than passing quietly.
export default function Page() {
return (
<>
<h1 id="message">Hello World</h1>
<p id="context-aware">{String(nativeAddon.CONTEXT_AWARE)}</p>
</>
)
}
import sqlite3 from 'sqlite3'
export default function Page() {
console.log(sqlite3.READONLY)
return <h1 id="message">Hello World</h1>
}
// 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"
}
// A context-aware addon. `NODE_MODULE_INIT` registers per-context, so this can
// be loaded from the main thread and from a worker thread in the same process.
// See https://nodejs.org/api/addons.html#context-aware-addons
#include <node.h>
NODE_MODULE_INIT(/* exports, module, context */) {
v8::Isolate* isolate = context->GetIsolate();
exports
->Set(context,
v8::String::NewFromUtf8(isolate, "CONTEXT_AWARE").ToLocalChecked(),
v8::Boolean::New(isolate, true))
.Check();
}
{
"targets": [
{
"target_name": "native_addon",
"sources": ["addon.cc"]
}
]
}
// Mirrors how `sqlite3` loads its binary, which is the shape both bundlers
// special-case: a single `require('bindings')('<name>.node')` call.
module.exports = require('bindings')('native_addon.node')
{
"name": "native-addon",
"version": "1.0.0",
"description": "Context-aware native addon fixture, compiled by node-gyp",
"main": "index.js"
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
const nextConfig = {
// `native-addon` resolves and loads a compiled binary at runtime, so it has to
// stay external instead of being bundled. Real native packages get this for
// free: `sqlite3`, which this fixture replaced, is on the built-in
// `serverExternalPackages` list in
// packages/next/src/lib/server-external-packages.jsonc.
serverExternalPackages: ['native-addon'],
}
module.exports = nextConfig
{
"dependencies": {
"native-addon": "file:native-addon",
"bindings": "file:bindings"
}
}
# `native-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:
native-addon: true
......@@ -3,18 +3,22 @@ import { nextTestSetup } from 'e2e-utils'
describe('turbopack-reports', () => {
const { next } = nextTestSetup({
files: __dirname,
dependencies: {
sqlite3: '5.1.7',
},
packageJson: {
pnpm: {
onlyBuiltDependencies: ['sqlite3'],
},
},
// `bindings` is a direct dependency rather than one of `native-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.
//
// Both 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 render page importing sqlite3', async () => {
const $ = await next.render$('/sqlite-import-5913')
it('should render page importing a package that loads a native binding', async () => {
const $ = await next.render$('/native-addon-import-5913')
expect($('#message').text()).toBe('Hello World')
// Read off the compiled binary, so a module that resolved to nothing fails here.
expect($('#context-aware').text()).toBe('true')
})
})
......@@ -563,9 +563,17 @@ export class NextDeployInstance extends NextInstance {
require('console').log(
`Writing .npmrc for preview-builds mirror: ${registryKey}`
)
// Appended rather than written, because a fixture may ship its own `.npmrc`
// (several do) and overwriting it silently drops that configuration.
const npmrcPath = path.join(this.testDir, '.npmrc')
const existing = (await fs.pathExists(npmrcPath))
? await fs.readFile(npmrcPath, 'utf8')
: ''
const separator = existing === '' || existing.endsWith('\n') ? '' : '\n'
await fs.writeFile(
path.join(this.testDir, '.npmrc'),
`${registryKey}:_authToken=\${VERCEL_OIDC_TOKEN}\n`
npmrcPath,
`${existing}${separator}${registryKey}:_authToken=\${VERCEL_OIDC_TOKEN}\n`
)
}
......
......@@ -8031,7 +8031,9 @@
"runtimeError": false
},
"test/e2e/app-dir/turbopack-reports/turbopack-reports.test.ts": {
"passed": ["turbopack-reports should render page importing sqlite3"],
"passed": [
"turbopack-reports should render page importing a package that loads a native binding"
],
"failed": [],
"pending": [],
"flakey": [],
......@@ -10484,7 +10484,9 @@
"runtimeError": false
},
"test/e2e/app-dir/turbopack-reports/turbopack-reports.test.ts": {
"passed": ["turbopack-reports should render page importing sqlite3"],
"passed": [
"turbopack-reports should render page importing a package that loads a native binding"
],
"failed": [],
"pending": [],
"flakey": [],
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