server_fn 0.8.0-alpha

RPC for any web framework.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
#![forbid(unsafe_code)]
#![deny(missing_docs)]

//! # Server Functions
//!
//! This package is based on a simple idea: sometimes it’s useful to write functions
//! that will only run on the server, and call them from the client.
//!
//! If you’re creating anything beyond a toy app, you’ll need to do this all the time:
//! reading from or writing to a database that only runs on the server, running expensive
//! computations using libraries you don’t want to ship down to the client, accessing
//! APIs that need to be called from the server rather than the client for CORS reasons
//! or because you need a secret API key that’s stored on the server and definitely
//! shouldn’t be shipped down to a user’s browser.
//!
//! Traditionally, this is done by separating your server and client code, and by setting
//! up something like a REST API or GraphQL API to allow your client to fetch and mutate
//! data on the server. This is fine, but it requires you to write and maintain your code
//! in multiple separate places (client-side code for fetching, server-side functions to run),
//! as well as creating a third thing to manage, which is the API contract between the two.
//!
//! This package provides two simple primitives that allow you instead to write co-located,
//! isomorphic server functions. (*Co-located* means you can write them in your app code so
//! that they are “located alongside” the client code that calls them, rather than separating
//! the client and server sides. *Isomorphic* means you can call them from the client as if
//! you were simply calling a function; the function call has the “same shape” on the client
//! as it does on the server.)
//!
//! ### `#[server]`
//!
//! The [`#[server]`](../leptos/attr.server.html) macro allows you to annotate a function to
//! indicate that it should only run on the server (i.e., when you have an `ssr` feature in your
//! crate that is enabled).
//!
//! **Important**: Before calling a server function on a non-web platform, you must set the server URL by calling
//! [`set_server_url`](crate::client::set_server_url).
//!
//! ```rust,ignore
//! #[server]
//! async fn read_posts(how_many: usize, query: String) -> Result<Vec<Posts>, ServerFnError> {
//!   // do some server-only work here to access the database
//!   let posts = ...;
//!   Ok(posts)
//! }
//!
//! // call the function
//! # #[tokio::main]
//! # async fn main() {
//! async {
//!   let posts = read_posts(3, "my search".to_string()).await;
//!   log::debug!("posts = {posts:#?}");
//! }
//! # }
//! ```
//!
//! If you call this function from the client, it will serialize the function arguments and `POST`
//! them to the server as if they were the URL-encoded inputs in `<form method="post">`.
//!
//! Here’s what you need to remember:
//! - **Server functions must be `async`.** Even if the work being done inside the function body
//!   can run synchronously on the server, from the client’s perspective it involves an asynchronous
//!   function call.
//! - **Server functions must return `Result<T, ServerFnError>`.** Even if the work being done
//!   inside the function body can’t fail, the processes of serialization/deserialization and the
//!   network call are fallible. [`ServerFnError`] can receive generic errors.
//! - **Server functions are part of the public API of your application.** A server function is an
//!   ad hoc HTTP API endpoint, not a magic formula. Any server function can be accessed by any HTTP
//!   client. You should take care to sanitize any data being returned from the function to ensure it
//!   does not leak data that should exist only on the server.
//! - **Server functions can’t be generic.** Because each server function creates a separate API endpoint,
//!   it is difficult to monomorphize. As a result, server functions cannot be generic (for now?) If you need to use
//!   a generic function, you can define a generic inner function called by multiple concrete server functions.
//! - **Arguments and return types must be serializable.** We support a variety of different encodings,
//!   but one way or another arguments need to be serialized to be sent to the server and deserialized
//!   on the server, and the return type must be serialized on the server and deserialized on the client.
//!   This means that the set of valid server function argument and return types is a subset of all
//!   possible Rust argument and return types. (i.e., server functions are strictly more limited than
//!   ordinary functions.)
//!
//! ## Server Function Encodings
//!
//! Server functions are designed to allow a flexible combination of input and output encodings, the set
//! of which can be found in the [`codec`] module.
//!
//! Calling and handling server functions is done through the [`Protocol`] trait, which is implemented
//! for the [`Http`] and [`Websocket`] protocols. Most server functions will use the [`Http`] protocol.
//!
//! When using the [`Http`] protocol, the serialization/deserialization process for server functions
//! consists of a series of steps, each of which is represented by a different trait:
//! 1. [`IntoReq`]: The client serializes the [`ServerFn`] argument type into an HTTP request.
//! 2. The [`Client`] sends the request to the server.
//! 3. [`FromReq`]: The server deserializes the HTTP request back into the [`ServerFn`] type.
//! 4. The server calls calls [`ServerFn::run_body`] on the data.
//! 5. [`IntoRes`]: The server serializes the [`ServerFn::Output`] type into an HTTP response.
//! 6. The server integration applies any middleware from [`ServerFn::middlewares`] and responds to the request.
//! 7. [`FromRes`]: The client deserializes the response back into the [`ServerFn::Output`] type.
//!
//! [server]: ../leptos/attr.server.html
//! [`serde_qs`]: <https://docs.rs/serde_qs/latest/serde_qs/>
//! [`cbor`]: <https://docs.rs/cbor/latest/cbor/>

/// Implementations of the client side of the server function call.
pub mod client;

/// Implementations of the server side of the server function call.
pub mod server;

/// Encodings for arguments and results.
pub mod codec;

#[macro_use]
/// Error types and utilities.
pub mod error;
/// Types to add server middleware to a server function.
pub mod middleware;
/// Utilities to allow client-side redirects.
pub mod redirect;
/// Types and traits for  for HTTP requests.
pub mod request;
/// Types and traits for HTTP responses.
pub mod response;

#[cfg(feature = "actix")]
#[doc(hidden)]
pub use ::actix_web as actix_export;
#[cfg(feature = "axum-no-default")]
#[doc(hidden)]
pub use ::axum as axum_export;
#[cfg(feature = "generic")]
#[doc(hidden)]
pub use ::bytes as bytes_export;
#[cfg(feature = "generic")]
#[doc(hidden)]
pub use ::http as http_export;
// re-exported to make it possible to implement a custom Client without adding a separate
// dependency on `bytes`
pub use bytes::Bytes;
use client::Client;
use codec::{Encoding, FromReq, FromRes, IntoReq, IntoRes};
#[doc(hidden)]
pub use const_format;
#[doc(hidden)]
pub use const_str;
use dashmap::DashMap;
pub use error::ServerFnError;
#[cfg(feature = "form-redirects")]
use error::ServerFnUrlError;
use error::{FromServerFnError, ServerFnErrorErr};
use futures::{pin_mut, SinkExt, Stream, StreamExt};
use http::Method;
use middleware::{BoxedService, Layer, Service};
use once_cell::sync::Lazy;
use redirect::call_redirect_hook;
use request::Req;
use response::{ClientRes, Res, TryRes};
#[cfg(feature = "rkyv")]
pub use rkyv;
#[doc(hidden)]
pub use serde;
#[doc(hidden)]
#[cfg(feature = "serde-lite")]
pub use serde_lite;
use server::Server;
use std::{
    fmt::{Debug, Display},
    future::Future,
    marker::PhantomData,
    ops::{Deref, DerefMut},
    pin::Pin,
    sync::Arc,
};
#[doc(hidden)]
pub use xxhash_rust;

type ServerFnServerRequest<Fn> = <<Fn as ServerFn>::Server as crate::Server<
    <Fn as ServerFn>::Error,
>>::Request;
type ServerFnServerResponse<Fn> = <<Fn as ServerFn>::Server as crate::Server<
    <Fn as ServerFn>::Error,
>>::Response;

/// Defines a function that runs only on the server, but can be called from the server or the client.
///
/// The type for which `ServerFn` is implemented is actually the type of the arguments to the function,
/// while the function body itself is implemented in [`run_body`](ServerFn::run_body).
///
/// This means that `Self` here is usually a struct, in which each field is an argument to the function.
/// In other words,
/// ```rust,ignore
/// #[server]
/// pub async fn my_function(foo: String, bar: usize) -> Result<usize, ServerFnError> {
///     Ok(foo.len() + bar)
/// }
/// ```
/// should expand to
/// ```rust,ignore
/// #[derive(Serialize, Deserialize)]
/// pub struct MyFunction {
///     foo: String,
///     bar: usize
/// }
///
/// impl ServerFn for MyFunction {
///     async fn run_body() -> Result<usize, ServerFnError> {
///         Ok(foo.len() + bar)
///     }
///
///     // etc.
/// }
/// ```
pub trait ServerFn: Send + Sized {
    /// A unique path for the server function’s API endpoint, relative to the host, including its prefix.
    const PATH: &'static str;

    /// The type of the HTTP client that will send the request from the client side.
    ///
    /// For example, this might be `gloo-net` in the browser, or `reqwest` for a desktop app.
    type Client: Client<Self::Error>;

    /// The type of the HTTP server that will send the response from the server side.
    ///
    /// For example, this might be `axum` or `actix-web`.
    type Server: Server<Self::Error>;

    /// The protocol the server function uses to communicate with the client.
    type Protocol: Protocol<
        Self,
        Self::Output,
        Self::Client,
        Self::Server,
        Self::Error,
    >;

    /// The return type of the server function.
    ///
    /// This needs to be converted into `ServerResponse` on the server side, and converted
    /// *from* `ClientResponse` when received by the client.
    type Output: Send;

    /// The type of the error on the server function. Typically [`ServerFnError`], but allowed to be any type that implements [`FromServerFnError`].
    type Error: FromServerFnError + Send + Sync;

    /// Returns [`Self::PATH`].
    fn url() -> &'static str {
        Self::PATH
    }

    /// Middleware that should be applied to this server function.
    fn middlewares() -> Vec<
        Arc<
            dyn Layer<
                ServerFnServerRequest<Self>,
                ServerFnServerResponse<Self>,
            >,
        >,
    > {
        Vec::new()
    }

    /// The body of the server function. This will only run on the server.
    fn run_body(
        self,
    ) -> impl Future<Output = Result<Self::Output, Self::Error>> + Send;

    #[doc(hidden)]
    fn run_on_server(
        req: ServerFnServerRequest<Self>,
    ) -> impl Future<Output = ServerFnServerResponse<Self>> + Send {
        // Server functions can either be called by a real Client,
        // or directly by an HTML <form>. If they're accessed by a <form>, default to
        // redirecting back to the Referer.
        #[cfg(feature = "form-redirects")]
        let accepts_html = req
            .accepts()
            .map(|n| n.contains("text/html"))
            .unwrap_or(false);
        #[cfg(feature = "form-redirects")]
        let mut referer = req.referer().as_deref().map(ToOwned::to_owned);

        async move {
            #[allow(unused_variables, unused_mut)]
            // used in form redirects feature
            let (mut res, err) =
                Self::Protocol::run_server(req, Self::run_body)
                    .await
                    .map(|res| (res, None))
                    .unwrap_or_else(|e| {
                        (
                            <<Self as ServerFn>::Server as crate::Server<
                                Self::Error,
                            >>::Response::error_response(
                                Self::PATH, e.ser()
                            ),
                            Some(e),
                        )
                    });

            // if it accepts HTML, we'll redirect to the Referer
            #[cfg(feature = "form-redirects")]
            if accepts_html {
                // if it had an error, encode that error in the URL
                if let Some(err) = err {
                    if let Ok(url) = ServerFnUrlError::new(Self::PATH, err)
                        .to_url(referer.as_deref().unwrap_or("/"))
                    {
                        referer = Some(url.to_string());
                    }
                }
                // otherwise, strip error info from referer URL, as that means it's from a previous
                // call
                else if let Some(referer) = referer.as_mut() {
                    ServerFnUrlError::<Self::Error>::strip_error_info(referer)
                }

                // set the status code and Location header
                res.redirect(referer.as_deref().unwrap_or("/"));
            }

            res
        }
    }

    #[doc(hidden)]
    fn run_on_client(
        self,
    ) -> impl Future<Output = Result<Self::Output, Self::Error>> + Send {
        async move { Self::Protocol::run_client(Self::PATH, self).await }
    }
}

/// The protocol that a server function uses to communicate with the client. This trait handles
/// the server and client side of running a server function. It is implemented for the [`Http`] and
/// [`Websocket`] protocols and can be used to implement custom protocols.
pub trait Protocol<Input, Output, Client, Server, E>
where
    Server: crate::Server<E>,
    Client: crate::Client<E>,
{
    /// The HTTP method used for requests.
    const METHOD: Method;

    /// Run the server function on the server. The implementation should handle deserializing the
    /// input, running the server function, and serializing the output.
    fn run_server<F, Fut>(
        request: Server::Request,
        server_fn: F,
    ) -> impl Future<Output = Result<Server::Response, E>> + Send
    where
        F: Fn(Input) -> Fut + Send,
        Fut: Future<Output = Result<Output, E>> + Send;

    /// Run the server function on the client. The implementation should handle serializing the
    /// input, sending the request, and deserializing the output.
    fn run_client(
        path: &str,
        input: Input,
    ) -> impl Future<Output = Result<Output, E>> + Send;
}

/// The http protocol with specific input and output encodings for the request and response. This is
/// the default protocol server functions use if no override is set in the server function macro
///
/// The http protocol accepts two generic argument that define how the input and output for a server
/// function are turned into HTTP requests and responses. For example, [`Http<GetUrl, Json>`] will
/// accept a Url encoded Get request and return a JSON post response.
///
/// # Example
///
/// ```rust, no_run
/// # use server_fn_macro_default::server;
/// use serde::{Serialize, Deserialize};
/// use server_fn::{Http, ServerFnError, codec::{Json, GetUrl}};
///
/// #[derive(Debug, Clone, Serialize, Deserialize)]
/// pub struct Message {
///     user: String,
///     message: String,
/// }
///
/// // The http protocol can be used on any server function that accepts and returns arguments that implement
/// // the [`IntoReq`] and [`FromRes`] traits.
/// //
/// // In this case, the input and output encodings are [`GetUrl`] and [`Json`], respectively which requires
/// // the items to implement [`IntoReq<GetUrl, ...>`] and [`FromRes<Json, ...>`]. Both of those implementations
/// // require the items to implement [`Serialize`] and [`Deserialize`].
/// # #[cfg(feature = "browser")] {
/// #[server(protocol = Http<GetUrl, Json>)]
/// async fn echo_http(
///     input: Message,
/// ) -> Result<Message, ServerFnError> {
///     Ok(input)
/// }
/// # }
/// ```
pub struct Http<InputProtocol, OutputProtocol>(
    PhantomData<(InputProtocol, OutputProtocol)>,
);

impl<InputProtocol, OutputProtocol, Input, Output, Client, Server, E>
    Protocol<Input, Output, Client, Server, E>
    for Http<InputProtocol, OutputProtocol>
where
    Input: IntoReq<InputProtocol, Client::Request, E>
        + FromReq<InputProtocol, Server::Request, E>
        + Send,
    Output: IntoRes<OutputProtocol, Server::Response, E>
        + FromRes<OutputProtocol, Client::Response, E>
        + Send,
    E: FromServerFnError,
    InputProtocol: Encoding,
    OutputProtocol: Encoding,
    Client: crate::Client<E>,
    Server: crate::Server<E>,
{
    const METHOD: Method = InputProtocol::METHOD;

    async fn run_server<F, Fut>(
        request: Server::Request,
        server_fn: F,
    ) -> Result<Server::Response, E>
    where
        F: Fn(Input) -> Fut + Send,
        Fut: Future<Output = Result<Output, E>> + Send,
    {
        let input = Input::from_req(request).await?;

        let output = server_fn(input).await?;

        let response = Output::into_res(output).await?;

        Ok(response)
    }

    async fn run_client(path: &str, input: Input) -> Result<Output, E>
    where
        Client: crate::Client<E>,
    {
        // create and send request on client
        let req = input.into_req(path, OutputProtocol::CONTENT_TYPE)?;
        let res = Client::send(req).await?;

        let status = res.status();
        let location = res.location();
        let has_redirect_header = res.has_redirect();

        // if it returns an error status, deserialize the error using FromStr
        let res = if (400..=599).contains(&status) {
            let text = res.try_into_string().await?;
            Err(E::de(&text))
        } else {
            // otherwise, deserialize the body as is
            let output = Output::from_res(res).await?;
            Ok(output)
        }?;

        // if redirected, call the redirect hook (if that's been set)
        if (300..=399).contains(&status) || has_redirect_header {
            call_redirect_hook(&location);
        }
        Ok(res)
    }
}

/// The websocket protocol that encodes the input and output streams using a websocket connection.
///
/// The websocket protocol accepts two generic argument that define the input and output serialization
/// formats. For example, [`Websocket<CborEncoding, JsonEncoding>`] would accept a stream of Cbor-encoded messages
/// and return a stream of JSON-encoded messages.
///
/// # Example
///
/// ```rust, no_run
/// # use server_fn_macro_default::server;
/// # #[cfg(feature = "browser")] {
/// use server_fn::{ServerFnError, BoxedStream, Websocket, codec::JsonEncoding};
/// use serde::{Serialize, Deserialize};
///
/// #[derive(Clone, Serialize, Deserialize)]
/// pub struct Message {
///     user: String,
///     message: String,
/// }
/// // The websocket protocol can be used on any server function that accepts and returns a [`BoxedStream`]
/// // with items that can be encoded by the input and output encoding generics.
/// //
/// // In this case, the input and output encodings are [`Json`] and [`Json`], respectively which requires
/// // the items to implement [`Serialize`] and [`Deserialize`].
/// #[server(protocol = Websocket<JsonEncoding, JsonEncoding>)]
/// async fn echo_websocket(
///     input: BoxedStream<Message, ServerFnError>,
/// ) -> Result<BoxedStream<Message, ServerFnError>, ServerFnError> {
///     Ok(input.into())
/// }
/// # }
/// ```
pub struct Websocket<InputEncoding, OutputEncoding>(
    PhantomData<(InputEncoding, OutputEncoding)>,
);

/// A boxed stream type that can be used with the websocket protocol.
///
/// You can easily convert any static type that implement [`futures::Stream`] into a [`BoxedStream`]
/// with the [`From`] trait.
///
/// # Example
///
/// ```rust, no_run
/// use futures::StreamExt;
/// use server_fn::{BoxedStream, ServerFnError};
///
/// let stream: BoxedStream<_, ServerFnError> =
///     futures::stream::iter(0..10).map(Result::Ok).into();
/// ```
pub struct BoxedStream<T, E> {
    stream: Pin<Box<dyn Stream<Item = Result<T, E>> + Send>>,
}

impl<T, E> From<BoxedStream<T, E>>
    for Pin<Box<dyn Stream<Item = Result<T, E>> + Send>>
{
    fn from(val: BoxedStream<T, E>) -> Self {
        val.stream
    }
}

impl<T, E> Deref for BoxedStream<T, E> {
    type Target = Pin<Box<dyn Stream<Item = Result<T, E>> + Send>>;
    fn deref(&self) -> &Self::Target {
        &self.stream
    }
}

impl<T, E> DerefMut for BoxedStream<T, E> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.stream
    }
}

impl<T, E> Debug for BoxedStream<T, E> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BoxedStream").finish()
    }
}

impl<T, E, S> From<S> for BoxedStream<T, E>
where
    S: Stream<Item = Result<T, E>> + Send + 'static,
{
    fn from(stream: S) -> Self {
        BoxedStream {
            stream: Box::pin(stream),
        }
    }
}

impl<
        Input,
        InputItem,
        OutputItem,
        InputEncoding,
        OutputEncoding,
        Client,
        Server,
        E,
    > Protocol<Input, BoxedStream<OutputItem, E>, Client, Server, E>
    for Websocket<InputEncoding, OutputEncoding>
where
    Input: Deref<Target = BoxedStream<InputItem, E>>
        + Into<BoxedStream<InputItem, E>>
        + From<BoxedStream<InputItem, E>>,
    InputEncoding: Encodes<InputItem> + Decodes<InputItem>,
    OutputEncoding: Encodes<OutputItem> + Decodes<OutputItem>,
    Server: crate::Server<E>,
    E: FromServerFnError + Send,
    Client: crate::Client<E>,
    OutputItem: Send + 'static,
    InputItem: Send + 'static,
{
    const METHOD: Method = Method::GET;

    async fn run_server<F, Fut>(
        request: Server::Request,
        server_fn: F,
    ) -> Result<Server::Response, E>
    where
        F: Fn(Input) -> Fut + Send,
        Fut: Future<Output = Result<BoxedStream<OutputItem, E>, E>> + Send,
    {
        let (request_bytes, response_stream, response) =
            request.try_into_websocket().await?;
        let input = request_bytes.map(|request_bytes| match request_bytes {
            Ok(request_bytes) => {
                InputEncoding::decode(request_bytes).map_err(|e| {
                    E::from_server_fn_error(ServerFnErrorErr::Deserialization(
                        e.to_string(),
                    ))
                })
            }
            Err(err) => Err(err),
        });
        let boxed = Box::pin(input)
            as Pin<Box<dyn Stream<Item = Result<InputItem, E>> + Send>>;
        let input = BoxedStream { stream: boxed };

        let output = server_fn(input.into()).await?;

        let output = output.stream.map(|output| match output {
            Ok(output) => OutputEncoding::encode(output).map_err(|e| {
                E::from_server_fn_error(ServerFnErrorErr::Serialization(
                    e.to_string(),
                ))
            }),
            Err(err) => Err(err),
        });

        Server::spawn(async move {
            pin_mut!(response_stream);
            pin_mut!(output);
            while let Some(output) = output.next().await {
                if response_stream.send(output).await.is_err() {
                    break;
                }
            }
        })?;

        Ok(response)
    }

    fn run_client(
        path: &str,
        input: Input,
    ) -> impl Future<Output = Result<BoxedStream<OutputItem, E>, E>> + Send
    {
        let input = input.into();

        async move {
            let (stream, sink) = Client::open_websocket(path).await?;

            // Forward the input stream to the websocket
            Client::spawn(async move {
                pin_mut!(input);
                pin_mut!(sink);
                while let Some(input) = input.stream.next().await {
                    if sink
                        .send(input.and_then(|input| {
                            InputEncoding::encode(input).map_err(|e| {
                                E::from_server_fn_error(
                                    ServerFnErrorErr::Serialization(
                                        e.to_string(),
                                    ),
                                )
                            })
                        }))
                        .await
                        .is_err()
                    {
                        break;
                    }
                }
            });

            // Return the output stream
            let stream = stream.map(|request_bytes| match request_bytes {
                Ok(request_bytes) => OutputEncoding::decode(request_bytes)
                    .map_err(|e| {
                        E::from_server_fn_error(
                            ServerFnErrorErr::Deserialization(e.to_string()),
                        )
                    }),
                Err(err) => Err(err),
            });
            let boxed = Box::pin(stream)
                as Pin<Box<dyn Stream<Item = Result<OutputItem, E>> + Send>>;
            let output = BoxedStream { stream: boxed };
            Ok(output)
        }
    }
}

/// A trait for types with an associated content type.
pub trait ContentType {
    /// The MIME type of the data.
    const CONTENT_TYPE: &'static str;
}

/// A trait for types that can be encoded into a bytes for a request body.
pub trait Encodes<T>: ContentType {
    /// The error type that can be returned if the encoding fails.
    type Error: Display;

    /// Encodes the given value into a bytes.
    fn encode(output: T) -> Result<Bytes, Self::Error>;
}

/// A trait for types that can be decoded from a bytes for a response body.
pub trait Decodes<T> {
    /// The error type that can be returned if the decoding fails.
    type Error: Display;

    /// Decodes the given bytes into a value.
    fn decode(bytes: Bytes) -> Result<T, Self::Error>;
}

#[cfg(feature = "ssr")]
#[doc(hidden)]
pub use inventory;

/// Uses the `inventory` crate to initialize a map between paths and server functions.
#[macro_export]
macro_rules! initialize_server_fn_map {
    ($req:ty, $res:ty) => {
        once_cell::sync::Lazy::new(|| {
            $crate::inventory::iter::<ServerFnTraitObj<$req, $res>>
                .into_iter()
                .map(|obj| {
                    ((obj.path().to_string(), obj.method()), obj.clone())
                })
                .collect()
        })
    };
}

/// A list of middlewares that can be applied to a server function.
pub type MiddlewareSet<Req, Res> = Vec<Arc<dyn Layer<Req, Res>>>;

/// A trait object that allows multiple server functions that take the same
/// request type and return the same response type to be gathered into a single
/// collection.
pub struct ServerFnTraitObj<Req, Res> {
    path: &'static str,
    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<
        S: ServerFn<
            Server: crate::Server<S::Error, Request = Req, Response = Res>,
        >,
    >(
        handler: fn(Req) -> Pin<Box<dyn Future<Output = Res> + Send>>,
    ) -> Self
    where
        Req: crate::Req<S::Error, WebsocketResponse = Res> + Send + 'static,
        Res: crate::TryRes<S::Error> + Send + 'static,
    {
        Self {
            path: S::PATH,
            method: S::Protocol::METHOD,
            handler,
            middleware: S::middlewares,
            ser: |e| S::Error::from_server_fn_error(e).ser(),
        }
    }

    /// The path of the server function.
    pub fn path(&self) -> &'static str {
        self.path
    }

    /// The HTTP method the server function expects.
    pub fn method(&self) -> Method {
        self.method.clone()
    }

    /// The handler for this server function.
    pub fn handler(&self, req: Req) -> impl Future<Output = Res> + Send {
        (self.handler)(req)
    }

    /// The set of middleware that should be applied to this function.
    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,
        _ser: fn(ServerFnErrorErr) -> String,
    ) -> Pin<Box<dyn Future<Output = Res> + Send>> {
        let handler = self.handler;
        Box::pin(async move { handler(req).await })
    }
}

impl<Req, Res> Clone for ServerFnTraitObj<Req, Res> {
    fn clone(&self) -> Self {
        Self {
            path: self.path,
            method: self.method.clone(),
            handler: self.handler,
            middleware: self.middleware,
            ser: self.ser,
        }
    }
}

#[allow(unused)] // used by server integrations
type LazyServerFnMap<Req, Res> =
    Lazy<DashMap<(String, Method), ServerFnTraitObj<Req, Res>>>;

#[cfg(feature = "ssr")]
impl<Req: 'static, Res: 'static> inventory::Collect
    for ServerFnTraitObj<Req, Res>
{
    #[inline]
    fn registry() -> &'static inventory::Registry {
        static REGISTRY: inventory::Registry = inventory::Registry::new();
        &REGISTRY
    }
}

/// Axum integration.
#[cfg(feature = "axum-no-default")]
pub mod axum {
    use crate::{
        error::FromServerFnError, middleware::BoxedService, LazyServerFnMap,
        Protocol, Server, ServerFn, ServerFnTraitObj,
    };
    use axum::body::Body;
    use http::{Method, Request, Response, StatusCode};
    use std::future::Future;

    static REGISTERED_SERVER_FUNCTIONS: LazyServerFnMap<
        Request<Body>,
        Response<Body>,
    > = initialize_server_fn_map!(Request<Body>, Response<Body>);

    /// The axum server function backend
    pub struct AxumServerFnBackend;

    impl<E: FromServerFnError + Send + Sync> Server<E> for AxumServerFnBackend {
        type Request = Request<Body>;
        type Response = Response<Body>;

        #[allow(unused_variables)]
        fn spawn(
            future: impl Future<Output = ()> + Send + 'static,
        ) -> Result<(), E> {
            #[cfg(feature = "axum")]
            {
                tokio::spawn(future);
                Ok(())
            }
            #[cfg(not(feature = "axum"))]
            {
                Err(E::from_server_fn_error(
                    crate::error::ServerFnErrorErr::Request(
                        "No async runtime available. You need to either \
                         enable the full axum feature to pull in tokio, or \
                         implement the `Server` trait for your async runtime \
                         manually."
                            .into(),
                    ),
                ))
            }
        }
    }

    /// Explicitly register a server function. This is only necessary if you are
    /// running the server in a WASM environment (or a rare environment that the
    /// `inventory` crate won't work in.).
    pub fn register_explicit<T>()
    where
        T: ServerFn<
                Server: crate::Server<
                    T::Error,
                    Request = Request<Body>,
                    Response = Response<Body>,
                >,
            > + 'static,
    {
        REGISTERED_SERVER_FUNCTIONS.insert(
            (T::PATH.into(), T::Protocol::METHOD),
            ServerFnTraitObj::new::<T>(|req| Box::pin(T::run_on_server(req))),
        );
    }

    /// The set of all registered server function paths.
    pub fn server_fn_paths() -> impl Iterator<Item = (&'static str, Method)> {
        REGISTERED_SERVER_FUNCTIONS
            .iter()
            .map(|item| (item.path(), item.method()))
    }

    /// An Axum handler that responds to a server function request.
    pub async fn handle_server_fn(req: Request<Body>) -> Response<Body> {
        let path = req.uri().path();

        if let Some(mut service) =
            get_server_fn_service(path, req.method().clone())
        {
            service.run(req).await
        } else {
            Response::builder()
                .status(StatusCode::BAD_REQUEST)
                .body(Body::from(format!(
                    "Could not find a server function at the route {path}. \
                     \n\nIt's likely that either\n 1. The API prefix you \
                     specify in the `#[server]` macro doesn't match the \
                     prefix at which your server function handler is mounted, \
                     or \n2. You are on a platform that doesn't support \
                     automatic server function registration and you need to \
                     call ServerFn::register_explicit() on the server \
                     function type, somewhere in your `main` function.",
                )))
                .unwrap()
        }
    }

    /// Returns the server function at the given path as a service that can be modified.
    pub fn get_server_fn_service(
        path: &str,
        method: Method,
    ) -> Option<BoxedService<Request<Body>, Response<Body>>> {
        let key = (path.into(), method);
        REGISTERED_SERVER_FUNCTIONS.get(&key).map(|server_fn| {
            let middleware = (server_fn.middleware)();
            let mut service = server_fn.clone().boxed();
            for middleware in middleware {
                service = middleware.layer(service);
            }
            service
        })
    }
}

/// Actix integration.
#[cfg(feature = "actix")]
pub mod actix {
    use crate::{
        error::FromServerFnError, middleware::BoxedService,
        request::actix::ActixRequest, response::actix::ActixResponse,
        server::Server, LazyServerFnMap, Protocol, ServerFn, ServerFnTraitObj,
    };
    use actix_web::{web::Payload, HttpRequest, HttpResponse};
    use http::Method;
    #[doc(hidden)]
    pub use send_wrapper::SendWrapper;
    use std::future::Future;

    static REGISTERED_SERVER_FUNCTIONS: LazyServerFnMap<
        ActixRequest,
        ActixResponse,
    > = initialize_server_fn_map!(ActixRequest, ActixResponse);

    /// The actix server function backend
    pub struct ActixServerFnBackend;

    impl<E: FromServerFnError + Send + Sync> Server<E> for ActixServerFnBackend {
        type Request = ActixRequest;
        type Response = ActixResponse;

        fn spawn(
            future: impl Future<Output = ()> + Send + 'static,
        ) -> Result<(), E> {
            actix_web::rt::spawn(future);
            Ok(())
        }
    }

    /// Explicitly register a server function. This is only necessary if you are
    /// running the server in a WASM environment (or a rare environment that the
    /// `inventory` crate won't work in.).
    pub fn register_explicit<T>()
    where
        T: ServerFn<
                Server: crate::Server<
                    T::Error,
                    Request = ActixRequest,
                    Response = ActixResponse,
                >,
            > + 'static,
    {
        REGISTERED_SERVER_FUNCTIONS.insert(
            (T::PATH.into(), T::Protocol::METHOD),
            ServerFnTraitObj::new::<T>(|req| Box::pin(T::run_on_server(req))),
        );
    }

    /// The set of all registered server function paths.
    pub fn server_fn_paths() -> impl Iterator<Item = (&'static str, Method)> {
        REGISTERED_SERVER_FUNCTIONS
            .iter()
            .map(|item| (item.path(), item.method()))
    }

    /// An Actix handler that responds to a server function request.
    pub async fn handle_server_fn(
        req: HttpRequest,
        payload: Payload,
    ) -> HttpResponse {
        let path = req.uri().path();
        let method = req.method();
        if let Some(mut service) = get_server_fn_service(path, method) {
            service
                .run(ActixRequest::from((req, payload)))
                .await
                .0
                .take()
        } else {
            HttpResponse::BadRequest().body(format!(
                "Could not find a server function at the route {path}. \
                 \n\nIt's likely that either\n 1. The API prefix you specify \
                 in the `#[server]` macro doesn't match the prefix at which \
                 your server function handler is mounted, or \n2. You are on \
                 a platform that doesn't support automatic server function \
                 registration and you need to call \
                 ServerFn::register_explicit() on the server function type, \
                 somewhere in your `main` function.",
            ))
        }
    }

    /// Returns the server function at the given path as a service that can be modified.
    pub fn get_server_fn_service(
        path: &str,
        method: &actix_web::http::Method,
    ) -> Option<BoxedService<ActixRequest, ActixResponse>> {
        use actix_web::http::Method as ActixMethod;

        let method = match *method {
            ActixMethod::GET => Method::GET,
            ActixMethod::POST => Method::POST,
            ActixMethod::PUT => Method::PUT,
            ActixMethod::PATCH => Method::PATCH,
            ActixMethod::DELETE => Method::DELETE,
            ActixMethod::HEAD => Method::HEAD,
            ActixMethod::TRACE => Method::TRACE,
            ActixMethod::OPTIONS => Method::OPTIONS,
            ActixMethod::CONNECT => Method::CONNECT,
            _ => unreachable!(),
        };
        REGISTERED_SERVER_FUNCTIONS.get(&(path.into(), method)).map(
            |server_fn| {
                let middleware = (server_fn.middleware)();
                let mut service = server_fn.clone().boxed();
                for middleware in middleware {
                    service = middleware.layer(service);
                }
                service
            },
        )
    }
}

/// Mocks for the server function backend types when compiling for the client.
pub mod mock {
    use std::future::Future;

    /// A mocked server type that can be used in place of the actual server,
    /// when compiling for the browser.
    ///
    /// ## Panics
    /// This always panics if its methods are called. It is used solely to stub out the
    /// server type when compiling for the client.
    pub struct BrowserMockServer;

    impl<E: Send + 'static> crate::server::Server<E> for BrowserMockServer {
        type Request = crate::request::BrowserMockReq;
        type Response = crate::response::BrowserMockRes;

        fn spawn(
            _: impl Future<Output = ()> + Send + 'static,
        ) -> Result<(), E> {
            unreachable!()
        }
    }
}