Unverified Commit 11ae7c5b authored by vercel[bot]'s avatar vercel[bot] Committed by GitHub

[turbopack] Add acknowledged edit transactions

Co-Authored-By: 's avatarMarcos Hernanz <96699542+marcoshernanz@users.noreply.github.com>
parent ccd47cfe
......@@ -738,6 +738,86 @@ async fn benchmark_file_io(turbo_tasks: &NextTurboTasks, dir: &Path) -> Result<(
Ok(())
}
#[turbo_tasks::function(operation, root)]
fn project_fs_control_operation(container: ResolvedVc<ProjectContainer>) -> Vc<DiskFileSystem> {
container.project().project_fs()
}
/// Starts an explicitly acknowledged source-edit transaction. Filesystem invalidations are held
/// until the matching token is ended or the watcher's safety timeout expires.
#[napi]
pub async fn project_begin_edit_transaction(
#[napi(ts_arg_type = "{ __napiType: \"Project\" }")] project: External<ProjectInstance>,
) -> napi::Result<u32> {
let ctx = &project.turbopack_ctx;
let container = project.container;
ctx.turbo_tasks()
.run(async move {
project_fs_control_operation(container)
.read_strongly_consistent()
.await?
.begin_edit_transaction()
.await
})
.or_else(|e| ctx.throw_turbopack_internal_result(&e.into()))
.await
}
/// Renews only the matching source-edit transaction's bounded lease.
#[napi]
pub async fn project_renew_edit_transaction(
#[napi(ts_arg_type = "{ __napiType: \"Project\" }")] project: External<ProjectInstance>,
token: u32,
) -> napi::Result<bool> {
let ctx = &project.turbopack_ctx;
let container = project.container;
ctx.turbo_tasks()
.run(async move {
project_fs_control_operation(container)
.read_strongly_consistent()
.await?
.renew_edit_transaction(token)
.await
})
.or_else(|e| ctx.throw_turbopack_internal_result(&e.into()))
.await
}
#[napi(object)]
pub struct NapiEditTransactionEndResult {
pub accepted: bool,
pub flushed: bool,
}
/// Ends a source-edit transaction. The acknowledgement reports whether the token was accepted and
/// whether this was the final active token whose invalidations were submitted before returning.
#[napi]
pub async fn project_end_edit_transaction(
#[napi(ts_arg_type = "{ __napiType: \"Project\" }")] project: External<ProjectInstance>,
token: u32,
changed_paths: Vec<String>,
) -> napi::Result<NapiEditTransactionEndResult> {
let ctx = &project.turbopack_ctx;
let container = project.container;
let changed_paths = changed_paths.into_iter().map(PathBuf::from).collect();
let (accepted, flushed) = ctx
.turbo_tasks()
.run(async move {
project_fs_control_operation(container)
.read_strongly_consistent()
.await?
.end_edit_transaction(token, changed_paths)
.await
})
.or_else(|e| ctx.throw_turbopack_internal_result(&e.into()))
.await?;
Ok(NapiEditTransactionEndResult { accepted, flushed })
}
#[tracing::instrument(level = "info", name = "update project", skip_all)]
#[napi]
pub async fn project_update(
......
......@@ -1463,5 +1463,13 @@
"1462": "Unexpected chunk emitted in Before stage",
"1463": "\\`experimental.turbopackGenerateComponentChunks\\` has been moved to \\`experimental.turbopackChunking.generateComponentChunks\\`. Please update your next.config.js file accordingly.",
"1464": "\\`experimental.turbopackChunkingHeuristics\\` has been renamed to \\`experimental.turbopackChunking\\`. Please update your next.config.js file accordingly.",
"1465": "\\`experimental.useCache\\` cannot be disabled when \\`cacheComponents\\` is enabled, because Cache Components relies on the \\`\"use cache\"\\` directive. Please remove it from %s."
"1465": "\\`experimental.useCache\\` cannot be disabled when \\`cacheComponents\\` is enabled, because Cache Components relies on the \\`\"use cache\"\\` directive. Please remove it from %s.",
"1466": "Turbopack project is not available. This tool requires the Turbopack bundler.",
"1467": "Changed path must be project-relative: %s",
"1468": "Changed path leaves the project root: %s",
"1469": "Too many active edit transactions (limit %s)",
"1470": "Changed path leaves the Turbopack filesystem root: %s",
"1471": "Edit transaction acknowledgement consumed its lease headroom; retry begin_edit_transaction",
"1472": "Changed path is watched outside the Turbopack source transaction: %s",
"1473": "Too much retained changed-path data (limit %s characters)"
}
......@@ -330,6 +330,31 @@ export declare function projectNew(
turboEngineOptions: NapiTurboEngineOptions,
napiCallbacks: NapiNextTurbopackCallbacksJsObject
): Promise<{ __napiType: 'Project' }>
/**
* Starts an explicitly acknowledged source-edit transaction. Filesystem invalidations are held
* until the matching token is ended or the watcher's safety timeout expires.
*/
export declare function projectBeginEditTransaction(project: {
__napiType: 'Project'
}): Promise<number>
/** Renews only the matching source-edit transaction's bounded lease. */
export declare function projectRenewEditTransaction(
project: { __napiType: 'Project' },
token: number
): Promise<boolean>
export interface NapiEditTransactionEndResult {
accepted: boolean
flushed: boolean
}
/**
* Ends a source-edit transaction. The acknowledgement reports whether the token was accepted and
* whether this was the final active token whose invalidations were submitted before returning.
*/
export declare function projectEndEditTransaction(
project: { __napiType: 'Project' },
token: number,
changedPaths: Array<string>
): Promise<NapiEditTransactionEndResult>
export declare function projectUpdate(
project: { __napiType: 'Project' },
options: NapiPartialProjectOptions
......
......@@ -26,6 +26,7 @@ import type {
CompilationEvent,
DefineEnv,
Endpoint,
EditTransactionEndResult,
HmrChunkNames,
Lockfile,
NodeJsHmrUpdate,
......@@ -683,6 +684,7 @@ function bindingToApi(
class ProjectImpl implements Project {
private readonly _nativeProject: { __napiType: 'Project' }
private _editTransactionControl: Promise<void> = Promise.resolve()
constructor(nativeProject: { __napiType: 'Project' }) {
this._nativeProject = nativeProject
......@@ -699,6 +701,42 @@ function bindingToApi(
)
}
private _serializeEditTransactionControl<T>(
operation: () => Promise<T>
): Promise<T> {
const result = this._editTransactionControl.then(operation, operation)
this._editTransactionControl = result.then(
() => undefined,
() => undefined
)
return result
}
beginEditTransaction(): Promise<number> {
return this._serializeEditTransactionControl(() =>
binding.projectBeginEditTransaction(this._nativeProject)
)
}
renewEditTransaction(token: number): Promise<boolean> {
return this._serializeEditTransactionControl(() =>
binding.projectRenewEditTransaction(this._nativeProject, token)
)
}
endEditTransaction(
token: number,
changedPaths: string[]
): Promise<EditTransactionEndResult> {
return this._serializeEditTransactionControl(() =>
binding.projectEndEditTransaction(
this._nativeProject,
token,
changedPaths
)
)
}
async writeAnalyzeData(
appDirOnly: boolean
): Promise<TurbopackResult<void>> {
......
......@@ -308,9 +308,33 @@ export interface UpdateInfo {
tasks: number
}
export interface EditTransactionEndResult {
accepted: boolean
flushed: boolean
}
export interface Project {
update(options: Partial<ProjectOptions>): Promise<void>
/**
* Begin a source-edit transaction and wait until the filesystem watcher has acknowledged it.
* The returned token must be passed to `endEditTransaction`.
*/
beginEditTransaction(): Promise<number>
/** Renew only this source-edit transaction's bounded lease. */
renewEditTransaction(token: number): Promise<boolean>
/**
* End a source-edit transaction and explicitly invalidate the controller-confirmed paths.
* The result distinguishes a rejected token, a token still held by another transaction, and the
* final token whose invalidations have been submitted.
*/
endEditTransaction(
token: number,
changedPaths: string[]
): Promise<EditTransactionEndResult>
writeAnalyzeData(appDirOnly: boolean): Promise<TurbopackResult<void>>
getAllCompilationIssues(): Promise<TurbopackResult<void>>
......
......@@ -6,6 +6,7 @@ import { registerGetLogsTool } from './tools/get-logs'
import { registerGetActionByIdTool } from './tools/get-server-action-by-id'
import { registerGetRoutesTool } from './tools/get-routes'
import { registerGetCompilationIssuesTool } from './tools/get-compilation-issues'
import { registerEditTransactionTools } from './tools/edit-transaction'
import { registerCompileRouteTool } from './tools/compile-route'
import { registerGetRequestInsightsTool } from './tools/get-request-insights'
import type { HmrMessageSentToBrowser } from '../dev/hot-reloader-types'
......@@ -68,6 +69,23 @@ export const getOrCreateMcpServer = (options: McpServerOptions) => {
if (options.getTurbopackProject) {
registerGetCompilationIssuesTool(mcpServer, options.getTurbopackProject)
if (process.env.__NEXT_EXPERIMENTAL_EDIT_TRANSACTIONS === 'true') {
const turbopackRoot =
options.nextConfig.turbopack?.root ||
options.nextConfig.outputFileTracingRoot ||
options.projectPath
registerEditTransactionTools(
mcpServer,
options.projectPath,
turbopackRoot,
{
appDir: options.appDir,
pagesDir: options.pagesDir,
pageExtensions: options.nextConfig.pageExtensions,
},
options.getTurbopackProject
)
}
}
if (options.compileRoute) {
......
This diff is collapsed.
This diff is collapsed.
......@@ -283,6 +283,9 @@ export type McpToolName =
| 'mcp/get_server_action_by_id'
| 'mcp/get_compilation_issues'
| 'mcp/compile_route'
| 'mcp/begin_edit_transaction'
| 'mcp/renew_edit_transaction'
| 'mcp/end_edit_transaction'
export type EventMcpToolUsage = {
toolName: McpToolName
......
......@@ -82,6 +82,9 @@ describe('MCP Telemetry Events', () => {
'mcp/get_server_action_by_id',
'mcp/get_compilation_issues',
'mcp/compile_route',
'mcp/begin_edit_transaction',
'mcp/renew_edit_transaction',
'mcp/end_edit_transaction',
]
const usages = allTools.map((tool, index) => ({
......@@ -91,7 +94,7 @@ describe('MCP Telemetry Events', () => {
const events = eventMcpToolUsage(usages)
expect(events).toHaveLength(9)
expect(events).toHaveLength(12)
events.forEach((event, index) => {
expect(event.eventName).toBe(EVENT_MCP_TOOL_USAGE)
......
......@@ -522,6 +522,46 @@ impl DiskFileSystem {
.await
}
pub async fn begin_edit_transaction(&self) -> Result<u32> {
self.inner.watcher.begin_edit_transaction().await
}
pub async fn renew_edit_transaction(&self, token: u32) -> Result<bool> {
self.inner.watcher.renew_edit_transaction(token).await
}
pub async fn end_edit_transaction(
&self,
token: u32,
changed_paths: Vec<PathBuf>,
) -> Result<(bool, bool)> {
let root = self.inner.root_path();
let mut absolute_changed_paths = Vec::with_capacity(changed_paths.len());
for path in changed_paths {
if path.is_absolute()
|| path.components().any(|component| {
matches!(
component,
std::path::Component::Prefix(_)
| std::path::Component::RootDir
| std::path::Component::CurDir
| std::path::Component::ParentDir
)
})
{
bail!(
"edit transaction changed path {} is not filesystem-root-relative",
path.display()
);
}
absolute_changed_paths.push(root.join(path));
}
self.inner
.watcher
.end_edit_transaction(token, absolute_changed_paths)
.await
}
pub async fn stop_watching(&self) {
self.inner.watcher.stop_watching().await;
}
......
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