kino 0.7.2 → 0.8.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.
Files changed (117) hide show
  1. checksums.yaml +4 -4
  2. data/.yardopts +5 -0
  3. data/CHANGELOG.md +281 -0
  4. data/Cargo.lock +164 -95
  5. data/README.md +269 -438
  6. data/doc/README.md +27 -2
  7. data/doc/architecture.md +862 -43
  8. data/doc/benchmarks.md +444 -214
  9. data/doc/configuration.md +215 -0
  10. data/doc/operations.md +258 -0
  11. data/doc/rails-on-ractors.md +161 -49
  12. data/doc/streaming.md +52 -0
  13. data/doc/websockets.md +469 -0
  14. data/doc/why-kino.md +6 -6
  15. data/doc/worker-loop.md +462 -0
  16. data/ext/kino/Cargo.toml +17 -1
  17. data/ext/kino/build.rs +32 -1
  18. data/ext/kino/clippy.toml +10 -0
  19. data/ext/kino/src/access_log.rs +70 -92
  20. data/ext/kino/src/control.rs +26 -685
  21. data/ext/kino/src/counters.rs +132 -0
  22. data/ext/kino/src/cpus.rs +1 -18
  23. data/ext/kino/src/dispatch/tests.rs +731 -0
  24. data/ext/kino/src/dispatch.rs +276 -0
  25. data/ext/kino/src/doorbell.rs +108 -0
  26. data/ext/kino/src/env_strings.rs +26 -30
  27. data/ext/kino/src/framing.rs +110 -0
  28. data/ext/kino/src/gvl.rs +292 -66
  29. data/ext/kino/src/hijack/tests.rs +416 -0
  30. data/ext/kino/src/hijack.rs +471 -0
  31. data/ext/kino/src/inline/answer.rs +488 -0
  32. data/ext/kino/src/inline/conn.rs +1124 -0
  33. data/ext/kino/src/inline/deadline.rs +421 -0
  34. data/ext/kino/src/inline/encode.rs +119 -0
  35. data/ext/kino/src/inline/io.rs +487 -0
  36. data/ext/kino/src/inline/mod.rs +766 -0
  37. data/ext/kino/src/inline/parity.rs +862 -0
  38. data/ext/kino/src/inline/parse.rs +131 -0
  39. data/ext/kino/src/inline/spin.rs +428 -0
  40. data/ext/kino/src/inline/testing.rs +628 -0
  41. data/ext/kino/src/io_shards.rs +240 -192
  42. data/ext/kino/src/lane_room.rs +99 -0
  43. data/ext/kino/src/lib.rs +139 -77
  44. data/ext/kino/src/listen.rs +180 -12
  45. data/ext/kino/src/log.rs +12 -47
  46. data/ext/kino/src/logsink.rs +3 -9
  47. data/ext/kino/src/mono.rs +12 -17
  48. data/ext/kino/src/pin.rs +3 -3
  49. data/ext/kino/src/queue/mod.rs +54 -0
  50. data/ext/kino/src/queue/take.rs +503 -0
  51. data/ext/kino/src/queue/testing.rs +107 -0
  52. data/ext/kino/src/queue/tests.rs +581 -0
  53. data/ext/kino/src/queue/worker.rs +501 -0
  54. data/ext/kino/src/registry.rs +168 -379
  55. data/ext/kino/src/request.rs +834 -235
  56. data/ext/kino/src/response.rs +532 -94
  57. data/ext/kino/src/server/accept.rs +322 -0
  58. data/ext/kino/src/server/config.rs +138 -0
  59. data/ext/kino/src/server/handle.rs +247 -0
  60. data/ext/kino/src/server/intake.rs +217 -0
  61. data/ext/kino/src/server/mod.rs +157 -0
  62. data/ext/kino/src/server/natives.rs +223 -0
  63. data/ext/kino/src/server/serve/intake_tests.rs +458 -0
  64. data/ext/kino/src/server/serve.rs +436 -0
  65. data/ext/kino/src/server/tests.rs +532 -0
  66. data/ext/kino/src/shared_gvl.rs +50 -0
  67. data/ext/kino/src/slot/lane.rs +138 -0
  68. data/ext/kino/src/slot/life.rs +111 -0
  69. data/ext/kino/src/slot/load.rs +193 -0
  70. data/ext/kino/src/slot/mod.rs +494 -0
  71. data/ext/kino/src/slot/park.rs +82 -0
  72. data/ext/kino/src/stats.rs +936 -0
  73. data/ext/kino/src/symbols.rs +66 -0
  74. data/ext/kino/src/test_support.rs +24 -14
  75. data/ext/kino/src/testing.rs +409 -0
  76. data/ext/kino/src/ticker.rs +87 -0
  77. data/ext/kino/src/timer.rs +4 -7
  78. data/ext/kino/src/tls.rs +101 -131
  79. data/ext/kino/src/typed_data.rs +131 -0
  80. data/ext/kino/src/upgrade.rs +77 -0
  81. data/ext/kino/src/ws/codec.rs +470 -0
  82. data/ext/kino/src/ws/drive.rs +600 -0
  83. data/ext/kino/src/ws/handshake.rs +267 -0
  84. data/ext/kino/src/ws/mod.rs +317 -0
  85. data/ext/kino/src/ws/server_tests.rs +759 -0
  86. data/ext/kino/src/ws/socket.rs +279 -0
  87. data/ext/kino/src/ws/stats.rs +88 -0
  88. data/ext/kino/src/ws/testing.rs +156 -0
  89. data/ext/kino/src/ws/topics.rs +550 -0
  90. data/lib/kino/cli.rb +100 -9
  91. data/lib/kino/configuration.rb +32 -10
  92. data/lib/kino/crash_backoff.rb +56 -0
  93. data/lib/kino/input.rb +36 -17
  94. data/lib/kino/log.rb +8 -1
  95. data/lib/kino/monitor.rb +1 -1
  96. data/lib/kino/pool.rb +169 -0
  97. data/lib/kino/pool_scaler.rb +12 -13
  98. data/lib/kino/quarantine_monitor.rb +3 -3
  99. data/lib/kino/ractor_supervisor.rb +201 -161
  100. data/lib/kino/server.rb +291 -185
  101. data/lib/kino/slot_bank.rb +21 -9
  102. data/lib/kino/stream.rb +2 -2
  103. data/lib/kino/teardown.rb +33 -0
  104. data/lib/kino/templates/kino.rb.tt +41 -6
  105. data/lib/kino/threaded_pool.rb +87 -102
  106. data/lib/kino/version.rb +1 -1
  107. data/lib/kino/web_socket.rb +125 -0
  108. data/lib/kino/worker/loop.rb +319 -0
  109. data/lib/kino/worker.rb +345 -79
  110. data/lib/kino/worker_hooks.rb +7 -1
  111. data/lib/kino/worker_row.rb +15 -0
  112. data/lib/kino.rb +27 -3
  113. data/lib/rackup/handler/kino.rb +1 -1
  114. data/sig/kino.rbs +93 -10
  115. metadata +66 -3
  116. data/ext/kino/src/queue.rs +0 -333
  117. data/ext/kino/src/server.rs +0 -1785
data/ext/kino/src/gvl.rs CHANGED
@@ -2,37 +2,94 @@
2
2
  //!
3
3
  //! magnus does not wrap `rb_thread_call_without_gvl`, so this is the one
4
4
  //! module that talks to rb-sys directly. Everything blocking (queue pops,
5
- //! body reads/writes) must go through `without_gvl` so other Ruby threads
5
+ //! body reads/writes) must release the GVL through here, so other Ruby threads
6
6
  //! in the same ractor keep running and the VM can interrupt us via the UBF.
7
+ //! Every release is rb_thread_call_without_gvl2, which checks no interrupts: Kino runs them in
8
+ //! protected calls (released, park), so a raise comes back as Err, never jumping over Rust frames.
9
+ //! The one other GVL hand-over, `pass`, is rb_thread_schedule in a protected call too.
7
10
 
8
11
  use std::any::Any;
9
12
  use std::ffi::c_void;
13
+ use std::marker::PhantomData;
10
14
  use std::panic::{catch_unwind, AssertUnwindSafe};
15
+ use std::sync::atomic::{AtomicBool, Ordering};
11
16
 
12
17
  use magnus::{Error, Ruby};
13
18
 
14
19
  /// An unblock function: called by the Ruby VM from another thread when it
15
20
  /// needs to interrupt the blocking region (Thread#kill, VM shutdown, ...).
16
21
  /// Implementations must be async-signal-safe in spirit: no locks, no Ruby
17
- /// API. A single lock-free channel send is the intended use.
18
- pub struct Ubf {
19
- pub func: unsafe extern "C" fn(*mut c_void),
20
- pub data: *mut c_void,
22
+ /// API. Its flag stays borrowed for as long as the release it is handed to runs.
23
+ #[derive(Clone, Copy)]
24
+ pub struct Ubf<'a> {
25
+ func: unsafe extern "C" fn(*mut c_void),
26
+ data: *mut c_void,
27
+ flag: PhantomData<&'a AtomicBool>,
21
28
  }
22
29
 
30
+ impl<'a> Ubf<'a> {
31
+ /// Raises `flag` (a slot's, or a wait's own), which the blocked region polls between waits.
32
+ pub fn interrupt(flag: &'a AtomicBool) -> Self {
33
+ Ubf {
34
+ func: ubf_interrupt,
35
+ data: flag as *const AtomicBool as *mut c_void,
36
+ flag: PhantomData,
37
+ }
38
+ }
39
+ }
40
+
41
+ unsafe extern "C" fn ubf_interrupt(data: *mut c_void) {
42
+ // SAFETY: `data` is the flag of a Ubf::interrupt, whose borrow
43
+ // outlives the release the VM calls this from.
44
+ let flag = unsafe { &*(data as *const AtomicBool) };
45
+ flag.store(true, Ordering::SeqCst);
46
+ }
47
+
48
+ /// What a release runs, then what it returned or the panic it raised. A release that did not
49
+ /// run it leaves it there.
50
+ type Slot<F, R> = (Option<F>, Option<std::thread::Result<R>>);
51
+
23
52
  unsafe extern "C" fn trampoline<F, R>(arg: *mut c_void) -> *mut c_void
24
53
  where
25
54
  F: FnOnce() -> R,
26
55
  {
27
- let slot = unsafe { &mut *(arg as *mut (Option<F>, Option<std::thread::Result<R>>)) };
28
- let f = slot.0.take().expect("without_gvl trampoline called twice");
56
+ // SAFETY: `arg` is the Slot<F, R> that `call` hands its release,
57
+ // borrowed by nothing else until the release returns.
58
+ let slot = unsafe { &mut *(arg as *mut Slot<F, R>) };
59
+ let f = slot.0.take().expect("a release ran its work twice");
29
60
  // A panic must not unwind into the VM's C frame beneath us (that
30
- // aborts the process); catch it here and let without_gvl rethrow it
61
+ // aborts the process); catch it here and let the caller rethrow it
31
62
  // as a Ruby exception once the GVL is held again.
32
63
  slot.1 = Some(catch_unwind(AssertUnwindSafe(f)));
33
64
  std::ptr::null_mut()
34
65
  }
35
66
 
67
+ /// Run what `slot` holds with the GVL released, unless an interrupt is pending (without_gvl2).
68
+ /// Always inlined, so each release stays a direct call, its slot on the caller's own frame.
69
+ #[inline(always)]
70
+ // The crate's one GVL release (clippy.toml bars the others).
71
+ #[allow(clippy::disallowed_methods)]
72
+ fn call<F, R>(slot: &mut Slot<F, R>, ubf: Option<Ubf<'_>>)
73
+ where
74
+ F: FnOnce() -> R,
75
+ {
76
+ let (ubf_func, ubf_data) = match ubf {
77
+ Some(u) => (Some(u.func), u.data),
78
+ None => (None, std::ptr::null_mut()),
79
+ };
80
+ // SAFETY: `slot` is borrowed for as long as the release runs, which runs `trampoline::<F, R>`
81
+ // on it at most once. The VM calls the unblock function only while the release runs, which
82
+ // the Ubf's borrow of its data outlives.
83
+ unsafe {
84
+ rb_sys::rb_thread_call_without_gvl2(
85
+ Some(trampoline::<F, R>),
86
+ slot as *mut Slot<F, R> as *mut c_void,
87
+ ubf_func,
88
+ ubf_data,
89
+ );
90
+ }
91
+ }
92
+
36
93
  /// The caught panic payload as a plain RuntimeError, built with the GVL
37
94
  /// held. Deliberately not magnus's own panic conversion: that raises
38
95
  /// `fatal`, which still ends the process; a RuntimeError flows through
@@ -45,7 +102,7 @@ fn panic_error(payload: Box<dyn Any + Send>) -> Error {
45
102
  } else {
46
103
  "opaque panic payload".to_string()
47
104
  };
48
- let ruby = Ruby::get().expect("without_gvl requires a Ruby thread");
105
+ let ruby = Ruby::get().expect("a release runs on a Ruby thread");
49
106
  Error::new(
50
107
  ruby.exception_runtime_error(),
51
108
  format!("Kino: panic in native blocking call: {msg}"),
@@ -54,83 +111,252 @@ fn panic_error(payload: Box<dyn Any + Send>) -> Error {
54
111
 
55
112
  /// Run `f` with the GVL released. Blocks the current Ruby thread but lets
56
113
  /// every other Ruby thread (in this ractor) run in parallel.
114
+ /// Pending interrupts run before and after `f` in protected calls: a raise comes back as Err.
57
115
  ///
58
- /// `f` MUST NOT touch any Ruby API. If `ubf` fires, `f` is responsible for
59
- /// noticing (e.g. a message on an interrupt channel) and returning promptly;
60
- /// pending VM interrupts are then delivered once we're back in Ruby.
116
+ /// `f` MUST NOT touch any Ruby API. The VM's unblock function raises `woken`, if any: `f` is
117
+ /// responsible for noticing and returning promptly.
61
118
  ///
62
119
  /// A panic in `f` comes back as `Err` (RuntimeError with the panic
63
120
  /// message); the default panic hook still reports it to stderr first.
64
- pub fn without_gvl<F, R>(f: F, ubf: Option<Ubf>) -> Result<R, Error>
65
- where
66
- F: FnOnce() -> R,
67
- {
68
- let mut slot: (Option<F>, Option<std::thread::Result<R>>) = (Some(f), None);
69
- let (ubf_func, ubf_data) = match ubf {
70
- Some(u) => (Some(u.func), u.data),
71
- None => (None, std::ptr::null_mut()),
72
- };
73
- unsafe {
74
- rb_sys::rb_thread_call_without_gvl(
75
- Some(trampoline::<F, R>),
76
- &mut slot as *mut _ as *mut c_void,
77
- ubf_func,
78
- ubf_data,
79
- );
121
+ pub fn released<R>(f: impl FnOnce() -> R, woken: Option<&AtomicBool>) -> Result<R, Error> {
122
+ let unread = AtomicBool::new(false);
123
+ released_by(&mut Released, woken.unwrap_or(&unread), f)
124
+ }
125
+
126
+ /// released, where `parker` waits: tests stand in for the VM.
127
+ pub(crate) fn released_by<P: Parker, R>(
128
+ parker: &mut P,
129
+ woken: &AtomicBool,
130
+ f: impl FnOnce() -> R,
131
+ ) -> Result<R, P::Error> {
132
+ let mut f = Some(f);
133
+ loop {
134
+ let ran = parker.release(woken, || f.take().map(|f| f()));
135
+ parker.check_ints()?;
136
+ if let Some(ran) = ran?.flatten() {
137
+ return Ok(ran);
138
+ }
80
139
  }
81
- match slot.1.expect("without_gvl block did not run") {
82
- Ok(value) => Ok(value),
83
- Err(payload) => Err(panic_error(payload)),
140
+ }
141
+
142
+ /// Run `f` with the GVL released, or held while an interrupt is pending: `f` always runs, and
143
+ /// no interrupt runs here (for paths that cannot pass an error on); a panic comes back as Err.
144
+ pub fn released_or_held<R>(f: impl FnOnce() -> R) -> Result<R, Error> {
145
+ let (unread, mut f) = (AtomicBool::new(false), Some(f));
146
+ let ran = Released
147
+ .release(&unread, || f.take().map(|f| f()))?
148
+ .flatten();
149
+ match f {
150
+ Some(f) => catch_unwind(AssertUnwindSafe(f)).map_err(panic_error),
151
+ None => Ok(ran.expect("a release that took its work ran it")),
84
152
  }
85
153
  }
86
154
 
87
- /// The standard UBF used across this crate: `data` points at an `AtomicBool`
88
- /// owned by a `WorkerSlot` kept alive by the caller's stack frame (an Arc
89
- /// clone held across the blocking call). The blocked region polls the flag
90
- /// between bounded waits, so a store here unblocks it within one tick.
91
- pub unsafe extern "C" fn ubf_interrupt(data: *mut c_void) {
92
- let flag = unsafe { &*(data as *const std::sync::atomic::AtomicBool) };
93
- flag.store(true, std::sync::atomic::Ordering::SeqCst);
155
+ /// Thread.pass: the threads waiting for this GVL run first, and this one returns once it holds it
156
+ /// again, at once when none waits. Its interrupt check runs in a protected call: a raise comes
157
+ /// back as Err.
158
+ // rb_thread_schedule is barred for its unprotected interrupt check, which this protects.
159
+ #[allow(clippy::disallowed_methods)]
160
+ pub fn pass() -> Result<(), Error> {
161
+ magnus::rb_sys::protect(|| {
162
+ // SAFETY: called on a Ruby thread holding its GVL, as every caller of this crate's
163
+ // natives is.
164
+ unsafe { rb_sys::rb_thread_schedule() };
165
+ rb_sys::Qnil as rb_sys::VALUE
166
+ })?;
167
+ Ok(())
94
168
  }
95
169
 
96
- /// The crate's one blocking idiom: release the GVL and run `attempt` in a
97
- /// loop (`Some(T)` finishes, `None` means "tick elapsed, go around"), and
98
- /// wake within a tick when `flag` is raised (by the VM's UBF or by
99
- /// interrupt_all_workers). Returns Ok(None) on interruption, Err when
100
- /// `attempt` panicked. `attempt` must bound each wait (recv_timeout-style)
101
- /// and must not touch the Ruby API.
102
- pub fn interruptible<T>(
103
- flag: &std::sync::atomic::AtomicBool,
104
- mut attempt: impl FnMut() -> Option<T>,
105
- ) -> Result<Option<T>, Error> {
106
- use std::sync::atomic::Ordering;
170
+ /// How a worker's thread waits: Released, or in place in tests (no VM).
171
+ pub(crate) trait Parker {
172
+ type Error;
173
+
174
+ /// Runs `f` (no Ruby inside), unblocked by raising `woken`; None while an interrupt is pending.
175
+ fn release<R>(
176
+ &mut self,
177
+ woken: &AtomicBool,
178
+ f: impl FnOnce() -> R,
179
+ ) -> Result<Option<R>, Self::Error>;
180
+
181
+ /// Runs the thread's pending VM interrupts; Err when one raised.
182
+ fn check_ints(&mut self) -> Result<(), Self::Error>;
183
+ }
184
+
185
+ /// The GVL released with no interrupt check of the release's own (nothing raises past the
186
+ /// caller's frames; a panic in `f` comes back as Err); check_ints runs them in a protected call.
187
+ pub(crate) struct Released;
188
+
189
+ impl Parker for Released {
190
+ type Error = Error;
107
191
 
108
- without_gvl(
109
- || loop {
110
- if flag.load(Ordering::SeqCst) {
192
+ fn release<R>(
193
+ &mut self,
194
+ woken: &AtomicBool,
195
+ f: impl FnOnce() -> R,
196
+ ) -> Result<Option<R>, Error> {
197
+ let mut slot = (Some(f), None);
198
+ let ubf = Some(Ubf::interrupt(woken));
199
+ call(&mut slot, ubf);
200
+ slot.1.map(|ran| ran.map_err(panic_error)).transpose()
201
+ }
202
+
203
+ fn check_ints(&mut self) -> Result<(), Error> {
204
+ Ruby::get()
205
+ .expect("a release runs on a Ruby thread")
206
+ .thread_check_ints()
207
+ }
208
+ }
209
+
210
+ /// The crate's blocking idiom (a worker's next item, a request body, room for a chunk):
211
+ /// `attempt` runs where `parker` waits until Some, bounding each wait and never touching Ruby.
212
+ /// Ok(None) once Kino stopped the wait (`stop`: WorkerSlot::halt). The VM's unblock
213
+ /// function raises a flag of the wait's own, so a wake for one thread never ends another's wait;
214
+ /// the wait runs the pending interrupts and waits again, or returns Err if one raised. What a
215
+ /// wait found as it fired goes to `put_back`, lest a pending Thread#raise beat it to Ruby.
216
+ pub(crate) fn park<T, P: Parker>(
217
+ parker: &mut P,
218
+ stop: &AtomicBool,
219
+ mut attempt: impl FnMut() -> Option<T>,
220
+ mut put_back: impl FnMut(T) -> Back<T>,
221
+ ) -> Result<Option<T>, P::Error> {
222
+ let woken = AtomicBool::new(false);
223
+ loop {
224
+ // `woken` is read only once an attempt waited a tick: one that finds something at once
225
+ // pays no load for it.
226
+ let mut wait = || loop {
227
+ if stop.load(Ordering::SeqCst) {
111
228
  return None;
112
229
  }
113
- if let Some(result) = attempt() {
114
- return Some(result);
230
+ if let Some(found) = attempt() {
231
+ return Some(found);
115
232
  }
116
- },
117
- Some(Ubf {
118
- func: ubf_interrupt,
119
- data: flag as *const _ as *mut c_void,
120
- }),
121
- )
233
+ if woken.load(Ordering::Relaxed) {
234
+ return None;
235
+ }
236
+ };
237
+ if let Some(found) = parker.release(&woken, &mut wait)?.flatten() {
238
+ // Whether the unblock function fired while the wait found something.
239
+ if !woken.load(Ordering::Relaxed) {
240
+ return Ok(Some(found));
241
+ }
242
+ match put_back(found) {
243
+ Back::Waits => {}
244
+ Back::HandedOver(found) => return Ok(Some(found)),
245
+ Back::Held(found) => {
246
+ parker.check_ints()?;
247
+ return Ok(Some(found));
248
+ }
249
+ }
250
+ }
251
+ woken.store(false, Ordering::Relaxed);
252
+ // Nothing found, or it went back. A stop ends every later wait on the slot too.
253
+ if stop.load(Ordering::SeqCst) {
254
+ return Ok(None);
255
+ }
256
+ parker.check_ints()?;
257
+ }
258
+ }
259
+
260
+ /// What put_back made of what a wait found as the unblock function fired.
261
+ pub enum Back<T> {
262
+ /// Back where another take finds it; the wait goes on once the interrupts ran.
263
+ Waits,
264
+ /// Held while the interrupts run, then the caller's; a raise drops it (its Drop answers).
265
+ Held(T),
266
+ /// The caller's as found; the interrupts fire at Ruby's next check.
267
+ HandedOver(T),
122
268
  }
123
269
 
124
270
  #[cfg(test)]
125
271
  mod tests {
126
- use std::sync::atomic::{AtomicBool, Ordering};
272
+ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
273
+ use std::sync::Arc;
274
+
275
+ use parking_lot::Mutex;
276
+
277
+ use super::released_by;
278
+ use crate::testing::InPlace;
279
+
280
+ /// The VM's pending interrupts, as the test sets them: none, a wake
281
+ /// (Thread#wakeup, which only ends the wait), or a raise.
282
+ #[derive(Clone, Copy, PartialEq)]
283
+ enum Pending {
284
+ Nothing,
285
+ Wake,
286
+ Raise,
287
+ }
288
+
289
+ /// Runs what `pending` holds, as rb_thread_check_ints would, and
290
+ /// takes it, counting the runs.
291
+ fn interrupts<'a>(
292
+ pending: &'a Mutex<Pending>,
293
+ flag: &'a AtomicBool,
294
+ runs: &'a AtomicUsize,
295
+ ) -> impl FnMut() -> Result<(), &'static str> + 'a {
296
+ move || {
297
+ runs.fetch_add(1, Ordering::SeqCst);
298
+ flag.store(false, Ordering::SeqCst);
299
+ match std::mem::replace(&mut *pending.lock(), Pending::Nothing) {
300
+ Pending::Raise => Err("Thread#raise"),
301
+ Pending::Wake | Pending::Nothing => Ok(()),
302
+ }
303
+ }
304
+ }
127
305
 
128
306
  #[test]
129
- fn ubf_sets_the_interrupt_flag() {
130
- let flag = AtomicBool::new(false);
131
- unsafe {
132
- super::ubf_interrupt(&flag as *const _ as *mut std::ffi::c_void);
307
+ fn a_raise_comes_back_with_the_work_unrun_or_its_result_dropped_and_a_wake_runs_it_once() {
308
+ // What the VM has pending as the release would start, and whether
309
+ // a raise comes as the work runs.
310
+ let rows = [
311
+ (Pending::Raise, false),
312
+ (Pending::Wake, false),
313
+ (Pending::Nothing, true),
314
+ ];
315
+ for (before, during) in rows {
316
+ let held = Arc::new(());
317
+ let (pending, flag, runs) = (
318
+ Mutex::new(before),
319
+ AtomicBool::new(before != Pending::Nothing),
320
+ AtomicUsize::new(0),
321
+ );
322
+ let ran_work = AtomicUsize::new(0);
323
+ let work = {
324
+ let (held, pending, ran_work) = (held.clone(), &pending, &ran_work);
325
+ move || {
326
+ ran_work.fetch_add(1, Ordering::SeqCst);
327
+ if during {
328
+ *pending.lock() = Pending::Raise;
329
+ }
330
+ held
331
+ }
332
+ };
333
+
334
+ // A release as rb_thread_call_without_gvl2 makes it, in place: with an interrupt
335
+ // pending (the flag) it leaves the work where it is; else it runs it.
336
+ let mut parker = InPlace {
337
+ release: |_: &AtomicBool, run: &mut dyn FnMut()| {
338
+ if !flag.load(Ordering::SeqCst) {
339
+ run();
340
+ }
341
+ },
342
+ interrupts: interrupts(&pending, &flag, &runs),
343
+ };
344
+ let result = released_by(&mut parker, &AtomicBool::new(false), work);
345
+ let (raised, ran) = (matches!(result, Err("Thread#raise")), result.is_ok());
346
+ drop(result);
347
+ let (work_runs, checks) =
348
+ (ran_work.load(Ordering::SeqCst), runs.load(Ordering::SeqCst));
349
+ match before {
350
+ // The interrupts run before the work and after it.
351
+ Pending::Wake => assert!(ran && work_runs == 1 && checks == 2, "a wake"),
352
+ Pending::Raise => assert!(raised && work_runs == 0, "a raise pending"),
353
+ Pending::Nothing => assert!(raised && work_runs == 1, "a raise as it ran"),
354
+ }
355
+ assert_eq!(
356
+ Arc::strong_count(&held),
357
+ 1,
358
+ "what the work held, or returned, outlived it"
359
+ );
133
360
  }
134
- assert!(flag.load(Ordering::SeqCst));
135
361
  }
136
362
  }