Unverified Commit 3a5d293c authored by Benjamin Woodruff's avatar Benjamin Woodruff Committed by GitHub

feat(turbopack): Log anonymized internal error (panic) information to telemetry (#81272)

## Goals

- Pass through a custom `TurbopackInternalError` type when a Rust panic or an unexpected top-level `anyhow::Error` occurs.
- Make a best-effort attempt to log a location of the error to telemetry.
  - In the case of a panic, we should have the file, line, and column where the panic occured. This could be obscured inside of a helper method, but it's better than nothing. Since this is a position in Turbopack's source code, there's zero risk of user data being included here, so it should be safe to log to telemetry.

## How it works

In previous PRs, @wbinnssmith did the following:
- Added a thread-local for storing the most recent panic information in Rust
- Added `catch_unwind` logic to intercept the panic in turbo-tasks and read the thread-local information, with care take to make sure we're reading from the same thread (not across an `await` boundary).
- Added a custom `std::error::Error` type for internal errors, with support for storing information about a source panic.
- Ensured we set up `Error::source` correctly everywhere so that you can trace an error back to the root cause (presumably a panic).

In #80881, I added a `NextTurbopackContext` type that we can extend to store additional helpers on.

In this PR:
- Adds a callback to the `Project` constructor called `throwTurbopackInternalError` that constructs and throws a custom `TurbopackInternalError`. The definition of `TurbopackInternalError` must be in JS, as we cannot reasonably define the error subclass using NAPI.
- Wraps the callback in a `ThreadsafeFunction` so that it can be called in any of our async functions.
- Replaces all the places we were previously converting to `napi::Error` with logic to run `throwTurbopackInternalError`.

In a subsequent PR, we could move more of the panic handling into JS using `throwTurbopackInternalError`.

## Testing

Added a panic and ran:

```
NEXT_TELEMETRY_DEBUG=1 pnpm next dev --turbopack examples/basic-css/
```

<img src="https://graphite-user-uploaded-assets-prod.s3.amazonaws.com/HAZVitxRNnZz8QMiPn4a/7f261d3f-351e-436a-9345-fd6e9056d20c.png" width="600">
parent f8afa172
......@@ -2321,9 +2321,9 @@ checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c"
[[package]]
name = "futures"
version = "0.3.30"
version = "0.3.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "645c6916888f6cb6350d2550b80fb63e734897a8498abe35cfb732b6487804b0"
checksum = "65bc07b1a8bc7c85c5f2e110c476c7389b4554ba72af57d8445ea63a576b0876"
dependencies = [
"futures-channel",
"futures-core",
......@@ -2352,9 +2352,9 @@ checksum = "05f29059c0c2090612e8d742178b0580d2dc940c837851ad723096f87af6663e"
[[package]]
name = "futures-executor"
version = "0.3.30"
version = "0.3.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a576fc72ae164fca6b9db127eaa9a9dda0d61316034f33a0a0d4eda41f02b01d"
checksum = "1e28d1d997f585e54aebc3f97d39e72338912123a67330d723fdbb564d646c9f"
dependencies = [
"futures-core",
"futures-task",
......@@ -4415,6 +4415,7 @@ dependencies = [
"console-subscriber",
"dhat",
"either",
"futures-util",
"getrandom 0.2.15",
"iana-time-zone",
"lightningcss-napi",
......
......@@ -349,7 +349,8 @@ dhat = { version = "0.3.2" }
dunce = "1.0.3"
either = "1.9.0"
erased-serde = "0.4.5"
futures = "0.3.26"
futures = "0.3.31"
futures-util = "0.3.31"
futures-retry = "0.6.0"
hashbrown = "0.14.5"
image = { version = "0.25.0", default-features = false }
......
......@@ -58,6 +58,7 @@ anyhow = "1.0.66"
console-subscriber = { workspace = true, optional = true }
dhat = { workspace = true, optional = true }
either = { workspace = true }
futures-util = { workspace = true }
owo-colors = { workspace = true }
napi = { workspace = true }
napi-derive = "2"
......
use std::{ops::Deref, sync::Arc};
use anyhow::Result;
use futures_util::TryFutureExt;
use napi::{JsFunction, bindgen_prelude::External};
use next_api::{
operation::OptionEndpoint,
......@@ -12,7 +13,7 @@ use next_api::{
};
use tracing::Instrument;
use turbo_tasks::{Completion, Effects, OperationVc, ReadRef, Vc};
use turbopack_core::{diagnostics::PlainDiagnostic, error::PrettyPrintError, issue::PlainIssue};
use turbopack_core::{diagnostics::PlainDiagnostic, issue::PlainIssue};
use super::utils::{
DetachedVc, NapiDiagnostic, NapiIssue, RootTask, TurbopackResult,
......@@ -125,6 +126,7 @@ async fn get_written_endpoint_with_issues_operation(
pub async fn endpoint_write_to_disk(
#[napi(ts_arg_type = "{ __napiType: \"Endpoint\" }")] endpoint: External<ExternalEndpoint>,
) -> napi::Result<TurbopackResult<NapiWrittenEndpoint>> {
let ctx = endpoint.turbopack_ctx();
let endpoint_op = ***endpoint;
let (written, issues, diags) = endpoint
.turbopack_ctx()
......@@ -144,8 +146,8 @@ pub async fn endpoint_write_to_disk(
Ok((written.clone(), issues.clone(), diagnostics.clone()))
})
.await
.map_err(|e| napi::Error::from_reason(PrettyPrintError(&e).to_string()))?;
.or_else(|e| ctx.throw_turbopack_internal_result(&e))
.await?;
Ok(TurbopackResult {
result: NapiWrittenEndpoint::from(written.map(ReadRef::into_owned)),
issues: issues.iter().map(|i| NapiIssue::from(&**i)).collect(),
......
use std::{borrow::Cow, io::Write, path::PathBuf, sync::Arc, thread, time::Duration};
use anyhow::{Context, Result, anyhow, bail};
use futures_util::TryFutureExt;
use napi::{
JsFunction, Status,
Env, JsFunction, JsObject, Status,
bindgen_prelude::{External, within_runtime_if_available},
threadsafe_function::{ThreadsafeFunction, ThreadsafeFunctionCallMode},
};
......@@ -62,7 +63,10 @@ use url::Url;
use crate::{
next_api::{
endpoint::ExternalEndpoint,
turbopack_ctx::{NextTurboTasks, NextTurbopackContext, create_turbo_tasks},
turbopack_ctx::{
NapiNextTurbopackCallbacks, NapiNextTurbopackCallbacksJsObject, NextTurboTasks,
NextTurbopackContext, create_turbo_tasks,
},
utils::{
DetachedVc, NapiDiagnostic, NapiIssue, RootTask, TurbopackResult, get_diagnostics,
get_issues, subscribe,
......@@ -330,10 +334,14 @@ pub struct ProjectInstance {
}
#[napi(ts_return_type = "Promise<{ __napiType: \"Project\" }>")]
pub async fn project_new(
pub fn project_new(
env: Env,
options: NapiProjectOptions,
turbo_engine_options: NapiTurboEngineOptions,
) -> napi::Result<External<ProjectInstance>> {
napi_callbacks: NapiNextTurbopackCallbacksJsObject,
) -> napi::Result<JsObject> {
let napi_callbacks = NapiNextTurbopackCallbacks::from_js(napi_callbacks)?;
env.spawn_future(async move {
register();
let (exit, exit_receiver) = ExitHandler::new_receiver();
......@@ -350,8 +358,9 @@ pub async fn project_new(
.filter(|v| !v.is_empty());
if cfg!(feature = "tokio-console") && trace.is_none() {
// ensure `trace` is set to *something* so that the `tokio-console` feature works, otherwise
// you just get empty output from `tokio-console`, which can be confusing.
// ensure `trace` is set to *something* so that the `tokio-console` feature works,
// otherwise you just get empty output from `tokio-console`, which can be
// confusing.
trace = Some("overview".to_owned());
}
......@@ -423,6 +432,7 @@ pub async fn project_new(
dependency_tracking,
is_ci,
)?;
let turbopack_ctx = NextTurbopackContext::new(turbo_tasks.clone(), napi_callbacks);
let stats_path = std::env::var_os("NEXT_TURBOPACK_TASK_STATISTICS");
if let Some(stats_path) = stats_path {
......@@ -440,6 +450,7 @@ pub async fn project_new(
.unwrap();
});
}
let options: ProjectOptions = options.into();
let container = turbo_tasks
.run_once(async move {
......@@ -448,8 +459,8 @@ pub async fn project_new(
project.initialize(options).await?;
Ok(project)
})
.await
.map_err(|e| napi::Error::from_reason(PrettyPrintError(&e).to_string()))?;
.or_else(|e| turbopack_ctx.throw_turbopack_internal_result(&e))
.await?;
turbo_tasks.spawn_once_task({
let tt = turbo_tasks.clone();
......@@ -459,14 +470,13 @@ pub async fn project_new(
.inspect_err(|err| tracing::warn!(%err, "failed to benchmark file IO"))
}
});
Ok(External::new_with_size_hint(
ProjectInstance {
turbopack_ctx: NextTurbopackContext::new(turbo_tasks),
Ok(External::new(ProjectInstance {
turbopack_ctx,
container,
exit_receiver: tokio::sync::Mutex::new(Some(exit_receiver)),
},
100,
))
}))
})
}
#[derive(Debug, Clone, Serialize)]
......@@ -571,18 +581,16 @@ pub async fn project_update(
#[napi(ts_arg_type = "{ __napiType: \"Project\" }")] project: External<ProjectInstance>,
options: NapiPartialProjectOptions,
) -> napi::Result<()> {
let ctx = &project.turbopack_ctx;
let options = options.into();
let container = project.container;
project
.turbopack_ctx
.turbo_tasks()
ctx.turbo_tasks()
.run_once(async move {
container.update(options).await?;
Ok(())
})
.or_else(|e| ctx.throw_turbopack_internal_result(&e))
.await
.map_err(|e| napi::Error::from_reason(PrettyPrintError(&e).to_string()))?;
Ok(())
}
/// Invalidates the persistent cache so that it will be deleted next time that a turbopack project
......@@ -876,12 +884,12 @@ pub async fn project_write_all_entrypoints_to_disk(
#[napi(ts_arg_type = "{ __napiType: \"Project\" }")] project: External<ProjectInstance>,
app_dir_only: bool,
) -> napi::Result<TurbopackResult<NapiEntrypoints>> {
let ctx = &project.turbopack_ctx;
let container = project.container;
let tt = project.turbopack_ctx.turbo_tasks().clone();
let tt = ctx.turbo_tasks();
let tt_clone = tt.clone();
let (entrypoints, issues, diags) = project
.turbopack_ctx
.turbo_tasks()
let (entrypoints, issues, diags) = tt
.run_once(async move {
let entrypoints_with_issues_op =
get_all_written_entrypoints_with_issues_operation(container, app_dir_only);
......@@ -903,15 +911,15 @@ pub async fn project_write_all_entrypoints_to_disk(
effects.apply().await?;
// Send a compilation event to indicate that the files have been written to disk
tt.send_compilation_event(Arc::new(TimingEvent::new(
tt_clone.send_compilation_event(Arc::new(TimingEvent::new(
"Finished writing to disk".to_owned(),
now.elapsed(),
)));
Ok((entrypoints.clone(), issues.clone(), diagnostics.clone()))
})
.await
.map_err(|e| napi::Error::from_reason(PrettyPrintError(&e).to_string()))?;
.or_else(|e| ctx.throw_turbopack_internal_result(&e))
.await?;
Ok(TurbopackResult {
result: NapiEntrypoints::from_entrypoints_op(&entrypoints, &project.turbopack_ctx)?,
......@@ -1560,21 +1568,23 @@ pub async fn project_trace_source(
current_directory_file_url: String,
) -> napi::Result<Option<StackFrame>> {
let container = project.container;
let traced_frame = project
.turbopack_ctx
.turbo_tasks()
let ctx = &project.turbopack_ctx;
ctx.turbo_tasks()
.run_once(async move {
project_trace_source_operation(
let traced_frame = project_trace_source_operation(
container,
frame,
RcStr::from(current_directory_file_url),
)
.read_strongly_consistent()
.await
.await?;
Ok(ReadRef::into_owned(traced_frame))
})
// HACK: Don't use `TurbopackInternalError`, this function is race-condition prone (the
// source files may have changed or been deleted), so these probably aren't internal errors?
// Ideally we should differentiate.
.await
.map_err(|e| napi::Error::from_reason(PrettyPrintError(&e).to_string()))?;
Ok(ReadRef::into_owned(traced_frame))
.map_err(|e| napi::Error::from_reason(PrettyPrintError(&e).to_string()))
}
#[napi]
......@@ -1583,9 +1593,8 @@ pub async fn project_get_source_for_asset(
file_path: RcStr,
) -> napi::Result<Option<String>> {
let container = project.container;
let source = project
.turbopack_ctx
.turbo_tasks()
let ctx = &project.turbopack_ctx;
ctx.turbo_tasks()
.run_once(async move {
let source_content = &*container
.project()
......@@ -1604,10 +1613,11 @@ pub async fn project_get_source_for_asset(
Ok(Some(source_content.content().to_str()?.into_owned()))
})
// HACK: Don't use `TurbopackInternalError`, this function is race-condition prone (the
// source files may have changed or been deleted), so these probably aren't internal errors?
// Ideally we should differentiate.
.await
.map_err(|e| napi::Error::from_reason(PrettyPrintError(&e).to_string()))?;
Ok(source)
.map_err(|e| napi::Error::from_reason(PrettyPrintError(&e).to_string()))
}
#[napi]
......@@ -1616,9 +1626,8 @@ pub async fn project_get_source_map(
file_path: RcStr,
) -> napi::Result<Option<String>> {
let container = project.container;
let source_map = project
.turbopack_ctx
.turbo_tasks()
let ctx = &project.turbopack_ctx;
ctx.turbo_tasks()
.run_once(async move {
let Some(map) = &*get_source_map_rope_operation(container, file_path)
.read_strongly_consistent()
......@@ -1628,10 +1637,11 @@ pub async fn project_get_source_map(
};
Ok(Some(map.to_str()?.to_string()))
})
// HACK: Don't use `TurbopackInternalError`, this function is race-condition prone (the
// source files may have changed or been deleted), so these probably aren't internal errors?
// Ideally we should differentiate.
.await
.map_err(|e| napi::Error::from_reason(PrettyPrintError(&e).to_string()))?;
Ok(source_map)
.map_err(|e| napi::Error::from_reason(PrettyPrintError(&e).to_string()))
}
#[napi]
......
//! Utilities for constructing and using the [`NextTurbopackContext`] type.
use std::{path::PathBuf, sync::Arc};
use std::{
env,
fs::OpenOptions,
io::{self, BufRead, Write},
path::PathBuf,
sync::{Arc, Mutex},
time::Instant,
};
use anyhow::Result;
use either::Either;
use napi::{JsFunction, threadsafe_function::ThreadsafeFunction};
use once_cell::sync::Lazy;
use owo_colors::OwoColorize;
use serde::Serialize;
use terminal_hyperlink::Hyperlink;
use turbo_tasks::{
TurboTasks, TurboTasksApi,
backend::TurboTasksExecutionError,
message_queue::{CompilationEvent, Severity},
};
use turbo_tasks_backend::{
......@@ -14,16 +26,21 @@ use turbo_tasks_backend::{
TurboTasksBackend, db_invalidation::invalidation_reasons, default_backing_storage,
noop_backing_storage,
};
use turbopack_core::error::PrettyPrintError;
pub type NextTurboTasks =
Arc<TurboTasks<TurboTasksBackend<Either<DefaultBackingStorage, NoopBackingStorage>>>>;
/// A value often wrapped in [`napi::bindgen_prelude::External`] that retains the Turbopack instance
/// used by Next.js, and various napi helpers that may have been passed to us from JS.
/// A value often wrapped in [`napi::bindgen_prelude::External`] that retains the [TurboTasks]
/// instance used by Next.js, and [various napi helpers that are passed to us from
/// JavaScript][NapiNextTurbopackCallbacks].
///
/// This is not a [`turbo_tasks::value`], and should only be used within the top-level napi layer.
/// It should not be passed to a [`turbo_tasks::function`]. For serializable information about the
/// project, use the [`next_api::project::Project`] type.
/// project, use the [`next_api::project::Project`] type instead.
///
/// This type is a wrapper around an [`Arc`] and is therefore cheaply clonable. It is [`Send`] and
/// [`Sync`].
#[derive(Clone)]
pub struct NextTurbopackContext {
inner: Arc<NextTurboContextInner>,
......@@ -31,18 +48,135 @@ pub struct NextTurbopackContext {
struct NextTurboContextInner {
turbo_tasks: NextTurboTasks,
napi_callbacks: NapiNextTurbopackCallbacks,
}
impl NextTurbopackContext {
pub fn new(turbo_tasks: NextTurboTasks) -> Self {
pub fn new(turbo_tasks: NextTurboTasks, napi_callbacks: NapiNextTurbopackCallbacks) -> Self {
NextTurbopackContext {
inner: Arc::new(NextTurboContextInner { turbo_tasks }),
inner: Arc::new(NextTurboContextInner {
turbo_tasks,
napi_callbacks,
}),
}
}
pub fn turbo_tasks(&self) -> &NextTurboTasks {
&self.inner.turbo_tasks
}
/// Constructs and throws a `TurbopackInternalError` from within JavaScript. This type is
/// defined within Next.js, and passed via [`NapiNextTurbopackCallbacks`]. This should be called
/// at the top level (a `napi` function) and only for errors that are not expected to occur an
/// indicate a bug in Turbopack or Next.js.
///
/// This may log anonymized information about the error to our telemetry service (via the
/// JS callback). It may log to stderr and write a log file to disk (in Rust), subject to
/// throttling.
///
/// The caller should exit immediately with the returned [`napi::Error`] after calling this, as
/// it sets a pending exception.
///
/// The returned future does not depend on the lifetime of `&self` or `&err`, making it easier
/// to compose with [`futures_util::TryFutureExt`] and similar utilities.
pub fn throw_turbopack_internal_error(
&self,
err: &anyhow::Error,
) -> impl Future<Output = napi::Error> + use<> {
let this = self.clone();
let message = PrettyPrintError(err).to_string();
let downcast_root_cause_err = err.root_cause().downcast_ref::<TurboTasksExecutionError>();
let panic_location =
if let Some(TurboTasksExecutionError::Panic(p)) = downcast_root_cause_err {
p.location.clone()
} else {
None
};
log_internal_error_and_inform(err);
async move {
this.inner
.napi_callbacks
.throw_turbopack_internal_error
.call_async::<()>(Ok(TurbopackInternalErrorOpts {
message,
anonymized_location: panic_location,
}))
.await
.expect_err("throwTurbopackInternalError must throw an error")
}
}
/// A utility method that calls [`NextTurbopackContext::throw_turbopack_internal_error`] and
/// wraps the [`napi::Error`] in a [`napi::Result`].
///
/// The returned future does not depend on the lifetime of `&self` or `&err`, making it easier
/// to compose with [`futures_util::TryFutureExt::or_else`].
///
/// The returned type uses a generic (`T`), but should be a never type (`!`) once that nightly
/// feature is stabilized.
pub fn throw_turbopack_internal_result<T>(
&self,
err: &anyhow::Error,
) -> impl Future<Output = napi::Result<T>> + use<T> {
let err_fut = self.throw_turbopack_internal_error(err);
async move { Err(err_fut.await) }
}
}
/// A version of [`NapiNextTurbopackCallbacks`] that can accepted as an argument to a napi function.
///
/// This can be converted into a [`NapiNextTurbopackCallbacks`] with
/// [`NapiNextTurbopackCallbacks::from_js`].
#[napi(object)]
pub struct NapiNextTurbopackCallbacksJsObject {
/// Called when we've encountered a bug in Turbopack and not in the user's code. Constructs and
/// throws a `TurbopackInternalError` type. Logs to anonymized telemetry.
///
/// As a result of the use of `ErrorStrategy::CalleeHandled`, the first argument is an error if
/// there's a runtime conversion error. This should never happen, but if it does, the function
/// can throw it instead.
#[napi(ts_type = "(conversionError: Error | null, opts: TurbopackInternalErrorOpts) => never")]
pub throw_turbopack_internal_error: JsFunction,
}
/// A collection of helper JavaScript functions passed into
/// [`crate::next_api::project::project_new`] and stored in the [`NextTurbopackContext`].
///
/// This type is [`Send`] and [`Sync`]. Callbacks are wrapped in [`ThreadsafeFunction`].
pub struct NapiNextTurbopackCallbacks {
// It's a little nasty to use a `ThreadsafeFunction` for this, but we don't expect exceptions
// to be a hot codepath.
//
// More ideally, we'd convert the error type in the JS thread after the execution of the future
// when resolving the JS `Promise` object. However, doing that would add a lot more boilerplate
// to all of our async entrypoints, and would be complicated by `FunctionRef` being `!Send` (I
// think it could be `Send`, as long as `napi::Env` is checked at call-time, which it should be
// anyways).
throw_turbopack_internal_error: ThreadsafeFunction<TurbopackInternalErrorOpts>,
}
/// Arguments for [`NapiNextTurbopackCallbacks::throw_turbopack_internal_error`].
#[napi(object)]
pub struct TurbopackInternalErrorOpts {
pub message: String,
pub anonymized_location: Option<String>,
}
impl NapiNextTurbopackCallbacks {
pub fn from_js(obj: NapiNextTurbopackCallbacksJsObject) -> napi::Result<Self> {
Ok(NapiNextTurbopackCallbacks {
throw_turbopack_internal_error: obj
.throw_turbopack_internal_error
.create_threadsafe_function(0, |ctx| {
// Avoid unpacking the struct into positional arguments, we really want to make
// sure we don't incorrectly order arguments and accidentally log a potentially
// PII-containing message in anonymized telemetry.
Ok(vec![ctx.value])
})?,
})
}
}
pub fn create_turbo_tasks(
......@@ -120,3 +254,123 @@ impl CompilationEvent for StartupCacheInvalidationEvent {
serde_json::to_string(self).unwrap()
}
}
static LOG_THROTTLE: Mutex<Option<Instant>> = Mutex::new(None);
static LOG_DIVIDER: &str = "---------------------------";
static PANIC_LOG: Lazy<PathBuf> = Lazy::new(|| {
let mut path = env::temp_dir();
path.push(format!("next-panic-{:x}.log", rand::random::<u128>()));
path
});
/// Log the error to stderr and write a log file to disk, subject to throttling.
//
// TODO: Now that we're passing the error to a JS callback, handle this logic in Next.js using the
// logger there instead of writing directly to stderr.
pub fn log_internal_error_and_inform(internal_error: &anyhow::Error) {
if cfg!(debug_assertions)
|| env::var("SWC_DEBUG") == Ok("1".to_string())
|| env::var("CI").is_ok_and(|v| !v.is_empty())
// Next's run-tests unsets CI and sets NEXT_TEST_CI
|| env::var("NEXT_TEST_CI").is_ok_and(|v| !v.is_empty())
{
eprintln!(
"{}: An unexpected Turbopack error occurred:\n{}",
"FATAL".red().bold(),
PrettyPrintError(internal_error)
);
return;
}
// hold open this mutex guard to prevent concurrent writes to the file!
let mut last_error_time = LOG_THROTTLE.lock().unwrap();
if let Some(last_error_time) = last_error_time.as_ref()
&& last_error_time.elapsed().as_secs() < 1
{
// Throttle panic logging to once per second
return;
}
*last_error_time = Some(Instant::now());
let size = std::fs::metadata(PANIC_LOG.as_path()).map(|m| m.len());
if let Ok(size) = size
&& size > 512 * 1024
{
// Truncate the earliest error from log file if it's larger than 512KB
let new_lines = {
let log_read = OpenOptions::new()
.read(true)
.open(PANIC_LOG.as_path())
.unwrap_or_else(|_| panic!("Failed to open {}", PANIC_LOG.to_string_lossy()));
io::BufReader::new(&log_read)
.lines()
.skip(1)
.skip_while(|line| match line {
Ok(line) => !line.starts_with(LOG_DIVIDER),
Err(_) => false,
})
.collect::<Vec<_>>()
};
let mut log_write = OpenOptions::new()
.create(true)
.truncate(true)
.write(true)
.open(PANIC_LOG.as_path())
.unwrap_or_else(|_| panic!("Failed to open {}", PANIC_LOG.to_string_lossy()));
for line in new_lines {
match line {
Ok(line) => {
writeln!(log_write, "{line}").unwrap();
}
Err(_) => {
break;
}
}
}
}
let mut log_file = OpenOptions::new()
.create(true)
.append(true)
.open(PANIC_LOG.as_path())
.unwrap_or_else(|_| panic!("Failed to open {}", PANIC_LOG.to_string_lossy()));
let internal_error_str: String = PrettyPrintError(internal_error).to_string();
writeln!(log_file, "{}\n{}", LOG_DIVIDER, &internal_error_str).unwrap();
let title = format!(
"Turbopack Error: {}",
internal_error_str.lines().next().unwrap_or("Unknown")
);
let version_str = format!(
"Turbopack version: `{}`\nNext.js version: `{}`",
env!("VERGEN_GIT_DESCRIBE"),
env!("NEXTJS_VERSION")
);
let new_discussion_url = if supports_hyperlinks::supports_hyperlinks() {
"clicking here.".hyperlink(
format!(
"https://github.com/vercel/next.js/discussions/new?category=turbopack-error-report&title={}&body={}&labels=Turbopack,Turbopack%20Panic%20Backtrace",
&urlencoding::encode(&title),
&urlencoding::encode(&format!("{}\n\nError message:\n```\n{}\n```", &version_str, &internal_error_str))
)
)
} else {
format!(
"clicking here: https://github.com/vercel/next.js/discussions/new?category=turbopack-error-report&title={}&body={}&labels=Turbopack,Turbopack%20Panic%20Backtrace",
&urlencoding::encode(&title),
&urlencoding::encode(&format!("{}\n\nError message:\n```\n{}\n```", &version_str, &title))
)
};
eprintln!(
"\n-----\n{}: An unexpected Turbopack error occurred. A panic log has been written to \
{}.\n\nTo help make Turbopack better, report this error by {}\n-----\n",
"FATAL".red().bold(),
PANIC_LOG.to_string_lossy(),
&new_discussion_url
);
}
use std::{future::Future, ops::Deref, sync::Arc};
use anyhow::{Context, Result, anyhow};
use futures_util::TryFutureExt;
use napi::{
JsFunction, JsObject, JsUnknown, NapiRaw, NapiValue, Status,
bindgen_prelude::{External, ToNapiValue},
......@@ -14,14 +15,13 @@ use turbo_tasks::{
use turbo_tasks_fs::FileContent;
use turbopack_core::{
diagnostics::{Diagnostic, DiagnosticContextExt, PlainDiagnostic},
error::PrettyPrintError,
issue::{
IssueDescriptionExt, IssueSeverity, PlainIssue, PlainIssueSource, PlainSource, StyledString,
},
source_pos::SourcePos,
};
use crate::{next_api::turbopack_ctx::NextTurbopackContext, util::log_internal_error_and_inform};
use crate::next_api::turbopack_ctx::NextTurbopackContext;
/// An [`OperationVc`] that can be passed back and forth to JS across the [`napi`][mod@napi]
/// boundary via [`External`].
......@@ -324,35 +324,35 @@ impl<T: ToNapiValue> ToNapiValue for TurbopackResult<T> {
}
pub fn subscribe<T: 'static + Send + Sync, F: Future<Output = Result<T>> + Send, V: ToNapiValue>(
turbopack_ctx: NextTurbopackContext,
ctx: NextTurbopackContext,
func: JsFunction,
handler: impl 'static + Sync + Send + Clone + Fn() -> F,
mapper: impl 'static + Sync + Send + FnMut(ThreadSafeCallContext<T>) -> napi::Result<Vec<V>>,
) -> napi::Result<External<RootTask>> {
let func: ThreadsafeFunction<T> = func.create_threadsafe_function(0, mapper)?;
let task_id = turbopack_ctx.turbo_tasks().spawn_root_task(move || {
let task_id = ctx.turbo_tasks().spawn_root_task({
let ctx = ctx.clone();
move || {
let ctx = ctx.clone();
let handler = handler.clone();
let func = func.clone();
Box::pin(async move {
let result = handler().await;
let status = func.call(
result.map_err(|e| {
log_internal_error_and_inform(&e);
napi::Error::from_reason(PrettyPrintError(&e).to_string())
}),
ThreadsafeFunctionCallMode::NonBlocking,
);
async move {
let result = handler()
.or_else(|e| ctx.throw_turbopack_internal_result(&e))
.await;
let status = func.call(result, ThreadsafeFunctionCallMode::NonBlocking);
if !matches!(status, Status::Ok) {
let error = anyhow!("Error calling JS function: {}", status);
eprintln!("{error}");
return Err::<Vc<()>, _>(error);
}
Ok(Default::default())
})
}
}
});
Ok(External::new(RootTask {
turbopack_ctx,
turbopack_ctx: ctx,
task_id: Some(task_id),
}))
}
......
......@@ -26,140 +26,12 @@ IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
use std::{
cell::RefCell,
env,
fs::OpenOptions,
io::{self, BufRead, Write},
path::PathBuf,
sync::Mutex,
time::Instant,
};
use std::{cell::RefCell, env, path::PathBuf};
use anyhow::anyhow;
use napi::bindgen_prelude::{External, Status};
use once_cell::sync::Lazy;
use owo_colors::OwoColorize;
use terminal_hyperlink::Hyperlink;
use tracing_chrome::{ChromeLayerBuilder, FlushGuard};
use tracing_subscriber::{Layer, filter, prelude::*, util::SubscriberInitExt};
use turbopack_core::error::PrettyPrintError;
static LOG_THROTTLE: Mutex<Option<Instant>> = Mutex::new(None);
static LOG_DIVIDER: &str = "---------------------------";
static PANIC_LOG: Lazy<PathBuf> = Lazy::new(|| {
let mut path = env::temp_dir();
path.push(format!("next-panic-{:x}.log", rand::random::<u128>()));
path
});
pub fn log_internal_error_and_inform(internal_error: &anyhow::Error) {
if cfg!(debug_assertions)
|| env::var("SWC_DEBUG") == Ok("1".to_string())
|| env::var("CI").is_ok_and(|v| !v.is_empty())
// Next's run-tests unsets CI and sets NEXT_TEST_CI
|| env::var("NEXT_TEST_CI").is_ok_and(|v| !v.is_empty())
{
eprintln!(
"{}: An unexpected Turbopack error occurred:\n{}",
"FATAL".red().bold(),
PrettyPrintError(internal_error)
);
return;
}
// hold open this mutex guard to prevent concurrent writes to the file!
let mut last_error_time = LOG_THROTTLE.lock().unwrap();
if let Some(last_error_time) = last_error_time.as_ref()
&& last_error_time.elapsed().as_secs() < 1
{
// Throttle panic logging to once per second
return;
}
*last_error_time = Some(Instant::now());
let size = std::fs::metadata(PANIC_LOG.as_path()).map(|m| m.len());
if let Ok(size) = size
&& size > 512 * 1024
{
// Truncate the earliest error from log file if it's larger than 512KB
let new_lines = {
let log_read = OpenOptions::new()
.read(true)
.open(PANIC_LOG.as_path())
.unwrap_or_else(|_| panic!("Failed to open {}", PANIC_LOG.to_string_lossy()));
io::BufReader::new(&log_read)
.lines()
.skip(1)
.skip_while(|line| match line {
Ok(line) => !line.starts_with(LOG_DIVIDER),
Err(_) => false,
})
.collect::<Vec<_>>()
};
let mut log_write = OpenOptions::new()
.create(true)
.truncate(true)
.write(true)
.open(PANIC_LOG.as_path())
.unwrap_or_else(|_| panic!("Failed to open {}", PANIC_LOG.to_string_lossy()));
for line in new_lines {
match line {
Ok(line) => {
writeln!(log_write, "{line}").unwrap();
}
Err(_) => {
break;
}
}
}
}
let mut log_file = OpenOptions::new()
.create(true)
.append(true)
.open(PANIC_LOG.as_path())
.unwrap_or_else(|_| panic!("Failed to open {}", PANIC_LOG.to_string_lossy()));
let internal_error_str: String = PrettyPrintError(internal_error).to_string();
writeln!(log_file, "{}\n{}", LOG_DIVIDER, &internal_error_str).unwrap();
let title = format!(
"Turbopack Error: {}",
internal_error_str.lines().next().unwrap_or("Unknown")
);
let version_str = format!(
"Turbopack version: `{}`\nNext.js version: `{}`",
env!("VERGEN_GIT_DESCRIBE"),
env!("NEXTJS_VERSION")
);
let new_discussion_url = if supports_hyperlinks::supports_hyperlinks() {
"clicking here.".hyperlink(
format!(
"https://github.com/vercel/next.js/discussions/new?category=turbopack-error-report&title={}&body={}&labels=Turbopack,Turbopack%20Panic%20Backtrace",
&urlencoding::encode(&title),
&urlencoding::encode(&format!("{}\n\nError message:\n```\n{}\n```", &version_str, &internal_error_str))
)
)
} else {
format!(
"clicking here: https://github.com/vercel/next.js/discussions/new?category=turbopack-error-report&title={}&body={}&labels=Turbopack,Turbopack%20Panic%20Backtrace",
&urlencoding::encode(&title),
&urlencoding::encode(&format!("{}\n\nError message:\n```\n{}\n```", &version_str, &title))
)
};
eprintln!(
"\n-----\n{}: An unexpected Turbopack error occurred. A panic log has been written to \
{}.\n\nTo help make Turbopack better, report this error by {}\n-----\n",
"FATAL".red().bold(),
PANIC_LOG.to_string_lossy(),
&new_discussion_url
);
}
use tracing_subscriber::{Layer, filter, layer::SubscriberExt, util::SubscriberInitExt};
#[napi]
pub fn get_target_triple() -> &'static str {
......
......@@ -720,5 +720,6 @@
"719": "Failed to get source map for '%s'. This is a bug in Next.js",
"720": "A client prerender store should not be used for a route handler.",
"721": "Render in Browser",
"722": "Unable to match pathname to a dynamic route"
"722": "Unable to match pathname to a dynamic route",
"723": "NAPI type conversion error in throwTurbopackInternalError"
}
......@@ -204,7 +204,8 @@ export interface NapiTurboEngineOptions {
}
export declare function projectNew(
options: NapiProjectOptions,
turboEngineOptions: NapiTurboEngineOptions
turboEngineOptions: NapiTurboEngineOptions,
napiCallbacks: NapiNextTurbopackCallbacksJsObject
): Promise<{ __napiType: 'Project' }>
export declare function projectUpdate(
project: { __napiType: 'Project' },
......@@ -350,6 +351,31 @@ export declare function projectGetSourceMapSync(
project: { __napiType: 'Project' },
filePath: RcStr
): string | null
/**
* A version of [`NapiNextTurbopackCallbacks`] that can accepted as an argument to a napi function.
*
* This can be converted into a [`NapiNextTurbopackCallbacks`] with
* [`NapiNextTurbopackCallbacks::from_js`].
*/
export interface NapiNextTurbopackCallbacksJsObject {
/**
* Called when we've encountered a bug in Turbopack and not in the user's code. Constructs and
* throws a `TurbopackInternalError` type. Logs to anonymized telemetry.
*
* As a result of the use of `ErrorStrategy::CalleeHandled`, the first argument is an error if
* there's a runtime conversion error. This should never happen, but if it does, the function
* can throw it instead.
*/
throwTurbopackInternalError: (
conversionError: Error | null,
opts: TurbopackInternalErrorOpts
) => never
}
/** Arguments for [`NapiNextTurbopackCallbacks::throw_turbopack_internal_error`]. */
export interface TurbopackInternalErrorOpts {
message: string
anonymizedLocation?: string
}
export declare function rootTaskDispose(rootTask: {
__napiType: 'RootTask'
}): void
......
......@@ -3,11 +3,11 @@
/* tslint:disable */
/* eslint-disable */
export function mdxCompileSync(value: string, opts: any): any
export function mdxCompile(value: string, opts: any): Promise<any>
export function minifySync(s: string, opts: any): any
export function minify(s: string, opts: any): Promise<any>
export function transformSync(s: any, opts: any): any
export function transform(s: any, opts: any): Promise<any>
export function parseSync(s: string, opts: any): any
export function parse(s: string, opts: any): Promise<any>
export function mdxCompileSync(value: string, opts: any): any
export function mdxCompile(value: string, opts: any): Promise<any>
......@@ -40,7 +40,7 @@ import type {
UpdateMessage,
WrittenEndpoint,
} from './types'
import { TurbopackInternalError } from '../../shared/lib/turbopack/utils'
import { throwTurbopackInternalError } from '../../shared/lib/turbopack/internal-error'
type RawBindings = typeof import('./generated-native')
type RawWasmBindings = typeof import('./generated-wasm') & {
......@@ -536,14 +536,6 @@ function bindingToApi(
throw new Error(`Invariant: ${computeMessage(never)}`)
}
async function withErrorCause<T>(fn: () => Promise<T>): Promise<T> {
try {
return await fn()
} catch (nativeError: any) {
throw TurbopackInternalError.createAndRecordTelemetry(nativeError)
}
}
/**
* Calls a native function and streams the result.
* If useBuffer is true, all values will be preserved, potentially buffered
......@@ -589,9 +581,7 @@ function bindingToApi(
}
async function* createIterator() {
const task = await withErrorCause<{ __napiType: 'RootTask' } | void>(() =>
nativeFunction(emitResult)
)
const task = await nativeFunction(emitResult)
try {
while (!canceled) {
if (buffer.length > 0) {
......@@ -607,9 +597,6 @@ function bindingToApi(
}
} catch (e) {
if (e === cancel) return
if (e instanceof Error) {
throw TurbopackInternalError.createAndRecordTelemetry(e)
}
throw e
} finally {
if (task) {
......@@ -662,25 +649,21 @@ function bindingToApi(
}
async update(options: Partial<ProjectOptions>) {
await withErrorCause(async () =>
binding.projectUpdate(
await binding.projectUpdate(
this._nativeProject,
await rustifyPartialProjectOptions(options)
)
)
}
async writeAllEntrypointsToDisk(
appDirOnly: boolean
): Promise<TurbopackResult<RawEntrypoints>> {
return await withErrorCause(async () => {
const napiEndpoints = (await binding.projectWriteAllEntrypointsToDisk(
this._nativeProject,
appDirOnly
)) as TurbopackResult<NapiEntrypoints>
return napiEntrypointsToRawEntrypoints(napiEndpoints)
})
}
entrypointsSubscribe() {
......@@ -777,22 +760,16 @@ function bindingToApi(
}
async writeToDisk(): Promise<TurbopackResult<WrittenEndpoint>> {
return await withErrorCause(
() =>
binding.endpointWriteToDisk(this._nativeEndpoint) as Promise<
TurbopackResult<WrittenEndpoint>
>
)
return (await binding.endpointWriteToDisk(
this._nativeEndpoint
)) as TurbopackResult<WrittenEndpoint>
}
async clientChanged(): Promise<AsyncIterableIterator<TurbopackResult<{}>>> {
const clientSubscription = subscribe<TurbopackResult>(
false,
async (callback) =>
binding.endpointClientChangedSubscribe(
await this._nativeEndpoint,
callback
)
binding.endpointClientChangedSubscribe(this._nativeEndpoint, callback)
)
await clientSubscription.next()
return clientSubscription
......@@ -805,7 +782,7 @@ function bindingToApi(
false,
async (callback) =>
binding.endpointServerChangedSubscribe(
await this._nativeEndpoint,
this._nativeEndpoint,
includeIssues,
callback
)
......@@ -1085,7 +1062,10 @@ function bindingToApi(
return new ProjectImpl(
await binding.projectNew(
await rustifyProjectOptions(options),
turboEngineOptions || {}
turboEngineOptions || {},
{
throwTurbopackInternalError,
}
)
)
}
......
......@@ -80,9 +80,9 @@ import { store as consoleStore } from '../../../build/output/store'
import {
isPersistentCachingEnabled,
ModuleBuildError,
TurbopackInternalError,
} from '../../../shared/lib/turbopack/utils'
import { getDefineEnv } from '../../../build/define-env'
import { TurbopackInternalError } from '../../../shared/lib/turbopack/internal-error'
export type SetupOpts = {
renderServer: LazyRenderServerInstance
......
import type { TurbopackInternalErrorOpts } from '../../../build/swc/generated-native'
import { eventErrorThrown } from '../../../telemetry/events'
import { traceGlobals } from '../../../trace/shared'
/**
* An error caused by a bug in Turbopack, and not the user's code (e.g. a Rust panic). These should
* be written to a log file and details should not be shown to the user.
*
* These are constructed in Turbopack by calling `throwTurbopackInternalError`.
*/
export class TurbopackInternalError extends Error {
name = 'TurbopackInternalError'
location: string | undefined
// Manually set this as this isn't statically determinable
__NEXT_ERROR_CODE = 'TurbopackInternalError'
constructor({ message, anonymizedLocation }: TurbopackInternalErrorOpts) {
super(message)
this.location = anonymizedLocation
}
}
/**
* A helper used by the napi Rust entrypoints to construct and throw a `TurbopackInternalError`.
*
* When called, this will emit a telemetry event.
*/
export function throwTurbopackInternalError(
conversionError: Error | null,
opts: TurbopackInternalErrorOpts
): never {
if (conversionError != null) {
// Somehow napi failed to convert `opts` to a JS object??? Just give up and throw that instead.
throw new Error(
'NAPI type conversion error in throwTurbopackInternalError',
{
cause: conversionError,
}
)
}
const err = new TurbopackInternalError(opts)
const telemetry = traceGlobals.get('telemetry')
if (telemetry) {
telemetry.record(eventErrorThrown(err, opts.anonymizedLocation))
} else {
console.error('Expected `telemetry` to be set in globals')
}
throw err
}
......@@ -15,47 +15,20 @@ import type { EntryKey } from './entry-key'
import * as Log from '../../../build/output/log'
import type { NextConfigComplete } from '../../../server/config-shared'
import loadJsConfig from '../../../build/load-jsconfig'
import { eventErrorThrown } from '../../../telemetry/events'
import { traceGlobals } from '../../../trace/shared'
type IssueKey = `${Issue['severity']}-${Issue['filePath']}-${string}-${string}`
export type IssuesMap = Map<IssueKey, Issue>
export type EntryIssuesMap = Map<EntryKey, IssuesMap>
export type TopLevelIssuesMap = IssuesMap
// An error generated from emitted Turbopack issues. This can include build
// errors caused by issues with user code.
/**
* An error generated from emitted Turbopack issues. This can include build
* errors caused by issues with user code.
*/
export class ModuleBuildError extends Error {
name = 'ModuleBuildError'
}
// An error caused by an internal issue in Turbopack. These should be written
// to a log file and details should not be shown to the user.
export class TurbopackInternalError extends Error {
name = 'TurbopackInternalError'
// Manually set this as this isn't statically determinable
__NEXT_ERROR_CODE = 'TurbopackInternalError'
static createAndRecordTelemetry(cause: Error) {
const error = new TurbopackInternalError(cause)
const telemetry = traceGlobals.get('telemetry')
if (telemetry) {
telemetry.record(eventErrorThrown(error))
} else {
console.error('Expected `telemetry` to be set in globals')
}
return error
}
constructor(cause: Error) {
super(cause.message)
this.stack = cause.stack
}
}
/**
* Thin stopgap workaround layer to mimic existing wellknown-errors-plugin in webpack's build
* to emit certain type of errors into cli.
......
......@@ -235,15 +235,24 @@ type ErrorThrownEvent = {
eventName: typeof ERROR_THROWN_EVENT
payload: {
errorCode: string | undefined
location: string | undefined
}
}
// Creates a Telemetry event for errors. For privacy, only includes the error code.
export function eventErrorThrown(error: Error): ErrorThrownEvent {
// Creates a Telemetry event for errors. For privacy, only includes the error code and not the error
// message.
//
// `location` may be included if it's a location internal to the next.js source tree (i.e. a
// non-absolute path).
export function eventErrorThrown(
error: Error,
anonymizedLocation: string | undefined
): ErrorThrownEvent {
return {
eventName: ERROR_THROWN_EVENT,
payload: {
errorCode: extractNextErrorCode(error) || 'Unknown',
location: anonymizedLocation,
},
}
}
import path from 'path'
import os from 'os'
import { TurbopackInternalError } from 'next/dist/shared/lib/turbopack/utils'
import {
throwTurbopackInternalError,
TurbopackInternalError,
} from 'next/dist/shared/lib/turbopack/internal-error'
import { Telemetry } from 'next/dist/telemetry/storage'
import { setGlobal } from 'next/dist/trace'
import { traceGlobals } from 'next/dist/trace/shared'
describe('TurbopackInternalError', () => {
it('sends a telemetry event when TurbopackInternalError.createAndRecordTelemetry() is called', async () => {
it('sends a telemetry event when throwTurbopackInternalError() is called', async () => {
const oldTelemetry = traceGlobals.get('telemetry')
try {
......@@ -18,12 +21,24 @@ describe('TurbopackInternalError', () => {
.spyOn(telemetry, 'submitRecord')
// @ts-ignore
.mockImplementation(() => Promise.resolve())
TurbopackInternalError.createAndRecordTelemetry(new Error('test error'))
let internalError = null
try {
throwTurbopackInternalError(null, {
message: 'test error',
anonymizedLocation: 'file.rs:120:1',
})
} catch (err) {
internalError = err
}
expect(internalError).toBeInstanceOf(TurbopackInternalError)
expect(submitRecord).toHaveBeenCalledWith({
eventName: 'NEXT_ERROR_THROWN',
payload: {
errorCode: 'TurbopackInternalError',
location: 'file.rs:120:1',
},
})
} finally {
......
......@@ -447,7 +447,7 @@ pub enum TurboTasksExecutionError {
}
impl TurboTasksExecutionError {
pub fn task_context(&self, task: impl Display) -> Self {
pub fn with_task_context(&self, task: impl Display) -> Self {
TurboTasksExecutionError::TaskContext(Arc::new(TurboTaskContextError {
task: RcStr::from(task.to_string()),
source: Some(self.clone()),
......
......@@ -831,7 +831,7 @@ impl<B: Backend + 'static> TurboTasks<B> {
let local_task = LocalTask::Done {
output: match result {
Ok(raw_vc) => OutputContent::Link(raw_vc),
Err(err) => OutputContent::Error(err.task_context(task_type)),
Err(err) => OutputContent::Error(err.with_task_context(task_type)),
},
};
......
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