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,247 @@
1
+ //! Native failures. Ruby maps each `kind` to core's fixed phrases; the detail
2
+ //! is diagnostic only and never carries paths or key material.
3
+ use std::error::Error as _;
4
+ use std::sync::OnceLock;
5
+
6
+ #[derive(Debug, Clone)]
7
+ pub struct Failure {
8
+ pub kind: &'static str,
9
+ pub detail: String,
10
+ /// HTTP/2 error code of a stream reset or connection error, if any: from
11
+ /// an RST_STREAM or GOAWAY the peer sent, or the code h2 resets a stream
12
+ /// or fails the connection with, which can reach a call before h2 writes
13
+ /// its own frame.
14
+ pub reset: Option<u32>,
15
+ pub errno: Option<i32>,
16
+ }
17
+
18
+ impl Failure {
19
+ pub fn new(kind: &'static str, detail: impl Into<String>) -> Self {
20
+ Self {
21
+ kind,
22
+ detail: detail.into(),
23
+ reset: None,
24
+ errno: None,
25
+ }
26
+ }
27
+
28
+ pub fn io(kind: &'static str, error: &std::io::Error) -> Self {
29
+ Self {
30
+ kind,
31
+ detail: error.kind().to_string(),
32
+ reset: None,
33
+ errno: error.raw_os_error().map(ruby_errno),
34
+ }
35
+ }
36
+
37
+ /// An I/O failure on an established connection. TLS 1.3 servers reject a
38
+ /// client certificate after the handshake, so their alert arrives here.
39
+ /// hyper's HTTP/1.1 body decoder reports bytes it rejects (a malformed
40
+ /// chunk, or trailers past the field or byte cap) as `InvalidData` or
41
+ /// `InvalidInput`, kinds a socket failure never has.
42
+ pub fn transport_io(error: &std::io::Error) -> Self {
43
+ match Self::rustls(error) {
44
+ Some(failure) => failure,
45
+ None if matches!(
46
+ error.kind(),
47
+ std::io::ErrorKind::InvalidData | std::io::ErrorKind::InvalidInput
48
+ ) =>
49
+ {
50
+ Self::new("protocol", "malformed response")
51
+ }
52
+ None => Self::io("closed", error),
53
+ }
54
+ }
55
+
56
+ /// The TLS failure an I/O error carries, when rustls raised it.
57
+ fn rustls(error: &std::io::Error) -> Option<Self> {
58
+ match error.get_ref()?.downcast_ref::<rustls::Error>()? {
59
+ rustls::Error::InvalidCertificate(_) => {
60
+ Some(Self::new("tls_verify", "certificate verification failed"))
61
+ }
62
+ _ => Some(Self::new("tls", "TLS failure")),
63
+ }
64
+ }
65
+
66
+ pub fn admission() -> Self {
67
+ Self::new("admission", "transport admission is closed")
68
+ }
69
+
70
+ pub fn shutdown() -> Self {
71
+ Self::new("shutdown", "transport closed")
72
+ }
73
+
74
+ /// A connection that ended under a call.
75
+ pub fn closed() -> Self {
76
+ Self::new("closed", "connection closed")
77
+ }
78
+
79
+ /// Classifies by type, HTTP/2 code and errno, never by message text. hyper
80
+ /// 1.13 fails a request waiting for a stream slot, when its connection
81
+ /// fails with a code other than NO_ERROR, with only that code
82
+ /// (`ClientTask::poll_dispatch`): an h2 error that is neither a stream
83
+ /// reset nor a GOAWAY. That is a connection failure, as h2 reports it to
84
+ /// the connection's other streams. Two other bare codes also count:
85
+ /// hyper's reset of an HTTP/2 CONNECT reply with status 200 and a nonzero
86
+ /// Content-Length, which reads "connection closed" rather than "stream
87
+ /// reset" although only that stream ended (Connect and gRPC never send
88
+ /// CONNECT), and the
89
+ /// CANCEL an aborted `CallBody` yields, which the call's abort outcome
90
+ /// supersedes.
91
+ pub fn from_hyper(error: &hyper::Error) -> Self {
92
+ let mut source = error.source();
93
+ while let Some(inner) = source {
94
+ if let Some(h2e) = inner.downcast_ref::<h2::Error>() {
95
+ if let Some(reason) = h2e.reason() {
96
+ let kind = if h2e.is_reset() { "reset" } else { "goaway" };
97
+ return Self {
98
+ kind,
99
+ detail: format!("HTTP/2 {kind} {}", u32::from(reason)),
100
+ reset: Some(u32::from(reason)),
101
+ errno: None,
102
+ };
103
+ }
104
+ if let Some(io) = h2e.get_io() {
105
+ return Self::transport_io(io);
106
+ }
107
+ }
108
+ if let Some(io) = inner.downcast_ref::<std::io::Error>() {
109
+ return Self::transport_io(io);
110
+ }
111
+ source = inner.source();
112
+ }
113
+ if error.is_parse() || error.is_parse_status() {
114
+ Self::new("protocol", "malformed response")
115
+ } else {
116
+ Self::closed()
117
+ }
118
+ }
119
+
120
+ /// A stream the server refused before processing it (RFC 9113 8.7):
121
+ /// RST_STREAM(REFUSED_STREAM), not a connection-level GOAWAY.
122
+ pub fn refused_stream(error: &hyper::Error) -> bool {
123
+ let mut source = error.source();
124
+ while let Some(inner) = source {
125
+ if let Some(h2e) = inner.downcast_ref::<h2::Error>() {
126
+ return h2e.is_reset()
127
+ && h2e.is_remote()
128
+ && h2e.reason() == Some(h2::Reason::REFUSED_STREAM);
129
+ }
130
+ source = inner.source();
131
+ }
132
+ false
133
+ }
134
+
135
+ /// h2 failed the stream for a GOAWAY the peer sent: h2 read that frame,
136
+ /// whatever else the tap saw on the socket.
137
+ pub fn remote_go_away(error: &hyper::Error) -> bool {
138
+ let mut source = error.source();
139
+ while let Some(inner) = source {
140
+ if let Some(h2e) = inner.downcast_ref::<h2::Error>() {
141
+ return h2e.is_go_away() && h2e.is_remote();
142
+ }
143
+ source = inner.source();
144
+ }
145
+ false
146
+ }
147
+ }
148
+
149
+ /// The first TLS failure rustls reported on one connection, whatever call was
150
+ /// running. hyper's HTTP/1.1 dispatcher returns an error that arrives with no
151
+ /// request queued (such as a TLS 1.3 server's `certificate_required` alert on
152
+ /// an idle connection) as its own output, so the next request only learns the
153
+ /// connection closed; h2 keeps only an I/O error's kind and text, losing the
154
+ /// rustls error. A call that then fails with a bare connection loss reports
155
+ /// this failure instead.
156
+ #[derive(Default)]
157
+ pub struct TlsFault {
158
+ failure: OnceLock<Failure>,
159
+ http2: bool,
160
+ }
161
+
162
+ impl TlsFault {
163
+ pub fn new(http2: bool) -> Self {
164
+ Self {
165
+ failure: OnceLock::new(),
166
+ http2,
167
+ }
168
+ }
169
+
170
+ /// Keeps `error`'s TLS failure if it is the first on the connection.
171
+ pub fn record(&self, error: &std::io::Error) {
172
+ if self.failure.get().is_none() {
173
+ if let Some(failure) = Failure::rustls(error) {
174
+ let _ = self.failure.set(failure);
175
+ }
176
+ }
177
+ }
178
+
179
+ /// A call's failure on this connection: a connection loss becomes the
180
+ /// recorded TLS failure. That is a closed connection, or on HTTP/2 a
181
+ /// protocol error, which is how h2 reports rustls's `InvalidData`; an
182
+ /// HTTP/1.1 protocol error is hyper's own decoding and stays. Resets,
183
+ /// GOAWAYs, limits and timeouts pass through.
184
+ pub fn resolve(&self, failure: Failure) -> Failure {
185
+ let lost = failure.kind == "closed" || (self.http2 && failure.kind == "protocol");
186
+ match self.failure.get() {
187
+ Some(tls) if lost => tls.clone(),
188
+ _ => failure,
189
+ }
190
+ }
191
+
192
+ pub fn failure(&self, error: &hyper::Error) -> Failure {
193
+ self.resolve(Failure::from_hyper(error))
194
+ }
195
+ }
196
+
197
+ /// Ruby's `Errno` number for an OS error code. Windows reports socket errors
198
+ /// as WSA codes, which Ruby maps to the C runtime's errno values when it
199
+ /// raises (win32.c's `errmap`), so `Errno::ECONNREFUSED::Errno` is 107 there,
200
+ /// not 10061. Codes without a C runtime value keep their WSA number, as Ruby
201
+ /// defines those constants.
202
+ fn ruby_errno(code: i32) -> i32 {
203
+ if cfg!(windows) {
204
+ WSA_ERRNO
205
+ .iter()
206
+ .find(|(wsa, _)| *wsa == code)
207
+ .map_or(code, |(_, errno)| *errno)
208
+ } else {
209
+ code
210
+ }
211
+ }
212
+
213
+ /// (WSA code, UCRT errno) for the socket errors Ruby's `errmap` maps.
214
+ const WSA_ERRNO: [(i32, i32); 32] = [
215
+ (10004, 4), // EINTR
216
+ (10009, 9), // EBADF
217
+ (10013, 13), // EACCES
218
+ (10014, 14), // EFAULT
219
+ (10022, 22), // EINVAL
220
+ (10024, 24), // EMFILE
221
+ (10035, 140), // EWOULDBLOCK
222
+ (10036, 112), // EINPROGRESS
223
+ (10037, 103), // EALREADY
224
+ (10038, 128), // ENOTSOCK
225
+ (10039, 109), // EDESTADDRREQ
226
+ (10040, 115), // EMSGSIZE
227
+ (10041, 136), // EPROTOTYPE
228
+ (10042, 123), // ENOPROTOOPT
229
+ (10043, 135), // EPROTONOSUPPORT
230
+ (10045, 130), // EOPNOTSUPP
231
+ (10047, 102), // EAFNOSUPPORT
232
+ (10048, 100), // EADDRINUSE
233
+ (10049, 101), // EADDRNOTAVAIL
234
+ (10050, 116), // ENETDOWN
235
+ (10051, 118), // ENETUNREACH
236
+ (10052, 117), // ENETRESET
237
+ (10053, 106), // ECONNABORTED
238
+ (10054, 108), // ECONNRESET
239
+ (10055, 119), // ENOBUFS
240
+ (10056, 113), // EISCONN
241
+ (10057, 126), // ENOTCONN
242
+ (10060, 138), // ETIMEDOUT
243
+ (10061, 107), // ECONNREFUSED
244
+ (10062, 114), // ELOOP
245
+ (10063, 38), // ENAMETOOLONG
246
+ (10065, 110), // EHOSTUNREACH
247
+ ];
@@ -0,0 +1,414 @@
1
+ //! Blocking waits with the GVL released and an unblocking function (UBF).
2
+ //!
3
+ //! Ruby calls the UBF from another thread when it wants this thread back
4
+ //! (Thread#raise, Thread#kill, signals, VM shutdown, a fiber scheduler's
5
+ //! cancellation). The UBF only fires a signal; the wait returns, and pending
6
+ //! interrupts are delivered by `rb_thread_check_ints` under `rb_protect`, so
7
+ //! no longjmp crosses Rust frames. Rust never calls Ruby inside the body.
8
+ //! A call's body may run on a fiber scheduler's worker thread
9
+ //! (RB_NOGVL_OFFLOAD_SAFE, on Ruby 4.0 and later; see `FLAGS`), so
10
+ //! everything it touches is `Send`; the close wait always runs on the
11
+ //! calling thread (see `wait_signal`).
12
+ use std::cell::Cell;
13
+ use std::ffi::c_void;
14
+ use std::future::Future;
15
+ use std::panic::{AssertUnwindSafe, catch_unwind, resume_unwind};
16
+ use std::pin::pin;
17
+ use std::sync::Arc;
18
+ use std::sync::atomic::{AtomicBool, AtomicI32, AtomicUsize, Ordering};
19
+ use std::task::{Context, Poll, Waker};
20
+ use std::time::Instant;
21
+
22
+ use magnus::{Error, Module, Ruby};
23
+ use tokio::sync::Notify;
24
+
25
+ use crate::failure::Failure;
26
+ use crate::{holds, runtime};
27
+
28
+ thread_local! {
29
+ /// Native operations driven by this Ruby thread, and the GVL releases
30
+ /// among them; specs read both to prove the unary fast path is one
31
+ /// operation that releases the GVL at most once. A ready result is taken
32
+ /// without a release, so releases alone cannot count operations.
33
+ static OPERATIONS: Cell<u64> = const { Cell::new(0) };
34
+ static WAITS: Cell<u64> = const { Cell::new(0) };
35
+ }
36
+
37
+ pub fn wait_count() -> u64 {
38
+ WAITS.with(Cell::get)
39
+ }
40
+
41
+ pub fn operation_count() -> u64 {
42
+ OPERATIONS.with(Cell::get)
43
+ }
44
+
45
+ /// Waits with the GVL released right now, across threads and fibers; specs
46
+ /// poll it to know a call is parked even when a fiber scheduler offloaded it.
47
+ static ACTIVE: AtomicUsize = AtomicUsize::new(0);
48
+
49
+ pub fn active_waits() -> usize {
50
+ ACTIVE.load(Ordering::SeqCst)
51
+ }
52
+
53
+ /// Waits that resumed the same operation after a wake without a pending
54
+ /// Ruby interrupt, across threads; specs read it to see one blocked
55
+ /// operation re-enter its wait.
56
+ static RESUMED: AtomicUsize = AtomicUsize::new(0);
57
+
58
+ pub fn resumed_waits() -> usize {
59
+ RESUMED.load(Ordering::SeqCst)
60
+ }
61
+
62
+ /// Wait bodies begun, and running now, across threads. A running body has
63
+ /// the GVL released and its unblocking function registered, so specs read
64
+ /// these to wake a wait that is really blocked rather than one between
65
+ /// bodies.
66
+ static ENTERED: AtomicUsize = AtomicUsize::new(0);
67
+ static RUNNING: AtomicUsize = AtomicUsize::new(0);
68
+
69
+ pub fn wait_bodies() -> (usize, usize) {
70
+ (
71
+ ENTERED.load(Ordering::SeqCst),
72
+ RUNNING.load(Ordering::SeqCst),
73
+ )
74
+ }
75
+
76
+ /// The `rb_nogvl` flags for a call's waits (`drive`), set once by
77
+ /// `init_flags`. The close wait never offloads (`DEFERRED_FLAGS`).
78
+ ///
79
+ /// RB_NOGVL_INTR_FAIL: with an interrupt already pending, rb_nogvl returns
80
+ /// NULL without running the body or raising.
81
+ ///
82
+ /// RB_NOGVL_OFFLOAD_SAFE lets a fiber scheduler with a worker pool run the
83
+ /// body on a worker, which `Data` and the pinned future on the waiting
84
+ /// thread's stack must outlive. Ruby 4.0's blocking-operation API (extract,
85
+ /// execute, cancel) lets io-event's worker pool finish a running body before
86
+ /// it re-raises a cancellation. Ruby 3.4 hands the body to the scheduler's
87
+ /// `blocking_operation_wait` as a plain proc (scheduler.c,
88
+ /// `rb_fiber_scheduler_blocking_operation_wait`), so a scheduler cancelled
89
+ /// while that body still runs could unwind the waiting frame under it. The
90
+ /// flag is passed only on Ruby 4.0 and later.
91
+ static FLAGS: AtomicI32 = AtomicI32::new(rb_sys::RB_NOGVL_INTR_FAIL as i32);
92
+
93
+ /// The `rb_nogvl` flags for the close wait: never RB_NOGVL_OFFLOAD_SAFE, so
94
+ /// its body runs on the calling Ruby thread. From a non-blocking fiber under
95
+ /// a fiber scheduler Ruby calls close from a helper thread
96
+ /// (`Transport#close`), so the wait takes neither the reactor thread nor one
97
+ /// of a worker pool's workers, which a sibling fiber's draining call may need.
98
+ const DEFERRED_FLAGS: i32 = rb_sys::RB_NOGVL_INTR_FAIL as i32;
99
+
100
+ /// Sets `FLAGS` from the running Ruby's version, not the headers the
101
+ /// extension was built against.
102
+ pub fn init_flags(ruby: &Ruby) -> Result<(), Error> {
103
+ let version: String = ruby.class_object().const_get("RUBY_VERSION")?;
104
+ let major: u32 = version
105
+ .split('.')
106
+ .next()
107
+ .and_then(|major| major.parse().ok())
108
+ .unwrap_or(0);
109
+ let mut flags = rb_sys::RB_NOGVL_INTR_FAIL;
110
+ if major >= 4 {
111
+ flags |= rb_sys::RB_NOGVL_OFFLOAD_SAFE;
112
+ }
113
+ FLAGS.store(flags as i32, Ordering::SeqCst);
114
+ Ok(())
115
+ }
116
+
117
+ struct Active;
118
+
119
+ impl Active {
120
+ fn enter() -> Self {
121
+ ACTIVE.fetch_add(1, Ordering::SeqCst);
122
+ Self
123
+ }
124
+ }
125
+
126
+ impl Drop for Active {
127
+ fn drop(&mut self) {
128
+ ACTIVE.fetch_sub(1, Ordering::SeqCst);
129
+ }
130
+ }
131
+
132
+ /// A one-shot wake-up signal that a UBF or another thread may fire.
133
+ #[derive(Default)]
134
+ pub struct Signal {
135
+ fired: AtomicBool,
136
+ notify: Notify,
137
+ }
138
+
139
+ impl Signal {
140
+ pub fn new() -> Arc<Self> {
141
+ Arc::new(Self::default())
142
+ }
143
+
144
+ pub fn fire(&self) {
145
+ self.fired.store(true, Ordering::SeqCst);
146
+ self.notify.notify_waiters();
147
+ }
148
+
149
+ pub fn fired(&self) -> bool {
150
+ self.fired.load(Ordering::SeqCst)
151
+ }
152
+
153
+ pub async fn wait(&self) {
154
+ loop {
155
+ let notified = self.notify.notified();
156
+ let mut notified = pin!(notified);
157
+ notified.as_mut().enable();
158
+ if self.fired() {
159
+ return;
160
+ }
161
+ notified.await;
162
+ }
163
+ }
164
+ }
165
+
166
+ struct Data<F, R> {
167
+ func: Option<F>,
168
+ out: Option<std::thread::Result<R>>,
169
+ }
170
+
171
+ unsafe extern "C" fn call<F: FnOnce() -> R, R>(data: *mut c_void) -> *mut c_void {
172
+ // SAFETY: `data` points at the caller's `Data`, which outlives rb_nogvl;
173
+ // only this body touches it while the wait runs.
174
+ let data = unsafe { &mut *(data as *mut Data<F, R>) };
175
+ let func = data.func.take().expect("nogvl body runs once");
176
+ ENTERED.fetch_add(1, Ordering::SeqCst);
177
+ RUNNING.fetch_add(1, Ordering::SeqCst);
178
+ data.out = Some(catch_unwind(AssertUnwindSafe(func)));
179
+ RUNNING.fetch_sub(1, Ordering::SeqCst);
180
+ // Any non-null value tells the caller the body ran.
181
+ std::ptr::dangling_mut::<c_void>()
182
+ }
183
+
184
+ unsafe extern "C" fn unblock(data: *mut c_void) {
185
+ // SAFETY: `data` is the `Signal` the caller keeps alive across rb_nogvl.
186
+ let signal = unsafe { &*(data as *const Signal) };
187
+ signal.fire();
188
+ }
189
+
190
+ /// Runs `func` without the GVL. `interrupt` fires when Ruby wants the thread
191
+ /// back, and `func` must return promptly once it does. Pending Ruby
192
+ /// interrupts are raised (as a magnus Error) after `func` returns.
193
+ fn without_gvl<F, R>(ruby: &Ruby, interrupt: &Arc<Signal>, func: F) -> Result<R, Error>
194
+ where
195
+ F: FnOnce() -> R + Send,
196
+ R: Send,
197
+ {
198
+ WAITS.with(|waits| waits.set(waits.get() + 1));
199
+ let _active = Active::enter();
200
+ let mut data = Data {
201
+ func: Some(func),
202
+ out: None,
203
+ };
204
+ loop {
205
+ let data_ptr = &mut data as *mut Data<F, R> as *mut c_void;
206
+ let signal_ptr = Arc::as_ptr(interrupt) as *mut c_void;
207
+ // See FLAGS. An offloading scheduler's cancellation re-raises through
208
+ // rb_nogvl after draining the body, so rb_protect keeps that raise
209
+ // from unwinding Rust frames.
210
+ let flags = FLAGS.load(Ordering::SeqCst);
211
+ let ran = magnus::rb_sys::protect(|| unsafe {
212
+ rb_sys::rb_nogvl(
213
+ Some(call::<F, R>),
214
+ data_ptr,
215
+ Some(unblock),
216
+ signal_ptr,
217
+ flags,
218
+ ) as rb_sys::VALUE
219
+ })?;
220
+ if ran != 0 {
221
+ break;
222
+ }
223
+ // Deliver the pending interrupt. A masked one (Thread.handle_interrupt)
224
+ // clears the flag without raising, and the body runs next time.
225
+ ruby.thread_check_ints()?;
226
+ }
227
+ let out = data.out.take().expect("nogvl body ran");
228
+ ruby.thread_check_ints()?;
229
+ match out {
230
+ Ok(value) => Ok(value),
231
+ Err(panic) => resume_unwind(panic),
232
+ }
233
+ }
234
+
235
+ /// What ends a wait besides the operation itself.
236
+ pub struct Waits<'a> {
237
+ /// The call's cancellation token, fired from Ruby's on_cancel.
238
+ pub cancel: Option<&'a Arc<Signal>>,
239
+ /// The exchange's abort.
240
+ pub abort: Option<&'a Arc<Signal>>,
241
+ /// The driver's forced teardown.
242
+ pub shutdown: &'a Arc<Signal>,
243
+ pub deadline: Option<Instant>,
244
+ }
245
+
246
+ enum Wake<T> {
247
+ Done(T),
248
+ Interrupted,
249
+ Canceled,
250
+ Aborted,
251
+ Shutdown,
252
+ Timeout,
253
+ }
254
+
255
+ /// Drives `future` to completion with the GVL released. The future lives in
256
+ /// this frame, so a wake without a pending Ruby interrupt resumes the same
257
+ /// operation state and never repeats a side effect. A ready result is taken
258
+ /// first without releasing the GVL, except while a spec hold point is armed:
259
+ /// one that parks the thread must not hold the GVL (see `holds`).
260
+ pub fn drive<T, F>(ruby: &Ruby, waits: &Waits<'_>, future: F) -> Result<Result<T, Failure>, Error>
261
+ where
262
+ F: Future<Output = Result<T, Failure>> + Send,
263
+ T: Send,
264
+ {
265
+ OPERATIONS.with(|operations| operations.set(operations.get() + 1));
266
+ let handle = runtime::handle();
267
+ let mut future = pin!(future);
268
+ if let Some(failure) = settled(waits) {
269
+ return Ok(Err(failure));
270
+ }
271
+ if !holds::any_armed() {
272
+ let _context = handle.enter();
273
+ let mut cx = Context::from_waker(Waker::noop());
274
+ if let Poll::Ready(result) = future.as_mut().poll(&mut cx) {
275
+ return Ok(result);
276
+ }
277
+ }
278
+ let never = Signal::new();
279
+ let cancel = waits.cancel.unwrap_or(&never);
280
+ let abort = waits.abort.unwrap_or(&never);
281
+ let shutdown = waits.shutdown;
282
+ let deadline = waits.deadline.map(tokio::time::Instant::from_std);
283
+ loop {
284
+ let interrupt = Signal::new();
285
+ let wake = without_gvl(ruby, &interrupt, || {
286
+ handle.block_on(async {
287
+ let expiry = async {
288
+ match deadline {
289
+ Some(at) => tokio::time::sleep_until(at).await,
290
+ None => std::future::pending().await,
291
+ }
292
+ };
293
+ tokio::select! {
294
+ biased;
295
+ _ = interrupt.wait() => Wake::Interrupted,
296
+ _ = abort.wait() => Wake::Aborted,
297
+ _ = shutdown.wait() => Wake::Shutdown,
298
+ _ = cancel.wait() => Wake::Canceled,
299
+ result = future.as_mut() => Wake::Done(result),
300
+ _ = expiry => Wake::Timeout,
301
+ }
302
+ })
303
+ })?;
304
+ return Ok(match wake {
305
+ Wake::Interrupted => {
306
+ RESUMED.fetch_add(1, Ordering::SeqCst);
307
+ continue;
308
+ }
309
+ Wake::Done(result) => result,
310
+ Wake::Canceled => Err(Failure::new("canceled", "call canceled")),
311
+ Wake::Aborted => Err(Failure::new("aborted", "exchange aborted")),
312
+ Wake::Shutdown => Err(Failure::shutdown()),
313
+ Wake::Timeout => Err(Failure::new("timeout", "wait timed out")),
314
+ });
315
+ }
316
+ }
317
+
318
+ fn settled(waits: &Waits<'_>) -> Option<Failure> {
319
+ if waits.abort.is_some_and(|abort| abort.fired()) {
320
+ return Some(Failure::new("aborted", "exchange aborted"));
321
+ }
322
+ if waits.shutdown.fired() {
323
+ return Some(Failure::shutdown());
324
+ }
325
+ if waits.cancel.is_some_and(|cancel| cancel.fired()) {
326
+ return Some(Failure::new("canceled", "call canceled"));
327
+ }
328
+ if waits.deadline.is_some_and(|at| at <= Instant::now()) {
329
+ return Some(Failure::new("timeout", "wait timed out"));
330
+ }
331
+ None
332
+ }
333
+
334
+ /// Waits with the GVL released until `signal` fires, for an outcome that a
335
+ /// runtime task publishes, such as a transport's teardown. A Ruby exception
336
+ /// raised meanwhile (a thread interrupt) does not end the wait: the first
337
+ /// one is held and returned once `signal` fired, for the caller to raise.
338
+ /// Every entry, re-entry after an interrupt included, waits on the calling
339
+ /// thread (`DEFERRED_FLAGS`); `Transport#close` holds a fiber scheduler's
340
+ /// cancellation, such as async's `Task#stop`, itself.
341
+ pub fn wait_signal(ruby: &Ruby, signal: &Arc<Signal>) -> Option<Error> {
342
+ let handle = runtime::handle();
343
+ let mut raised: Option<Error> = None;
344
+ while !signal.fired() {
345
+ let interrupt = Signal::new();
346
+ let (_, error) = without_gvl_deferred(ruby, &interrupt, || {
347
+ handle.block_on(async {
348
+ tokio::select! {
349
+ biased;
350
+ _ = interrupt.wait() => {}
351
+ _ = signal.wait() => {}
352
+ }
353
+ })
354
+ });
355
+ if let Some(error) = error {
356
+ raised.get_or_insert(error);
357
+ }
358
+ }
359
+ raised
360
+ }
361
+
362
+ /// Like `without_gvl`, but never raises and never offloads: it returns the
363
+ /// body's result, if the body ran, and any Ruby exception raised around it,
364
+ /// for the caller to raise later. The body runs on the calling thread.
365
+ fn without_gvl_deferred<F, R>(
366
+ ruby: &Ruby,
367
+ interrupt: &Arc<Signal>,
368
+ func: F,
369
+ ) -> (Option<R>, Option<Error>)
370
+ where
371
+ F: FnOnce() -> R + Send,
372
+ R: Send,
373
+ {
374
+ let _active = Active::enter();
375
+ let mut data = Data {
376
+ func: Some(func),
377
+ out: None,
378
+ };
379
+ loop {
380
+ let data_ptr = &mut data as *mut Data<F, R> as *mut c_void;
381
+ let signal_ptr = Arc::as_ptr(interrupt) as *mut c_void;
382
+ // With RB_NOGVL_INTR_FAIL and no offload, rb_nogvl returns without
383
+ // raising; rb_protect still keeps any raise from unwinding Rust
384
+ // frames.
385
+ let ran = magnus::rb_sys::protect(|| unsafe {
386
+ rb_sys::rb_nogvl(
387
+ Some(call::<F, R>),
388
+ data_ptr,
389
+ Some(unblock),
390
+ signal_ptr,
391
+ DEFERRED_FLAGS,
392
+ ) as rb_sys::VALUE
393
+ });
394
+ match ran {
395
+ Ok(0) => {}
396
+ Ok(_) => return (ran_output(&mut data), None),
397
+ Err(error) => return (ran_output(&mut data), Some(error)),
398
+ }
399
+ // An interrupt is pending. The caller masks thread interrupts around
400
+ // close, so this usually only clears the flag; one that raises is
401
+ // returned for the caller to hold.
402
+ if let Err(error) = ruby.thread_check_ints() {
403
+ return (None, Some(error));
404
+ }
405
+ }
406
+ }
407
+
408
+ /// The body's result, if it ran; a panic in the body resumes here.
409
+ fn ran_output<F, R>(data: &mut Data<F, R>) -> Option<R> {
410
+ match data.out.take()? {
411
+ Ok(value) => Some(value),
412
+ Err(panic) => resume_unwind(panic),
413
+ }
414
+ }