jsonrpsee_server/future.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//! Utilities for handling async code.
28
29use std::sync::{
30 atomic::{AtomicUsize, Ordering},
31 Arc,
32};
33
34use tokio::sync::watch;
35
36/// Create channel to determine whether
37/// the server shall continue to run or not.
38pub fn stop_channel() -> (StopHandle, ServerHandle) {
39 let (tx, rx) = tokio::sync::watch::channel(());
40 (StopHandle::new(rx), ServerHandle::new(tx))
41}
42
43/// Represent a stop handle which is a wrapper over a `multi-consumer receiver`
44/// and cloning [`StopHandle`] will get a separate instance of the underlying receiver.
45#[derive(Debug, Clone)]
46pub struct StopHandle(watch::Receiver<()>);
47
48impl StopHandle {
49 /// Create a new stop handle.
50 pub(crate) fn new(rx: watch::Receiver<()>) -> Self {
51 Self(rx)
52 }
53
54 /// A future that resolves when server has been stopped
55 /// it consumes the stop handle.
56 pub async fn shutdown(mut self) {
57 let _ = self.0.changed().await;
58 }
59}
60
61/// Error when the server has already been stopped.
62#[derive(Debug, Copy, Clone, thiserror::Error)]
63#[error("The server is already stopped")]
64pub struct AlreadyStoppedError;
65
66/// Server handle.
67///
68/// When all [`StopHandle`]'s have been `dropped` or `stop` has been called
69/// the server will be stopped.
70#[derive(Debug, Clone)]
71pub struct ServerHandle(Arc<watch::Sender<()>>);
72
73impl ServerHandle {
74 /// Create a new server handle.
75 pub(crate) fn new(tx: watch::Sender<()>) -> Self {
76 Self(Arc::new(tx))
77 }
78
79 /// Tell the server to stop without waiting for the server to stop.
80 pub fn stop(&self) -> Result<(), AlreadyStoppedError> {
81 self.0.send(()).map_err(|_| AlreadyStoppedError)
82 }
83
84 /// Wait for the server to stop.
85 pub async fn stopped(self) {
86 self.0.closed().await
87 }
88}
89
90/// Limits the number of connections.
91///
92/// Permits are only ever tried, never waited for, so they are counted with an atomic: a semaphore
93/// would lock its waiter list on every release.
94#[derive(Clone, Debug)]
95pub struct ConnectionGuard {
96 in_use: Arc<AtomicUsize>,
97 max: usize,
98}
99
100impl ConnectionGuard {
101 /// Create a new connection guard.
102 pub fn new(limit: usize) -> Self {
103 Self { in_use: Arc::new(AtomicUsize::new(0)), max: limit }
104 }
105
106 /// Acquire a connection permit.
107 pub fn try_acquire(&self) -> Option<ConnectionPermit> {
108 self.in_use
109 .try_update(Ordering::Relaxed, Ordering::Relaxed, |in_use| {
110 (in_use < self.max).then_some(in_use + 1)
111 })
112 .ok()
113 .map(|_| ConnectionPermit(self.in_use.clone()))
114 }
115
116 /// Get the number of available connection slots.
117 pub fn available_connections(&self) -> usize {
118 self.max - self.in_use.load(Ordering::Relaxed)
119 }
120
121 /// Get the maximum number of connections.
122 pub fn max_connections(&self) -> usize {
123 self.max
124 }
125}
126
127/// Connection permit, which frees its connection slot when dropped.
128#[derive(Debug)]
129pub struct ConnectionPermit(Arc<AtomicUsize>);
130
131impl Drop for ConnectionPermit {
132 fn drop(&mut self) {
133 self.0.fetch_sub(1, Ordering::Relaxed);
134 }
135}