ajj 0.6.2

Simple, modern, ergonomic JSON-RPC 2.0 router built with tower and axum
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
use crate::{
    routes::HandlerArgs, types::Response, HandlerCtx, ResponsePayload, Route, RpcRecv, RpcSend,
};
use serde_json::value::RawValue;
use std::{convert::Infallible, future::Future, marker::PhantomData, pin::Pin, task};
use tracing::{trace, Instrument};

/// Hint type for differentiating certain handler impls. See the [`Handler`]
/// trait "Handler argument type inference" section for more information.
#[derive(Debug)]
#[repr(transparent)]
pub struct State<S>(pub S);

/// Hint type for differentiating certain handler impls. See the [`Handler`]
/// trait "Handler argument type inference" section for more information.
#[derive(Debug)]
#[repr(transparent)]
pub struct Params<T>(pub T);

impl<T> From<T> for Params<T> {
    fn from(value: T) -> Self {
        Self(value)
    }
}

/// Marker type used for differentiating certain handler impls.
#[allow(missing_debug_implementations, unreachable_pub)]
pub struct PhantomState<S>(PhantomData<S>);

/// Marker type used for differentiating certain handler impls.
#[allow(missing_debug_implementations, unreachable_pub)]
pub struct PhantomParams<T>(PhantomData<T>);

/// A trait describing handlers for JSON-RPC methods.
///
/// Handlers map some input type `T` to a future that resolve to a
/// [`ResponsePayload`]. The handler may also require some state `S` to operate.
///
/// ### Returning error messages
///
/// Note that when a [`Handler`] returns a `Result`, the error type will be in
/// the [`ResponsePayload`]'s `data` field, and the message and code will
/// indicate an internal server error. To return a response with an error code
/// and custom `message` field, use a handler that returns an instance of the
/// [`ResponsePayload`] enum, and instantiate that error payload manually.
///
/// ```
/// # use ajj::ResponsePayload;
/// let handler_a = || async { Err::<(), _>("appears in \"data\"") };
/// let handler_b = || async {
///     ResponsePayload::<(), ()>::internal_error_message("appears in \"message\"".into())
/// };
/// ```
///
/// ### The [`HandlerCtx`]: tasks and notifications.
///
/// Any handler may accept the [`HandlerCtx`] as its first argument. This
/// context object is used to context associated with the client connection. It
/// can be used to spawn tasks and (when `pubsub` is enabled) send notifications
/// to the client.
///
/// Handlers **SHOULD NOT** use [`tokio::spawn`] or
/// [`tokio::task::spawn_blocking`] directly. Instead, they should use the
/// [`HandlerCtx::spawn`] or [`HandlerCtx::spawn_blocking`] methods. These
/// methods ensure that tasks are associated with the client connection, and
/// are cleaned up promptly when the connection is closed, and that the server's
/// runtime configuration is respected.
///
/// When the task itself requires a context, [`HandlerCtx::spawn_with_ctx`]
/// and [`HandlerCtx::spawn_blocking_with_ctx`] can be used to provide a context
/// to the spawned task. This is a thin wrapper around cloning the context and
/// moving it into the spawned future.
///
/// ```
/// use ajj::{Router, HandlerCtx};
///
/// # fn test_fn() -> Router<()> {
/// Router::new()
///     .route("good citizenship", |ctx: HandlerCtx| async move {
///         // Properly implemented task management. This task will
///         // automatically be cleaned up when the connection is closed.
///         ctx.spawn(async {
///            // do something
///         });
///         Ok::<_, ()>(())
///     })
///     .route("bad citizenship", |ctx: HandlerCtx| async move {
///         // Incorrect task management. Will result in the task running for
///         // some amount of time after the connection is closed.
///         tokio::spawn(async {
///            // do something
///         });
///         Ok::<_, ()>(())
///     })
/// # }
/// ```
///
/// When running on pubsub, handlers can send notifications to the client. This
/// is done by calling [`HandlerCtx::notify`]. Notifications are sent as JSON
/// objects, and are queued for sending to the client. If the client is not
/// reading from the connection, the notification will be queued in a buffer.
/// If the buffer is full, the handler will be backpressured until the buffer
/// has room.
///
/// We recommend that handler tasks `await` on the result of
/// [`HandlerCtx::notify`], to ensure that they are backpressured when the
/// notification buffer is full. If many tasks are attempting to notify the
/// same client, the buffer may fill up, and backpressure the `RouteTask` from
/// reading requests from the connection. This can lead to delays in request
/// processing.
///
///
/// ### Handler argument type inference
///
/// When the following conditions are true, the compiler may fail to infer
/// whether a handler argument is `params` or `state`:
///
/// 1. The handler takes EITHER `params` or `state`.
/// 2. The `S` type of the router would also be a valid `Params` type (i.e. it
///    impls [`DeserializeOwned`] and satisfies the other
///    requirements of [`RpcRecv`]).
/// 3. The argument to the handler matches the `S` type of the router.
///
/// ```compile_fail
/// use ajj::Router;
///
/// async fn ok() -> Result<(), ()> { Ok(()) }
///
/// # fn test_fn() -> Router<()> {
/// // These will fail to infer the `Handler` impl as the argument could be
/// // either `params` or `state`.
/// //
/// // The error will look like this:
/// // cannot infer type for type parameter `T` declared on the method
/// // `route`
/// Router::<u8>::new()
///     // "foo" and "bar" are ambiguous, as the `S` type is `u8`
///     .route("foo", |params: u8| ok())
///     .route("bar", |state: u8| ok())
///     // "baz" is unambiguous, as it has both `params` and `state` arguments
///     .route("baz", |params: u8, state: u8| ok())
///     // this is unambiguous, but a bit ugly.
///     .route("qux", |params: u8, _: u8| ok())
///     .with_state(3u8)
/// # }
/// ```
///
/// In these cases the compiler will find multiple valid impls of the `Handler`
/// trait.
///
/// The easiest way to resolve this is to avoid using the `S` type of the
/// router as the `params` argument to the handler. This will ensure that the
/// compiler can always infer the correct impl of the `Handler` trait. In cases
/// where `Params` and `S` must be the same type, you can use the [`Params`] and
/// [`State`] wrapper structs in your handler arguments to disambiguate the
/// argument type.
///
/// The usual way to fix this is to reorganize route invocations to avoid the
/// ambiguity:
///
/// ```
/// # use ajj::{Router, Params, State};
/// # async fn ok() -> Result<(), ()> { Ok(()) }
/// # fn test_fn() -> Router<()> {
/// // When "foo" is routed, the argument is unambiguous, as the `S` type
/// // is no longer `u8`.
/// Router::<u8>::new()
///     // This was already unambiguous, as having both `params` and `state` is
///     // never ambiguous
///     .route("baz", |params: u8, state: u8| ok())
///
///     // "bar" presents a problem. We'll come back to this in the next
///     // example.
///     // .route("bar", |state: u8| ok())
///
///     .with_state::<()>(3u8)
///
///     // `S` is now `()`, so the argument is unambiguous.
///     .route("foo", |params: u8| ok())
/// # }
/// ```
///
/// However this still leaves the problem of "bar". There is no way to express
/// "bar" unambiguously by reordering method invocations. In this case, you can
/// use the [`Params`] and [`State`] wrapper structs to disambiguate the
/// argument type. This should seem familiar to users of [`axum`].
///
/// ```
/// # use ajj::{Router, Params, State};
/// # async fn ok() -> Result<(), ()> { Ok(()) }
/// # fn test_fn() -> Router<()> {
/// Router::<u8>::new()
///     // This is now unambiguous, as the `Params` wrapper indicates that the
///     // argument is `params`
///     .route("foo", |Params(params): Params<u8>| ok())
///
///     // This is now umabiguous, as the `State` wrapper indicates that the
///     // argument is `state`
///     .route("bar", |State(state): State<u8>| ok())
///
///     // This was already unambiguous, as having both `params` and `state` is
///     // never ambiguous
///     .route("baz", |params: u8, state: u8| ok())
///     .with_state::<()>(3u8)
/// # }
/// ```
///
/// These wrapper structs are available only when necessary, and may not be
/// used when the `Handler` impl is unambiguous. Ambiguous handlers will always
/// result in a compilation error.
///
/// ### Handler return type inference
///
/// Handlers that always succeed or always fail may have trouble with type
/// inference, as they contain an unknown type parameter, which could be
/// anything. Here's an example of code with failed type inference:
///
/// ```compile_fail
/// # use ajj::ResponsePayload;
/// // cannot infer type of the type parameter `T` declared on the enum `Result`
/// let cant_infer_ok = || async { Err(1) };
///
/// // cannot infer type of the type parameter `E` declared on the enum `Result`
/// let cant_infer_err = || async { Ok(2) };
///
/// // cannot infer type of the type parameter `ErrData` declared on the enum `ResponsePayload`
/// let cant_infer_failure = || async { ResponsePayload(Ok(3)) };
///
/// // cannot infer type of the type parameter `ErrData` declared on the enum `ResponsePayload`
/// let cant_infer_success = || async { ResponsePayload::internal_error_with_obj(4) };
/// ```
///
/// If you encounter these sorts of inference errors, you can add turbofish to
/// your handlers' return values like so:
///
/// ```
/// # use ajj::ResponsePayload;
/// // specify the Err on your Ok
/// let handler_a = || async { Ok::<_, ()>(1) };
///
/// // specify the Ok on your Err
/// let handler_b = || async { Err::<(), _>(2) };
///
/// // specify the ErrData on your Success
/// let handler_c = || async { ResponsePayload::<_, ()>(Ok(3)) };
///
/// // specify the Payload on your Failure
/// let handler_d = || async { ResponsePayload::<(), _>::internal_error_with_obj(4) };
/// ```
#[cfg_attr(
    feature = "pubsub",
    doc = "see the [`Listener`] documetnation for more information."
)]
///
/// ## Note on `S`
///
/// The `S` type parameter is "missing" state. It represents the state that the
/// handler needs to operate. This state is passed to the handler when calling
/// [`Handler::call_with_state`].
///
/// ## Blanket Implementations
///
/// This trait is blanket implemented for the following function and closure
/// types, where `Fut` is a [`Future`] returning either [`ResponsePayload`] or
/// [`Result`]:
///
/// - `async fn()`
/// - `async fn(HandlerCtx) -> Fut`
/// - `async fn(HandlerCtx, Params) -> Fut`
/// - `async fn(HandlerCtx, S) -> Fut`
/// - `async fn(HandlerCtx, Params, S) -> Fut`
/// - `async fn(Params) -> Fut`
/// - `async fn(Params, S) -> Fut`
///
/// ### Implementer's note:
///
/// The generics on the implementation of the `Handler` trait are actually very
/// straightforward, even though they look intimidating.
///
/// The `T` type parameter is a **marker** and never needs be constructed.
/// It exists to differentiate the output impls, so that the trait can be
/// blanket implemented for many different function types. If it were simply
/// `Handler<S>`, there could only be 1 blanket impl.
///
/// However the `T` type must constrain the relevant input types. When
/// implementing `Handler<T, S>` for your own type, it is recommended to do the
/// following:
///
/// ```
/// use ajj::{Handler, HandlerArgs, ResponsePayload, RawValue};
/// use std::{pin::Pin, future::Future};
///
/// /// A marker type to differentiate this handler from other blanket impls.
/// pub struct MyMarker {
///   _sealed: (),
/// }
///
/// #[derive(Clone)]
/// pub struct MyHandler;
///
/// // the `T` type parameter should be a tuple, containing your marker type,
/// // and the components that your handler actually uses. This ensures that
/// // the implementations are always unambiguous.
/// //
/// // e.g.
/// // - (MyMarker, )
/// // - (MyMarker, HandlerArgs)
/// // - (MyMarker, HandlerArgs, Params)
/// // etc.
///
/// impl<S> Handler<(MyMarker, ), S> for MyHandler {
///   type Future = Pin<Box<dyn Future<Output = Option<Box<RawValue>>> + Send>>;
///
///   fn call_with_state(self, _args: HandlerArgs, _state: S) -> Self::Future {
///     todo!("use nothing but your struct")
///   }
/// }
///
/// impl<S> Handler<(MyMarker, HandlerArgs), S> for MyHandler {
///   type Future = Pin<Box<dyn Future<Output = Option<Box<RawValue>>> + Send>>;
///
///   fn call_with_state(self, args: HandlerArgs, _state: S) -> Self::Future {
///     todo!("use the args")
///   }
/// }
/// ```
///
/// [`DeserializeOwned`]: serde::de::DeserializeOwned
#[cfg_attr(feature = "pubsub", doc = " [`Listener`]: crate::pubsub::Listener")]
pub trait Handler<T, S>: Clone + Send + Sync + Sized + 'static {
    /// The future returned by the handler.
    type Future: Future<Output = Option<Box<RawValue>>> + Send + 'static;

    /// Call the handler with the given request and state.
    fn call_with_state(self, args: HandlerArgs, state: S) -> Self::Future;
}

/// Extension trait for [`Handler`]s.
pub(crate) trait HandlerInternal<T, S>: Handler<T, S> {
    /// Create a new handler that wraps this handler and has some state.
    fn with_state(self, state: S) -> HandlerService<Self, T, S> {
        HandlerService::new(self, state)
    }

    /// Convert the handler into a [`Route`], ready for internal registration
    /// on a [`Router`].
    ///
    /// [`Router`]: crate::Router
    #[allow(private_interfaces)]
    fn into_route(self, state: S) -> Route
    where
        T: Send + 'static,
        S: Clone + Send + Sync + 'static,
    {
        Route::new(self.with_state(state))
    }
}

impl<T, S, H> HandlerInternal<T, S> for H where H: Handler<T, S> {}

/// A [`Handler`] with some state `S` and params type `T`.
#[derive(Debug)]
pub(crate) struct HandlerService<H, T, S> {
    handler: H,
    state: S,
    _marker: std::marker::PhantomData<fn() -> T>,
}

impl<H, T, S> Clone for HandlerService<H, T, S>
where
    H: Clone,
    S: Clone,
{
    fn clone(&self) -> Self {
        Self {
            handler: self.handler.clone(),
            state: self.state.clone(),
            _marker: PhantomData,
        }
    }
}

impl<H, T, S> HandlerService<H, T, S> {
    /// Create a new handler service.
    pub(crate) const fn new(handler: H, state: S) -> Self {
        Self {
            handler,
            state,
            _marker: PhantomData,
        }
    }
}

impl<H, T, S> tower::Service<HandlerArgs> for HandlerService<H, T, S>
where
    Self: Clone,
    H: Handler<T, S>,
    T: Send + 'static,
    S: Clone + Send + Sync + 'static,
{
    type Response = Option<Box<RawValue>>;
    type Error = Infallible;
    type Future = Pin<Box<dyn Future<Output = Result<Option<Box<RawValue>>, Infallible>> + Send>>;

    fn poll_ready(&mut self, _cx: &mut task::Context<'_>) -> task::Poll<Result<(), Self::Error>> {
        task::Poll::Ready(Ok(()))
    }

    fn call(&mut self, args: HandlerArgs) -> Self::Future {
        let this = self.clone();
        Box::pin(async move {
            // This span captures standard OpenTelemetry attributes for
            // JSON-RPC according to OTEL semantic conventions.
            let span = args.span().clone();

            Ok(this
                .handler
                .call_with_state(args, this.state.clone())
                .instrument(span)
                .await
                .inspect(|res| {
                    trace!(?res, "handler response");
                }))
        })
    }
}

/// A marker type for handlers that return a [`Result`].
///
/// This type should never be constructed, and importing it is almost certainly
/// a mistake.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct OutputResult {
    _sealed: (),
}

/// A marker type for handlers that return a [`ResponsePayload`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct OutputResponsePayload {
    _sealed: (),
}

// Takes nothing, returns ResponsePayload
impl<F, Fut, Payload, ErrData, S> Handler<(OutputResponsePayload,), S> for F
where
    F: FnOnce() -> Fut + Clone + Send + Sync + 'static,
    Fut: Future<Output = ResponsePayload<Payload, ErrData>> + Send + 'static,
    Payload: RpcSend,
    ErrData: RpcSend,
{
    type Future = Pin<Box<dyn Future<Output = Option<Box<RawValue>>> + Send>>;

    fn call_with_state(self, args: HandlerArgs, _state: S) -> Self::Future {
        impl_handler_call!(args, self())
    }
}

// Takes Ctx, returns ResponsePayload
impl<F, Fut, Payload, ErrData, S> Handler<(OutputResponsePayload, HandlerCtx), S> for F
where
    F: FnOnce(HandlerCtx) -> Fut + Clone + Send + Sync + 'static,
    Fut: Future<Output = ResponsePayload<Payload, ErrData>> + Send + 'static,
    Payload: RpcSend,
    ErrData: RpcSend,
{
    type Future = Pin<Box<dyn Future<Output = Option<Box<RawValue>>> + Send>>;

    fn call_with_state(self, args: HandlerArgs, _state: S) -> Self::Future {
        impl_handler_call!(args, self(ctx))
    }
}

// Takes Params, returns ResponsePayload
impl<F, Fut, Input, Payload, ErrData, S> Handler<(OutputResponsePayload, PhantomParams<Input>), S>
    for F
where
    F: FnOnce(Input) -> Fut + Clone + Send + Sync + 'static,
    Fut: Future<Output = ResponsePayload<Payload, ErrData>> + Send + 'static,
    Input: RpcRecv,
    Payload: RpcSend,
    ErrData: RpcSend,
{
    type Future = Pin<Box<dyn Future<Output = Option<Box<RawValue>>> + Send>>;

    fn call_with_state(self, args: HandlerArgs, _state: S) -> Self::Future {
        impl_handler_call!(args, self(params: Input))
    }
}

// Takes Params<Params>, returns ResponsePayload
impl<F, Fut, Input, Payload, ErrData, S> Handler<(OutputResponsePayload, Params<Input>), S> for F
where
    F: FnOnce(Params<Input>) -> Fut + Clone + Send + Sync + 'static,
    Fut: Future<Output = ResponsePayload<Payload, ErrData>> + Send + 'static,
    Input: RpcRecv,
    Payload: RpcSend,
    ErrData: RpcSend,
{
    type Future = Pin<Box<dyn Future<Output = Option<Box<RawValue>>> + Send>>;

    fn call_with_state(self, args: HandlerArgs, _state: S) -> Self::Future {
        impl_handler_call!(args, self(params: Input))
    }
}

// Takes State, returns ResponsePayload
impl<F, Fut, Payload, ErrData, S> Handler<(OutputResponsePayload, PhantomState<S>), S> for F
where
    F: FnOnce(S) -> Fut + Clone + Send + Sync + 'static,
    Fut: Future<Output = ResponsePayload<Payload, ErrData>> + Send + 'static,
    Payload: RpcSend,
    ErrData: RpcSend,
    S: Send + Sync + 'static,
{
    type Future = Pin<Box<dyn Future<Output = Option<Box<RawValue>>> + Send>>;

    fn call_with_state(self, args: HandlerArgs, state: S) -> Self::Future {
        impl_handler_call!(args, self(state))
    }
}

// Takes State<State>, returns ResponsePayload
impl<F, Fut, Payload, ErrData, S> Handler<(OutputResponsePayload, State<S>), S> for F
where
    F: FnOnce(State<S>) -> Fut + Clone + Send + Sync + 'static,
    Fut: Future<Output = ResponsePayload<Payload, ErrData>> + Send + 'static,
    Payload: RpcSend,
    ErrData: RpcSend,
    S: Send + Sync + 'static,
{
    type Future = Pin<Box<dyn Future<Output = Option<Box<RawValue>>> + Send>>;

    fn call_with_state(self, args: HandlerArgs, state: S) -> Self::Future {
        impl_handler_call!(args, self(State(state)))
    }
}

// Takes Ctx, Params, returns ResponsePayload
impl<F, Fut, Input, Payload, ErrData, S>
    Handler<(OutputResponsePayload, HandlerCtx, PhantomParams<Input>), S> for F
where
    F: FnOnce(HandlerCtx, Input) -> Fut + Clone + Send + Sync + 'static,
    Fut: Future<Output = ResponsePayload<Payload, ErrData>> + Send + 'static,
    Input: RpcRecv,
    Payload: RpcSend,
    ErrData: RpcSend,
{
    type Future = Pin<Box<dyn Future<Output = Option<Box<RawValue>>> + Send>>;

    fn call_with_state(self, args: HandlerArgs, _state: S) -> Self::Future {
        impl_handler_call!(args, self(ctx, params: Input))
    }
}

// Takes Ctx, Params<Params>, returns ResponsePayload
impl<F, Fut, Input, Payload, ErrData, S>
    Handler<(OutputResponsePayload, HandlerCtx, Params<Input>), S> for F
where
    F: FnOnce(HandlerCtx, Params<Input>) -> Fut + Clone + Send + Sync + 'static,
    Fut: Future<Output = ResponsePayload<Payload, ErrData>> + Send + 'static,
    Input: RpcRecv,
    Payload: RpcSend,
    ErrData: RpcSend,
{
    type Future = Pin<Box<dyn Future<Output = Option<Box<RawValue>>> + Send>>;

    fn call_with_state(self, args: HandlerArgs, _state: S) -> Self::Future {
        impl_handler_call!(args, self(ctx, params: Input))
    }
}

// Takes Params, State, returns ResponsePayload
impl<F, Fut, Input, Payload, ErrData, S> Handler<(OutputResponsePayload, Input, S), S> for F
where
    F: FnOnce(Input, S) -> Fut + Clone + Send + Sync + 'static,
    Fut: Future<Output = ResponsePayload<Payload, ErrData>> + Send + 'static,
    Input: RpcRecv,
    Payload: RpcSend,
    ErrData: RpcSend,
    S: Send + Sync + 'static,
{
    type Future = Pin<Box<dyn Future<Output = Option<Box<RawValue>>> + Send>>;

    fn call_with_state(self, args: HandlerArgs, state: S) -> Self::Future {
        impl_handler_call!(args, self(params: Input, state))
    }
}

// Takes Ctx, State, returns ResponsePayload
impl<F, Fut, Payload, ErrData, S> Handler<(OutputResponsePayload, HandlerCtx, PhantomState<S>), S>
    for F
where
    F: FnOnce(HandlerCtx, S) -> Fut + Clone + Send + Sync + 'static,
    Fut: Future<Output = ResponsePayload<Payload, ErrData>> + Send + 'static,
    Payload: RpcSend,
    ErrData: RpcSend,
    S: Send + Sync + 'static,
{
    type Future = Pin<Box<dyn Future<Output = Option<Box<RawValue>>> + Send>>;

    fn call_with_state(self, args: HandlerArgs, state: S) -> Self::Future {
        impl_handler_call!(args, self(ctx, state))
    }
}

// Takes Ctx, State<State>, returns ResponsePayload
impl<F, Fut, Payload, ErrData, S> Handler<(OutputResponsePayload, HandlerCtx, State<S>), S> for F
where
    F: FnOnce(HandlerCtx, State<S>) -> Fut + Clone + Send + Sync + 'static,
    Fut: Future<Output = ResponsePayload<Payload, ErrData>> + Send + 'static,
    Payload: RpcSend,
    ErrData: RpcSend,
    S: Send + Sync + 'static,
{
    type Future = Pin<Box<dyn Future<Output = Option<Box<RawValue>>> + Send>>;

    fn call_with_state(self, args: HandlerArgs, state: S) -> Self::Future {
        impl_handler_call!(args, self(ctx, State(state)))
    }
}

// Takes Ctx, Params, State, returns ResponsePayload
impl<F, Fut, Input, Payload, ErrData, S> Handler<(OutputResponsePayload, HandlerCtx, Input, S), S>
    for F
where
    F: FnOnce(HandlerCtx, Input, S) -> Fut + Clone + Send + Sync + 'static,
    Fut: Future<Output = ResponsePayload<Payload, ErrData>> + Send + 'static,
    Input: RpcRecv,
    Payload: RpcSend,
    ErrData: RpcSend,
    S: Send + Sync + 'static,
{
    type Future = Pin<Box<dyn Future<Output = Option<Box<RawValue>>> + Send>>;

    fn call_with_state(self, args: HandlerArgs, state: S) -> Self::Future {
        impl_handler_call!(args, self(ctx, params: Input, state))
    }
}

// Takes nothing, returns Result
impl<F, Fut, Payload, ErrData, S> Handler<(OutputResult,), S> for F
where
    F: FnOnce() -> Fut + Clone + Send + Sync + 'static,
    Fut: Future<Output = Result<Payload, ErrData>> + Send + 'static,
    Payload: RpcSend,
    ErrData: RpcSend,
{
    type Future = Pin<Box<dyn Future<Output = Option<Box<RawValue>>> + Send>>;

    fn call_with_state(self, args: HandlerArgs, _state: S) -> Self::Future {
        impl_handler_call!(args, self())
    }
}

impl<F, Fut, Payload, ErrData, S> Handler<(OutputResult, HandlerCtx), S> for F
where
    F: FnOnce(HandlerCtx) -> Fut + Clone + Send + Sync + 'static,
    Fut: Future<Output = Result<Payload, ErrData>> + Send + 'static,
    Payload: RpcSend,
    ErrData: RpcSend,
{
    type Future = Pin<Box<dyn Future<Output = Option<Box<RawValue>>> + Send>>;

    fn call_with_state(self, args: HandlerArgs, _state: S) -> Self::Future {
        impl_handler_call!(args, self(ctx))
    }
}

impl<F, Fut, Input, Payload, ErrData, S> Handler<(OutputResult, PhantomParams<Input>), S> for F
where
    F: FnOnce(Input) -> Fut + Clone + Send + Sync + 'static,
    Fut: Future<Output = Result<Payload, ErrData>> + Send + 'static,
    Input: RpcRecv,
    Payload: RpcSend,
    ErrData: RpcSend,
{
    type Future = Pin<Box<dyn Future<Output = Option<Box<RawValue>>> + Send>>;

    fn call_with_state(self, args: HandlerArgs, _state: S) -> Self::Future {
        impl_handler_call!(args, self(params: Input))
    }
}

impl<F, Fut, Input, Payload, ErrData, S> Handler<(OutputResult, Params<Input>), S> for F
where
    F: FnOnce(Params<Input>) -> Fut + Clone + Send + Sync + 'static,
    Fut: Future<Output = Result<Payload, ErrData>> + Send + 'static,
    Input: RpcRecv,
    Payload: RpcSend,
    ErrData: RpcSend,
{
    type Future = Pin<Box<dyn Future<Output = Option<Box<RawValue>>> + Send>>;

    fn call_with_state(self, args: HandlerArgs, _state: S) -> Self::Future {
        impl_handler_call!(args, self(params: Input))
    }
}

impl<F, Fut, Payload, ErrData, S> Handler<(OutputResult, PhantomState<S>), S> for F
where
    F: FnOnce(S) -> Fut + Clone + Send + Sync + 'static,
    Fut: Future<Output = Result<Payload, ErrData>> + Send + 'static,
    Payload: RpcSend,
    ErrData: RpcSend,
    S: Send + Sync + 'static,
{
    type Future = Pin<Box<dyn Future<Output = Option<Box<RawValue>>> + Send>>;

    fn call_with_state(self, args: HandlerArgs, state: S) -> Self::Future {
        impl_handler_call!(args, self(state))
    }
}

impl<F, Fut, Payload, ErrData, S> Handler<(OutputResult, State<S>), S> for F
where
    F: FnOnce(State<S>) -> Fut + Clone + Send + Sync + 'static,
    Fut: Future<Output = Result<Payload, ErrData>> + Send + 'static,
    Payload: RpcSend,
    ErrData: RpcSend,
    S: Send + Sync + 'static,
{
    type Future = Pin<Box<dyn Future<Output = Option<Box<RawValue>>> + Send>>;

    fn call_with_state(self, args: HandlerArgs, state: S) -> Self::Future {
        impl_handler_call!(args, self(State(state)))
    }
}

impl<F, Fut, Input, Payload, ErrData, S>
    Handler<(OutputResult, HandlerCtx, PhantomParams<Input>), S> for F
where
    F: FnOnce(HandlerCtx, Input) -> Fut + Clone + Send + Sync + 'static,
    Fut: Future<Output = Result<Payload, ErrData>> + Send + 'static,
    Input: RpcRecv,
    Payload: RpcSend,
    ErrData: RpcSend,
{
    type Future = Pin<Box<dyn Future<Output = Option<Box<RawValue>>> + Send>>;

    fn call_with_state(self, args: HandlerArgs, _state: S) -> Self::Future {
        impl_handler_call!(args, self(ctx, params: Input))
    }
}

impl<F, Fut, Input, Payload, ErrData, S> Handler<(OutputResult, HandlerCtx, Params<Input>), S> for F
where
    F: FnOnce(HandlerCtx, Params<Input>) -> Fut + Clone + Send + Sync + 'static,
    Fut: Future<Output = Result<Payload, ErrData>> + Send + 'static,
    Input: RpcRecv,
    Payload: RpcSend,
    ErrData: RpcSend,
{
    type Future = Pin<Box<dyn Future<Output = Option<Box<RawValue>>> + Send>>;

    fn call_with_state(self, args: HandlerArgs, _state: S) -> Self::Future {
        impl_handler_call!(args, self(ctx, params: Input))
    }
}

impl<F, Fut, Input, Payload, ErrData, S> Handler<(OutputResult, Input, S), S> for F
where
    F: FnOnce(Input, S) -> Fut + Clone + Send + Sync + 'static,
    Fut: Future<Output = Result<Payload, ErrData>> + Send + 'static,
    Input: RpcRecv,
    Payload: RpcSend,
    ErrData: RpcSend,
    S: Send + Sync + 'static,
{
    type Future = Pin<Box<dyn Future<Output = Option<Box<RawValue>>> + Send>>;

    fn call_with_state(self, args: HandlerArgs, state: S) -> Self::Future {
        impl_handler_call!(args, self(params: Input, state))
    }
}

impl<F, Fut, Payload, ErrData, S> Handler<(OutputResult, HandlerCtx, PhantomState<S>), S> for F
where
    F: FnOnce(HandlerCtx, S) -> Fut + Clone + Send + Sync + 'static,
    Fut: Future<Output = Result<Payload, ErrData>> + Send + 'static,
    Payload: RpcSend,
    ErrData: RpcSend,
    S: Send + Sync + 'static,
{
    type Future = Pin<Box<dyn Future<Output = Option<Box<RawValue>>> + Send>>;

    fn call_with_state(self, args: HandlerArgs, state: S) -> Self::Future {
        impl_handler_call!(args, self(ctx, state))
    }
}

impl<F, Fut, Payload, ErrData, S> Handler<(OutputResult, HandlerCtx, State<S>), S> for F
where
    F: FnOnce(HandlerCtx, State<S>) -> Fut + Clone + Send + Sync + 'static,
    Fut: Future<Output = Result<Payload, ErrData>> + Send + 'static,
    Payload: RpcSend,
    ErrData: RpcSend,
    S: Send + Sync + 'static,
{
    type Future = Pin<Box<dyn Future<Output = Option<Box<RawValue>>> + Send>>;

    fn call_with_state(self, args: HandlerArgs, state: S) -> Self::Future {
        impl_handler_call!(args, self(ctx, State(state)))
    }
}

impl<F, Fut, Input, Payload, ErrData, S> Handler<(OutputResult, HandlerCtx, Input, S), S> for F
where
    F: FnOnce(HandlerCtx, Input, S) -> Fut + Clone + Send + Sync + 'static,
    Fut: Future<Output = Result<Payload, ErrData>> + Send + 'static,
    Input: RpcRecv,
    Payload: RpcSend,
    ErrData: RpcSend,
    S: Send + Sync + 'static,
{
    type Future = Pin<Box<dyn Future<Output = Option<Box<RawValue>>> + Send>>;

    fn call_with_state(self, args: HandlerArgs, state: S) -> Self::Future {
        impl_handler_call!(args, self(ctx, params: Input, state))
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::{HandlerCtx, ResponsePayload};

    #[derive(Clone)]
    struct NewType;

    async fn resp_ok() -> ResponsePayload<(), ()> {
        ResponsePayload(Ok(()))
    }

    async fn ok() -> Result<(), ()> {
        Ok(())
    }

    #[test]
    #[ignore = "compilation_only"]
    #[allow(unused_variables)]
    fn combination_inference() {
        let router: crate::Router<()> = crate::Router::<NewType>::new()
            //responses
            .route("respnse", ok)
            .route("respnse, ctx", |_: HandlerCtx| resp_ok())
            .route("respnse, params", |_: u16| resp_ok())
            .route("respnse, ctx, params", |_: HandlerCtx, _: u16| resp_ok())
            .route("respnse, params, state", |_: u8, _: NewType| resp_ok())
            .route("respnse, ctx, state", |_: HandlerCtx, _: NewType| resp_ok())
            .route(
                "respnse, ctx, params, state",
                |_: HandlerCtx, _: u8, _: NewType| resp_ok(),
            )
            // results
            .route("result", ok)
            .route("result, ctx", |_: HandlerCtx| ok())
            .route("result, params", |_: u16| ok())
            .route("result, ctx, params", |_: HandlerCtx, _: u16| ok())
            .route("result, params, state", |_: u8, _: NewType| ok())
            .route("result, ctx, state", |_: HandlerCtx, _: NewType| ok())
            .route(
                "result, ctx, params, state",
                |_: HandlerCtx, _: u8, _: NewType| ok(),
            )
            .with_state::<u8>(NewType)
            .route::<_, (OutputResult, State<u8>)>("no inference error", |State(state)| ok())
            .with_state(1u8);
    }
}

// Some code is this file is reproduced under the terms of the MIT license. It
// originates from the `axum` crate. The original source code can be found at
// the following URL, and the original license is included below.
//
// https://github.com/tokio-rs/axum/
//
// The MIT License (MIT)
//
// Copyright (c) 2019 Axum Contributors
//
// Permission is hereby granted, free of charge, to any
// person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the
// Software without restriction, including without
// limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software
// is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice
// shall be included in all copies or substantial portions
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.