Unverified Commit af18c32b authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Improve lock dir error message (#89119)

parent 7517e3ec
use std::{ use std::{
fs::{File, OpenOptions}, fs::{File, OpenOptions},
io::Write,
mem::ManuallyDrop, mem::ManuallyDrop,
sync::Mutex, sync::Mutex,
}; };
...@@ -24,10 +25,10 @@ pub struct LockfileInner { ...@@ -24,10 +25,10 @@ pub struct LockfileInner {
} }
#[napi(ts_return_type = "{ __napiType: \"Lockfile\" } | null")] #[napi(ts_return_type = "{ __napiType: \"Lockfile\" } | null")]
pub fn lockfile_try_acquire_sync(path: String) -> napi::Result<Option<External<JsLockfile>>> { pub fn lockfile_try_acquire_sync(
let mut open_options = OpenOptions::new(); path: String,
open_options.write(true).create(true); content: Option<String>,
) -> napi::Result<Option<External<JsLockfile>>> {
// On Windows, we don't use `File::lock` because that grabs a mandatory lock. That can break // On Windows, we don't use `File::lock` because that grabs a mandatory lock. That can break
// tools or code that read the contents of the `.next` directory because the mandatory lock // tools or code that read the contents of the `.next` directory because the mandatory lock
// file will fail with EBUSY when read. Instead, we open a file with write mode, but without // file will fail with EBUSY when read. Instead, we open a file with write mode, but without
...@@ -42,13 +43,24 @@ pub fn lockfile_try_acquire_sync(path: String) -> napi::Result<Option<External<J ...@@ -42,13 +43,24 @@ pub fn lockfile_try_acquire_sync(path: String) -> napi::Result<Option<External<J
use windows_sys::Win32::{Foundation, Storage::FileSystem}; use windows_sys::Win32::{Foundation, Storage::FileSystem};
// On Windows, opening with write mode without FILE_SHARE_WRITE acts as the lock.
// We use truncate(true) here because if we can open the file, we have the lock.
let mut open_options = OpenOptions::new();
open_options.write(true).create(true).truncate(true);
open_options open_options
.share_mode(FileSystem::FILE_SHARE_READ | FileSystem::FILE_SHARE_DELETE) .share_mode(FileSystem::FILE_SHARE_READ | FileSystem::FILE_SHARE_DELETE)
.custom_flags(FileSystem::FILE_FLAG_DELETE_ON_CLOSE); .custom_flags(FileSystem::FILE_FLAG_DELETE_ON_CLOSE);
match open_options.open(&path) { match open_options.open(&path) {
Ok(file) => Ok(Some(External::new(Mutex::new(ManuallyDrop::new(Some( Ok(mut file) => {
LockfileInner { file }, // Write content to the lockfile if provided
)))))), if let Some(ref data) = content {
file.write_all(data.as_bytes())?;
file.flush()?;
}
Ok(Some(External::new(Mutex::new(ManuallyDrop::new(Some(
LockfileInner { file },
))))))
}
Err(err) Err(err)
if err.raw_os_error() if err.raw_os_error()
== Some(Foundation::ERROR_SHARING_VIOLATION.try_into().unwrap()) => == Some(Foundation::ERROR_SHARING_VIOLATION.try_into().unwrap()) =>
...@@ -61,16 +73,31 @@ pub fn lockfile_try_acquire_sync(path: String) -> napi::Result<Option<External<J ...@@ -61,16 +73,31 @@ pub fn lockfile_try_acquire_sync(path: String) -> napi::Result<Option<External<J
#[cfg(not(windows))] #[cfg(not(windows))]
return { return {
use std::fs::TryLockError; use std::{fs::TryLockError, io::Seek};
// On Unix, we must NOT truncate on open because flock is advisory -
// opening with truncate would clear another process's lockfile content.
// Instead, open without truncate, acquire the lock, then truncate.
let mut open_options = OpenOptions::new();
open_options.write(true).create(true).read(true);
let file = open_options.open(&path)?; let file = open_options.open(&path)?;
match file.try_lock() { match file.try_lock() {
Ok(_) => Ok(Some(External::new(Mutex::new(ManuallyDrop::new(Some( Ok(_) => {
LockfileInner { // We have the lock - now truncate and write content
file, file.set_len(0)?;
path: path.into(), (&file).seek(std::io::SeekFrom::Start(0))?;
}, if let Some(ref data) = content {
)))))), (&file).write_all(data.as_bytes())?;
(&file).flush()?;
}
Ok(Some(External::new(Mutex::new(ManuallyDrop::new(Some(
LockfileInner {
file,
path: path.into(),
},
))))))
}
Err(TryLockError::WouldBlock) => Ok(None), Err(TryLockError::WouldBlock) => Ok(None),
Err(TryLockError::Error(err)) => Err(err.into()), Err(TryLockError::Error(err)) => Err(err.into()),
} }
...@@ -78,8 +105,11 @@ pub fn lockfile_try_acquire_sync(path: String) -> napi::Result<Option<External<J ...@@ -78,8 +105,11 @@ pub fn lockfile_try_acquire_sync(path: String) -> napi::Result<Option<External<J
} }
#[napi(ts_return_type = "Promise<{ __napiType: \"Lockfile\" } | null>")] #[napi(ts_return_type = "Promise<{ __napiType: \"Lockfile\" } | null>")]
pub async fn lockfile_try_acquire(path: String) -> napi::Result<Option<External<JsLockfile>>> { pub async fn lockfile_try_acquire(
tokio::task::spawn_blocking(move || lockfile_try_acquire_sync(path)) path: String,
content: Option<String>,
) -> napi::Result<Option<External<JsLockfile>>> {
tokio::task::spawn_blocking(move || lockfile_try_acquire_sync(path, content))
.await .await
.context("panicked while attempting to acquire lockfile")? .context("panicked while attempting to acquire lockfile")?
} }
......
import fs from 'fs'
import nodePath from 'path'
import { bold, cyan } from '../lib/picocolors' import { bold, cyan } from '../lib/picocolors'
import * as Log from './output/log' import * as Log from './output/log'
import { getBindingsSync } from './swc' import { getBindingsSync } from './swc'
...@@ -7,6 +9,44 @@ import type { Binding, Lockfile as NativeLockfile } from './swc/types' ...@@ -7,6 +9,44 @@ import type { Binding, Lockfile as NativeLockfile } from './swc/types'
const RETRY_DELAY_MS = 10 const RETRY_DELAY_MS = 10
const MAX_RETRY_MS = 1000 const MAX_RETRY_MS = 1000
/**
* Information about a running dev server, stored inside the lock file itself.
* This is a common pattern in Unix applications (e.g., storing PID in a lockfile).
*/
export interface DevServerInfo {
pid: number
port: number
hostname: string
appUrl: string
startedAt: number
}
/**
* Reads dev server info from a lockfile.
* Returns undefined if the file doesn't exist or can't be parsed.
*
* Uses Node's fs.readFileSync which works on both Unix (with advisory flock)
* and Windows (with FILE_SHARE_READ flag set by the lock holder).
*/
export function readLockfileContent(lockfilePath: string): string | undefined {
try {
return fs.readFileSync(lockfilePath, 'utf-8')
} catch {
return undefined
}
}
/**
* Parses dev server info from lockfile content.
*/
export function parseDevServerInfo(content: string): DevServerInfo | undefined {
try {
return JSON.parse(content) as DevServerInfo
} catch {
return undefined
}
}
/** /**
* A cross-platform on-disk best-effort advisory exclusive lockfile * A cross-platform on-disk best-effort advisory exclusive lockfile
* implementation. * implementation.
...@@ -56,10 +96,15 @@ export class Lockfile { ...@@ -56,10 +96,15 @@ export class Lockfile {
* *
* - If we fail to acquire the lock, we return `undefined`. * - If we fail to acquire the lock, we return `undefined`.
* - If we're on wasm, this always returns a dummy `Lockfile` object. * - If we're on wasm, this always returns a dummy `Lockfile` object.
*
* @param path - Path to the lock file
* @param unlockOnExit - Whether to unlock the file on process exit
* @param content - Optional content to write to the lockfile (e.g., JSON with server info)
*/ */
static tryAcquire( static tryAcquire(
path: string, path: string,
unlockOnExit: boolean = true unlockOnExit: boolean = true,
content?: string
): Lockfile | undefined { ): Lockfile | undefined {
const bindings = getBindingsSync() const bindings = getBindingsSync()
if (bindings.isWasm) { if (bindings.isWasm) {
...@@ -70,7 +115,7 @@ export class Lockfile { ...@@ -70,7 +115,7 @@ export class Lockfile {
} else { } else {
let nativeLockfile let nativeLockfile
try { try {
nativeLockfile = bindings.lockfileTryAcquireSync(path) nativeLockfile = bindings.lockfileTryAcquireSync(path, content)
} catch (e) { } catch (e) {
// this happens if there's an IO error (e.g. `ENOENT`), which is // this happens if there's an IO error (e.g. `ENOENT`), which is
// different than if we just didn't acquire the lock // different than if we just didn't acquire the lock
...@@ -110,26 +155,76 @@ export class Lockfile { ...@@ -110,26 +155,76 @@ export class Lockfile {
* This will retry a small number of times. This can be useful when running * This will retry a small number of times. This can be useful when running
* processes in a loop, e.g. if cleanup isn't fully synchronous due to child * processes in a loop, e.g. if cleanup isn't fully synchronous due to child
* parent/processes. * parent/processes.
*
* @param path - Path to the lock file
* @param processName - Name of the process for error messages (e.g., 'next dev')
* @param unlockOnExit - Whether to unlock the file on process exit
* @param content - Optional content to write to the lockfile (e.g., JSON with server info)
* @param projectDir - Optional project directory for enhanced error messages
* @param relativeDistDir - Optional relative dist directory path (e.g., '.next/dev')
*/ */
static async acquireWithRetriesOrExit( static async acquireWithRetriesOrExit(
path: string, path: string,
processName: string, processName: string,
unlockOnExit: boolean = true unlockOnExit: boolean = true,
content?: string,
projectDir?: string,
relativeDistDir?: string
): Promise<Lockfile> { ): Promise<Lockfile> {
const startMs = Date.now() const startMs = Date.now()
let lockfile let lockfile
while (Date.now() - startMs < MAX_RETRY_MS) { while (Date.now() - startMs < MAX_RETRY_MS) {
lockfile = Lockfile.tryAcquire(path, unlockOnExit) lockfile = Lockfile.tryAcquire(path, unlockOnExit, content)
if (lockfile !== undefined) break if (lockfile !== undefined) break
await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY_MS)) await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY_MS))
} }
if (lockfile === undefined) { if (lockfile === undefined) {
Log.error( const isDev = processName === 'next dev'
`Unable to acquire lock at ${cyan(path)}, is another instance of ${cyan(processName)} running?`
) if (isDev) {
Log.info( // For dev server, try to read server info from the lockfile itself
`${bold('Suggestion:')} If you intended to restart ${cyan(processName)}, terminate the other process, and then try again.` const lockfileContent = readLockfileContent(path)
) const serverInfo = lockfileContent
? parseDevServerInfo(lockfileContent)
: undefined
if (serverInfo) {
Log.error(`Another ${cyan(processName)} server is already running.`)
console.error()
console.error(`- Local: ${cyan(serverInfo.appUrl)}`)
console.error(`- PID: ${serverInfo.pid}`)
if (projectDir) {
console.error(`- Dir: ${projectDir}`)
}
if (relativeDistDir) {
console.error(
`- Log: ${nodePath.join(relativeDistDir, 'logs', 'next-development.log')}`
)
}
console.error()
// Use platform-appropriate kill command
const killCommand =
process.platform === 'win32'
? `taskkill /PID ${serverInfo.pid} /F`
: `kill ${serverInfo.pid}`
console.error(`Run ${cyan(killCommand)} to stop it.`)
} else {
// Fallback when we can't read server info from the lockfile
Log.error(
`Another ${cyan(processName)} server is already running in this directory.`
)
console.error(`Stop the other server before starting a new one.`)
}
} else {
// For build, show that a build is in progress
Log.error(`Another ${cyan(processName)} process is already running.`)
console.error()
console.error(` This could be:`)
console.error(` - A ${cyan('next build')} still in progress`)
console.error(` - A previous build that didn't exit cleanly`)
console.error()
Log.info(`${bold('Suggestion:')} Wait for the build to complete.`)
}
process.exit(1) process.exit(1)
} }
return lockfile return lockfile
......
...@@ -35,10 +35,12 @@ export declare class ExternalObject<T> { ...@@ -35,10 +35,12 @@ export declare class ExternalObject<T> {
} }
} }
export declare function lockfileTryAcquireSync( export declare function lockfileTryAcquireSync(
path: string path: string,
content?: string | undefined | null
): { __napiType: 'Lockfile' } | null ): { __napiType: 'Lockfile' } | null
export declare function lockfileTryAcquire( export declare function lockfileTryAcquire(
path: string path: string,
content?: string | undefined | null
): Promise<{ __napiType: 'Lockfile' } | null> ): Promise<{ __napiType: 'Lockfile' } | null>
export declare function lockfileUnlockSync(lockfile: { export declare function lockfileUnlockSync(lockfile: {
__napiType: 'Lockfile' __napiType: 'Lockfile'
......
...@@ -1350,12 +1350,12 @@ async function loadWasm(importPath = '') { ...@@ -1350,12 +1350,12 @@ async function loadWasm(importPath = '') {
imports imports
) )
}, },
lockfileTryAcquire(_filePath: string) { lockfileTryAcquire(_filePath: string, _content?: string | null) {
throw new Error( throw new Error(
'`lockfileTryAcquire` is not supported by the wasm bindings.' '`lockfileTryAcquire` is not supported by the wasm bindings.'
) )
}, },
lockfileTryAcquireSync(_filePath: string) { lockfileTryAcquireSync(_filePath: string, _content?: string | null) {
throw new Error( throw new Error(
'`lockfileTryAcquireSync` is not supported by the wasm bindings.' '`lockfileTryAcquireSync` is not supported by the wasm bindings.'
) )
...@@ -1570,11 +1570,11 @@ function loadNative(importPath?: string) { ...@@ -1570,11 +1570,11 @@ function loadNative(importPath?: string) {
imports imports
) )
}, },
lockfileTryAcquire(filePath: string) { lockfileTryAcquire(filePath: string, content?: string | null) {
return bindings.lockfileTryAcquire(filePath) return bindings.lockfileTryAcquire(filePath, content)
}, },
lockfileTryAcquireSync(filePath: string) { lockfileTryAcquireSync(filePath: string, content?: string | null) {
return bindings.lockfileTryAcquireSync(filePath) return bindings.lockfileTryAcquireSync(filePath, content)
}, },
lockfileUnlock(lockfile: Lockfile) { lockfileUnlock(lockfile: Lockfile) {
return bindings.lockfileUnlock(lockfile) return bindings.lockfileUnlock(lockfile)
......
...@@ -68,8 +68,11 @@ export interface Binding { ...@@ -68,8 +68,11 @@ export interface Binding {
imports: Record<string, string | null> imports: Record<string, string | null>
): string ): string
lockfileTryAcquire(path: string): Promise<Lockfile | null> lockfileTryAcquire(
lockfileTryAcquireSync(path: string): Lockfile | null path: string,
content?: string | null
): Promise<Lockfile | null>
lockfileTryAcquireSync(path: string, content?: string | null): Lockfile | null
lockfileUnlock(lockfile: Lockfile): Promise<void> lockfileUnlock(lockfile: Lockfile): Promise<void>
lockfileUnlockSync(lockfile: Lockfile): void lockfileUnlockSync(lockfile: Lockfile): void
} }
......
...@@ -93,7 +93,7 @@ import { ...@@ -93,7 +93,7 @@ import {
import { writeCacheLifeTypes } from './cache-life-type-utils' import { writeCacheLifeTypes } from './cache-life-type-utils'
import { isParallelRouteSegment } from '../../../shared/lib/segment' import { isParallelRouteSegment } from '../../../shared/lib/segment'
import { ensureLeadingSlash } from '../../../shared/lib/page-path/ensure-leading-slash' import { ensureLeadingSlash } from '../../../shared/lib/page-path/ensure-leading-slash'
import { Lockfile } from '../../../build/lockfile' import { Lockfile, type DevServerInfo } from '../../../build/lockfile'
import { deobfuscateText } from '../../../shared/lib/magic-identifier' import { deobfuscateText } from '../../../shared/lib/magic-identifier'
export type SetupOpts = { export type SetupOpts = {
...@@ -188,9 +188,25 @@ async function startWatcher( ...@@ -188,9 +188,25 @@ async function startWatcher(
let lockfile let lockfile
if (opts.nextConfig.experimental.lockDistDir) { if (opts.nextConfig.experimental.lockDistDir) {
fs.mkdirSync(distDir, { recursive: true }) fs.mkdirSync(distDir, { recursive: true })
// Create server info to store in the lockfile itself
// This allows other processes to discover the running server
const appUrl = `http://localhost:${opts.port}`
const serverInfo: DevServerInfo = {
pid: process.pid,
port: opts.port,
hostname: 'localhost',
appUrl,
startedAt: Date.now(),
}
lockfile = await Lockfile.acquireWithRetriesOrExit( lockfile = await Lockfile.acquireWithRetriesOrExit(
path.join(distDir, 'lock'), path.join(distDir, 'lock'),
'next dev' 'next dev',
true,
JSON.stringify(serverInfo),
opts.dir,
opts.nextConfig.distDir
) )
} }
...@@ -249,8 +265,6 @@ async function startWatcher( ...@@ -249,8 +265,6 @@ async function startWatcher(
await hotReloader.start() await hotReloader.start()
// have to write this after starting hot-reloader since that
// cleans the dist dir
const distTypesDir = path.join(distDir, 'types') const distTypesDir = path.join(distDir, 'types')
await writeRouteTypesManifest( await writeRouteTypesManifest(
{ {
......
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import execa from 'execa' import execa from 'execa'
import fs from 'fs'
import path from 'path'
import stripAnsi from 'strip-ansi' import stripAnsi from 'strip-ansi'
describe('lockfile', () => { describe('lockfile', () => {
...@@ -11,6 +13,23 @@ describe('lockfile', () => { ...@@ -11,6 +13,23 @@ describe('lockfile', () => {
const browser = await next.browser('/') const browser = await next.browser('/')
expect(await browser.elementByCss('p').text()).toBe('Page') expect(await browser.elementByCss('p').text()).toBe('Page')
// Verify lockfile was created with server info inside it
// With isolatedDevBuild (default), distDir is .next/dev
const distDir = path.join(next.testDir, '.next', 'dev')
const lockfilePath = path.join(distDir, 'lock')
expect(fs.existsSync(lockfilePath)).toBe(true)
// Read server info from the lockfile itself
const serverInfo = JSON.parse(fs.readFileSync(lockfilePath, 'utf-8'))
expect(serverInfo).toMatchObject({
pid: expect.any(Number),
port: expect.any(Number),
hostname: expect.any(String),
appUrl: expect.any(String),
startedAt: expect.any(Number),
})
// Try to start another dev server - should fail with helpful error
const { stdout, stderr, exitCode } = await execa( const { stdout, stderr, exitCode } = await execa(
'pnpm', 'pnpm',
[ [
...@@ -24,11 +43,28 @@ describe('lockfile', () => { ...@@ -24,11 +43,28 @@ describe('lockfile', () => {
reject: false, reject: false,
} }
) )
expect(stripAnsi(stdout + stderr)).toContain('Unable to acquire lock')
const output = stripAnsi(stdout + stderr)
// Match the whole error message pattern with fuzzy matching for dynamic parts
// The kill command varies by platform: `kill <pid>` on Unix, `taskkill /PID <pid> /F` on Windows
const killPattern =
process.platform === 'win32'
? 'Run taskkill /PID \\d+ /F to stop it\\.'
: 'Run kill \\d+ to stop it\\.'
const errorPattern = new RegExp(
'Another next dev server is already running\\.\\s*' +
'- Local:\\s+http://[^\\s]+\\s+' +
'- PID:\\s+\\d+\\s+' +
'- Dir:\\s+[^\\s]+\\s+' +
'- Log:\\s+\\.next/dev/logs/next-development\\.log\\s+' +
killPattern
)
expect(output).toMatch(errorPattern)
expect(exitCode).toBe(1) expect(exitCode).toBe(1)
// make sure the other instance of `next dev` didn't mess anything up // Make sure the other instance of `next dev` didn't mess anything up
browser.refresh() await browser.refresh()
expect(await browser.elementByCss('p').text()).toBe('Page') expect(await browser.elementByCss('p').text()).toBe('Page')
}) })
}) })
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