connectrpc-hyper 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,241 @@
1
+ //! Spec hold points. A spec arms a named point on one driver; whatever
2
+ //! reaches an armed point parks there until the spec releases it or the
3
+ //! point's bound passes, so a spec can hold one step of an interleaving that
4
+ //! a race would otherwise decide. Two kinds of point ignore the bound and
5
+ //! hold until release: a stalled poll (`poll_stall`) and a kept value
6
+ //! (`keep`). A driver with no armed point pays one atomic load per point.
7
+ //!
8
+ //! A point that parks its thread must never park a Ruby thread holding the
9
+ //! GVL: the whole VM would stall for the point's bound, and the spec waiting
10
+ //! to observe the hold could not run. `drive` therefore skips its GVL-held
11
+ //! first poll while any point is armed in the process (`any_armed`).
12
+ use std::any::Any;
13
+ use std::collections::HashMap;
14
+ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
15
+ use std::sync::{Arc, Condvar, Mutex};
16
+ use std::task::{Context, Poll, Waker};
17
+ use std::time::Duration;
18
+
19
+ use tokio::sync::Notify;
20
+
21
+ /// Points armed across every driver in the process.
22
+ static ARMED: AtomicUsize = AtomicUsize::new(0);
23
+
24
+ pub fn any_armed() -> bool {
25
+ ARMED.load(Ordering::Acquire) > 0
26
+ }
27
+
28
+ #[derive(Default)]
29
+ pub struct Holds {
30
+ armed: AtomicBool,
31
+ points: Mutex<HashMap<String, Arc<Point>>>,
32
+ }
33
+
34
+ struct Point {
35
+ bound: Duration,
36
+ reached: AtomicUsize,
37
+ released: Mutex<bool>,
38
+ changed: Condvar,
39
+ notify: Notify,
40
+ /// Polls stalled at the point (`poll_stall`), woken on release or when
41
+ /// a re-arm retires the point.
42
+ stalled: Mutex<Stalled>,
43
+ /// Values `keep` took, dropped with the point (release, re-arm or the
44
+ /// driver's end).
45
+ kept: Mutex<Vec<Box<dyn Any + Send>>>,
46
+ }
47
+
48
+ #[derive(Default)]
49
+ struct Stalled {
50
+ wakers: Vec<Waker>,
51
+ /// A re-arm replaced the point: a poll that finds this looks up the
52
+ /// current point instead of stalling here.
53
+ retired: bool,
54
+ }
55
+
56
+ impl Point {
57
+ fn is_released(&self) -> bool {
58
+ *self.released.lock().unwrap_or_else(|e| e.into_inner())
59
+ }
60
+
61
+ fn release(&self) {
62
+ *self.released.lock().unwrap_or_else(|e| e.into_inner()) = true;
63
+ self.changed.notify_all();
64
+ self.notify.notify_waiters();
65
+ self.wake_stalled(false);
66
+ }
67
+
68
+ /// Wakes the polls stalled here, so each looks at its point again;
69
+ /// `retire` also turns away polls that have not registered yet.
70
+ fn wake_stalled(&self, retire: bool) {
71
+ let wakers = {
72
+ let mut stalled = self.stalled.lock().unwrap_or_else(|e| e.into_inner());
73
+ stalled.retired |= retire;
74
+ std::mem::take(&mut stalled.wakers)
75
+ };
76
+ for waker in wakers {
77
+ waker.wake();
78
+ }
79
+ }
80
+ }
81
+
82
+ impl Holds {
83
+ fn point(&self, name: &str) -> Option<Arc<Point>> {
84
+ if !self.armed.load(Ordering::Acquire) {
85
+ return None;
86
+ }
87
+ let points = self.points.lock().unwrap_or_else(|e| e.into_inner());
88
+ points.get(name).cloned()
89
+ }
90
+
91
+ /// Parks the current task at `name` while it is armed. A zero bound only
92
+ /// counts the arrival, without yielding: even a zero timeout waits for a
93
+ /// timer tick, which a worker parked at another point may be holding up.
94
+ pub async fn reach(&self, name: &str) {
95
+ let Some(point) = self.point(name) else {
96
+ return;
97
+ };
98
+ point.reached.fetch_add(1, Ordering::SeqCst);
99
+ if point.bound.is_zero() {
100
+ return;
101
+ }
102
+ let released = async {
103
+ loop {
104
+ let notified = point.notify.notified();
105
+ tokio::pin!(notified);
106
+ notified.as_mut().enable();
107
+ if point.is_released() {
108
+ return;
109
+ }
110
+ notified.await;
111
+ }
112
+ };
113
+ let _ = tokio::time::timeout(point.bound, released).await;
114
+ }
115
+
116
+ /// Parks the calling thread itself at `name` while it is armed: for an
117
+ /// ordering inside one poll or under a lock, where yielding would let
118
+ /// another branch of the same poll decide it. A zero bound only counts.
119
+ pub fn block(&self, name: &str) {
120
+ let Some(point) = self.point(name) else {
121
+ return;
122
+ };
123
+ point.reached.fetch_add(1, Ordering::SeqCst);
124
+ if point.bound.is_zero() {
125
+ return;
126
+ }
127
+ let released = point.released.lock().unwrap_or_else(|e| e.into_inner());
128
+ let _ = point
129
+ .changed
130
+ .wait_timeout_while(released, point.bound, |released| !*released);
131
+ }
132
+
133
+ /// Takes `value` while `name` is armed, counting the arrival, and keeps
134
+ /// it until the point is released, re-armed or dropped with the driver;
135
+ /// hands it back when unarmed. The bound does not apply: a kept value
136
+ /// stands for one that never moves on (see `request:strand`), and specs
137
+ /// arm the point with a zero bound only to count.
138
+ pub fn keep<T: Send + 'static>(&self, name: &str, value: T) -> Option<T> {
139
+ let Some(point) = self.point(name) else {
140
+ return Some(value);
141
+ };
142
+ point.reached.fetch_add(1, Ordering::SeqCst);
143
+ point
144
+ .kept
145
+ .lock()
146
+ .unwrap_or_else(|e| e.into_inner())
147
+ .push(Box::new(value));
148
+ None
149
+ }
150
+
151
+ /// Whether any point is armed on this driver: callers that build a
152
+ /// point's name check this first.
153
+ pub fn armed(&self) -> bool {
154
+ self.armed.load(Ordering::Acquire)
155
+ }
156
+
157
+ /// Stalls a poll at `name` while it is armed and not released, for an
158
+ /// IO operation a spec holds back; the bound does not apply. Each
159
+ /// stalled poll counts an arrival.
160
+ pub fn poll_stall(&self, name: &str, cx: &mut Context<'_>) -> Poll<()> {
161
+ loop {
162
+ let Some(point) = self.point(name) else {
163
+ return Poll::Ready(());
164
+ };
165
+ // Registering under the lock a release or re-arm drains with
166
+ // means neither can miss this poll.
167
+ let mut stalled = point.stalled.lock().unwrap_or_else(|e| e.into_inner());
168
+ if stalled.retired {
169
+ continue;
170
+ }
171
+ if point.is_released() {
172
+ return Poll::Ready(());
173
+ }
174
+ point.reached.fetch_add(1, Ordering::SeqCst);
175
+ if !stalled
176
+ .wakers
177
+ .iter()
178
+ .any(|waker| waker.will_wake(cx.waker()))
179
+ {
180
+ stalled.wakers.push(cx.waker().clone());
181
+ }
182
+ return Poll::Pending;
183
+ }
184
+ }
185
+
186
+ /// Arms `name`; each arrival parks for at most `bound`, except at
187
+ /// `poll_stall` and `keep`, which hold until release.
188
+ pub fn arm(&self, name: String, bound: Duration) {
189
+ let point = Arc::new(Point {
190
+ bound,
191
+ reached: AtomicUsize::new(0),
192
+ released: Mutex::new(false),
193
+ changed: Condvar::new(),
194
+ notify: Notify::new(),
195
+ stalled: Mutex::new(Stalled::default()),
196
+ kept: Mutex::new(Vec::new()),
197
+ });
198
+ let mut points = self.points.lock().unwrap_or_else(|e| e.into_inner());
199
+ match points.insert(name, point) {
200
+ // Polls stalled on the old point have no bound: they look again
201
+ // and stall on this one. Arrivals parked there keep their bound.
202
+ Some(replaced) => replaced.wake_stalled(true),
203
+ None => {
204
+ ARMED.fetch_add(1, Ordering::AcqRel);
205
+ }
206
+ }
207
+ self.armed.store(true, Ordering::Release);
208
+ }
209
+
210
+ /// Releases every arrival at `name` and disarms it. A driver with no
211
+ /// armed point goes back to the one-load check.
212
+ pub fn release(&self, name: &str) {
213
+ let point = {
214
+ let mut points = self.points.lock().unwrap_or_else(|e| e.into_inner());
215
+ let point = points.remove(name);
216
+ if points.is_empty() {
217
+ self.armed.store(false, Ordering::Release);
218
+ }
219
+ point
220
+ };
221
+ if let Some(point) = point {
222
+ ARMED.fetch_sub(1, Ordering::AcqRel);
223
+ point.release();
224
+ }
225
+ }
226
+
227
+ /// Arrivals at an armed `name`.
228
+ pub fn reached(&self, name: &str) -> usize {
229
+ let points = self.points.lock().unwrap_or_else(|e| e.into_inner());
230
+ points
231
+ .get(name)
232
+ .map_or(0, |point| point.reached.load(Ordering::SeqCst))
233
+ }
234
+ }
235
+
236
+ impl Drop for Holds {
237
+ fn drop(&mut self) {
238
+ let points = self.points.get_mut().unwrap_or_else(|e| e.into_inner());
239
+ ARMED.fetch_sub(points.len(), Ordering::AcqRel);
240
+ }
241
+ }