Skip to content

Commit

Permalink
Fix not to use err.to_string for error encoding
Browse files Browse the repository at this point in the history
  • Loading branch information
ryo33 committed Nov 22, 2024
1 parent f3a4470 commit 9578607
Show file tree
Hide file tree
Showing 16 changed files with 130 additions and 100 deletions.
1 change: 0 additions & 1 deletion integrations/actix/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -369,7 +369,6 @@ pub fn handle_server_fns_with_context(
// actually run the server fn
let mut res = ActixResponse(
service
.0
.run(ActixRequest::from((req, payload)))
.await
.take(),
Expand Down
4 changes: 2 additions & 2 deletions server_fn/src/codec/cbor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use super::{Encoding, FromReq, FromRes, IntoReq, IntoRes};
use crate::{
error::{FromServerFnError, IntoAppError, ServerFnErrorErr},
request::{ClientReq, Req},
response::{ClientRes, Res},
response::{ClientRes, TryRes},
};
use bytes::Bytes;
use http::Method;
Expand Down Expand Up @@ -51,7 +51,7 @@ where

impl<E, T, Response> IntoRes<Cbor, Response, E> for T
where
Response: Res<E>,
Response: TryRes<E>,
T: Serialize + Send,
E: FromServerFnError,
{
Expand Down
6 changes: 3 additions & 3 deletions server_fn/src/codec/json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use super::{Encoding, FromReq, FromRes, Streaming};
use crate::{
error::{FromServerFnError, IntoAppError, ServerFnErrorErr},
request::{ClientReq, Req},
response::{ClientRes, Res},
response::{ClientRes, TryRes},
IntoReq, IntoRes,
};
use bytes::Bytes;
Expand Down Expand Up @@ -47,7 +47,7 @@ where

impl<E, T, Response> IntoRes<Json, Response, E> for T
where
Response: Res<E>,
Response: TryRes<E>,
T: Serialize + Send,
E: FromServerFnError,
{
Expand Down Expand Up @@ -184,7 +184,7 @@ where

impl<E, T, Response> IntoRes<StreamingJson, Response, E> for JsonStream<T, E>
where
Response: Res<E>,
Response: TryRes<E>,
T: Serialize + 'static,
E: FromServerFnError,
{
Expand Down
4 changes: 2 additions & 2 deletions server_fn/src/codec/msgpack.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use super::{Encoding, FromReq, FromRes, IntoReq, IntoRes};
use crate::{
error::{FromServerFnError, IntoAppError, ServerFnErrorErr},
request::{ClientReq, Req},
response::{ClientRes, Res},
response::{ClientRes, TryRes},
};
use bytes::Bytes;
use http::Method;
Expand Down Expand Up @@ -50,7 +50,7 @@ where

impl<T, Response, E> IntoRes<MsgPack, Response, E> for T
where
Response: Res<E>,
Response: TryRes<E>,
T: Serialize + Send,
E: FromServerFnError,
{
Expand Down
2 changes: 1 addition & 1 deletion server_fn/src/codec/multipart.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ where
.expect("couldn't parse boundary");
let stream = req.try_into_stream()?;
let data = multer::Multipart::new(
stream.map(|data| data.map_err(|e| e.to_string())),
stream.map(|data| data.map_err(|e| e.ser())),
boundary,
);
Ok(MultipartData::Server(data).into())
Expand Down
4 changes: 2 additions & 2 deletions server_fn/src/codec/postcard.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use super::{Encoding, FromReq, FromRes, IntoReq, IntoRes};
use crate::{
error::{FromServerFnError, IntoAppError, ServerFnErrorErr},
request::{ClientReq, Req},
response::{ClientRes, Res},
response::{ClientRes, TryRes},
};
use bytes::Bytes;
use http::Method;
Expand Down Expand Up @@ -50,7 +50,7 @@ where

impl<T, Response, E> IntoRes<Postcard, Response, E> for T
where
Response: Res<E>,
Response: TryRes<E>,
T: Serialize + Send,
E: FromServerFnError,
{
Expand Down
9 changes: 3 additions & 6 deletions server_fn/src/codec/rkyv.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use super::{Encoding, FromReq, FromRes, IntoReq, IntoRes};
use crate::{
error::{FromServerFnError, IntoAppError, ServerFnErrorErr},
request::{ClientReq, Req},
response::{ClientRes, Res},
response::{ClientRes, TryRes},
};
use bytes::Bytes;
use futures::StreamExt;
Expand Down Expand Up @@ -60,10 +60,7 @@ where
while let Some(chunk) = body_stream.next().await {
match chunk {
Err(e) => {
return Err(ServerFnErrorErr::Deserialization(
e.to_string(),
)
.into_app_error());
return Err(e);
}
Ok(bytes) => {
for byte in bytes {
Expand All @@ -79,7 +76,7 @@ where

impl<E, T, Response> IntoRes<Rkyv, Response, E> for T
where
Response: Res<E>,
Response: TryRes<E>,
T: Send,
T: Archive + for<'a> Serialize<RkyvSerializer<'a>>,
T::Archived: Deserialize<T, RkyvDeserializer>
Expand Down
4 changes: 2 additions & 2 deletions server_fn/src/codec/serde_lite.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use super::{Encoding, FromReq, FromRes};
use crate::{
error::{FromServerFnError, IntoAppError, ServerFnErrorErr},
request::{ClientReq, Req},
response::{ClientRes, Res},
response::{ClientRes, TryRes},
IntoReq, IntoRes,
};
use http::Method;
Expand Down Expand Up @@ -49,7 +49,7 @@ where

impl<E, T, Response> IntoRes<SerdeLite, Response, E> for T
where
Response: Res<E>,
Response: TryRes<E>,
T: Serialize + Send,
E: FromServerFnError,
{
Expand Down
6 changes: 3 additions & 3 deletions server_fn/src/codec/stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use super::{Encoding, FromReq, FromRes, IntoReq};
use crate::{
error::{FromServerFnError, IntoAppError, ServerFnErrorErr},
request::{ClientReq, Req},
response::{ClientRes, Res},
response::{ClientRes, TryRes},
IntoRes, ServerFnError,
};
use bytes::Bytes;
Expand Down Expand Up @@ -102,7 +102,7 @@ where

impl<E, Response> IntoRes<Streaming, Response, E> for ByteStream<E>
where
Response: Res<E>,
Response: TryRes<E>,
E: 'static,
{
async fn into_res(self) -> Result<Response, E> {
Expand Down Expand Up @@ -226,7 +226,7 @@ where

impl<E, Response> IntoRes<StreamingText, Response, E> for TextStream<E>
where
Response: Res<E>,
Response: TryRes<E>,
E: 'static,
{
async fn into_res(self) -> Result<Response, E> {
Expand Down
6 changes: 3 additions & 3 deletions server_fn/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -502,11 +502,11 @@ impl<E> From<ServerFnUrlError<ServerFnError<E>>> for ServerFnError<E> {
#[derive(Debug)]
#[doc(hidden)]
/// Only used instantly only when a framework needs E: Error.
pub struct ServerFnErrorWrapper<E>(pub E);
pub struct ServerFnErrorWrapper<E: FromServerFnError>(pub E);

impl<E: FromServerFnError> Display for ServerFnErrorWrapper<E> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
write!(f, "{}", self.0.ser())
}
}

Expand All @@ -518,7 +518,7 @@ impl<E: FromServerFnError> std::error::Error for ServerFnErrorWrapper<E> {

/// A trait for types that can be returned from a server function.
pub trait FromServerFnError:
Display + std::fmt::Debug + Serialize + DeserializeOwned + 'static
std::fmt::Debug + Serialize + DeserializeOwned + 'static
{
/// Converts a [`ServerFnErrorErr`] into the application-specific custom error type.
fn from_server_fn_error(value: ServerFnErrorErr) -> Self;
Expand Down
66 changes: 36 additions & 30 deletions server_fn/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,16 +131,16 @@ use codec::{Encoding, FromReq, FromRes, IntoReq, IntoRes};
#[doc(hidden)]
pub use const_format;
use dashmap::DashMap;
use error::FromServerFnError;
pub use error::ServerFnError;
#[cfg(feature = "form-redirects")]
use error::ServerFnUrlError;
use error::{FromServerFnError, ServerFnErrorErr};
use http::Method;
use middleware::{Layer, Service};
use middleware::{BoxedService, Layer, Service};
use once_cell::sync::Lazy;
use redirect::RedirectHook;
use request::Req;
use response::{ClientRes, Res};
use response::{ClientRes, Res, TryRes};
#[cfg(feature = "rkyv")]
pub use rkyv;
#[doc(hidden)]
Expand Down Expand Up @@ -203,7 +203,7 @@ where
type ServerRequest: Req<Self::Error> + Send;

/// The type of the HTTP response returned by the server function on the server side.
type ServerResponse: Res<Self::Error> + Send;
type ServerResponse: Res + TryRes<Self::Error> + Send;

/// The return type of the server function.
///
Expand Down Expand Up @@ -264,7 +264,10 @@ where
.map(|res| (res, None))
.unwrap_or_else(|e| {
(
Self::ServerResponse::error_response(Self::PATH, &e),
Self::ServerResponse::error_response(
Self::PATH,
e.ser(),
),
Some(e),
)
});
Expand Down Expand Up @@ -383,21 +386,20 @@ pub struct ServerFnTraitObj<Req, Res> {
method: Method,
handler: fn(Req) -> Pin<Box<dyn Future<Output = Res> + Send>>,
middleware: fn() -> MiddlewareSet<Req, Res>,
ser: fn(ServerFnErrorErr) -> String,
}

impl<Req, Res> ServerFnTraitObj<Req, Res> {
/// Converts the relevant parts of a server function into a trait object.
pub const fn new(
path: &'static str,
method: Method,
pub const fn new<S: ServerFn<ServerRequest = Req, ServerResponse = Res>>(
handler: fn(Req) -> Pin<Box<dyn Future<Output = Res> + Send>>,
middleware: fn() -> MiddlewareSet<Req, Res>,
) -> Self {
Self {
path,
method,
path: S::PATH,
method: S::InputEncoding::METHOD,
handler,
middleware,
middleware: S::middlewares,
ser: |e| S::Error::from_server_fn_error(e).ser(),
}
}

Expand All @@ -420,14 +422,28 @@ impl<Req, Res> ServerFnTraitObj<Req, Res> {
pub fn middleware(&self) -> MiddlewareSet<Req, Res> {
(self.middleware)()
}

/// Converts the server function into a boxed service.
pub fn boxed(self) -> BoxedService<Req, Res>
where
Self: Service<Req, Res>,
Req: 'static,
Res: 'static,
{
BoxedService::new(self.ser, self)
}
}

impl<Req, Res> Service<Req, Res> for ServerFnTraitObj<Req, Res>
where
Req: Send + 'static,
Res: 'static,
{
fn run(&mut self, req: Req) -> Pin<Box<dyn Future<Output = Res> + Send>> {
fn run(
&mut self,
req: Req,
_ser: fn(ServerFnErrorErr) -> String,
) -> Pin<Box<dyn Future<Output = Res> + Send>> {
let handler = self.handler;
Box::pin(async move { handler(req).await })
}
Expand All @@ -440,6 +456,7 @@ impl<Req, Res> Clone for ServerFnTraitObj<Req, Res> {
method: self.method.clone(),
handler: self.handler,
middleware: self.middleware,
ser: self.ser,
}
}
}
Expand All @@ -463,8 +480,8 @@ impl<Req: 'static, Res: 'static> inventory::Collect
#[cfg(feature = "axum-no-default")]
pub mod axum {
use crate::{
middleware::{BoxedService, Service},
Encoding, LazyServerFnMap, ServerFn, ServerFnTraitObj,
middleware::BoxedService, Encoding, LazyServerFnMap, ServerFn,
ServerFnTraitObj,
};
use axum::body::Body;
use http::{Method, Request, Response, StatusCode};
Expand All @@ -486,12 +503,7 @@ pub mod axum {
{
REGISTERED_SERVER_FUNCTIONS.insert(
(T::PATH.into(), T::InputEncoding::METHOD),
ServerFnTraitObj::new(
T::PATH,
T::InputEncoding::METHOD,
|req| Box::pin(T::run_on_server(req)),
T::middlewares,
),
ServerFnTraitObj::new::<T>(|req| Box::pin(T::run_on_server(req))),
);
}

Expand Down Expand Up @@ -535,7 +547,7 @@ pub mod axum {
let key = (path.into(), method);
REGISTERED_SERVER_FUNCTIONS.get(&key).map(|server_fn| {
let middleware = (server_fn.middleware)();
let mut service = BoxedService::new(server_fn.clone());
let mut service = server_fn.clone().boxed();
for middleware in middleware {
service = middleware.layer(service);
}
Expand Down Expand Up @@ -574,12 +586,7 @@ pub mod actix {
{
REGISTERED_SERVER_FUNCTIONS.insert(
(T::PATH.into(), T::InputEncoding::METHOD),
ServerFnTraitObj::new(
T::PATH,
T::InputEncoding::METHOD,
|req| Box::pin(T::run_on_server(req)),
T::middlewares,
),
ServerFnTraitObj::new::<T>(|req| Box::pin(T::run_on_server(req))),
);
}

Expand All @@ -599,7 +606,6 @@ pub mod actix {
let method = req.method();
if let Some(mut service) = get_server_fn_service(path, method) {
service
.0
.run(ActixRequest::from((req, payload)))
.await
.0
Expand Down Expand Up @@ -640,7 +646,7 @@ pub mod actix {
REGISTERED_SERVER_FUNCTIONS.get(&(path.into(), method)).map(
|server_fn| {
let middleware = (server_fn.middleware)();
let mut service = BoxedService::new(server_fn.clone());
let mut service = server_fn.clone().boxed();
for middleware in middleware {
service = middleware.layer(service);
}
Expand Down
Loading

0 comments on commit 9578607

Please sign in to comment.