mini_racer_rs 1.3.0 → 1.4.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.
@@ -3,7 +3,7 @@ use std::ffi::{c_int, c_long, c_void};
3
3
  use magnus::encoding::Coderange;
4
4
  use magnus::rb_sys::{AsRawId, AsRawValue, FromRawValue, protect};
5
5
  use magnus::value::{IntoId, LazyId, ReprValue};
6
- use magnus::{Error, RArray, RHash, RString, Ruby, Value};
6
+ use magnus::{Error, Exception, RArray, RHash, RString, Ruby, Value};
7
7
 
8
8
  static CALL: LazyId = LazyId::new("call");
9
9
 
@@ -62,6 +62,109 @@ where
62
62
  call.result
63
63
  }
64
64
 
65
+ struct Ensure<'a> {
66
+ ruby: &'a Ruby,
67
+ before: rb_sys::VALUE,
68
+ after: &'a mut dyn FnMut(&Ruby, Option<Exception>),
69
+ }
70
+
71
+ unsafe extern "C" fn run_after(data: rb_sys::VALUE) -> rb_sys::VALUE {
72
+ let _ = guard(|| {
73
+ // VALUE is as wide as a pointer, which rb-sys checks as it builds.
74
+ let Ok(address) = usize::try_from(data) else {
75
+ return;
76
+ };
77
+ let ensure = std::ptr::with_exposed_provenance_mut::<Ensure<'_>>(address);
78
+ // SAFETY: `data` is the address of the `Ensure` that `yield_ensuring`
79
+ // keeps on its stack for the whole rb_ensure call, which runs this once.
80
+ let ensure = unsafe { &mut *ensure };
81
+ // SAFETY: rb_ensure runs this holding the GVL, and rb_errinfo only
82
+ // reads the current execution context.
83
+ let now = unsafe { rb_sys::rb_errinfo() };
84
+ // rb_ensure leaves an exception the block raised in place for this
85
+ // call and clears what a break, a throw or Thread#kill carries, so an
86
+ // exception that was not there before the block is the one it raised.
87
+ let raised = if now == ensure.before {
88
+ None
89
+ } else {
90
+ // SAFETY: `now` is the live value the execution context holds.
91
+ Exception::from_value(unsafe { Value::from_raw(now) })
92
+ };
93
+ (ensure.after)(ensure.ruby, raised);
94
+ });
95
+ rb_sys::Qnil as rb_sys::VALUE
96
+ }
97
+
98
+ /// Yields `value` to the block of the method Ruby is running, then runs
99
+ /// `after` however the block ends: a return, an exception, `break`, `throw`
100
+ /// or `Thread#kill`, as `File.open` closes its file. `after` gets the
101
+ /// exception the block raised, if it raised one. It must not call a Ruby
102
+ /// method: `rb_funcall` runs pending interrupts as it returns, and an
103
+ /// exception one raised there could not be raised from `after`.
104
+ pub fn yield_ensuring(
105
+ ruby: &Ruby,
106
+ value: Value,
107
+ after: &mut dyn FnMut(&Ruby, Option<Exception>),
108
+ ) -> Result<Value, Error> {
109
+ // SAFETY: the `&Ruby` argument proves this thread holds the GVL, and
110
+ // rb_errinfo only reads the current execution context.
111
+ let before = unsafe { rb_sys::rb_errinfo() };
112
+ let mut ensure = Ensure {
113
+ ruby,
114
+ before,
115
+ after,
116
+ };
117
+ let data = std::ptr::addr_of_mut!(ensure).expose_provenance() as rb_sys::VALUE;
118
+ let raw = value.as_raw();
119
+ let result = protect(|| {
120
+ // SAFETY: the GVL is held; rb_yield is C, so a jump out of the block
121
+ // reaches rb_ensure's handler without crossing a Rust frame;
122
+ // `ensure` outlives the call, and `protect` catches whatever rb_ensure
123
+ // resumes once `run_after` has returned.
124
+ unsafe { rb_sys::rb_ensure(Some(rb_sys::rb_yield), raw, Some(run_after), data) }
125
+ })?;
126
+ // SAFETY: `result` is the live value the block returned.
127
+ Ok(unsafe { Value::from_raw(result) })
128
+ }
129
+
130
+ unsafe extern "C" fn thread_body(data: *mut c_void) -> rb_sys::VALUE {
131
+ // SAFETY: `data` is the box `thread_create` leaked for this thread, and
132
+ // Ruby calls a thread's function once.
133
+ let run = unsafe { Box::from_raw(data.cast::<Box<dyn FnOnce(&Ruby) + Send>>()) };
134
+ let _ = guard(move || {
135
+ // SAFETY: Ruby runs a thread's function holding the GVL.
136
+ let ruby = unsafe { Ruby::get_unchecked() };
137
+ run(&ruby);
138
+ });
139
+ rb_sys::Qnil as rb_sys::VALUE
140
+ }
141
+
142
+ /// A new Ruby thread running `run`, which must handle whatever its Ruby calls
143
+ /// raise. Ruby values `run` uses must be kept alive by the caller, as
144
+ /// `gc_root::spawn` does.
145
+ pub fn thread_create(
146
+ ruby: &Ruby,
147
+ run: Box<dyn FnOnce(&Ruby) + Send>,
148
+ ) -> Result<magnus::Thread, Error> {
149
+ let data = Box::into_raw(Box::new(run));
150
+ let created = protect(|| {
151
+ // SAFETY: the `&Ruby` argument proves this thread holds the GVL;
152
+ // `thread_body` takes `data` back, and `protect` catches the
153
+ // ThreadError Ruby raises when it cannot start a thread.
154
+ unsafe { rb_sys::rb_thread_create(Some(thread_body), data.cast()) }
155
+ });
156
+ match created {
157
+ // SAFETY: `raw` is the live Thread rb_thread_create returned.
158
+ Ok(raw) => magnus::Thread::from_value(unsafe { Value::from_raw(raw) })
159
+ .ok_or_else(|| Error::new(ruby.exception_type_error(), "expected Thread")),
160
+ Err(error) => {
161
+ // SAFETY: no thread started, so nothing else took the box back.
162
+ drop(unsafe { Box::from_raw(data) });
163
+ Err(error)
164
+ }
165
+ }
166
+ }
167
+
65
168
  // Runs pending interrupts: signal traps return Ok, while Thread#raise, #kill,
66
169
  // Timeout and SIGINT come back as the Err the caller must eventually return.
67
170
  pub fn check_ints(_ruby: &Ruby) -> Result<(), Error> {
@@ -80,6 +183,88 @@ pub fn mutex_lock(_ruby: &Ruby, mutex: magnus::Mutex) -> Result<(), Error> {
80
183
  mutex.lock()
81
184
  }
82
185
 
186
+ #[derive(Clone, Copy)]
187
+ struct Setting {
188
+ receiver: rb_sys::VALUE,
189
+ method: rb_sys::ID,
190
+ set: [rb_sys::VALUE; 2],
191
+ restore: [rb_sys::VALUE; 2],
192
+ }
193
+
194
+ fn setting(data: rb_sys::VALUE) -> Option<Setting> {
195
+ // VALUE is as wide as a pointer, which rb-sys checks as it builds.
196
+ let address = usize::try_from(data).ok()?;
197
+ let setting = std::ptr::with_exposed_provenance::<Setting>(address);
198
+ // SAFETY: `data` is the address of the `Setting` that `yield_setting`
199
+ // keeps on its stack for the whole rb_ensure call.
200
+ Some(unsafe { *setting })
201
+ }
202
+
203
+ // A raise or a throw out of the call or the block leaves this frame, which
204
+ // holds only copies of raw values, for rb_ensure's handler.
205
+ unsafe extern "C" fn set_and_yield(data: rb_sys::VALUE) -> rb_sys::VALUE {
206
+ let Ok(Some(setting)) = guard(|| setting(data)) else {
207
+ return rb_sys::Qnil as rb_sys::VALUE;
208
+ };
209
+ // SAFETY: rb_ensure runs this holding the GVL; the receiver and arguments
210
+ // stay live on `yield_setting`'s stack, and rb_ensure's handler catches
211
+ // whatever the call raises or throws.
212
+ unsafe { rb_sys::rb_funcallv(setting.receiver, setting.method, 2, setting.set.as_ptr()) };
213
+ // SAFETY: as above, for the block of the method `yield_setting` serves.
214
+ unsafe { rb_sys::rb_yield(rb_sys::Qundef as rb_sys::VALUE) }
215
+ }
216
+
217
+ // rb_ensure keeps a pending break, throw or exception aside while this runs
218
+ // and puts it back after, so a trap or interrupt handled inside the call
219
+ // cannot clear it. One this call raises or throws instead replaces it, as in
220
+ // Ruby's own ensure, and leaves this frame, which holds only copies of raw
221
+ // values, for the protect around rb_ensure.
222
+ unsafe extern "C" fn restore_setting(data: rb_sys::VALUE) -> rb_sys::VALUE {
223
+ let Ok(Some(setting)) = guard(|| setting(data)) else {
224
+ return rb_sys::Qnil as rb_sys::VALUE;
225
+ };
226
+ // SAFETY: rb_ensure runs this holding the GVL; the receiver and arguments
227
+ // stay live on `yield_setting`'s stack.
228
+ unsafe {
229
+ rb_sys::rb_funcallv(
230
+ setting.receiver,
231
+ setting.method,
232
+ 2,
233
+ setting.restore.as_ptr(),
234
+ )
235
+ }
236
+ }
237
+
238
+ /// `receiver.method(key, value)`, then a yield to the block of the method
239
+ /// Ruby is running, then `receiver.method(key, restored)` however the block
240
+ /// ends, as an `ensure` clause runs. The protect around it catches whatever
241
+ /// ends the block and resumes nothing, so a break, return or throw comes back
242
+ /// as the Err with its state intact, for the method entry to resume once the
243
+ /// Rust frames below it have returned (I6).
244
+ pub fn yield_setting(
245
+ ruby: &Ruby,
246
+ receiver: Value,
247
+ method: impl IntoId,
248
+ key: Value,
249
+ (value, restored): (Value, Value),
250
+ ) -> Result<Value, Error> {
251
+ let setting = Setting {
252
+ receiver: receiver.as_raw(),
253
+ method: method.into_id_with(ruby).as_raw(),
254
+ set: [key.as_raw(), value.as_raw()],
255
+ restore: [key.as_raw(), restored.as_raw()],
256
+ };
257
+ let data = std::ptr::addr_of!(setting).expose_provenance() as rb_sys::VALUE;
258
+ let raw = protect(|| {
259
+ // SAFETY: the `&Ruby` argument proves this thread holds the GVL;
260
+ // `setting` outlives the call, and `protect` catches whatever
261
+ // rb_ensure resumes once the restoring call has run.
262
+ unsafe { rb_sys::rb_ensure(Some(set_and_yield), data, Some(restore_setting), data) }
263
+ })?;
264
+ // SAFETY: `raw` is the live value the block returned.
265
+ Ok(unsafe { Value::from_raw(raw) })
266
+ }
267
+
83
268
  // Ruby's GC cannot see an isolate's native memory, so it is reported here;
84
269
  // without it, contexts left to finalizers pile up between collections.
85
270
  pub fn adjust_memory(_ruby: &Ruby, bytes: isize) {
@@ -0,0 +1,132 @@
1
+ use std::sync::Arc;
2
+ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
3
+ use std::time::Duration;
4
+
5
+ use magnus::value::{IntoId, LazyId, ReprValue, StaticSymbol};
6
+ use magnus::{
7
+ Class, DataTypeFunctions, Error, Module, Object, RClass, RModule, Ruby, TryConvert, TypedData,
8
+ Value,
9
+ };
10
+
11
+ use crate::context::{option_error, option_value};
12
+ use crate::gc_root::StaticRoot;
13
+ use crate::{export, options, rb_raw};
14
+
15
+ // Scopes open in this process. While there are none, a dispatch reads no
16
+ // fiber storage, so code that never opens one pays only this load.
17
+ static OPEN: AtomicUsize = AtomicUsize::new(0);
18
+
19
+ static KEY: LazyId = LazyId::new("mini_racer_rs_timeout");
20
+ static AREF: LazyId = LazyId::new("[]");
21
+ static ASET: LazyId = LazyId::new("[]=");
22
+
23
+ #[expect(
24
+ clippy::expect_used,
25
+ reason = "Ruby defines Fiber, and a root initializer cannot return an error"
26
+ )]
27
+ static FIBER: StaticRoot<RClass> = StaticRoot::new(|ruby| {
28
+ ruby.class_object()
29
+ .const_get("Fiber")
30
+ .expect("Ruby defines Fiber")
31
+ });
32
+
33
+ struct Scope {
34
+ budget: Duration,
35
+ open: AtomicBool,
36
+ // The scope open on this fiber when this one opened. A fiber started
37
+ // inside a scope inherits it through fiber storage and may outlive it,
38
+ // so a scope it opens can outlast the one it encloses.
39
+ enclosing: Option<Arc<Self>>,
40
+ }
41
+
42
+ impl Scope {
43
+ fn budget(&self) -> Option<Duration> {
44
+ let mut budget: Option<Duration> = None;
45
+ let mut scope = Some(self);
46
+ while let Some(current) = scope {
47
+ if current.open.load(Ordering::Relaxed) {
48
+ budget = Some(budget.map_or(current.budget, |b| b.min(current.budget)));
49
+ }
50
+ scope = current.enclosing.as_deref();
51
+ }
52
+ budget
53
+ }
54
+
55
+ fn close(&self) {
56
+ if self.open.swap(false, Ordering::Relaxed) {
57
+ OPEN.fetch_sub(1, Ordering::Relaxed);
58
+ }
59
+ }
60
+ }
61
+
62
+ #[derive(TypedData)]
63
+ #[magnus(class = "MiniRacerRs::TimeoutScope", free_immediately, size)]
64
+ struct TimeoutScope(Arc<Scope>);
65
+
66
+ impl DataTypeFunctions for TimeoutScope {}
67
+
68
+ impl Drop for TimeoutScope {
69
+ // A fiber collected while suspended inside the block never returns to
70
+ // close its scope.
71
+ fn drop(&mut self) {
72
+ self.0.close();
73
+ }
74
+ }
75
+
76
+ pub fn init(ruby: &Ruby, rs: RModule) -> Result<(), Error> {
77
+ rs.define_class("TimeoutScope", ruby.class_object())?
78
+ .undef_default_alloc_func();
79
+ TimeoutScope::class(ruby);
80
+ FIBER.get(ruby);
81
+ rs.define_singleton_method("timeout", export!(function timeout, 1))?;
82
+ Ok(())
83
+ }
84
+
85
+ /// The timeout the scopes open on the current fiber give a script it starts.
86
+ pub fn current(ruby: &Ruby) -> Result<Option<Duration>, Error> {
87
+ if OPEN.load(Ordering::Relaxed) == 0 {
88
+ return Ok(None);
89
+ }
90
+ let stored: Value = FIBER.get(ruby).funcall(*AREF, (*KEY,))?;
91
+ Ok(<&TimeoutScope>::try_convert(stored)
92
+ .ok()
93
+ .and_then(|scope| scope.0.budget()))
94
+ }
95
+
96
+ // The scope lives in fiber storage, which fibers and threads started inside
97
+ // the block inherit; a copy that outlives the block finds the scope closed.
98
+ fn timeout(ruby: &Ruby, milliseconds: Value) -> Result<Value, Error> {
99
+ let budget = options::timeout(&option_value(ruby, milliseconds))
100
+ .map_err(|error| option_error(ruby, &error))?;
101
+ if !ruby.block_given() {
102
+ return Err(Error::new(
103
+ ruby.exception_local_jump_error(),
104
+ "no block given (yield)",
105
+ ));
106
+ }
107
+ let Some(budget) = budget else {
108
+ return ruby.yield_values(());
109
+ };
110
+ let fiber = FIBER.get(ruby);
111
+ let previous: Value = fiber.funcall(*AREF, (*KEY,))?;
112
+ let enclosing = <&TimeoutScope>::try_convert(previous)
113
+ .ok()
114
+ .map(|scope| Arc::clone(&scope.0));
115
+ let scope = Arc::new(Scope {
116
+ budget,
117
+ open: AtomicBool::new(true),
118
+ enclosing,
119
+ });
120
+ let stored = ruby.obj_wrap(TimeoutScope(Arc::clone(&scope)));
121
+ OPEN.fetch_add(1, Ordering::Relaxed);
122
+ let key = StaticSymbol::from((*KEY).into_id_with(ruby)).as_value();
123
+ let result = rb_raw::yield_setting(
124
+ ruby,
125
+ fiber.as_value(),
126
+ *ASET,
127
+ key,
128
+ (stored.as_value(), previous),
129
+ );
130
+ scope.close();
131
+ result
132
+ }
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module MiniRacerRs
4
+ # Only the native extension's heap limit raises it, so it exists only on CRuby.
5
+ class HeapLimitError < MiniRacer::V8OutOfMemoryError
6
+ end
7
+ end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module MiniRacerRs
4
- VERSION = "1.3.0"
4
+ VERSION = "1.4.0"
5
5
  end
data/lib/mini_racer_rs.rb CHANGED
@@ -18,6 +18,7 @@ if RUBY_ENGINE == "truffleruby"
18
18
  require_relative "mini_racer/truffleruby"
19
19
  else
20
20
  require_relative "mini_racer_rs/internal_error"
21
+ require_relative "mini_racer_rs/heap_limit_error"
21
22
  native = ["#{RUBY_VERSION[/\A\d+\.\d+/]}/mini_racer_rs", "mini_racer_rs"].find do |name|
22
23
  File.file?(File.join(__dir__, "mini_racer_rs", "#{name}.#{RbConfig::CONFIG["DLEXT"]}"))
23
24
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: mini_racer_rs
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.3.0
4
+ version: 1.4.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Andy Aragon
@@ -100,20 +100,24 @@ files:
100
100
  - ext/mini_racer_rs/src/fork.rs
101
101
  - ext/mini_racer_rs/src/gc_root.rs
102
102
  - ext/mini_racer_rs/src/guard.rs
103
+ - ext/mini_racer_rs/src/heap_limit.rs
103
104
  - ext/mini_racer_rs/src/host.rs
104
105
  - ext/mini_racer_rs/src/lib.rs
105
106
  - ext/mini_racer_rs/src/options.rs
106
107
  - ext/mini_racer_rs/src/platform.rs
108
+ - ext/mini_racer_rs/src/pool.rs
107
109
  - ext/mini_racer_rs/src/rb_raw.rs
108
110
  - ext/mini_racer_rs/src/snapshot.rs
109
111
  - ext/mini_racer_rs/src/source_maps.rs
110
112
  - ext/mini_racer_rs/src/spin.rs
113
+ - ext/mini_racer_rs/src/timeout.rs
111
114
  - ext/mini_racer_rs/v8-archives.sha256
112
115
  - lib/mini_racer.rb
113
116
  - lib/mini_racer/shared.rb
114
117
  - lib/mini_racer/truffleruby.rb
115
118
  - lib/mini_racer/version.rb
116
119
  - lib/mini_racer_rs.rb
120
+ - lib/mini_racer_rs/heap_limit_error.rb
117
121
  - lib/mini_racer_rs/internal_error.rb
118
122
  - lib/mini_racer_rs/version.rb
119
123
  - lib/mini_racer_rs/vocabulary.rb