Unverified Commit 891cfe69 authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

Turbopack: Add Next.js version to "initialize project" trace span (#90545)

## Summary

Adds the Next.js version as a `version` field on the Turbopack
"initialize project" tracing span. The version is passed from the
TypeScript side (`process.env.__NEXT_VERSION`) through the NAPI bindings
into Rust `ProjectOptions`, where it is recorded on the span.

This makes it easy to correlate trace data with the specific Next.js
version that produced it.

Also standardizes all version reads in `packages/next/src/` to use
`process.env.__NEXT_VERSION` (which is inlined at build time by
`taskfile-swc.js`) instead of `require('next/package.json').version` or
`import { version } from 'next/package.json'`.

### Changes

**Trace span (commit 1):**
- **`crates/next-api/src/project.rs`** — Added `next_version` field to
`ProjectOptions`; recorded as `version` on the `"initialize project"`
span
- **`crates/next-napi-bindings/src/next_api/project.rs`** — Added
`next_version` to `NapiProjectOptions` and wired it through the `From`
impl
- **`crates/next-build-test/src/main.rs`** — Added `next_version` to
test `ProjectOptions` init
- **`packages/next/src/build/swc/generated-native.d.ts`** — Added
`nextVersion` to the TypeScript `NapiProjectOptions` interface
- **`packages/next/src/server/dev/hot-reloader-turbopack.ts`**,
**`packages/next/src/build/turbopack-build/impl.ts`**,
**`packages/next/src/build/turbopack-analyze/index.ts`** — Pass
`nextVersion: process.env.__NEXT_VERSION` when creating the Turbopack
project
- **`test/development/basic/next-rs-api.test.ts`** — Added `nextVersion`
to both `createProject` call sites

**Consistent `__NEXT_VERSION` usage (commit 2):**
- **`packages/next/src/server/dev/hot-reloader-shared-utils.ts`** —
`require('next/package.json').version` → `process.env.__NEXT_VERSION`
- **`packages/next/src/lib/patch-incorrect-lockfile.ts`** —
`nextPkgJson.version` → `process.env.__NEXT_VERSION`; narrowed import to
only `optionalDependencies`
- **`packages/next/src/telemetry/events/swc-load-failure.ts`** — `import
{ version as nextVersion }` → `process.env.__NEXT_VERSION`; narrowed
import to only `optionalDependencies`

## Test Plan

- Verified Rust compilation with `cargo check -p next-api`, `cargo check
-p next-build-test`
- Verified TypeScript types with `pnpm --filter=next types`

---------
Co-authored-by: 's avatarClaude <noreply@anthropic.com>
parent 26a38229
...@@ -360,6 +360,9 @@ pub struct ProjectOptions { ...@@ -360,6 +360,9 @@ pub struct ProjectOptions {
/// Whether to enable persistent caching /// Whether to enable persistent caching
pub is_persistent_caching_enabled: bool, pub is_persistent_caching_enabled: bool,
/// The version of Next.js that is running.
pub next_version: RcStr,
} }
#[derive(Default)] #[derive(Default)]
...@@ -567,6 +570,7 @@ impl ProjectContainer { ...@@ -567,6 +570,7 @@ impl ProjectContainer {
let span = tracing::info_span!( let span = tracing::info_span!(
"initialize project", "initialize project",
project_name = %self.await?.name, project_name = %self.await?.name,
version = options.next_version.as_str(),
env_diff = Empty env_diff = Empty
); );
let span_clone = span.clone(); let span_clone = span.clone();
......
...@@ -187,6 +187,7 @@ fn main() { ...@@ -187,6 +187,7 @@ fn main() {
debug_build_paths: None, debug_build_paths: None,
deferred_entries: None, deferred_entries: None,
is_persistent_caching_enabled: false, is_persistent_caching_enabled: false,
next_version: rcstr!("0.0.0"),
}; };
let json = serde_json::to_string_pretty(&options).unwrap(); let json = serde_json::to_string_pretty(&options).unwrap();
......
...@@ -201,6 +201,9 @@ pub struct NapiProjectOptions { ...@@ -201,6 +201,9 @@ pub struct NapiProjectOptions {
// Whether persistent caching is enabled // Whether persistent caching is enabled
pub is_persistent_caching_enabled: bool, pub is_persistent_caching_enabled: bool,
/// The version of Next.js that is running.
pub next_version: RcStr,
} }
/// [NapiProjectOptions] with all fields optional. /// [NapiProjectOptions] with all fields optional.
...@@ -307,6 +310,7 @@ impl From<NapiProjectOptions> for ProjectOptions { ...@@ -307,6 +310,7 @@ impl From<NapiProjectOptions> for ProjectOptions {
debug_build_paths, debug_build_paths,
deferred_entries, deferred_entries,
is_persistent_caching_enabled, is_persistent_caching_enabled,
next_version,
} = val; } = val;
ProjectOptions { ProjectOptions {
root_path, root_path,
...@@ -329,6 +333,7 @@ impl From<NapiProjectOptions> for ProjectOptions { ...@@ -329,6 +333,7 @@ impl From<NapiProjectOptions> for ProjectOptions {
}), }),
deferred_entries, deferred_entries,
is_persistent_caching_enabled, is_persistent_caching_enabled,
next_version,
} }
} }
} }
......
...@@ -169,6 +169,8 @@ export interface NapiProjectOptions { ...@@ -169,6 +169,8 @@ export interface NapiProjectOptions {
/** App-router page routes that should be built after non-deferred routes. */ /** App-router page routes that should be built after non-deferred routes. */
deferredEntries?: Array<RcStr> deferredEntries?: Array<RcStr>
isPersistentCachingEnabled: boolean isPersistentCachingEnabled: boolean
/** The version of Next.js that is running. */
nextVersion: RcStr
} }
/** [NapiProjectOptions] with all fields optional. */ /** [NapiProjectOptions] with all fields optional. */
export interface NapiPartialProjectOptions { export interface NapiPartialProjectOptions {
......
...@@ -89,6 +89,7 @@ export async function turbopackAnalyze( ...@@ -89,6 +89,7 @@ export async function turbopackAnalyze(
writeRoutesHashesManifest: false, writeRoutesHashesManifest: false,
currentNodeJsVersion, currentNodeJsVersion,
isPersistentCachingEnabled: persistentCaching, isPersistentCachingEnabled: persistentCaching,
nextVersion: process.env.__NEXT_VERSION as string,
}, },
{ {
memoryLimit: config.experimental?.turbopackMemoryLimit, memoryLimit: config.experimental?.turbopackMemoryLimit,
......
...@@ -105,6 +105,7 @@ export async function turbopackBuild(): Promise<{ ...@@ -105,6 +105,7 @@ export async function turbopackBuild(): Promise<{
currentNodeJsVersion, currentNodeJsVersion,
isPersistentCachingEnabled: persistentCaching, isPersistentCachingEnabled: persistentCaching,
deferredEntries: config.experimental.deferredEntries, deferredEntries: config.experimental.deferredEntries,
nextVersion: process.env.__NEXT_VERSION as string,
} }
const sharedTurboOptions = { const sharedTurboOptions = {
......
...@@ -2,7 +2,7 @@ import { promises } from 'fs' ...@@ -2,7 +2,7 @@ import { promises } from 'fs'
import * as Log from '../build/output/log' import * as Log from '../build/output/log'
import findUp from 'next/dist/compiled/find-up' import findUp from 'next/dist/compiled/find-up'
// @ts-ignore no-json types // @ts-ignore no-json types
import nextPkgJson from 'next/package.json' import { optionalDependencies as nextOptionalDeps } from 'next/package.json'
import type { UnwrapPromise } from './coalesced-function' import type { UnwrapPromise } from './coalesced-function'
import { isCI } from '../server/ci-info' import { isCI } from '../server/ci-info'
import { getRegistry } from './helpers/get-registry' import { getRegistry } from './helpers/get-registry'
...@@ -19,7 +19,7 @@ async function fetchPkgInfo(pkg: string) { ...@@ -19,7 +19,7 @@ async function fetchPkgInfo(pkg: string) {
) )
} }
const data = await res.json() const data = await res.json()
const versionData = data.versions[nextPkgJson.version] const versionData = data.versions[process.env.__NEXT_VERSION as string]
return { return {
os: versionData.os, os: versionData.os,
...@@ -56,16 +56,16 @@ export async function patchIncorrectLockfile(dir: string) { ...@@ -56,16 +56,16 @@ export async function patchIncorrectLockfile(dir: string) {
const lockfileParsed = JSON.parse(content) const lockfileParsed = JSON.parse(content)
const lockfileVersion = parseInt(lockfileParsed?.lockfileVersion, 10) const lockfileVersion = parseInt(lockfileParsed?.lockfileVersion, 10)
const expectedSwcPkgs = Object.keys( const expectedSwcPkgs = Object.keys(nextOptionalDeps || {}).filter((pkg) =>
nextPkgJson['optionalDependencies'] || {} pkg.startsWith('@next/swc-')
).filter((pkg) => pkg.startsWith('@next/swc-')) )
const patchDependency = ( const patchDependency = (
pkg: string, pkg: string,
pkgData: UnwrapPromise<ReturnType<typeof fetchPkgInfo>> pkgData: UnwrapPromise<ReturnType<typeof fetchPkgInfo>>
) => { ) => {
lockfileParsed.dependencies[pkg] = { lockfileParsed.dependencies[pkg] = {
version: nextPkgJson.version, version: process.env.__NEXT_VERSION as string,
resolved: pkgData.tarball, resolved: pkgData.tarball,
integrity: pkgData.integrity, integrity: pkgData.integrity,
optional: true, optional: true,
...@@ -77,7 +77,7 @@ export async function patchIncorrectLockfile(dir: string) { ...@@ -77,7 +77,7 @@ export async function patchIncorrectLockfile(dir: string) {
pkgData: UnwrapPromise<ReturnType<typeof fetchPkgInfo>> pkgData: UnwrapPromise<ReturnType<typeof fetchPkgInfo>>
) => { ) => {
lockfileParsed.packages[pkg] = { lockfileParsed.packages[pkg] = {
version: nextPkgJson.version, version: process.env.__NEXT_VERSION as string,
resolved: pkgData.tarball, resolved: pkgData.tarball,
integrity: pkgData.integrity, integrity: pkgData.integrity,
cpu: pkgData.cpu, cpu: pkgData.cpu,
......
...@@ -403,6 +403,7 @@ export async function createHotReloaderTurbopack( ...@@ -403,6 +403,7 @@ export async function createHotReloaderTurbopack(
isPersistentCachingEnabled: isFileSystemCacheEnabledForDev( isPersistentCachingEnabled: isFileSystemCacheEnabledForDev(
opts.nextConfig opts.nextConfig
), ),
nextVersion: process.env.__NEXT_VERSION as string,
}, },
{ {
memoryLimit: opts.nextConfig.experimental?.turbopackMemoryLimit, memoryLimit: opts.nextConfig.experimental?.turbopackMemoryLimit,
......
import { traceGlobals } from '../../trace/shared' import { traceGlobals } from '../../trace/shared'
import type { Telemetry } from '../storage' import type { Telemetry } from '../storage'
// @ts-ignore JSON // @ts-ignore JSON
import { version as nextVersion, optionalDependencies } from 'next/package.json' import { optionalDependencies } from 'next/package.json'
const EVENT_PLUGIN_PRESENT = 'NEXT_SWC_LOAD_FAILURE' const EVENT_PLUGIN_PRESENT = 'NEXT_SWC_LOAD_FAILURE'
export type EventSwcLoadFailure = { export type EventSwcLoadFailure = {
...@@ -54,7 +54,7 @@ export async function eventSwcLoadFailure( ...@@ -54,7 +54,7 @@ export async function eventSwcLoadFailure(
telemetry.record({ telemetry.record({
eventName: EVENT_PLUGIN_PRESENT, eventName: EVENT_PLUGIN_PRESENT,
payload: { payload: {
nextVersion, nextVersion: process.env.__NEXT_VERSION as string,
glibcVersion, glibcVersion,
installedSwcPackages, installedSwcPackages,
arch: process.arch, arch: process.arch,
......
...@@ -232,6 +232,7 @@ async function main() { ...@@ -232,6 +232,7 @@ async function main() {
writeRoutesHashesManifest: false, writeRoutesHashesManifest: false,
currentNodeJsVersion: '18.0.0', currentNodeJsVersion: '18.0.0',
isPersistentCachingEnabled: false, isPersistentCachingEnabled: false,
nextVersion: '0.0.0',
}); });
const entrypointsSubscription = project.entrypointsSubscribe(); const entrypointsSubscription = project.entrypointsSubscribe();
...@@ -391,6 +392,7 @@ describe('next.rs api', () => { ...@@ -391,6 +392,7 @@ describe('next.rs api', () => {
writeRoutesHashesManifest: false, writeRoutesHashesManifest: false,
currentNodeJsVersion: '18.0.0', currentNodeJsVersion: '18.0.0',
isPersistentCachingEnabled: false, isPersistentCachingEnabled: false,
nextVersion: '0.0.0',
}) })
projectUpdateSubscription = filterMapAsyncIterator( projectUpdateSubscription = filterMapAsyncIterator(
project.updateInfoSubscribe(1000), project.updateInfoSubscribe(1000),
......
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