jsonrpsee_server/middleware/rpc/layer/
either.rs

1// Copyright 2019-2021 Parity Technologies (UK) Ltd.
2//
3// Permission is hereby granted, free of charge, to any
4// person obtaining a copy of this software and associated
5// documentation files (the "Software"), to deal in the
6// Software without restriction, including without
7// limitation the rights to use, copy, modify, merge,
8// publish, distribute, sublicense, and/or sell copies of
9// the Software, and to permit persons to whom the Software
10// is furnished to do so, subject to the following
11// conditions:
12//
13// The above copyright notice and this permission notice
14// shall be included in all copies or substantial portions
15// of the Software.
16//
17// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
18// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
19// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
20// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
21// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
22// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
23// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
24// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
25// DEALINGS IN THE SOFTWARE.
26
27//! [`tower::util::Either`] but
28//! adjusted to satisfy the trait bound [`RpcServiceT].
29//!
30//! NOTE: This is introduced because it doesn't
31//! work to implement tower::Layer for
32//! external types such as future::Either.
33
34use crate::middleware::rpc::RpcServiceT;
35use jsonrpsee_types::Request;
36
37/// [`tower::util::Either`] but
38/// adjusted to satisfy the trait bound [`RpcServiceT].
39#[derive(Clone, Debug)]
40pub enum Either<A, B> {
41	/// One type of backing [`RpcServiceT`].
42	Left(A),
43	/// The other type of backing [`RpcServiceT`].
44	Right(B),
45}
46
47impl<S, A, B> tower::Layer<S> for Either<A, B>
48where
49	A: tower::Layer<S>,
50	B: tower::Layer<S>,
51{
52	type Service = Either<A::Service, B::Service>;
53
54	fn layer(&self, inner: S) -> Self::Service {
55		match self {
56			Either::Left(layer) => Either::Left(layer.layer(inner)),
57			Either::Right(layer) => Either::Right(layer.layer(inner)),
58		}
59	}
60}
61
62impl<'a, A, B> RpcServiceT<'a> for Either<A, B>
63where
64	A: RpcServiceT<'a> + Send + 'a,
65	B: RpcServiceT<'a> + Send + 'a,
66{
67	type Future = futures_util::future::Either<A::Future, B::Future>;
68
69	fn call(&self, request: Request<'a>) -> Self::Future {
70		match self {
71			Either::Left(service) => futures_util::future::Either::Left(service.call(request)),
72			Either::Right(service) => futures_util::future::Either::Right(service.call(request)),
73		}
74	}
75}