mini_racer_rs 1.1.0 → 1.2.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.
@@ -4559,3 +4559,203 @@ https://chromium.googlesource.com/chromium/src/+/refs/tags/152.0.7977.89/LICENSE
4559
4559
  // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
4560
4560
  ```
4561
4561
 
4562
+ ### musl
4563
+
4564
+ https://git.musl-libc.org/cgit/musl/plain/COPYRIGHT?h=v1.2.5
4565
+
4566
+ ```text
4567
+ musl as a whole is licensed under the following standard MIT license:
4568
+
4569
+ ----------------------------------------------------------------------
4570
+ Copyright © 2005-2020 Rich Felker, et al.
4571
+
4572
+ Permission is hereby granted, free of charge, to any person obtaining
4573
+ a copy of this software and associated documentation files (the
4574
+ "Software"), to deal in the Software without restriction, including
4575
+ without limitation the rights to use, copy, modify, merge, publish,
4576
+ distribute, sublicense, and/or sell copies of the Software, and to
4577
+ permit persons to whom the Software is furnished to do so, subject to
4578
+ the following conditions:
4579
+
4580
+ The above copyright notice and this permission notice shall be
4581
+ included in all copies or substantial portions of the Software.
4582
+
4583
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
4584
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
4585
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
4586
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
4587
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
4588
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
4589
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
4590
+ ----------------------------------------------------------------------
4591
+
4592
+ Authors/contributors include:
4593
+
4594
+ A. Wilcox
4595
+ Ada Worcester
4596
+ Alex Dowad
4597
+ Alex Suykov
4598
+ Alexander Monakov
4599
+ Andre McCurdy
4600
+ Andrew Kelley
4601
+ Anthony G. Basile
4602
+ Aric Belsito
4603
+ Arvid Picciani
4604
+ Bartosz Brachaczek
4605
+ Benjamin Peterson
4606
+ Bobby Bingham
4607
+ Boris Brezillon
4608
+ Brent Cook
4609
+ Chris Spiegel
4610
+ Clément Vasseur
4611
+ Daniel Micay
4612
+ Daniel Sabogal
4613
+ Daurnimator
4614
+ David Carlier
4615
+ David Edelsohn
4616
+ Denys Vlasenko
4617
+ Dmitry Ivanov
4618
+ Dmitry V. Levin
4619
+ Drew DeVault
4620
+ Emil Renner Berthing
4621
+ Fangrui Song
4622
+ Felix Fietkau
4623
+ Felix Janda
4624
+ Gianluca Anzolin
4625
+ Hauke Mehrtens
4626
+ He X
4627
+ Hiltjo Posthuma
4628
+ Isaac Dunham
4629
+ Jaydeep Patil
4630
+ Jens Gustedt
4631
+ Jeremy Huntwork
4632
+ Jo-Philipp Wich
4633
+ Joakim Sindholt
4634
+ John Spencer
4635
+ Julien Ramseier
4636
+ Justin Cormack
4637
+ Kaarle Ritvanen
4638
+ Khem Raj
4639
+ Kylie McClain
4640
+ Leah Neukirchen
4641
+ Luca Barbato
4642
+ Luka Perkov
4643
+ M Farkas-Dyck (Strake)
4644
+ Mahesh Bodapati
4645
+ Markus Wichmann
4646
+ Masanori Ogino
4647
+ Michael Clark
4648
+ Michael Forney
4649
+ Mikhail Kremnyov
4650
+ Natanael Copa
4651
+ Nicholas J. Kain
4652
+ orc
4653
+ Pascal Cuoq
4654
+ Patrick Oppenlander
4655
+ Petr Hosek
4656
+ Petr Skocik
4657
+ Pierre Carrier
4658
+ Reini Urban
4659
+ Rich Felker
4660
+ Richard Pennington
4661
+ Ryan Fairfax
4662
+ Samuel Holland
4663
+ Segev Finer
4664
+ Shiz
4665
+ sin
4666
+ Solar Designer
4667
+ Stefan Kristiansson
4668
+ Stefan O'Rear
4669
+ Szabolcs Nagy
4670
+ Timo Teräs
4671
+ Trutz Behn
4672
+ Valentin Ochs
4673
+ Will Dietz
4674
+ William Haddon
4675
+ William Pitcock
4676
+
4677
+ Portions of this software are derived from third-party works licensed
4678
+ under terms compatible with the above MIT license:
4679
+
4680
+ The TRE regular expression implementation (src/regex/reg* and
4681
+ src/regex/tre*) is Copyright © 2001-2008 Ville Laurikari and licensed
4682
+ under a 2-clause BSD license (license text in the source files). The
4683
+ included version has been heavily modified by Rich Felker in 2012, in
4684
+ the interests of size, simplicity, and namespace cleanliness.
4685
+
4686
+ Much of the math library code (src/math/* and src/complex/*) is
4687
+ Copyright © 1993,2004 Sun Microsystems or
4688
+ Copyright © 2003-2011 David Schultz or
4689
+ Copyright © 2003-2009 Steven G. Kargl or
4690
+ Copyright © 2003-2009 Bruce D. Evans or
4691
+ Copyright © 2008 Stephen L. Moshier or
4692
+ Copyright © 2017-2018 Arm Limited
4693
+ and labelled as such in comments in the individual source files. All
4694
+ have been licensed under extremely permissive terms.
4695
+
4696
+ The ARM memcpy code (src/string/arm/memcpy.S) is Copyright © 2008
4697
+ The Android Open Source Project and is licensed under a two-clause BSD
4698
+ license. It was taken from Bionic libc, used on Android.
4699
+
4700
+ The AArch64 memcpy and memset code (src/string/aarch64/*) are
4701
+ Copyright © 1999-2019, Arm Limited.
4702
+
4703
+ The implementation of DES for crypt (src/crypt/crypt_des.c) is
4704
+ Copyright © 1994 David Burren. It is licensed under a BSD license.
4705
+
4706
+ The implementation of blowfish crypt (src/crypt/crypt_blowfish.c) was
4707
+ originally written by Solar Designer and placed into the public
4708
+ domain. The code also comes with a fallback permissive license for use
4709
+ in jurisdictions that may not recognize the public domain.
4710
+
4711
+ The smoothsort implementation (src/stdlib/qsort.c) is Copyright © 2011
4712
+ Valentin Ochs and is licensed under an MIT-style license.
4713
+
4714
+ The x86_64 port was written by Nicholas J. Kain and is licensed under
4715
+ the standard MIT terms.
4716
+
4717
+ The mips and microblaze ports were originally written by Richard
4718
+ Pennington for use in the ellcc project. The original code was adapted
4719
+ by Rich Felker for build system and code conventions during upstream
4720
+ integration. It is licensed under the standard MIT terms.
4721
+
4722
+ The mips64 port was contributed by Imagination Technologies and is
4723
+ licensed under the standard MIT terms.
4724
+
4725
+ The powerpc port was also originally written by Richard Pennington,
4726
+ and later supplemented and integrated by John Spencer. It is licensed
4727
+ under the standard MIT terms.
4728
+
4729
+ All other files which have no copyright comments are original works
4730
+ produced specifically for use as part of this library, written either
4731
+ by Rich Felker, the main author of the library, or by one or more
4732
+ contibutors listed above. Details on authorship of individual files
4733
+ can be found in the git version control history of the project. The
4734
+ omission of copyright and license comments in each file is in the
4735
+ interest of source tree size.
4736
+
4737
+ In addition, permission is hereby granted for all public header files
4738
+ (include/* and arch/*/bits/*) and crt files intended to be linked into
4739
+ applications (crt/*, ldso/dlstart.c, and arch/*/crt_arch.h) to omit
4740
+ the copyright notice and permission notice otherwise required by the
4741
+ license, and to use these files without any requirement of
4742
+ attribution. These files include substantial contributions from:
4743
+
4744
+ Bobby Bingham
4745
+ John Spencer
4746
+ Nicholas J. Kain
4747
+ Rich Felker
4748
+ Richard Pennington
4749
+ Stefan Kristiansson
4750
+ Szabolcs Nagy
4751
+
4752
+ all of whom have explicitly granted such permission.
4753
+
4754
+ This file previously contained text expressing a belief that most of
4755
+ the files covered by the above exception were sufficiently trivial not
4756
+ to be subject to copyright, resulting in confusion over whether it
4757
+ negated the permissions granted in the license. In the spirit of
4758
+ permissive licensing, and of not having licensing issues being an
4759
+ obstacle to adoption, that text has been removed.
4760
+ ```
4761
+
@@ -12,7 +12,12 @@ version.workspace = true
12
12
  thiserror.workspace = true
13
13
 
14
14
  [dev-dependencies]
15
+ criterion.workspace = true
15
16
  proptest.workspace = true
16
17
 
18
+ [[bench]]
19
+ harness = false
20
+ name = "wire"
21
+
17
22
  [lints]
18
23
  workspace = true
@@ -0,0 +1,293 @@
1
+ //! Decoding, writing and transcoding V8's wire format, without V8 or Ruby, on
2
+ //! the shapes the extension sees: seeded server rendering props, and runs of
3
+ //! numbers and strings. Strings take the forms V8's serializer gives them.
4
+
5
+ use std::convert::Infallible;
6
+ use std::hint::black_box;
7
+
8
+ use criterion::{Criterion, Throughput, criterion_group, criterion_main};
9
+ use mini_racer_wire::{Begun, Container, Limits, Scalar, Visitor, Writer, decode_value, text};
10
+
11
+ const WORDS: [&str; 12] = [
12
+ "alpha", "beta", "gamma", "delta", "epsilon", "zeta", "theta", "kappa", "lambda", "sigma",
13
+ "omega", "omicron",
14
+ ];
15
+ const INTL: [&str; 5] = ["café", "naïve", "Zürich", "東京", "😀 party"];
16
+ // The words of INTL that V8 keeps one byte a character.
17
+ const LATIN1: [&str; 3] = ["café", "naïve", "Zürich"];
18
+
19
+ /// Reads every value and keeps nothing, so the decoder's own work is what
20
+ /// is measured.
21
+ struct Discard;
22
+
23
+ impl Visitor for Discard {
24
+ type Value = ();
25
+ type Frame = ();
26
+ type Error = Infallible;
27
+
28
+ fn scalar(&mut self, scalar: Scalar<'_>) -> Result<(), Infallible> {
29
+ black_box(scalar);
30
+ Ok(())
31
+ }
32
+
33
+ fn begin(&mut self, container: Container) -> Result<Begun<(), ()>, Infallible> {
34
+ black_box(container);
35
+ Ok(Begun {
36
+ frame: (),
37
+ value: None,
38
+ })
39
+ }
40
+
41
+ fn push(&mut self, (): &mut (), (): ()) -> Result<(), Infallible> {
42
+ Ok(())
43
+ }
44
+
45
+ fn insert(&mut self, (): &mut (), (): (), (): ()) -> Result<(), Infallible> {
46
+ Ok(())
47
+ }
48
+
49
+ fn end(&mut self, (): ()) -> Result<(), Infallible> {
50
+ Ok(())
51
+ }
52
+
53
+ fn register(&mut self, id: u32, (): ()) -> Result<(), Infallible> {
54
+ black_box(id);
55
+ Ok(())
56
+ }
57
+
58
+ fn back_ref(&mut self, id: u32) -> Result<(), Infallible> {
59
+ black_box(id);
60
+ Ok(())
61
+ }
62
+ }
63
+
64
+ enum Node {
65
+ Int(i64),
66
+ Number(f64),
67
+ Bool(bool),
68
+ Latin1(Vec<u8>),
69
+ Utf16(Vec<u16>),
70
+ Object(Vec<(Vec<u8>, Self)>),
71
+ Array(Vec<Self>),
72
+ }
73
+
74
+ impl Node {
75
+ fn text(text: &str) -> Self {
76
+ let latin1: Option<Vec<u8>> = text
77
+ .chars()
78
+ .map(|c| u8::try_from(u32::from(c)).ok())
79
+ .collect();
80
+ latin1.map_or_else(|| Self::Utf16(text.encode_utf16().collect()), Self::Latin1)
81
+ }
82
+
83
+ fn object(entries: Vec<(&str, Self)>) -> Self {
84
+ Self::Object(
85
+ entries
86
+ .into_iter()
87
+ .map(|(key, value)| (key.as_bytes().to_vec(), value))
88
+ .collect(),
89
+ )
90
+ }
91
+
92
+ fn write(&self, writer: &mut Writer<'_>) {
93
+ match self {
94
+ Self::Int(n) => writer.integer(*n),
95
+ Self::Number(n) => writer.number(*n),
96
+ Self::Bool(b) => writer.bool(*b),
97
+ Self::Latin1(bytes) => writer.latin1(bytes),
98
+ Self::Utf16(units) => writer.utf16_aligned(units),
99
+ Self::Object(entries) => {
100
+ writer.begin_object();
101
+ for (key, value) in entries {
102
+ writer.latin1(key);
103
+ value.write(writer);
104
+ }
105
+ writer.end_object(count(entries.len()));
106
+ }
107
+ Self::Array(items) => {
108
+ writer.begin_array(count(items.len()));
109
+ for item in items {
110
+ item.write(writer);
111
+ }
112
+ writer.end_array(count(items.len()));
113
+ }
114
+ }
115
+ }
116
+
117
+ fn bytes(&self) -> Vec<u8> {
118
+ let mut out = Vec::new();
119
+ self.write(&mut Writer::versioned(&mut out, 15));
120
+ out
121
+ }
122
+ }
123
+
124
+ fn count(len: usize) -> u32 {
125
+ u32::try_from(len).unwrap_or(u32::MAX)
126
+ }
127
+
128
+ /// xorshift64, so the payload is the same on every machine.
129
+ struct Seeded(u64);
130
+
131
+ impl Seeded {
132
+ const fn next(&mut self) -> u64 {
133
+ self.0 ^= self.0 << 13;
134
+ self.0 ^= self.0 >> 7;
135
+ self.0 ^= self.0 << 17;
136
+ self.0
137
+ }
138
+
139
+ fn below(&mut self, bound: usize) -> usize {
140
+ usize::try_from(self.next()).unwrap_or(0) % bound
141
+ }
142
+
143
+ fn words(&mut self, count: usize) -> Node {
144
+ self.words_from(count, &INTL)
145
+ }
146
+
147
+ fn words_from(&mut self, count: usize, intl: &[&str]) -> Node {
148
+ let words: Vec<&str> = (0..count)
149
+ .map(|_| {
150
+ if self.below(10) == 0 {
151
+ intl[self.below(intl.len())]
152
+ } else {
153
+ WORDS[self.below(WORDS.len())]
154
+ }
155
+ })
156
+ .collect();
157
+ Node::text(&words.join(" "))
158
+ }
159
+
160
+ fn cents(&mut self) -> f64 {
161
+ f64::from(u32::try_from(self.below(100_000)).unwrap_or(0)) / 100.0
162
+ }
163
+ }
164
+
165
+ /// About 1 MB of props, the size the end-to-end benchmark sends.
166
+ fn props() -> Node {
167
+ let mut seeded = Seeded(42);
168
+ let items = (0..5_000)
169
+ .map(|id| {
170
+ let length = 3 + seeded.below(6);
171
+ Node::object(vec![
172
+ ("id", Node::Int(id)),
173
+ (
174
+ "sku",
175
+ Node::text(&format!("SKU-{}", seeded.below(1_000_000))),
176
+ ),
177
+ ("title", seeded.words(length)),
178
+ ("price", Node::Number(seeded.cents())),
179
+ ("rating", Node::Number(seeded.cents() / 200.0)),
180
+ ("inStock", Node::Bool(seeded.below(4) != 0)),
181
+ (
182
+ "tags",
183
+ Node::Array(vec![seeded.words(1), seeded.words(1), seeded.words(1)]),
184
+ ),
185
+ (
186
+ "seller",
187
+ Node::object(vec![
188
+ ("name", seeded.words(2)),
189
+ (
190
+ "reviews",
191
+ Node::Int(i64::try_from(seeded.below(5_000)).unwrap_or(0)),
192
+ ),
193
+ ]),
194
+ ),
195
+ ])
196
+ })
197
+ .collect();
198
+ Node::object(vec![
199
+ (
200
+ "page",
201
+ Node::object(vec![
202
+ ("title", Node::text("Products")),
203
+ ("locale", Node::text("en-US")),
204
+ ]),
205
+ ),
206
+ ("items", Node::Array(items)),
207
+ ])
208
+ }
209
+
210
+ fn numbers() -> Node {
211
+ let mut seeded = Seeded(7);
212
+ Node::Array((0..10_000).map(|_| Node::Number(seeded.cents())).collect())
213
+ }
214
+
215
+ fn latin1_strings() -> Node {
216
+ let mut seeded = Seeded(9);
217
+ Node::Array((0..10_000).map(|_| seeded.words_from(2, &LATIN1)).collect())
218
+ }
219
+
220
+ fn two_byte_strings() -> Node {
221
+ Node::Array(
222
+ (0..1_000)
223
+ .map(|n| Node::text(&format!("東京の天気は晴れです {n}")))
224
+ .collect(),
225
+ )
226
+ }
227
+
228
+ fn decode(c: &mut Criterion) {
229
+ let mut group = c.benchmark_group("decode");
230
+ for (name, node) in [
231
+ ("ssr_props", props()),
232
+ ("dense_numbers", numbers()),
233
+ ("latin1_strings", latin1_strings()),
234
+ ("two_byte_strings", two_byte_strings()),
235
+ ] {
236
+ let bytes = node.bytes();
237
+ group.throughput(Throughput::Bytes(
238
+ bytes.len().try_into().unwrap_or(u64::MAX),
239
+ ));
240
+ group.bench_function(name, |b| {
241
+ b.iter(|| decode_value(black_box(&bytes), Limits::default(), &mut Discard));
242
+ });
243
+ }
244
+ group.finish();
245
+ }
246
+
247
+ fn write(c: &mut Criterion) {
248
+ let node = props();
249
+ let mut out = Vec::new();
250
+ node.write(&mut Writer::new(&mut out));
251
+ let mut group = c.benchmark_group("write");
252
+ group.throughput(Throughput::Bytes(out.len().try_into().unwrap_or(u64::MAX)));
253
+ group.bench_function("ssr_props", |b| {
254
+ b.iter(|| {
255
+ let mut writer = Writer::new(&mut out);
256
+ black_box(&node).write(&mut writer);
257
+ });
258
+ });
259
+ group.finish();
260
+ }
261
+
262
+ fn transcode(c: &mut Criterion) {
263
+ let latin1: Vec<u8> = "Le café de la naïveté à Zürich, déjà vu. "
264
+ .chars()
265
+ .filter_map(|ch| u8::try_from(u32::from(ch)).ok())
266
+ .cycle()
267
+ .take(64 << 10)
268
+ .collect();
269
+ let utf16: Vec<u8> = "東京の天気は晴れです。"
270
+ .encode_utf16()
271
+ .cycle()
272
+ .take(32 << 10)
273
+ .flat_map(u16::to_le_bytes)
274
+ .collect();
275
+ let mut out = vec![0; 192 << 10];
276
+ let mut group = c.benchmark_group("transcode");
277
+ group.throughput(Throughput::Bytes(
278
+ latin1.len().try_into().unwrap_or(u64::MAX),
279
+ ));
280
+ group.bench_function("latin1_to_utf8", |b| {
281
+ b.iter(|| text::latin1_to_utf8_into(black_box(&latin1), &mut out));
282
+ });
283
+ group.throughput(Throughput::Bytes(
284
+ utf16.len().try_into().unwrap_or(u64::MAX),
285
+ ));
286
+ group.bench_function("utf16le_to_utf8", |b| {
287
+ b.iter(|| text::utf16le_to_utf8_into(black_box(&utf16), &mut out));
288
+ });
289
+ group.finish();
290
+ }
291
+
292
+ criterion_group!(benches, decode, write, transcode);
293
+ criterion_main!(benches);
@@ -10,6 +10,8 @@ end
10
10
  TARGETS = {
11
11
  %w[x86_64 linux] => "x86_64-unknown-linux-gnu",
12
12
  %w[aarch64 linux] => "aarch64-unknown-linux-gnu",
13
+ %w[x86_64 linux-musl] => "x86_64-unknown-linux-musl",
14
+ %w[aarch64 linux-musl] => "aarch64-unknown-linux-musl",
13
15
  %w[arm64 darwin] => "aarch64-apple-darwin",
14
16
  %w[aarch64 darwin] => "aarch64-apple-darwin",
15
17
  %w[x86_64 darwin] => "x86_64-apple-darwin",
@@ -18,13 +20,13 @@ MINIMUM_RUST = Gem::Version.new("1.91.0")
18
20
 
19
21
  host_os = RbConfig::CONFIG["host_os"]
20
22
  os = case host_os
21
- when /linux-musl/ then nil
23
+ when /linux-musl/ then "linux-musl"
22
24
  when /linux/ then "linux"
23
25
  when /darwin/ then "darwin"
24
26
  end
25
27
  target = os && TARGETS[[RbConfig::CONFIG["host_cpu"], os]]
26
28
  unless target
27
- abort "mini_racer_rs supports Linux (glibc) on x86_64 and aarch64 and macOS on arm64 and x86_64; " \
29
+ abort "mini_racer_rs supports Linux (glibc or musl) on x86_64 and aarch64 and macOS on arm64 and x86_64; " \
28
30
  "#{RbConfig::CONFIG["host_cpu"]}-#{host_os} is not supported"
29
31
  end
30
32
 
@@ -74,5 +76,8 @@ require "rb_sys/mkmf"
74
76
 
75
77
  create_rust_makefile("mini_racer_rs/mini_racer_rs") do |r|
76
78
  r.extra_cargo_args += ["--locked"]
79
+ # rb_sys hands -crt-static to rustc alone, but cargo refuses a musl cdylib
80
+ # from RUSTFLAGS before rustc runs.
81
+ r.extra_rustflags += ["-C", "target-feature=-crt-static"] if os == "linux-musl"
77
82
  r.env.merge!(build_env)
78
83
  end
@@ -1,7 +1,6 @@
1
1
  use std::cell::Cell;
2
2
  use std::os::fd::{AsRawFd, IntoRawFd};
3
- use std::sync::OnceLock;
4
- use std::time::Duration;
3
+ use std::time::Instant;
5
4
 
6
5
  use magnus::error::ErrorType;
7
6
  use magnus::gc::Marker;
@@ -14,32 +13,9 @@ use mini_racer_engine::{
14
13
 
15
14
  use crate::encode;
16
15
  use crate::gc_root::OwnedRoot;
16
+ use crate::spin::{self, History};
17
17
  use crate::{context, decode, errors, rb_raw};
18
18
 
19
- struct SpinBudget {
20
- gvl: Duration,
21
- nogvl: Duration,
22
- }
23
-
24
- // Unstable tuning knob: MINI_RACER_RS_SPIN_US=<with GVL>,<without GVL>.
25
- fn budget() -> &'static SpinBudget {
26
- static BUDGET: OnceLock<SpinBudget> = OnceLock::new();
27
- BUDGET.get_or_init(|| {
28
- let setting = std::env::var("MINI_RACER_RS_SPIN_US").unwrap_or_default();
29
- let parts: Vec<Option<u64>> = setting
30
- .split(',')
31
- .map(|part| part.trim().parse().ok())
32
- .collect();
33
- let at = |i: usize, default: u64| {
34
- Duration::from_micros(parts.get(i).copied().flatten().unwrap_or(default))
35
- };
36
- SpinBudget {
37
- gvl: at(0, 20),
38
- nogvl: at(1, 50),
39
- }
40
- })
41
- }
42
-
43
19
  /// What a context's callbacks run: its attached callables by id, and where
44
20
  /// the exception the latest callback raised is kept, as `mini_racer` keeps one
45
21
  /// per context and clears it after every dispatch, nested ones included.
@@ -69,6 +45,7 @@ pub struct RubyHost<'r> {
69
45
  pub struct Waiter {
70
46
  io: OwnedRoot<Value>,
71
47
  epoch: Cell<u64>,
48
+ history: History,
72
49
  }
73
50
 
74
51
  impl Waiter {
@@ -268,28 +245,44 @@ fn message(ruby: &Ruby, exception: Exception) -> JsText {
268
245
 
269
246
  impl Host for RubyHost<'_> {
270
247
  fn wait(&mut self, wait: &WaitHandle<'_>) -> WaitOutcome {
271
- let budget = budget();
272
- if wait.spin(budget.gvl) {
273
- return WaitOutcome::Ready;
248
+ let budget = spin::budget();
249
+ let history = self.waiter.map(|waiter| &waiter.history);
250
+ let spins = history.is_none_or(History::spins);
251
+ // A wait that does not spin times itself to tell whether spinning
252
+ // would have caught the answer.
253
+ let started = (!spins).then(Instant::now);
254
+ let answered = |spun: bool| {
255
+ if let Some(history) = history {
256
+ history.record(started.map_or(spun, |at| at.elapsed() <= budget.total()));
257
+ }
258
+ WaitOutcome::Ready
259
+ };
260
+ if spins && wait.spin(budget.gvl) {
261
+ return answered(true);
274
262
  }
275
263
  if rb_raw::fiber_scheduler(self.ruby)
276
264
  && let Some(outcome) = self.wait_in_fiber(wait)
277
265
  {
278
- return outcome;
266
+ return match outcome {
267
+ WaitOutcome::Ready => answered(false),
268
+ WaitOutcome::Cancel => outcome,
269
+ };
279
270
  }
280
271
  let unparker = wait.unparker();
281
272
  loop {
282
273
  let parked = rb_raw::nogvl(
283
274
  self.ruby,
284
275
  || {
285
- if !wait.spin(budget.nogvl) {
276
+ let spun = spins && wait.spin(budget.nogvl);
277
+ if !spun {
286
278
  wait.park();
287
279
  }
280
+ spun
288
281
  },
289
282
  &move || unparker.unpark(),
290
283
  );
291
284
  if wait.ready() {
292
- return WaitOutcome::Ready;
285
+ return answered(matches!(parked, Some(Ok(true))));
293
286
  }
294
287
  if parked.as_ref().is_some_and(Result::is_err) {
295
288
  self.pending = Some(errors::internal(self.ruby, "panic while waiting"));
@@ -19,6 +19,7 @@ mod platform;
19
19
  mod rb_raw;
20
20
  mod snapshot;
21
21
  mod source_maps;
22
+ mod spin;
22
23
 
23
24
  use magnus::{Error, Module, Ruby};
24
25