tokio_postgres/driven.rs
1//! A connection its client's calls drive too.
2//!
3//! A [`Connection`] is a future a task runs: a request reaches the socket
4//! once the client has queued it, woken that task, and a thread has taken the
5//! task up. For a caller on a thread of its own, such as one calling in over
6//! a C ABI, that wake is a thread switch on every request, with the request
7//! written only after it.
8//!
9//! [`Connection::driven_by`] shares the connection between its task and its
10//! client instead: a call that queues a request polls the connection there
11//! and then, on its own thread, which writes the request, and wakes the task
12//! only if it could not (the task, or another call, was polling it just
13//! then). What the connection waits for, its socket above all, still wakes
14//! the task: a call polls with the task's waker.
15
16use crate::client::InnerClient;
17use crate::{Client, Connection, Error};
18use std::cell::Cell;
19use std::future::Future;
20use std::pin::Pin;
21use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
22use std::task::{Context, Poll, Wake, Waker};
23use tokio::io::{AsyncRead, AsyncWrite};
24
25thread_local! {
26 /// Whether this thread is queuing a request it will drive itself, and so
27 /// needs no wake of the connection's task for; set to [`SUPPRESSED`] once
28 /// it has withheld one.
29 static QUEUING: Cell<u8> = const { Cell::new(IDLE) };
30}
31
32const IDLE: u8 = 0;
33const SUPPRESS: u8 = 1;
34const SUPPRESSED: u8 = 2;
35
36/// What wakes the connection's task for a new request, unless the thread
37/// that queued it drives the connection itself: the waker the connection
38/// polls its requests with.
39pub(crate) struct Gate {
40 /// The task's waker, as of its last poll.
41 task: Mutex<Option<Waker>>,
42}
43
44impl Gate {
45 fn task(&self) -> MutexGuard<'_, Option<Waker>> {
46 self.task.lock().unwrap_or_else(PoisonError::into_inner)
47 }
48
49 fn wake_task(&self) {
50 let waker = self.task().clone();
51 if let Some(waker) = waker {
52 waker.wake();
53 }
54 }
55}
56
57impl Wake for Gate {
58 fn wake(self: Arc<Self>) {
59 self.wake_by_ref();
60 }
61
62 fn wake_by_ref(self: &Arc<Self>) {
63 if QUEUING.get() == IDLE {
64 self.wake_task();
65 } else {
66 QUEUING.set(SUPPRESSED);
67 }
68 }
69}
70
71/// The client's end of a driven connection.
72pub(crate) trait Drive: Send + Sync {
73 /// Runs `queue`, which queues a request, and then drives the connection
74 /// on this thread, so that the request is written before this returns
75 /// if the socket takes it. Wakes the connection's task instead only if
76 /// it cannot.
77 fn queue_and_drive(&self, queue: &mut dyn FnMut() -> Result<(), Error>) -> Result<(), Error>;
78}
79
80// One per connection, behind an `Arc`: its size is no matter, and a box would
81// be one more pointer to follow at each poll.
82#[allow(clippy::large_enum_variant)]
83enum State<S, T> {
84 Running(Connection<S, T>),
85 /// Ended by a call that drove it, with what its task is to return.
86 Ended(Option<Result<(), Error>>),
87}
88
89struct Shared<S, T> {
90 state: Mutex<State<S, T>>,
91 gate: Arc<Gate>,
92}
93
94impl<S, T> Drive for Shared<S, T>
95where
96 S: AsyncRead + AsyncWrite + Unpin + Send,
97 T: AsyncRead + AsyncWrite + Unpin + Send,
98{
99 fn queue_and_drive(&self, queue: &mut dyn FnMut() -> Result<(), Error>) -> Result<(), Error> {
100 QUEUING.set(SUPPRESS);
101 let queued = queue();
102 let suppressed = QUEUING.replace(IDLE) == SUPPRESSED;
103 queued?;
104
105 let driven = match self.state.try_lock() {
106 Ok(mut state) => {
107 let task = self.gate.task().clone();
108 match (&mut *state, task) {
109 (State::Running(connection), Some(task)) => {
110 let mut cx = Context::from_waker(&task);
111 if let Poll::Ready(result) = Pin::new(connection).poll(&mut cx) {
112 // Dropping the connection fails what it had
113 // queued. Its task returns the result.
114 *state = State::Ended(Some(result));
115 drop(state);
116 task.wake();
117 }
118 true
119 }
120 // Not polled by its task yet, which will find the
121 // request when it is; or ended, the request dropped.
122 _ => false,
123 }
124 }
125 // Polled right now, by its task or another call, which may be
126 // past looking for requests.
127 Err(_) => false,
128 };
129 if suppressed && !driven {
130 self.gate.wake_task();
131 }
132 Ok(())
133 }
134}
135
136/// A [`Connection`] that its client's calls drive as well as the task that
137/// runs it: see [`Connection::driven_by`]. Like the connection, a future to
138/// spawn, which resolves when the connection closes.
139#[must_use = "futures do nothing unless polled"]
140pub struct DrivenConnection<S, T> {
141 shared: Arc<Shared<S, T>>,
142}
143
144impl<S, T> Connection<S, T>
145where
146 S: AsyncRead + AsyncWrite + Unpin + Send + 'static,
147 T: AsyncRead + AsyncWrite + Unpin + Send + 'static,
148{
149 /// Has `client`, this connection's, drive the connection from the calls
150 /// that send its requests, on their threads, rather than wake the task
151 /// running the connection for each: a request is on its way before the
152 /// call that made it first returns. The returned future is spawned in
153 /// the connection's place.
154 ///
155 /// Worth it for calls made from outside the runtime's threads, each of
156 /// which would otherwise wait for one to wake.
157 pub fn driven_by(mut self, client: &Client) -> DrivenConnection<S, T> {
158 let gate = Arc::new(Gate {
159 task: Mutex::new(None),
160 });
161 self.set_request_waker(Waker::from(gate.clone()));
162 let shared = Arc::new(Shared {
163 state: Mutex::new(State::Running(self)),
164 gate,
165 });
166 InnerClient::set_driver(client.inner(), shared.clone());
167 DrivenConnection { shared }
168 }
169}
170
171impl<S, T> Future for DrivenConnection<S, T>
172where
173 S: AsyncRead + AsyncWrite + Unpin,
174 T: AsyncRead + AsyncWrite + Unpin,
175{
176 type Output = Result<(), Error>;
177
178 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Error>> {
179 // Held by a call only while it polls the connection, which never
180 // blocks.
181 let mut state = self
182 .shared
183 .state
184 .lock()
185 .unwrap_or_else(PoisonError::into_inner);
186 let connection = match &mut *state {
187 State::Running(connection) => connection,
188 State::Ended(result) => return Poll::Ready(result.take().unwrap_or(Ok(()))),
189 };
190 {
191 let mut task = self.shared.gate.task();
192 if !task.as_ref().is_some_and(|w| w.will_wake(cx.waker())) {
193 *task = Some(cx.waker().clone());
194 }
195 }
196 let result = std::task::ready!(Pin::new(connection).poll(cx));
197 *state = State::Ended(None);
198 Poll::Ready(result)
199 }
200}
201
202impl<S, T> Drop for DrivenConnection<S, T> {
203 fn drop(&mut self) {
204 // The client keeps the shared state alive: the connection closes
205 // with its task, as one not shared does, and lets go of the task.
206 let ended = std::mem::replace(
207 &mut *self
208 .shared
209 .state
210 .lock()
211 .unwrap_or_else(PoisonError::into_inner),
212 State::Ended(None),
213 );
214 *self.shared.gate.task() = None;
215 drop(ended);
216 }
217}