Unverified Commit 6b651b0b authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

add support for instrumentation (#59070)

<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

### Improving Documentation

- Run `pnpm prettier-fix` to fix formatting issues before opening the
PR.
- Read the Docs Contribution Guide to ensure your contribution follows
the docs guidelines:
https://nextjs.org/docs/community/contribution-guide

### Adding or Updating Examples

- The "examples guidelines" are followed from our contributing doc
https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See
https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md


## For Maintainers

- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->


Closes PACK-2057
parent e17b3687
...@@ -39,8 +39,6 @@ pub struct NapiWrittenEndpoint { ...@@ -39,8 +39,6 @@ pub struct NapiWrittenEndpoint {
pub r#type: String, pub r#type: String,
pub entry_path: Option<String>, pub entry_path: Option<String>,
pub server_paths: Option<Vec<NapiServerPath>>, pub server_paths: Option<Vec<NapiServerPath>>,
pub files: Option<Vec<String>>,
pub global_var_name: Option<String>,
pub config: NapiEndpointConfig, pub config: NapiEndpointConfig,
} }
...@@ -56,15 +54,9 @@ impl From<&WrittenEndpoint> for NapiWrittenEndpoint { ...@@ -56,15 +54,9 @@ impl From<&WrittenEndpoint> for NapiWrittenEndpoint {
server_paths: Some(server_paths.iter().map(From::from).collect()), server_paths: Some(server_paths.iter().map(From::from).collect()),
..Default::default() ..Default::default()
}, },
WrittenEndpoint::Edge { WrittenEndpoint::Edge { server_paths } => Self {
files,
global_var_name,
server_paths,
} => Self {
r#type: "edge".to_string(), r#type: "edge".to_string(),
files: Some(files.clone()),
server_paths: Some(server_paths.iter().map(From::from).collect()), server_paths: Some(server_paths.iter().map(From::from).collect()),
global_var_name: Some(global_var_name.clone()),
..Default::default() ..Default::default()
}, },
} }
......
...@@ -7,7 +7,10 @@ use napi::{ ...@@ -7,7 +7,10 @@ use napi::{
JsFunction, Status, JsFunction, Status,
}; };
use next_api::{ use next_api::{
project::{DefineEnv, Middleware, PartialProjectOptions, ProjectContainer, ProjectOptions}, project::{
DefineEnv, Instrumentation, Middleware, PartialProjectOptions, ProjectContainer,
ProjectOptions,
},
route::{Endpoint, Route}, route::{Endpoint, Route},
}; };
use next_core::tracing_presets::{ use next_core::tracing_presets::{
...@@ -385,10 +388,36 @@ impl NapiMiddleware { ...@@ -385,10 +388,36 @@ impl NapiMiddleware {
}) })
} }
} }
#[napi(object)]
struct NapiInstrumentation {
pub node_js: External<ExternalEndpoint>,
pub edge: External<ExternalEndpoint>,
}
impl NapiInstrumentation {
fn from_instrumentation(
value: &Instrumentation,
turbo_tasks: &Arc<TurboTasks<MemoryBackend>>,
) -> Result<Self> {
Ok(NapiInstrumentation {
node_js: External::new(ExternalEndpoint(VcArc::new(
turbo_tasks.clone(),
value.node_js,
))),
edge: External::new(ExternalEndpoint(VcArc::new(
turbo_tasks.clone(),
value.edge,
))),
})
}
}
#[napi(object)] #[napi(object)]
struct NapiEntrypoints { struct NapiEntrypoints {
pub routes: Vec<NapiRoute>, pub routes: Vec<NapiRoute>,
pub middleware: Option<NapiMiddleware>, pub middleware: Option<NapiMiddleware>,
pub instrumentation: Option<NapiInstrumentation>,
pub pages_document_endpoint: External<ExternalEndpoint>, pub pages_document_endpoint: External<ExternalEndpoint>,
pub pages_app_endpoint: External<ExternalEndpoint>, pub pages_app_endpoint: External<ExternalEndpoint>,
pub pages_error_endpoint: External<ExternalEndpoint>, pub pages_error_endpoint: External<ExternalEndpoint>,
...@@ -430,6 +459,11 @@ pub fn project_entrypoints_subscribe( ...@@ -430,6 +459,11 @@ pub fn project_entrypoints_subscribe(
.as_ref() .as_ref()
.map(|m| NapiMiddleware::from_middleware(m, &turbo_tasks)) .map(|m| NapiMiddleware::from_middleware(m, &turbo_tasks))
.transpose()?, .transpose()?,
instrumentation: entrypoints
.instrumentation
.as_ref()
.map(|m| NapiInstrumentation::from_instrumentation(m, &turbo_tasks))
.transpose()?,
pages_document_endpoint: External::new(ExternalEndpoint(VcArc::new( pages_document_endpoint: External::new(ExternalEndpoint(VcArc::new(
turbo_tasks.clone(), turbo_tasks.clone(),
entrypoints.pages_document_endpoint, entrypoints.pages_document_endpoint,
......
...@@ -918,10 +918,10 @@ impl AppEndpoint { ...@@ -918,10 +918,10 @@ impl AppEndpoint {
}; };
let middleware_manifest_v2 = MiddlewaresManifestV2 { let middleware_manifest_v2 = MiddlewaresManifestV2 {
sorted_middleware: vec![app_entry.original_name.clone()], sorted_middleware: vec![app_entry.original_name.clone()],
middleware: Default::default(),
functions: [(app_entry.original_name.clone(), edge_function_definition)] functions: [(app_entry.original_name.clone(), edge_function_definition)]
.into_iter() .into_iter()
.collect(), .collect(),
..Default::default()
}; };
let manifest_path_prefix = get_asset_prefix_from_pathname(&app_entry.pathname); let manifest_path_prefix = get_asset_prefix_from_pathname(&app_entry.pathname);
let middleware_manifest_v2 = Vc::upcast(VirtualOutputAsset::new( let middleware_manifest_v2 = Vc::upcast(VirtualOutputAsset::new(
...@@ -1111,21 +1111,7 @@ impl Endpoint for AppEndpoint { ...@@ -1111,21 +1111,7 @@ impl Endpoint for AppEndpoint {
.to_string(), .to_string(),
server_paths, server_paths,
}, },
AppEndpointOutput::Edge { files, .. } => WrittenEndpoint::Edge { AppEndpointOutput::Edge { .. } => WrittenEndpoint::Edge { server_paths },
files: files
.await?
.iter()
.map(|&file| async move {
Ok(node_root_ref
.get_path_to(&*file.ident().path().await?)
.context("edge chunk file path must be inside the node root")?
.to_string())
})
.try_join()
.await?,
global_var_name: "TODO".to_string(),
server_paths,
},
}; };
Ok(written_endpoint.cell()) Ok(written_endpoint.cell())
} }
......
...@@ -2,7 +2,7 @@ use indexmap::IndexMap; ...@@ -2,7 +2,7 @@ use indexmap::IndexMap;
use turbo_tasks::Vc; use turbo_tasks::Vc;
use crate::{ use crate::{
project::Middleware, project::{Instrumentation, Middleware},
route::{Endpoint, Route}, route::{Endpoint, Route},
}; };
...@@ -10,6 +10,7 @@ use crate::{ ...@@ -10,6 +10,7 @@ use crate::{
pub struct Entrypoints { pub struct Entrypoints {
pub routes: IndexMap<String, Route>, pub routes: IndexMap<String, Route>,
pub middleware: Option<Middleware>, pub middleware: Option<Middleware>,
pub instrumentation: Option<Instrumentation>,
pub pages_document_endpoint: Vc<Box<dyn Endpoint>>, pub pages_document_endpoint: Vc<Box<dyn Endpoint>>,
pub pages_app_endpoint: Vc<Box<dyn Endpoint>>, pub pages_app_endpoint: Vc<Box<dyn Endpoint>>,
pub pages_error_endpoint: Vc<Box<dyn Endpoint>>, pub pages_error_endpoint: Vc<Box<dyn Endpoint>>,
......
use anyhow::{bail, Context, Result};
use next_core::{
mode::NextMode,
next_edge::entry::wrap_edge_entry,
next_manifests::{InstrumentationDefinition, MiddlewaresManifestV2},
next_server::{get_server_chunking_context, get_server_runtime_entries, ServerContextType},
};
use turbo_tasks::{Completion, TryJoinIterExt, Value, Vc};
use turbopack_binding::{
turbo::tasks_fs::{File, FileContent},
turbopack::{
core::{
asset::AssetContent,
chunk::ChunkingContext,
context::AssetContext,
module::Module,
output::{OutputAsset, OutputAssets},
virtual_output::VirtualOutputAsset,
},
ecmascript::chunk::EcmascriptChunkPlaceable,
},
};
use crate::{
project::Project,
route::{Endpoint, WrittenEndpoint},
server_paths::all_server_paths,
};
#[turbo_tasks::value]
pub struct InstrumentationEndpoint {
project: Vc<Project>,
context: Vc<Box<dyn AssetContext>>,
userland_module: Vc<Box<dyn Module>>,
is_edge: bool,
}
#[turbo_tasks::value_impl]
impl InstrumentationEndpoint {
#[turbo_tasks::function]
pub fn new(
project: Vc<Project>,
context: Vc<Box<dyn AssetContext>>,
userland_module: Vc<Box<dyn Module>>,
is_edge: bool,
) -> Vc<Self> {
Self {
project,
context,
userland_module,
is_edge,
}
.cell()
}
#[turbo_tasks::function]
async fn edge_files(&self) -> Result<Vc<OutputAssets>> {
let module = wrap_edge_entry(
self.context,
self.project.project_path(),
self.userland_module,
"instrumentation".to_string(),
);
let mut evaluatable_assets = get_server_runtime_entries(
Value::new(ServerContextType::Middleware),
NextMode::Development,
)
.resolve_entries(self.context)
.await?
.clone_value();
let Some(module) =
Vc::try_resolve_downcast::<Box<dyn EcmascriptChunkPlaceable>>(module).await?
else {
bail!("Entry module must be evaluatable");
};
let Some(evaluatable) = Vc::try_resolve_sidecast(module).await? else {
bail!("Entry module must be evaluatable");
};
evaluatable_assets.push(evaluatable);
let edge_chunking_context = self.project.edge_chunking_context();
let edge_files = edge_chunking_context
.evaluated_chunk_group(module.ident(), Vc::cell(evaluatable_assets));
Ok(edge_files)
}
#[turbo_tasks::function]
async fn node_chunk(&self) -> Result<Vc<Box<dyn OutputAsset>>> {
let chunking_context = get_server_chunking_context(
self.project.project_path(),
self.project.node_root(),
self.project.client_relative_path(),
self.project.next_config().computed_asset_prefix(),
self.project.server_compile_time_info().environment(),
);
let Some(module) = Vc::try_resolve_downcast(self.userland_module).await? else {
bail!("Entry module must be evaluatable");
};
let chunk = chunking_context.entry_chunk_group(
self.project
.node_root()
.join("server/instrumentation.js".to_string()),
module,
get_server_runtime_entries(
Value::new(ServerContextType::Instrumentation),
NextMode::Development,
)
.resolve_entries(self.context),
);
Ok(chunk)
}
#[turbo_tasks::function]
async fn output_assets(self: Vc<Self>) -> Result<Vc<OutputAssets>> {
let this = self.await?;
if this.is_edge {
let mut output_assets = self.edge_files().await?.clone_value();
let node_root = this.project.node_root();
let files_paths_from_root = {
let node_root = &node_root.await?;
output_assets
.iter()
.map(|&file| async move {
Ok(node_root
.get_path_to(&*file.ident().path().await?)
.context("middleware file path must be inside the node root")?
.to_string())
})
.try_join()
.await?
};
let instrumentation_definition = InstrumentationDefinition {
files: files_paths_from_root,
name: "instrumentation".to_string(),
..Default::default()
};
let middleware_manifest_v2 = MiddlewaresManifestV2 {
instrumentation: Some(instrumentation_definition),
..Default::default()
};
let middleware_manifest_v2 = Vc::upcast(VirtualOutputAsset::new(
node_root.join("server/instrumentation/middleware-manifest.json".to_string()),
AssetContent::file(
FileContent::Content(File::from(serde_json::to_string_pretty(
&middleware_manifest_v2,
)?))
.cell(),
),
));
output_assets.push(middleware_manifest_v2);
Ok(Vc::cell(output_assets))
} else {
Ok(Vc::cell(vec![self.node_chunk()]))
}
}
}
#[turbo_tasks::value_impl]
impl Endpoint for InstrumentationEndpoint {
#[turbo_tasks::function]
async fn write_to_disk(self: Vc<Self>) -> Result<Vc<WrittenEndpoint>> {
let this = self.await?;
let output_assets = self.output_assets();
this.project
.emit_all_output_assets(Vc::cell(output_assets))
.await?;
let node_root = this.project.node_root();
let server_paths = all_server_paths(output_assets, node_root)
.await?
.clone_value();
Ok(WrittenEndpoint::Edge { server_paths }.cell())
}
#[turbo_tasks::function]
async fn server_changed(self: Vc<Self>) -> Result<Vc<Completion>> {
Ok(self.await?.project.server_changed(self.output_assets()))
}
#[turbo_tasks::function]
fn client_changed(self: Vc<Self>) -> Vc<Completion> {
Completion::immutable()
}
}
...@@ -4,6 +4,7 @@ ...@@ -4,6 +4,7 @@
mod app; mod app;
mod dynamic_imports; mod dynamic_imports;
mod entrypoints; mod entrypoints;
mod instrumentation;
mod middleware; mod middleware;
mod pages; mod pages;
pub mod project; pub mod project;
......
...@@ -143,11 +143,10 @@ impl MiddlewareEndpoint { ...@@ -143,11 +143,10 @@ impl MiddlewareEndpoint {
..Default::default() ..Default::default()
}; };
let middleware_manifest_v2 = MiddlewaresManifestV2 { let middleware_manifest_v2 = MiddlewaresManifestV2 {
sorted_middleware: Default::default(),
middleware: [("/".to_string(), edge_function_definition)] middleware: [("/".to_string(), edge_function_definition)]
.into_iter() .into_iter()
.collect(), .collect(),
functions: Default::default(), ..Default::default()
}; };
let middleware_manifest_v2 = Vc::upcast(VirtualOutputAsset::new( let middleware_manifest_v2 = Vc::upcast(VirtualOutputAsset::new(
node_root.join("server/middleware/middleware-manifest.json".to_string()), node_root.join("server/middleware/middleware-manifest.json".to_string()),
...@@ -169,7 +168,6 @@ impl Endpoint for MiddlewareEndpoint { ...@@ -169,7 +168,6 @@ impl Endpoint for MiddlewareEndpoint {
#[turbo_tasks::function] #[turbo_tasks::function]
async fn write_to_disk(self: Vc<Self>) -> Result<Vc<WrittenEndpoint>> { async fn write_to_disk(self: Vc<Self>) -> Result<Vc<WrittenEndpoint>> {
let this = self.await?; let this = self.await?;
let files = self.edge_files();
let output_assets = self.output_assets(); let output_assets = self.output_assets();
this.project this.project
.emit_all_output_assets(Vc::cell(output_assets)) .emit_all_output_assets(Vc::cell(output_assets))
...@@ -180,26 +178,7 @@ impl Endpoint for MiddlewareEndpoint { ...@@ -180,26 +178,7 @@ impl Endpoint for MiddlewareEndpoint {
.await? .await?
.clone_value(); .clone_value();
let node_root = &node_root.await?; Ok(WrittenEndpoint::Edge { server_paths }.cell())
let files = files
.await?
.iter()
.map(|&file| async move {
Ok(node_root
.get_path_to(&*file.ident().path().await?)
.context("middleware file path must be inside the node root")?
.to_string())
})
.try_join()
.await?;
Ok(WrittenEndpoint::Edge {
files,
global_var_name: "TODO".to_string(),
server_paths,
}
.cell())
} }
#[turbo_tasks::function] #[turbo_tasks::function]
......
...@@ -1012,10 +1012,10 @@ impl PageEndpoint { ...@@ -1012,10 +1012,10 @@ impl PageEndpoint {
}; };
let middleware_manifest_v2 = MiddlewaresManifestV2 { let middleware_manifest_v2 = MiddlewaresManifestV2 {
sorted_middleware: vec![pathname.to_string()], sorted_middleware: vec![pathname.to_string()],
middleware: Default::default(),
functions: [(pathname.to_string(), edge_function_definition)] functions: [(pathname.to_string(), edge_function_definition)]
.into_iter() .into_iter()
.collect(), .collect(),
..Default::default()
}; };
let manifest_path_prefix = get_asset_prefix_from_pathname(&this.pathname.await?); let manifest_path_prefix = get_asset_prefix_from_pathname(&this.pathname.await?);
let middleware_manifest_v2 = Vc::upcast(VirtualOutputAsset::new( let middleware_manifest_v2 = Vc::upcast(VirtualOutputAsset::new(
...@@ -1081,21 +1081,7 @@ impl Endpoint for PageEndpoint { ...@@ -1081,21 +1081,7 @@ impl Endpoint for PageEndpoint {
.to_string(), .to_string(),
server_paths, server_paths,
}, },
PageEndpointOutput::Edge { files, .. } => WrittenEndpoint::Edge { PageEndpointOutput::Edge { .. } => WrittenEndpoint::Edge { server_paths },
files: files
.await?
.iter()
.map(|&file| async move {
Ok(node_root
.get_path_to(&*file.ident().path().await?)
.context("ssr chunk file path must be inside the node root")?
.to_string())
})
.try_join()
.await?,
global_var_name: "TODO".to_string(),
server_paths,
},
}; };
Ok(written_endpoint.cell()) Ok(written_endpoint.cell())
......
...@@ -7,13 +7,14 @@ use next_core::{ ...@@ -7,13 +7,14 @@ use next_core::{
app_structure::find_app_dir, app_structure::find_app_dir,
emit_assets, get_edge_chunking_context, get_edge_compile_time_info, emit_assets, get_edge_chunking_context, get_edge_compile_time_info,
get_edge_resolve_options_context, get_edge_resolve_options_context,
instrumentation::instrumentation_files,
middleware::middleware_files, middleware::middleware_files,
mode::NextMode, mode::NextMode,
next_client::{get_client_chunking_context, get_client_compile_time_info}, next_client::{get_client_chunking_context, get_client_compile_time_info},
next_config::{JsConfig, NextConfig}, next_config::{JsConfig, NextConfig},
next_server::{ next_server::{
get_server_chunking_context, get_server_compile_time_info, get_server_chunking_context, get_server_compile_time_info,
get_server_module_options_context, ServerContextType, get_server_module_options_context, get_server_resolve_options_context, ServerContextType,
}, },
next_telemetry::NextFeatureTelemetry, next_telemetry::NextFeatureTelemetry,
}; };
...@@ -57,6 +58,7 @@ use crate::{ ...@@ -57,6 +58,7 @@ use crate::{
app::{AppProject, OptionAppProject}, app::{AppProject, OptionAppProject},
build, build,
entrypoints::Entrypoints, entrypoints::Entrypoints,
instrumentation::InstrumentationEndpoint,
middleware::MiddlewareEndpoint, middleware::MiddlewareEndpoint,
pages::PagesProject, pages::PagesProject,
route::{Endpoint, Route}, route::{Endpoint, Route},
...@@ -136,6 +138,12 @@ pub struct Middleware { ...@@ -136,6 +138,12 @@ pub struct Middleware {
pub endpoint: Vc<Box<dyn Endpoint>>, pub endpoint: Vc<Box<dyn Endpoint>>,
} }
#[derive(Serialize, Deserialize, TraceRawVcs, PartialEq, Eq, ValueDebugFormat)]
pub struct Instrumentation {
pub node_js: Vc<Box<dyn Endpoint>>,
pub edge: Vc<Box<dyn Endpoint>>,
}
#[turbo_tasks::value] #[turbo_tasks::value]
pub struct ProjectContainer { pub struct ProjectContainer {
options_state: State<ProjectOptions>, options_state: State<ProjectOptions>,
...@@ -661,9 +669,34 @@ impl Project { ...@@ -661,9 +669,34 @@ impl Project {
None None
}; };
let instrumentation = find_context_file(
self.project_path(),
instrumentation_files(self.next_config().page_extensions()),
);
let instrumentation = if let FindContextFileResult::Found(fs_path, _) =
*instrumentation.await?
{
let source = Vc::upcast(FileSource::new(fs_path));
Some(Instrumentation {
node_js: TraitRef::cell(
Vc::upcast::<Box<dyn Endpoint>>(self.instrumentation_endpoint(source, false))
.into_trait_ref()
.await?,
),
edge: TraitRef::cell(
Vc::upcast::<Box<dyn Endpoint>>(self.instrumentation_endpoint(source, true))
.into_trait_ref()
.await?,
),
})
} else {
None
};
Ok(Entrypoints { Ok(Entrypoints {
routes, routes,
middleware, middleware,
instrumentation,
pages_document_endpoint, pages_document_endpoint,
pages_app_endpoint, pages_app_endpoint,
pages_error_endpoint, pages_error_endpoint,
...@@ -706,6 +739,49 @@ impl Project { ...@@ -706,6 +739,49 @@ impl Project {
MiddlewareEndpoint::new(self, context, module) MiddlewareEndpoint::new(self, context, module)
} }
#[turbo_tasks::function]
fn node_instrumentation_context(self: Vc<Self>) -> Vc<Box<dyn AssetContext>> {
Vc::upcast(ModuleAssetContext::new(
Default::default(),
self.server_compile_time_info(),
get_server_module_options_context(
self.project_path(),
self.execution_context(),
Value::new(ServerContextType::Instrumentation),
NextMode::Development,
self.next_config(),
),
get_server_resolve_options_context(
self.project_path(),
Value::new(ServerContextType::Instrumentation),
NextMode::Development,
self.next_config(),
self.execution_context(),
),
Vc::cell("instrumentation".to_string()),
))
}
#[turbo_tasks::function]
fn instrumentation_endpoint(
self: Vc<Self>,
source: Vc<Box<dyn Source>>,
is_edge: bool,
) -> Vc<InstrumentationEndpoint> {
let context = if is_edge {
self.middleware_context()
} else {
self.node_instrumentation_context()
};
let module = context.process(
source,
Value::new(ReferenceType::Entry(EntryReferenceSubType::Undefined)),
);
InstrumentationEndpoint::new(self, context, module, is_edge)
}
#[turbo_tasks::function] #[turbo_tasks::function]
pub async fn emit_all_output_assets( pub async fn emit_all_output_assets(
self: Vc<Self>, self: Vc<Self>,
......
...@@ -39,9 +39,6 @@ pub enum WrittenEndpoint { ...@@ -39,9 +39,6 @@ pub enum WrittenEndpoint {
server_paths: Vec<ServerPath>, server_paths: Vec<ServerPath>,
}, },
Edge { Edge {
/// Relative to the root_path
files: Vec<String>,
global_var_name: String,
server_paths: Vec<ServerPath>, server_paths: Vec<ServerPath>,
}, },
} }
......
use anyhow::Result;
use turbo_tasks::Vc;
#[turbo_tasks::function]
pub async fn instrumentation_files(page_extensions: Vc<Vec<String>>) -> Result<Vc<Vec<String>>> {
let extensions = page_extensions.await?;
let files = ["instrumentation.", "src/instrumentation."]
.into_iter()
.flat_map(|f| {
extensions
.iter()
.map(move |ext| String::from(f) + ext.as_str())
})
.collect();
Ok(Vc::cell(files))
}
...@@ -11,6 +11,7 @@ mod babel; ...@@ -11,6 +11,7 @@ mod babel;
mod bootstrap; mod bootstrap;
mod embed_js; mod embed_js;
mod emit; mod emit;
pub mod instrumentation;
mod loader_tree; mod loader_tree;
pub mod middleware; pub mod middleware;
pub mod mode; pub mod mode;
......
...@@ -117,7 +117,8 @@ pub async fn get_edge_resolve_options_context( ...@@ -117,7 +117,8 @@ pub async fn get_edge_resolve_options_context(
| ServerContextType::PagesData { .. } | ServerContextType::PagesData { .. }
| ServerContextType::PagesApi { .. } | ServerContextType::PagesApi { .. }
| ServerContextType::AppSSR { .. } | ServerContextType::AppSSR { .. }
| ServerContextType::Middleware { .. } => {} | ServerContextType::Middleware { .. }
| ServerContextType::Instrumentation { .. } => {}
}; };
let resolve_options_context = ResolveOptionsContext { let resolve_options_context = ResolveOptionsContext {
......
...@@ -318,7 +318,7 @@ pub async fn get_next_server_import_map( ...@@ -318,7 +318,7 @@ pub async fn get_next_server_import_map(
request_to_import_mapping(project_path, "next/dist/shared/lib/app-dynamic"), request_to_import_mapping(project_path, "next/dist/shared/lib/app-dynamic"),
); );
} }
ServerContextType::Middleware => {} ServerContextType::Middleware | ServerContextType::Instrumentation => {}
} }
insert_next_server_special_aliases( insert_next_server_special_aliases(
...@@ -428,7 +428,7 @@ pub async fn get_next_edge_import_map( ...@@ -428,7 +428,7 @@ pub async fn get_next_edge_import_map(
request_to_import_mapping(project_path, "next/dist/shared/lib/app-dynamic"), request_to_import_mapping(project_path, "next/dist/shared/lib/app-dynamic"),
); );
} }
ServerContextType::Middleware => {} ServerContextType::Middleware | ServerContextType::Instrumentation => {}
} }
insert_next_server_special_aliases( insert_next_server_special_aliases(
...@@ -562,7 +562,7 @@ async fn insert_next_server_special_aliases( ...@@ -562,7 +562,7 @@ async fn insert_next_server_special_aliases(
rsc_aliases(import_map, project_path, ty, runtime, next_config).await?; rsc_aliases(import_map, project_path, ty, runtime, next_config).await?;
} }
ServerContextType::Middleware => {} ServerContextType::Middleware | ServerContextType::Instrumentation => {}
} }
// see https://github.com/vercel/next.js/blob/8013ef7372fc545d49dbd060461224ceb563b454/packages/next/src/build/webpack-config.ts#L1449-L1531 // see https://github.com/vercel/next.js/blob/8013ef7372fc545d49dbd060461224ceb563b454/packages/next/src/build/webpack-config.ts#L1449-L1531
...@@ -584,7 +584,8 @@ async fn insert_next_server_special_aliases( ...@@ -584,7 +584,8 @@ async fn insert_next_server_special_aliases(
// TODO: should include `ServerContextType::PagesApi` routes, but that type doesn't exist. // TODO: should include `ServerContextType::PagesApi` routes, but that type doesn't exist.
ServerContextType::AppRSC { .. } ServerContextType::AppRSC { .. }
| ServerContextType::AppRoute { .. } | ServerContextType::AppRoute { .. }
| ServerContextType::Middleware => { | ServerContextType::Middleware
| ServerContextType::Instrumentation => {
insert_exact_alias_map( insert_exact_alias_map(
import_map, import_map,
project_path, project_path,
......
...@@ -29,6 +29,7 @@ pub struct BuildManifest { ...@@ -29,6 +29,7 @@ pub struct BuildManifest {
#[derive(Serialize, Debug)] #[derive(Serialize, Debug)]
#[serde(rename_all = "camelCase", tag = "version")] #[serde(rename_all = "camelCase", tag = "version")]
#[allow(clippy::large_enum_variant)]
pub enum MiddlewaresManifest { pub enum MiddlewaresManifest {
#[serde(rename = "2")] #[serde(rename = "2")]
MiddlewaresManifestV2(MiddlewaresManifestV2), MiddlewaresManifestV2(MiddlewaresManifestV2),
...@@ -100,6 +101,18 @@ pub struct EdgeFunctionDefinition { ...@@ -100,6 +101,18 @@ pub struct EdgeFunctionDefinition {
pub regions: Option<Regions>, pub regions: Option<Regions>,
} }
#[derive(Serialize, Default, Debug)]
pub struct InstrumentationDefinition {
pub files: Vec<String>,
pub name: String,
// TODO: AssetBinding[]
#[serde(skip_serializing_if = "Option::is_none")]
pub wasm: Option<Vec<()>>,
// TODO: AssetBinding[]
#[serde(skip_serializing_if = "Option::is_none")]
pub assets: Option<Vec<()>>,
}
#[derive(Serialize, Debug)] #[derive(Serialize, Debug)]
#[serde(untagged)] #[serde(untagged)]
pub enum Regions { pub enum Regions {
...@@ -111,6 +124,7 @@ pub enum Regions { ...@@ -111,6 +124,7 @@ pub enum Regions {
pub struct MiddlewaresManifestV2 { pub struct MiddlewaresManifestV2 {
pub sorted_middleware: Vec<String>, pub sorted_middleware: Vec<String>,
pub middleware: HashMap<String, EdgeFunctionDefinition>, pub middleware: HashMap<String, EdgeFunctionDefinition>,
pub instrumentation: Option<InstrumentationDefinition>,
pub functions: HashMap<String, EdgeFunctionDefinition>, pub functions: HashMap<String, EdgeFunctionDefinition>,
} }
......
...@@ -90,6 +90,7 @@ pub enum ServerContextType { ...@@ -90,6 +90,7 @@ pub enum ServerContextType {
app_dir: Vc<FileSystemPath>, app_dir: Vc<FileSystemPath>,
}, },
Middleware, Middleware,
Instrumentation,
} }
#[turbo_tasks::function] #[turbo_tasks::function]
...@@ -140,7 +141,8 @@ pub async fn get_server_resolve_options_context( ...@@ -140,7 +141,8 @@ pub async fn get_server_resolve_options_context(
| ServerContextType::PagesData { .. } | ServerContextType::PagesData { .. }
| ServerContextType::PagesApi { .. } | ServerContextType::PagesApi { .. }
| ServerContextType::AppSSR { .. } | ServerContextType::AppSSR { .. }
| ServerContextType::Middleware { .. } => {} | ServerContextType::Middleware { .. }
| ServerContextType::Instrumentation { .. } => {}
}; };
let external_cjs_modules_plugin = ExternalCjsModulesResolvePlugin::new( let external_cjs_modules_plugin = ExternalCjsModulesResolvePlugin::new(
project_path, project_path,
...@@ -168,8 +170,7 @@ pub async fn get_server_resolve_options_context( ...@@ -168,8 +170,7 @@ pub async fn get_server_resolve_options_context(
} }
ServerContextType::AppSSR { .. } ServerContextType::AppSSR { .. }
| ServerContextType::AppRSC { .. } | ServerContextType::AppRSC { .. }
| ServerContextType::AppRoute { .. } | ServerContextType::AppRoute { .. } => {
| ServerContextType::Middleware { .. } => {
vec![ vec![
Vc::upcast(module_feature_report_resolve_plugin), Vc::upcast(module_feature_report_resolve_plugin),
Vc::upcast(server_component_externals_plugin), Vc::upcast(server_component_externals_plugin),
...@@ -178,6 +179,21 @@ pub async fn get_server_resolve_options_context( ...@@ -178,6 +179,21 @@ pub async fn get_server_resolve_options_context(
Vc::upcast(next_node_shared_runtime_plugin), Vc::upcast(next_node_shared_runtime_plugin),
] ]
} }
ServerContextType::Middleware { .. } => {
vec![
Vc::upcast(module_feature_report_resolve_plugin),
Vc::upcast(unsupported_modules_resolve_plugin),
Vc::upcast(next_node_shared_runtime_plugin),
]
}
ServerContextType::Instrumentation { .. } => {
vec![
Vc::upcast(module_feature_report_resolve_plugin),
Vc::upcast(unsupported_modules_resolve_plugin),
Vc::upcast(next_external_plugin),
Vc::upcast(next_node_shared_runtime_plugin),
]
}
}; };
let resolve_options_context = ResolveOptionsContext { let resolve_options_context = ResolveOptionsContext {
enable_node_modules: Some(root_dir), enable_node_modules: Some(root_dir),
...@@ -594,7 +610,7 @@ pub async fn get_server_module_options_context( ...@@ -594,7 +610,7 @@ pub async fn get_server_module_options_context(
..module_options_context ..module_options_context
} }
} }
ServerContextType::Middleware => { ServerContextType::Middleware | ServerContextType::Instrumentation => {
let mut base_source_transforms: Vec<Vc<TransformPlugin>> = vec![ let mut base_source_transforms: Vec<Vc<TransformPlugin>> = vec![
styled_components_transform_plugin, styled_components_transform_plugin,
styled_jsx_transform_plugin, styled_jsx_transform_plugin,
......
...@@ -68,7 +68,9 @@ pub async fn get_next_server_transforms_rules( ...@@ -68,7 +68,9 @@ pub async fn get_next_server_transforms_rules(
(true, None) (true, None)
} }
ServerContextType::AppRoute { .. } => (false, None), ServerContextType::AppRoute { .. } => (false, None),
ServerContextType::Middleware { .. } => (false, None), ServerContextType::Middleware { .. } | ServerContextType::Instrumentation { .. } => {
(false, None)
}
}; };
rules.push( rules.push(
...@@ -112,6 +114,7 @@ pub async fn get_next_server_internal_transforms_rules( ...@@ -112,6 +114,7 @@ pub async fn get_next_server_internal_transforms_rules(
} }
ServerContextType::AppRoute { .. } => {} ServerContextType::AppRoute { .. } => {}
ServerContextType::Middleware { .. } => {} ServerContextType::Middleware { .. } => {}
ServerContextType::Instrumentation { .. } => {}
}; };
Ok(rules) Ok(rules)
......
...@@ -531,9 +531,15 @@ export interface Middleware { ...@@ -531,9 +531,15 @@ export interface Middleware {
endpoint: Endpoint endpoint: Endpoint
} }
export interface Instrumentation {
nodeJs: Endpoint
edge: Endpoint
}
export interface Entrypoints { export interface Entrypoints {
routes: Map<string, Route> routes: Map<string, Route>
middleware?: Middleware middleware?: Middleware
instrumentation?: Instrumentation
pagesDocumentEndpoint: Endpoint pagesDocumentEndpoint: Endpoint
pagesAppEndpoint: Endpoint pagesAppEndpoint: Endpoint
pagesErrorEndpoint: Endpoint pagesErrorEndpoint: Endpoint
...@@ -648,10 +654,8 @@ export type WrittenEndpoint = ...@@ -648,10 +654,8 @@ export type WrittenEndpoint =
} }
| { | {
type: 'edge' type: 'edge'
files: string[]
/** All server paths that has been written for the endpoint. */ /** All server paths that has been written for the endpoint. */
serverPaths: ServerPath[] serverPaths: ServerPath[]
globalVarName: string
config: EndpointConfig config: EndpointConfig
} }
...@@ -797,6 +801,7 @@ function bindingToApi(binding: any, _wasm: boolean) { ...@@ -797,6 +801,7 @@ function bindingToApi(binding: any, _wasm: boolean) {
type NapiEntrypoints = { type NapiEntrypoints = {
routes: NapiRoute[] routes: NapiRoute[]
middleware?: NapiMiddleware middleware?: NapiMiddleware
instrumentation?: NapiInstrumentation
pagesDocumentEndpoint: NapiEndpoint pagesDocumentEndpoint: NapiEndpoint
pagesAppEndpoint: NapiEndpoint pagesAppEndpoint: NapiEndpoint
pagesErrorEndpoint: NapiEndpoint pagesErrorEndpoint: NapiEndpoint
...@@ -808,6 +813,11 @@ function bindingToApi(binding: any, _wasm: boolean) { ...@@ -808,6 +813,11 @@ function bindingToApi(binding: any, _wasm: boolean) {
matcher?: string[] matcher?: string[]
} }
type NapiInstrumentation = {
nodeJs: NapiEndpoint
edge: NapiEndpoint
}
type NapiRoute = { type NapiRoute = {
pathname: string pathname: string
} & ( } & (
...@@ -894,9 +904,19 @@ function bindingToApi(binding: any, _wasm: boolean) { ...@@ -894,9 +904,19 @@ function bindingToApi(binding: any, _wasm: boolean) {
const middleware = entrypoints.middleware const middleware = entrypoints.middleware
? napiMiddlewareToMiddleware(entrypoints.middleware) ? napiMiddlewareToMiddleware(entrypoints.middleware)
: undefined : undefined
const napiInstrumentationToInstrumentation = (
instrumentation: NapiInstrumentation
) => ({
nodeJs: new EndpointImpl(instrumentation.nodeJs),
edge: new EndpointImpl(instrumentation.edge),
})
const instrumentation = entrypoints.instrumentation
? napiInstrumentationToInstrumentation(entrypoints.instrumentation)
: undefined
yield { yield {
routes, routes,
middleware, middleware,
instrumentation,
pagesDocumentEndpoint: new EndpointImpl( pagesDocumentEndpoint: new EndpointImpl(
entrypoints.pagesDocumentEndpoint entrypoints.pagesDocumentEndpoint
), ),
......
...@@ -68,6 +68,7 @@ const supportedTurbopackNextConfigOptions = [ ...@@ -68,6 +68,7 @@ const supportedTurbopackNextConfigOptions = [
'experimental.deploymentId', 'experimental.deploymentId',
'experimental.useLightningcss', 'experimental.useLightningcss',
'experimental.windowHistorySupport', 'experimental.windowHistorySupport',
'experimental.instrumentationHook',
// Experimental options that don't affect compilation // Experimental options that don't affect compilation
'experimental.ppr', 'experimental.ppr',
...@@ -106,7 +107,6 @@ const supportedTurbopackNextConfigOptions = [ ...@@ -106,7 +107,6 @@ const supportedTurbopackNextConfigOptions = [
// 'compiler.removeConsole', // 'compiler.removeConsole',
// 'compiler.styledComponents', // 'compiler.styledComponents',
// 'experimental.fetchCacheKeyPrefix', // 'experimental.fetchCacheKeyPrefix',
// 'experimental.instrumentationHook',
// Left to be implemented // Left to be implemented
'excludeDefaultMomentLocales', 'excludeDefaultMomentLocales',
......
...@@ -573,13 +573,18 @@ async function startWatcher(opts: SetupOpts) { ...@@ -573,13 +573,18 @@ async function startWatcher(opts: SetupOpts) {
async function loadPartialManifest<T>( async function loadPartialManifest<T>(
name: string, name: string,
pageName: string, pageName: string,
type: 'pages' | 'app' | 'app-route' | 'middleware' = 'pages' type:
| 'pages'
| 'app'
| 'app-route'
| 'middleware'
| 'instrumentation' = 'pages'
): Promise<T> { ): Promise<T> {
const manifestPath = path.posix.join( const manifestPath = path.posix.join(
distDir, distDir,
`server`, `server`,
type === 'app-route' ? 'app' : type, type === 'app-route' ? 'app' : type,
type === 'middleware' type === 'middleware' || type === 'instrumentation'
? '' ? ''
: pageName === '/' : pageName === '/'
? 'index' ? 'index'
...@@ -594,11 +599,18 @@ async function startWatcher(opts: SetupOpts) { ...@@ -594,11 +599,18 @@ async function startWatcher(opts: SetupOpts) {
) as T ) as T
} }
type TurbopackMiddlewareManifest = MiddlewareManifest & {
instrumentation?: {
files: string[]
name: 'instrumentation'
}
}
const buildManifests = new Map<string, BuildManifest>() const buildManifests = new Map<string, BuildManifest>()
const appBuildManifests = new Map<string, AppBuildManifest>() const appBuildManifests = new Map<string, AppBuildManifest>()
const pagesManifests = new Map<string, PagesManifest>() const pagesManifests = new Map<string, PagesManifest>()
const appPathsManifests = new Map<string, PagesManifest>() const appPathsManifests = new Map<string, PagesManifest>()
const middlewareManifests = new Map<string, MiddlewareManifest>() const middlewareManifests = new Map<string, TurbopackMiddlewareManifest>()
const actionManifests = new Map<string, ActionManifest>() const actionManifests = new Map<string, ActionManifest>()
const clientToHmrSubscription = new Map< const clientToHmrSubscription = new Map<
ws, ws,
...@@ -609,7 +621,7 @@ async function startWatcher(opts: SetupOpts) { ...@@ -609,7 +621,7 @@ async function startWatcher(opts: SetupOpts) {
async function loadMiddlewareManifest( async function loadMiddlewareManifest(
pageName: string, pageName: string,
type: 'pages' | 'app' | 'app-route' | 'middleware' type: 'pages' | 'app' | 'app-route' | 'middleware' | 'instrumentation'
): Promise<void> { ): Promise<void> {
middlewareManifests.set( middlewareManifests.set(
pageName, pageName,
...@@ -751,7 +763,7 @@ async function startWatcher(opts: SetupOpts) { ...@@ -751,7 +763,7 @@ async function startWatcher(opts: SetupOpts) {
} }
function mergeMiddlewareManifests( function mergeMiddlewareManifests(
manifests: Iterable<MiddlewareManifest> manifests: Iterable<TurbopackMiddlewareManifest>
): MiddlewareManifest { ): MiddlewareManifest {
const manifest: MiddlewareManifest = { const manifest: MiddlewareManifest = {
version: 2, version: 2,
...@@ -759,13 +771,20 @@ async function startWatcher(opts: SetupOpts) { ...@@ -759,13 +771,20 @@ async function startWatcher(opts: SetupOpts) {
sortedMiddleware: [], sortedMiddleware: [],
functions: {}, functions: {},
} }
let instrumentation = undefined
for (const m of manifests) { for (const m of manifests) {
Object.assign(manifest.functions, m.functions) Object.assign(manifest.functions, m.functions)
Object.assign(manifest.middleware, m.middleware) Object.assign(manifest.middleware, m.middleware)
if (m.instrumentation) {
instrumentation = m.instrumentation
}
} }
for (const fun of Object.values(manifest.functions).concat( for (const fun of Object.values(manifest.functions).concat(
Object.values(manifest.middleware) Object.values(manifest.middleware)
)) { )) {
if (instrumentation) {
fun.files.unshift(...instrumentation.files)
}
for (const matcher of fun.matchers) { for (const matcher of fun.matchers) {
if (!matcher.regexp) { if (!matcher.regexp) {
matcher.regexp = pathToRegexp(matcher.originalSource, [], { matcher.regexp = pathToRegexp(matcher.originalSource, [], {
...@@ -777,6 +796,7 @@ async function startWatcher(opts: SetupOpts) { ...@@ -777,6 +796,7 @@ async function startWatcher(opts: SetupOpts) {
} }
} }
manifest.sortedMiddleware = Object.keys(manifest.middleware) manifest.sortedMiddleware = Object.keys(manifest.middleware)
return manifest return manifest
} }
...@@ -1091,7 +1111,7 @@ async function startWatcher(opts: SetupOpts) { ...@@ -1091,7 +1111,7 @@ async function startWatcher(opts: SetupOpts) {
} }
} }
const { middleware } = entrypoints const { middleware, instrumentation } = entrypoints
// We check for explicit true/false, since it's initialized to // We check for explicit true/false, since it's initialized to
// undefined during the first loop (middlewareChanges event is // undefined during the first loop (middlewareChanges event is
// unnecessary during the first serve) // unnecessary during the first serve)
...@@ -1107,6 +1127,43 @@ async function startWatcher(opts: SetupOpts) { ...@@ -1107,6 +1127,43 @@ async function startWatcher(opts: SetupOpts) {
event: HMR_ACTIONS_SENT_TO_BROWSER.MIDDLEWARE_CHANGES, event: HMR_ACTIONS_SENT_TO_BROWSER.MIDDLEWARE_CHANGES,
}) })
} }
if (instrumentation) {
const processInstrumentation = async (
displayName: string,
name: string,
prop: 'nodeJs' | 'edge'
) => {
const writtenEndpoint = await processResult(
displayName,
await instrumentation[prop].writeToDisk()
)
processIssues(displayName, name, writtenEndpoint)
}
await processInstrumentation(
'instrumentation (node.js)',
'instrumentation.nodeJs',
'nodeJs'
)
await processInstrumentation(
'instrumentation (edge)',
'instrumentation.edge',
'edge'
)
await loadMiddlewareManifest('instrumentation', 'instrumentation')
NextBuildContext.hasInstrumentationHook = true
serverFields.actualInstrumentationHookFile = '/instrumentation'
await propagateServerField(
'actualInstrumentationHookFile',
serverFields.actualInstrumentationHookFile
)
} else {
NextBuildContext.hasInstrumentationHook = false
serverFields.actualInstrumentationHookFile = undefined
await propagateServerField(
'actualInstrumentationHookFile',
serverFields.actualInstrumentationHookFile
)
}
if (middleware) { if (middleware) {
const processMiddleware = async () => { const processMiddleware = async () => {
const writtenEndpoint = await processResult( const writtenEndpoint = await processResult(
...@@ -1418,6 +1475,8 @@ async function startWatcher(opts: SetupOpts) { ...@@ -1418,6 +1475,8 @@ async function startWatcher(opts: SetupOpts) {
if (page === '/_document') return if (page === '/_document') return
if (page === '/middleware') return if (page === '/middleware') return
if (page === '/src/middleware') return if (page === '/src/middleware') return
if (page === '/instrumentation') return
if (page === '/src/instrumentation') return
throw new PageNotFoundError(`route not found ${page}`) throw new PageNotFoundError(`route not found ${page}`)
} }
......
import { createNextDescribe } from 'e2e-utils' import { createNextDescribe } from 'e2e-utils'
import { check } from 'next-test-utils' import { check } from 'next-test-utils'
;(process.env.TURBOPACK ? describe.skip : describe)( describe('instrumentation-hook-rsc', () => {
'instrumentation-hook-rsc', createNextDescribe(
() => { 'instrumentation',
createNextDescribe( {
'instrumentation', files: __dirname,
{ nextConfig: {
files: __dirname, experimental: {
nextConfig: { instrumentationHook: true,
experimental: {
instrumentationHook: true,
},
}, },
skipDeployment: true,
}, },
({ next, isNextDev }) => { skipDeployment: true,
it('should run the instrumentation hook', async () => { },
({ next, isNextDev }) => {
it('should run the instrumentation hook', async () => {
await next.render('/')
await check(() => next.cliOutput, /instrumentation hook/)
})
it('should not overlap with a instrumentation page', async () => {
const page = await next.render('/instrumentation')
expect(page).toContain('Hello')
})
it('should run the edge instrumentation compiled version with the edge runtime', async () => {
await next.render('/edge')
await check(() => next.cliOutput, /instrumentation hook on the edge/)
})
if (isNextDev) {
// TODO: Implement handling for changing the instrument file.
it.skip('should reload the server when the instrumentation hook changes', async () => {
await next.render('/') await next.render('/')
await check(() => next.cliOutput, /instrumentation hook/) await next.patchFile(
'./src/instrumentation.js',
`export function register() {console.log('toast')}`
)
await check(() => next.cliOutput, /toast/)
await next.renameFile(
'./src/instrumentation.js',
'./src/instrumentation.js.bak'
)
await check(
() => next.cliOutput,
/The instrumentation file has been removed/
)
await next.patchFile(
'./src/instrumentation.js.bak',
`export function register() {console.log('bread')}`
)
await next.renameFile(
'./src/instrumentation.js.bak',
'./src/instrumentation.js'
)
await check(
() => next.cliOutput,
/The instrumentation file was added/
)
await check(() => next.cliOutput, /bread/)
}) })
it('should not overlap with a instrumentation page', async () => {
const page = await next.render('/instrumentation')
expect(page).toContain('Hello')
})
it('should run the edge instrumentation compiled version with the edge runtime', async () => {
await next.render('/edge')
await check(() => next.cliOutput, /instrumentation hook on the edge/)
})
if (isNextDev) {
// TODO: Implement handling for changing the instrument file.
it.skip('should reload the server when the instrumentation hook changes', async () => {
await next.render('/')
await next.patchFile(
'./src/instrumentation.js',
`export function register() {console.log('toast')}`
)
await check(() => next.cliOutput, /toast/)
await next.renameFile(
'./src/instrumentation.js',
'./src/instrumentation.js.bak'
)
await check(
() => next.cliOutput,
/The instrumentation file has been removed/
)
await next.patchFile(
'./src/instrumentation.js.bak',
`export function register() {console.log('bread')}`
)
await next.renameFile(
'./src/instrumentation.js.bak',
'./src/instrumentation.js'
)
await check(
() => next.cliOutput,
/The instrumentation file was added/
)
await check(() => next.cliOutput, /bread/)
})
}
} }
) }
} )
) })
...@@ -20,123 +20,117 @@ const describeCase = ( ...@@ -20,123 +20,117 @@ const describeCase = (
callback callback
) )
} }
;(process.env.TURBOPACK ? describe.skip : describe)( describe('Instrumentation Hook', () => {
'Instrumentation Hook', // TODO: investigate the failure with esm import
() => { // createNextDescribe(
// TODO: investigate the failure with esm import // 'with-esm-import',
// createNextDescribe( // {
// 'with-esm-import', // files: path.join(__dirname, 'with-esm-import'),
// { // nextConfig: {
// files: path.join(__dirname, 'with-esm-import'), // experimental: {
// nextConfig: { // instrumentationHook: true,
// experimental: { // },
// instrumentationHook: true, // },
// }, // dependencies: {
// }, // // This test is mostly for compatibility with this package
// dependencies: { // '@vercel/otel': 'latest',
// // This test is mostly for compatibility with this package // },
// '@vercel/otel': 'latest', // skipDeployment: true,
// }, // },
// skipDeployment: true, // ({ next }) => {
// }, // eslint-disable-next-line jest/no-commented-out-tests
// ({ next }) => { // it('with-esm-import should run the instrumentation hook', async () => {
// eslint-disable-next-line jest/no-commented-out-tests // await next.render('/')
// it('with-esm-import should run the instrumentation hook', async () => { // await check(
// await next.render('/') // () => next.cliOutput,
// await check( // /register in instrumentation\.js is running/
// () => next.cliOutput, // )
// /register in instrumentation\.js is running/ // })
// ) // }
// }) // )
// }
// )
describeCase('with-middleware', ({ next }) => { describeCase('with-middleware', ({ next }) => {
it('with-middleware should run the instrumentation hook', async () => { it('with-middleware should run the instrumentation hook', async () => {
await next.render('/') await next.render('/')
await check(() => next.cliOutput, /instrumentation hook on the edge/) await check(() => next.cliOutput, /instrumentation hook on the edge/)
})
}) })
})
describeCase('with-edge-api', ({ next }) => { describeCase('with-edge-api', ({ next }) => {
it('with-edge-api should run the instrumentation hook', async () => { it('with-edge-api should run the instrumentation hook', async () => {
await next.render('/api') await next.render('/api')
await check(() => next.cliOutput, /instrumentation hook on the edge/) await check(() => next.cliOutput, /instrumentation hook on the edge/)
})
}) })
})
describeCase('with-edge-page', ({ next }) => { describeCase('with-edge-page', ({ next }) => {
it('with-edge-page should run the instrumentation hook', async () => { it('with-edge-page should run the instrumentation hook', async () => {
await next.render('/') await next.render('/')
await check(() => next.cliOutput, /instrumentation hook on the edge/) await check(() => next.cliOutput, /instrumentation hook on the edge/)
})
}) })
})
describeCase('with-node-api', ({ next }) => { describeCase('with-node-api', ({ next }) => {
it('with-node-api should run the instrumentation hook', async () => { it('with-node-api should run the instrumentation hook', async () => {
await next.render('/api') await next.render('/api')
await check(() => next.cliOutput, /instrumentation hook on nodejs/) await check(() => next.cliOutput, /instrumentation hook on nodejs/)
})
}) })
})
describeCase('with-node-page', ({ next }) => { describeCase('with-node-page', ({ next }) => {
it('with-node-page should run the instrumentation hook', async () => { it('with-node-page should run the instrumentation hook', async () => {
await next.render('/') await next.render('/')
await check(() => next.cliOutput, /instrumentation hook on nodejs/) await check(() => next.cliOutput, /instrumentation hook on nodejs/)
})
}) })
})
describeCase('with-async-node-page', ({ next }) => { describeCase('with-async-node-page', ({ next }) => {
it('with-async-node-page should run the instrumentation hook', async () => { it('with-async-node-page should run the instrumentation hook', async () => {
const page = await next.render('/') const page = await next.render('/')
expect(page).toContain('Node - finished: true') expect(page).toContain('Node - finished: true')
})
}) })
})
describeCase('with-async-edge-page', ({ next }) => { describeCase('with-async-edge-page', ({ next }) => {
it('with-async-edge-page should run the instrumentation hook', async () => { it('with-async-edge-page should run the instrumentation hook', async () => {
const page = await next.render('/') const page = await next.render('/')
expect(page).toContain('Edge - finished: true') expect(page).toContain('Edge - finished: true')
})
}) })
})
describeCase('general', ({ next, isNextDev }) => { describeCase('general', ({ next, isNextDev }) => {
it('should not overlap with a instrumentation page', async () => { it('should not overlap with a instrumentation page', async () => {
const page = await next.render('/instrumentation') const page = await next.render('/instrumentation')
expect(page).toContain('Hello') expect(page).toContain('Hello')
})
if (isNextDev) {
// TODO: Implement handling for changing the instrument file.
it.skip('should reload the server when the instrumentation hook changes', async () => {
await next.render('/')
await next.patchFile(
'./instrumentation.js',
`export function register() {console.log('toast')}`
)
await check(() => next.cliOutput, /toast/)
await next.renameFile(
'./instrumentation.js',
'./instrumentation.js.bak'
)
await check(
() => next.cliOutput,
/The instrumentation file has been removed/
)
await next.patchFile(
'./instrumentation.js.bak',
`export function register() {console.log('bread')}`
)
await next.renameFile(
'./instrumentation.js.bak',
'./instrumentation.js'
)
await check(
() => next.cliOutput,
/The instrumentation file was added/
)
await check(() => next.cliOutput, /bread/)
})
}
}) })
} if (isNextDev) {
) // TODO: Implement handling for changing the instrument file.
it.skip('should reload the server when the instrumentation hook changes', async () => {
await next.render('/')
await next.patchFile(
'./instrumentation.js',
`export function register() {console.log('toast')}`
)
await check(() => next.cliOutput, /toast/)
await next.renameFile(
'./instrumentation.js',
'./instrumentation.js.bak'
)
await check(
() => next.cliOutput,
/The instrumentation file has been removed/
)
await next.patchFile(
'./instrumentation.js.bak',
`export function register() {console.log('bread')}`
)
await next.renameFile(
'./instrumentation.js.bak',
'./instrumentation.js'
)
await check(() => next.cliOutput, /The instrumentation file was added/)
await check(() => next.cliOutput, /bread/)
})
}
})
})
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