Box large errors as much as possible.

This commit is contained in:
Sebastian Jeltsch
2025-05-18 11:29:39 +02:00
parent b77da65b29
commit f1009827b7
5 changed files with 36 additions and 23 deletions

View File

@@ -87,7 +87,7 @@ pub fn pnpm_run(args: &[&str]) -> Result<std::process::Output> {
match env::var("SKIP_ERROR") {
Ok(v) if is_true(&v) => warn!("{}", msg),
_ => {
return Err(std::io::Error::new(std::io::ErrorKind::Other, msg));
return Err(std::io::Error::other(msg));
}
}
}

View File

@@ -12,7 +12,7 @@ use thiserror::Error;
use tokio::sync::oneshot;
use trailbase_js::runtime::{
Error as RSError, JsUser, Message, Module, Runtime, RuntimeHandle,
JsUser, LargeRSError, Message, Module, Runtime, RuntimeHandle,
build_call_async_js_function_message, get_arg,
};
@@ -30,7 +30,7 @@ pub struct DispatchArgs {
pub user: Option<JsUser>,
pub body: bytes::Bytes,
pub reply: oneshot::Sender<Result<JsHttpResponse, RSError>>,
pub reply: oneshot::Sender<Result<JsHttpResponse, Box<LargeRSError>>>,
}
#[derive(Deserialize, Default, Debug)]
@@ -47,7 +47,7 @@ pub enum JsHttpResponseError {
#[error("Internal: {0}")]
Internal(Box<dyn std::error::Error + Send + Sync>),
#[error("Runtime: {0}")]
Runtime(#[from] RSError),
Runtime(#[from] Box<LargeRSError>),
}
impl IntoResponse for JsHttpResponseError {
@@ -116,7 +116,7 @@ fn add_route_to_router(
csrf: u.csrf_token,
});
let (sender, receiver) = oneshot::channel::<Result<JsHttpResponse, RSError>>();
let (sender, receiver) = oneshot::channel::<Result<JsHttpResponse, Box<LargeRSError>>>();
debug!("dispatch {method} {uri}");
runtime_handle
@@ -207,7 +207,7 @@ async fn install_routes_and_jobs(
let route: String = get_arg(args, 1)?;
let router = add_route_to_router(runtime_handle_clone.clone(), method, route)
.map_err(|err| RSError::Runtime(err.to_string()))?;
.map_err(|err| LargeRSError::Runtime(err.to_string()))?;
router_sender.send(router).expect("send");
@@ -223,7 +223,7 @@ async fn install_routes_and_jobs(
let name: String = get_arg(args, 0)?;
let default_spec: String = get_arg(args, 1)?;
let schedule = cron::Schedule::from_str(&default_spec).map_err(|err| {
return RSError::Runtime(err.to_string());
return LargeRSError::Runtime(err.to_string());
})?;
let runtime_handle = runtime_handle.clone();
@@ -244,7 +244,7 @@ async fn install_routes_and_jobs(
};
let (sender, receiver) =
oneshot::channel::<Result<Option<String>, RSError>>();
oneshot::channel::<Result<Option<String>, Box<LargeRSError>>>();
let id = id_receiver.await?;
first_isolate
.send_privately(build_call_async_js_function_message::<Option<String>>(
@@ -265,11 +265,11 @@ async fn install_routes_and_jobs(
};
}),
) else {
return Err(RSError::Runtime("Failed to add job".to_string()));
return Err(LargeRSError::Runtime("Failed to add job".to_string()));
};
if let Err(err) = id_sender.send(job.id as i64) {
return Err(RSError::Runtime(err.to_string()));
return Err(LargeRSError::Runtime(err.to_string()));
}
job.start();

View File

@@ -6,7 +6,8 @@ use rusqlite::functions::Context;
use std::collections::HashMap;
use std::sync::{Arc, LazyLock};
pub type ValidationError = jsonschema::ValidationError<'static>;
// NOTE:: Validation error is very large, we thus Box it.
pub type ValidationError = Box<jsonschema::ValidationError<'static>>;
type CustomValidatorFn = Arc<dyn Fn(&serde_json::Value, Option<&str>) -> bool + Send + Sync>;

View File

@@ -19,7 +19,10 @@ use trailbase_sqlite::rows::{JsonError, row_to_json_array};
use crate::JsRuntimeAssets;
use crate::util::cow_to_string;
pub use rustyscript::{Error, Module, ModuleHandle, Runtime};
pub use rustyscript::{Error as LargeRSError, Module, ModuleHandle, Runtime};
/// Boxed rustyscript error, since error is ~200B.
pub type Error = Box<rustyscript::Error>;
type AnyError = Box<dyn std::error::Error + Send + Sync>;
@@ -125,7 +128,7 @@ impl<T: serde::de::DeserializeOwned + Send + 'static> Completer for CompleterImp
let promise = self.promise;
Box::pin(async {
let _ = sender.send(promise.into_future(runtime).await);
let _ = sender.send(promise.into_future(runtime).await.map_err(Box::new));
})
}
}
@@ -254,8 +257,11 @@ where
return Message::Run(
module,
Box::new(move |module_handle, runtime: &mut Runtime| {
let _ =
response.send(runtime.call_function_immediate::<T>(module_handle, function_name, &args));
let _ = response.send(
runtime
.call_function_immediate::<T>(module_handle, function_name, &args)
.map_err(Box::new),
);
return None;
}),
);
@@ -297,7 +303,7 @@ where
sender: response,
})),
Err(err) => {
let _ = response.send(Err(err));
let _ = response.send(Err(Box::new(err)));
None
}
};
@@ -457,8 +463,8 @@ self_cell!(
);
pub fn register_database_functions(handle: &RuntimeHandle, conn: trailbase_sqlite::Connection) {
fn error_mapper(err: impl std::error::Error) -> Error {
return Error::Runtime(err.to_string());
fn error_mapper(err: impl std::error::Error) -> rustyscript::Error {
return rustyscript::Error::Runtime(err.to_string());
}
fn register(runtime: &mut Runtime, conn: trailbase_sqlite::Connection) -> Result<(), Error> {
@@ -654,6 +660,8 @@ pub fn register_database_functions(handle: &RuntimeHandle, conn: trailbase_sqlit
}
}
// NOTE: We cannot Box the large error, since we're using this in a rustyscript callback.
#[allow(clippy::result_large_err)]
fn json_value_to_param(
value: serde_json::Value,
) -> Result<trailbase_sqlite::Value, rustyscript::Error> {
@@ -682,22 +690,26 @@ fn json_value_to_param(
});
}
// NOTE: We cannot Box the large error, since we're using this in a rustyscript callback.
#[allow(clippy::result_large_err)]
fn json_values_to_params(
values: Vec<serde_json::Value>,
) -> Result<Vec<trailbase_sqlite::Value>, rustyscript::Error> {
return values.into_iter().map(json_value_to_param).collect();
}
// NOTE: We cannot Box the large error, since we're using this in a rustyscript callback.
#[allow(clippy::result_large_err)]
pub fn get_arg<T>(args: &[serde_json::Value], i: usize) -> Result<T, rustyscript::Error>
where
T: serde::de::DeserializeOwned,
{
use rustyscript::Error;
let arg = args
.get(i)
.ok_or_else(|| Error::Runtime(format!("Range err {i} > {}", args.len())))?;
.ok_or_else(|| rustyscript::Error::Runtime(format!("Range err {i} > {}", args.len())))?;
return serde_json::from_value::<T>(arg.clone()).map_err(|err| Error::Runtime(err.to_string()));
return serde_json::from_value::<T>(arg.clone())
.map_err(|err| rustyscript::Error::Runtime(err.to_string()));
}
pub async fn write_js_runtime_files(data_dir: impl AsRef<Path>) {

View File

@@ -92,7 +92,7 @@ pub fn set_user_schema(name: &str, pattern: Option<serde_json::Value>) -> Result
}
if let Some(p) = pattern {
let entry = SchemaEntry::from(p, None).map_err(|err| Error::JsonSchema(Arc::new(err)))?;
let entry = SchemaEntry::from(p, None).map_err(|err| Error::JsonSchema(err.into()))?;
trailbase_extension::jsonschema::set_schema(name, Some(entry));
} else {
trailbase_extension::jsonschema::set_schema(name, None);
@@ -114,7 +114,7 @@ pub fn set_user_schemas(schemas: Vec<(String, serde_json::Value)>) -> Result<(),
for (name, schema) in schemas {
entries.push((
name,
SchemaEntry::from(schema, None).map_err(|err| Error::JsonSchema(Arc::new(err)))?,
SchemaEntry::from(schema, None).map_err(|err| Error::JsonSchema(err.into()))?,
));
}