mini_racer_rs 1.3.0 → 1.5.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 (35) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +16 -0
  3. data/COMPATIBILITY.md +45 -48
  4. data/Cargo.lock +5 -5
  5. data/Cargo.toml +1 -1
  6. data/README.md +80 -37
  7. data/crates/mini_racer_engine/src/context.rs +45 -22
  8. data/crates/mini_racer_engine/src/control.rs +70 -1
  9. data/crates/mini_racer_engine/src/error.rs +66 -9
  10. data/crates/mini_racer_engine/src/lib.rs +3 -2
  11. data/crates/mini_racer_engine/src/process/platform.rs +360 -2
  12. data/crates/mini_racer_engine/src/process/watchdog.rs +63 -14
  13. data/crates/mini_racer_engine/src/runner.rs +274 -50
  14. data/crates/mini_racer_engine/src/snapshot.rs +259 -41
  15. data/crates/mini_racer_engine/src/sys.rs +26 -0
  16. data/crates/mini_racer_sourcemap/src/map.rs +3 -2
  17. data/crates/mini_racer_sync/src/termination.rs +183 -45
  18. data/ext/mini_racer_rs/src/context.rs +41 -23
  19. data/ext/mini_racer_rs/src/decode.rs +10 -2
  20. data/ext/mini_racer_rs/src/encode.rs +72 -27
  21. data/ext/mini_racer_rs/src/errors.rs +21 -6
  22. data/ext/mini_racer_rs/src/gc_root.rs +31 -1
  23. data/ext/mini_racer_rs/src/heap_limit.rs +42 -0
  24. data/ext/mini_racer_rs/src/host.rs +1 -1
  25. data/ext/mini_racer_rs/src/lib.rs +6 -0
  26. data/ext/mini_racer_rs/src/options.rs +90 -8
  27. data/ext/mini_racer_rs/src/pool.rs +811 -0
  28. data/ext/mini_racer_rs/src/rb_raw.rs +186 -1
  29. data/ext/mini_racer_rs/src/snapshot.rs +6 -10
  30. data/ext/mini_racer_rs/src/timeout.rs +132 -0
  31. data/lib/mini_racer/version.rb +1 -1
  32. data/lib/mini_racer_rs/heap_limit_error.rb +7 -0
  33. data/lib/mini_racer_rs/version.rb +1 -1
  34. data/lib/mini_racer_rs.rb +1 -0
  35. metadata +7 -3
data/README.md CHANGED
@@ -9,28 +9,28 @@ A drop-in replacement for mini_racer, implemented in Rust on V8 15.2.
9
9
  [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
10
10
  [![Ruby 3.3 | 3.4 | 4.0](https://img.shields.io/badge/ruby-3.3%20%7C%203.4%20%7C%204.0-red.svg)](#scope)
11
11
  [![V8 15.2](https://img.shields.io/badge/V8-15.2-4285F4.svg)](#how-it-works)
12
- [![mini_racer 0.22.1 suite](https://img.shields.io/badge/mini__racer%200.22.1%20suite-passing-success.svg)](COMPATIBILITY.md)
12
+ [![mini_racer 0.22.2 suite](https://img.shields.io/badge/mini__racer%200.22.2%20suite-passing-success.svg)](COMPATIBILITY.md)
13
13
 
14
14
  **[Install](#install)** · **[Quick start](#quick-start)** · **[API](#api-at-a-glance)** · **[Switching](#switching-from-mini_racer)** · **[Benchmarks](#benchmarks)** · **[How it works](#how-it-works)** · **[Compatibility](COMPATIBILITY.md)** · **[Architecture](ARCHITECTURE.md)**
15
15
 
16
16
  </div>
17
17
 
18
- mini_racer_rs implements the `MiniRacer` API from mini_racer 0.22.1. It defines `MiniRacer` and ships `lib/mini_racer.rb`, so `require "mini_racer"` and ExecJS keep working.
18
+ mini_racer_rs implements the `MiniRacer` API from mini_racer 0.22.2. It defines `MiniRacer` and ships `lib/mini_racer.rb`, so `require "mini_racer"` and ExecJS keep working.
19
19
 
20
20
  > mini_racer_rs is an independent project and is not affiliated with the Discourse staff who maintain mini_racer.
21
21
 
22
22
  ## Highlights
23
23
 
24
- - **Round trips:** 5 to 9 times faster (0.72 µs vs 6.51 µs per call).
25
- - **Babel through ExecJS:** 1.95x faster (5.15 ms vs 10.05 ms).
24
+ - **Round trips:** 5 to 9 times faster (0.75 µs vs 6.45 µs per call).
25
+ - **Babel through ExecJS:** 1.97x faster (5.11 ms vs 10.06 ms).
26
26
  - **Bundle load:** 4.6x faster for a 44 MB production server rendering bundle (215 ms vs 983 ms).
27
- - **Memory:** A context holding the MUI bundle uses 44 MB vs 110 MB.
27
+ - **Memory:** A context holding the MUI bundle uses 43 MB vs 110 MB.
28
28
  - **Forks:** After loading and rendering React: 20 of 20 clean mini_racer_rs exits vs 20 of 20 mini_racer aborts.
29
- - **V8:** V8 15.2.124.1 vs V8 13.6.233.17 in mini_racer 0.22.1.
29
+ - **V8:** V8 15.2.124.1 vs V8 13.6.233.17 in mini_racer 0.22.2.
30
30
  - **No compiler:** Native gems cover glibc and musl Linux, including Alpine, and macOS, on both architectures, with Ruby 3.3, 3.4 and 4.0 extensions.
31
31
  - **Fiber scheduler:** Three 100 ms loops in separate contexts and fibers finish in 100 ms vs 300 ms.
32
- - **Upstream suites:** mini_racer passes 171 of 174 with 3 skipped by itself; ExecJS passes 197 of 198 with 1 skipped.
33
- - **Difficult values:** A `Map` with a function key returns an error Hash instead of aborting with SIGABRT.
32
+ - **Upstream suites:** mini_racer passes 187 of 190 with 3 skipped by itself; ExecJS passes 197 of 198 with 1 skipped.
33
+ - **Callback jumps:** A `throw` out of an attached callback ends the script with `Error: terminated` and continues after `eval`; mini_racer 0.22.2 crashes with a segmentation fault.
34
34
  - **Checks:** Script-enforced crate boundaries, four fenced `unsafe` modules, loom, wire-codec fuzzing, nightly sanitizers and mini_racer differential tests.
35
35
 
36
36
  These numbers compare with mini_racer 0.22.1. See [Benchmarks](#benchmarks) for the method.
@@ -103,6 +103,9 @@ ExecJS.eval("[1, 2].map(x => x * 2)") # => [2, 4]
103
103
  | `Platform.set_flags!(*flags)` | Sets V8 flags before the first context. |
104
104
  | `MiniRacerRs.register_source_map(bundle, map)` | Registers a source map for a bundle, so `MiniRacer::RuntimeError` backtraces show its original files and positions. CRuby only. |
105
105
  | `MiniRacerRs.counters(context)` | Returns per-context activity counters without dispatching or taking the context lock, including while a script runs and after disposal. CRuby only. |
106
+ | `MiniRacerRs.timeout(milliseconds) { }` | Gives each JavaScript call started in the block a time budget, including calls made by ExecJS and react-rails. CRuby only. |
107
+ | `MiniRacerRs.heap_limit = bytes` | Sets a process-wide V8 heap limit for contexts created afterward, allowing heap exhaustion to raise `MiniRacerRs::HeapLimitError` instead of fatally ending the process. CRuby only. |
108
+ | `MiniRacerRs::Pool.new(size:, max_uses: nil, **options) { }`, `#with`, `#shutdown` | Prebuilds ready contexts, checks them out in arrival order, replaces them on a separate thread, and disposes them at shutdown. CRuby only. |
106
109
 
107
110
  `Context.new` accepts these options:
108
111
 
@@ -123,6 +126,45 @@ Detailed stack capture makes creating and throwing errors more expensive in affe
123
126
 
124
127
  **Counters.** `MiniRacerRs.counters(context)` returns a Hash of symbol-keyed counts for activity since context creation. It reads without a dispatch or the context lock, so another thread can inspect it while a script runs. After `dispose`, it returns the last counts. A forked child that takes a context over continues from the parent's counts. Values are read individually, so an in-flight request can appear in `dispatches` before its result bytes. Keys are `dispatches` (runner requests, including nested callback requests), `callbacks` (Ruby callables run for JavaScript), `bytes_to_js` (sources, requests, callback returns and errors), `bytes_from_js` (results and callback arguments), `js_ns` (runner time excluding callback, await task and fork waits), `gc_count` and `gc_ns` (V8 collections and time), and `terminated` (counts by `stop`, `timeout`, `interrupt`, `max_memory` and `heap_exhausted`). A non-context argument raises `TypeError`. CRuby only. In release builds, timing `js_ns` added about 30 ns to a roughly 0.72 µs call round trip. Counting alone measured within noise.
125
128
 
129
+ **Timeouts per call.** `MiniRacerRs.timeout` gives each `eval`, `eval_await`, `call`, and `call_await` started in the block on the current fiber its own time budget. This bounds calls made through ExecJS and react-rails, whose contexts are created without options.
130
+
131
+ ```ruby
132
+ MiniRacerRs.timeout(200) { React::ServerRendering.render("Page", props, {}) }
133
+ MiniRacerRs.timeout(5_000) { context.eval(bundle) }
134
+ ```
135
+
136
+ The method returns the block's value. Fibers, threads, enumerators, and Async tasks started inside the block inherit its timeout while the block remains open. The effective budget is the smallest of every open scope and the context's own `timeout:`. A scope never loosens that context limit. A tighter scope inside an attached callback can terminate its nested script at any depth while the outer script continues. An overrun raises `MiniRacer::ScriptTerminatedError`, and leftover microtasks receive the same bound. The context remains usable. `milliseconds` is validated like `timeout:`. Passing `0` adds no bound, and omitting the block raises `LocalJumpError`. CRuby only.
137
+
138
+ **Heap limits.** Set `MiniRacerRs.heap_limit` to make V8 heap exhaustion raise into Ruby. Without it, reaching V8's own limit fatally ends the process and takes every in-flight request with it.
139
+
140
+ ```ruby
141
+ MiniRacerRs.heap_limit = 512 * 1024 * 1024
142
+ begin
143
+ React::ServerRendering.render("Page", props, {})
144
+ rescue MiniRacerRs::HeapLimitError
145
+ React::ServerRendering.reset_pool
146
+ end
147
+ ```
148
+
149
+ `bytes` must be 32 MiB to 4 GiB; `nil` clears it. The process-wide setting sizes every context created afterward, including ExecJS and react-rails contexts. The reader returns the configured value. V8 rounds each heap down to its page size, by at most 256 KiB. A hit raises `MiniRacerRs::HeapLimitError`, a subclass of `MiniRacer::V8OutOfMemoryError`, then mini_racer_rs runs a full collection. The context remains usable if its heap fits; otherwise evals, calls, await forms, microtask checkpoints, and pumps keep raising until disposal. `attach`, `heap_stats`, `heap_snapshot`, `low_memory_notification`, and `dispose` remain available. Hits increment `MiniRacerRs.counters(context)[:terminated][:heap_exhausted]`. `max_memory:` remains a per-context post-collection check. The limit is soft: unwinding may use up to three times the old generation. It excludes ArrayBuffer and typed array backing stores, shared large sources, and parser memory. Heap-sizing flags conflict. The limit setter and `Platform.set_flags!` raise `ArgumentError` when the other configured `max_old_space_size`, `max_heap_size`, `max_semi_space_size`, or `predictable_gc_schedule`; context creation is also refused when flags would exceed the limit. Some single allocations can still abort. In 540 processes, 534 hits raised and left the context usable; six aborts were `JSON.parse` results about twice the limit under `--minor-ms`.
150
+
151
+ **Context pools.**
152
+
153
+ ```ruby
154
+ pool = MiniRacerRs::Pool.new(size: 4, max_uses: 5_000) do |context|
155
+ context.eval(bundle, filename: "bundle.js")
156
+ end
157
+ html = pool.with { |context| context.call("render", props) }
158
+ ```
159
+
160
+ `Pool.new` builds `size` contexts (1 to 1024) at once, passes `options` to `MiniRacer::Context.new`, and runs the setup block for initial and replacement contexts. Attach callbacks there. A setup error makes construction raise.
161
+
162
+ `with` returns its block's value. Waiting checkouts are served in arrival order. With a fiber scheduler, a waiting fiber parks without blocking its thread. Nested `with` calls on one fiber reuse its context and do not count as another use.
163
+
164
+ A context is replaced after `max_uses` checkouts, disposal by the block, `MiniRacer::V8OutOfMemoryError`, or `MiniRacer::ContextDisposedError`; either error still reaches the caller. Other errors, including `MiniRacer::ScriptTerminatedError`, keep it.
165
+
166
+ Replacements run on a separate Ruby thread, which disposes the old context before building the new one. The checkout that retires a context does not wait for its replacement to load, and two loaded contexts do not overlap. Failed replacement setup raises from the next checkout. After a fork, the child forgets inherited contexts without disposing them and builds new ones. `shutdown` disposes idle contexts immediately and in-use contexts at check-in. Later checkouts raise `MiniRacerRs::Pool::ShutdownError`. CRuby only.
167
+
126
168
  ## Switching from mini_racer
127
169
 
128
170
  ### What changes
@@ -135,7 +177,7 @@ The public API and require path stay the same. Changes include native installati
135
177
 
136
178
  - You're affected if an attached callback reenters its context from another fiber, including inside `Enumerator#next`. mini_racer_rs raises `ThreadError`; mini_racer allows it.
137
179
 
138
- - You're affected if a callback exits by `throw`, returns from a proc, or receives `Thread#kill`. The script ends with `Error: terminated`. The jump continues after `eval` returns. mini_racer hangs.
180
+ - You're affected if an attached callback exits by `throw`, returns from a proc while its method is still running, or receives `Thread#kill`. mini_racer_rs ends the script with `Error: terminated`, then continues the jump after `eval` or `call` returns. In mini_racer 0.22.2, `throw` and `return` cause a segmentation fault. `Thread#kill` gives JavaScript a catchable `Error: Ruby exception`; the script continues, and the thread ends after `eval` returns.
139
181
 
140
182
  - You're affected if JavaScript reads a callback exception's non-ASCII message. mini_racer_rs passes UTF-8, such as `"café"`; mini_racer passes `"café"`.
141
183
 
@@ -155,20 +197,20 @@ See [COMPATIBILITY.md](COMPATIBILITY.md) for every difference.
155
197
 
156
198
  ### Gems that depend on mini_racer
157
199
 
158
- If another gem adds `mini_racer`, point Bundler to the repository's shim. This empty `mini_racer` gem is version 0.22.1. It depends on the `mini_racer_rs` version from the same checkout.
200
+ If another gem adds `mini_racer`, point Bundler to the repository's shim. This empty `mini_racer` gem is version 0.22.2. It depends on the `mini_racer_rs` version from the same checkout.
159
201
 
160
202
  ```ruby
161
203
  gem "mini_racer_rs"
162
204
  gem "mini_racer", github: "andymai/mini_racer_rs", tag: "vX.Y.Z", glob: "shim/*.gemspec"
163
205
  ```
164
206
 
165
- The repository tests the `path:` form of the shim with rtlcss in `test/consumers/transitive/`. A dependency excluding `mini_racer` 0.22.1 cannot use the shim.
207
+ The repository tests the `path:` form of the shim with rtlcss in `test/consumers/transitive/`. A dependency excluding `mini_racer` 0.22.2 cannot use the shim.
166
208
 
167
209
  ### Forking servers such as Puma
168
210
 
169
211
  Before forking, evaluate each bundle of 1 MiB or more twice in the master, then dispose those contexts. Use the renderer's exact source text and file name. The second evaluation builds the process-wide V8 code cache. Matching evaluations compile from it, and forked children inherit it. For Babel's 2.3 MB bundle at commit `5e13c1c`, a forked child's first load took 60.8 ms without a parent load. It took 65.5 ms after one load and 25.0 ms after two. These are medians across 5 trials. Prime a `react-rails` app by building its server renderer twice. Children do not use parent contexts. Only the cache carries over.
170
212
 
171
- For Ruby's `fork`, `IO.popen("-")`, or `Process.daemon`, mini_racer_rs waits for context runners, pauses its worker pool and waits for running tasks. An async `WebAssembly.compile` in a new default-mode child completes on the child's own pool. On Ubuntu 24.04 with glibc 2.39, 20 of 20 mini_racer children aborted with signal 6 after React rendering; all mini_racer_rs children exited cleanly. On Fedora, mini_racer hung within 50 `test/stress/fork_busy.rb` forks; mini_racer_rs completed 300 per run on Fedora and Ubuntu.
213
+ For Ruby's `fork`, `IO.popen("-")`, or `Process.daemon`, mini_racer_rs waits for context runners, pauses its worker pool and waits for running tasks. An async `WebAssembly.compile` in a new default-mode child completes on the child's own pool. On Ubuntu 24.04 with glibc 2.39, 20 of 20 mini_racer 0.22.1 children aborted with signal 6 after React rendering; all mini_racer_rs children exited cleanly. mini_racer 0.22.2 has the same fork handling. On Fedora, `test/stress/fork_busy.rb` aborted with mini_racer 0.22.2 in 3 of 3 runs, after 5, 14 and 19 forks, when an evaluating parent thread raised `TypeError`. mini_racer_rs completed 300 forks per run on Fedora and Ubuntu.
172
214
 
173
215
  With `mini_racer` 0.22.1, each worker compiles the bundle from source on its first load because it has no code cache.
174
216
 
@@ -176,32 +218,33 @@ With `mini_racer` 0.22.1, each worker compiles the bundle from source on its fir
176
218
 
177
219
  | Workload | mini_racer 0.22.1 | mini_racer_rs | Ratio |
178
220
  |---|---:|---:|---:|
179
- | Babel transform of a 3 KB JSX component, through ExecJS | 10.1 ms | 5.2 ms | 2.0x |
180
- | Terser minify of a 78 KB library, through ExecJS | 51.1 ms | 52.0 ms | 1.0x |
181
- | React server render of 1,000 items (17 KB of HTML), through ExecJS | 191 µs | 174 µs | 1.1x |
182
- | React in a new context: load the bundle and render 1,000 items, through ExecJS | 11.9 ms | 11.8 ms | 1.0x |
183
- | Handlebars render of 50 rows, through `Context#call` | 49.1 µs | 34.9 µs | 1.4x |
184
- | Autoprefixer on Bootstrap's 280 KB stylesheet, through ExecJS | 26.3 ms | 23.7 ms | 1.1x |
185
- | MUI dashboard server render of 200 rows and 299 icons (469 KB of HTML), through ExecJS | 32.6 ms | 29.8 ms | 1.1x |
186
- | MUI in a new context: load the 8.2 MB bundle and render once, through ExecJS | 167 ms | 105 ms | 1.6x |
221
+ | Babel transform of a 3 KB JSX component, through ExecJS | 10.1 ms | 5.1 ms | 2.0x |
222
+ | Terser minify of a 78 KB library, through ExecJS | 51.4 ms | 50.9 ms | 1.0x |
223
+ | React server render of 1,000 items (17 KB of HTML), through ExecJS | 192 µs | 182 µs | 1.1x |
224
+ | React in a new context: load the bundle and render 1,000 items, through ExecJS | 11.8 ms | 11.8 ms | 1.0x |
225
+ | Handlebars render of 50 rows, through `Context#call` | 49.0 µs | 34.7 µs | 1.4x |
226
+ | Autoprefixer on Bootstrap's 280 KB stylesheet, through ExecJS | 26.2 ms | 23.8 ms | 1.1x |
227
+ | MUI dashboard server render of 200 rows and 299 icons (469 KB of HTML), through ExecJS | 30.3 ms | 29.2 ms | 1.0x |
228
+ | MUI in a new context: load the 8.2 MB bundle and render once, through ExecJS | 166 ms | 104 ms | 1.6x |
187
229
  | Load a 44 MB production server rendering bundle into a new context, through ExecJS | 983 ms | 215 ms | 4.6x |
188
230
 
189
- Results are medians of 5 runs. Every workload produced identical output in both gems. The eight library workloads use the release build of commit `220bfe7`. The 44 MB production bundle load uses commit `2513a48`. Benchmarks ran on Ruby 3.4.2 and Linux with an AMD Ryzen 9 7950X3D. The governor was `performance`. Both gems were pinned to CPUs 0 through 7.
231
+ Results are medians of 5 runs. Every workload produced identical output in both gems. The eight library workloads use one run of the Ruby 3.4 extension from the published mini_racer_rs 1.4.0 `x86_64-linux-gnu` gem. The 44 MB production bundle load uses commit `2513a48`. Benchmarks ran on Ruby 3.4.2 and Linux with an AMD Ryzen 9 7950X3D. The governor was `performance`. Both gems were pinned to CPUs 0 through 7.
190
232
 
191
- The per-call and memory figures below were measured on the same machine. Startup plus Babel, Babel context and MUI context figures come from commit `220bfe7`. One watchdog thread serves the whole process, making a call with `timeout:` fast. Scripts of 1 MiB or more use a process-wide V8 code cache. Contexts loading the same large script share one source copy.
233
+ The per-call and memory figures below come from the same run of that extension on the same machine. One watchdog thread serves the whole process, making a call with `timeout:` fast. Scripts of 1 MiB or more use a process-wide V8 code cache. Contexts loading the same large script share one source copy.
192
234
 
193
235
  | Measure | mini_racer 0.22.1 | mini_racer_rs |
194
236
  |---|---:|---:|
195
- | eval round trip | 6.91 µs | 1.09 µs |
196
- | call round trip | 6.51 µs | 0.72 µs |
197
- | callback round trip | 6.12 µs | 1.12 µs |
198
- | call on a context with `timeout:` | 20.48 µs | 0.76 µs |
237
+ | eval round trip | 6.76 µs | 1.14 µs |
238
+ | call round trip | 6.45 µs | 0.75 µs |
239
+ | callback round trip | 6.06 µs | 1.11 µs |
240
+ | call on a context with `timeout:` | 20.50 µs | 0.78 µs |
241
+ | call inside `MiniRacerRs.timeout` (mini_racer: on a context with `timeout:`) | 20.61 µs | 0.85 µs |
199
242
  | Babel inside V8 | 10.3 ms | 5.3 ms |
200
- | startup plus Babel | 44.4 ms | 13.3 ms |
201
- | context holding Babel | 28.5 MB | 15.2 MB |
202
- | context holding the 8.2 MB MUI bundle | 110 MB | 44 MB |
243
+ | startup plus Babel | 44.3 ms | 13.2 ms |
244
+ | context holding Babel | 28.5 MB | 15.0 MB |
245
+ | context holding the 8.2 MB MUI bundle | 110 MB | 43 MB |
203
246
  | context holding the 44 MB production bundle, at commit `2513a48` before sources were shared | 301 MB | 136 MB |
204
- | peak resident memory with 20,000 contexts left to Ruby's garbage collector | 2,920 MB | 102 MB |
247
+ | peak resident memory with 20,000 contexts left to Ruby's garbage collector | 2,910 MB | 106 MB |
205
248
 
206
249
  ```sh
207
250
  bundle exec ruby bench/run.rb --cpus 0-7
@@ -214,7 +257,7 @@ bundle exec ruby bench/run.rb --cpus 0-7
214
257
 
215
258
  | Engine | Done | Planned | Deviation |
216
259
  |---|---|---|---|
217
- | CRuby | 54 | 0 | 28 |
260
+ | CRuby | 54 | 0 | 26 |
218
261
  | TruffleRuby | 58 | 0 | 0 |
219
262
 
220
263
  See [COMPATIBILITY.md](COMPATIBILITY.md).
@@ -240,7 +283,7 @@ mini_racer_rs uses the `v8` crate, rusty_v8 152.2.0, with magnus and rb-sys Ruby
240
283
 
241
284
  A waiting Ruby thread spins with the GVL held, then without it. It then parks with the GVL released. After enough consecutive answers arrive beyond the spin budget, that context skips spinning and parks at once until an answer arrives within the budget. Under a fiber scheduler, only the waiting fiber parks. Values use V8's serialization format and decode directly into Ruby objects. There is no intermediate tree. Repeated objects keep their identity.
242
285
 
243
- One watchdog thread per process enforces every context's `timeout:`. In both platform modes, a fork through Ruby waits for every runner to be idle or parked. Under `:single_threaded`, the child takes over contexts whose runners were idle at the fork, while contexts in use raise there. Default multi-threaded children refuse every inherited context. mini_racer_rs gives V8 a copied platform vtable in each process. Worker-thread slots post to its own pool. V8's platform has one worker thread, which receives no tasks. Forking pauses the pool. The parent resumes it afterward.
286
+ One watchdog thread per process enforces every context's `timeout:`. Fork behavior is covered in [Forking servers such as Puma](#forking-servers-such-as-puma), and the protocol, including the worker pool that runs V8's tasks, is documented in [ARCHITECTURE.md](ARCHITECTURE.md#forks).
244
287
 
245
288
  The implementation has five crates:
246
289
 
@@ -258,24 +301,24 @@ The release pipeline runs the full suites for every released extension.
258
301
 
259
302
  mini_racer_rs does not:
260
303
 
261
- - Run on Windows. It supports glibc and musl Linux, including Alpine, on x86_64 and aarch64, and macOS on arm64 and x86_64.
304
+ - Run on Windows. Supported platforms are listed in [STABILITY.md](STABILITY.md#platforms-rubies-and-v8).
262
305
 
263
306
  - Provide Node.js APIs. JavaScript runs in plain V8 without file system, network, or process access. It can reach only Ruby callables you `attach`.
264
307
 
265
308
  - Work reliably without Bundler. RubyGems may activate the original mini_racer first.
266
309
 
267
- - Satisfy dependencies pinning `mini_racer` versions other than 0.22.1. This includes minibars and its `~> 0.6.4` requirement.
310
+ - Satisfy dependencies pinning `mini_racer` versions other than 0.22.2. This includes minibars and its `~> 0.6.4` requirement.
268
311
 
269
- - Extend the `MiniRacer` API beyond mini_racer 0.22.1. [COMPATIBILITY.md](COMPATIBILITY.md) records deliberate differences.
312
+ - Extend the `MiniRacer` API beyond mini_racer 0.22.2. [COMPATIBILITY.md](COMPATIBILITY.md) records deliberate differences.
270
313
 
271
- Supported implementations are CRuby 3.3, 3.4, and 4.0, plus TruffleRuby through mini_racer's unchanged TruffleRuby backend.
314
+ Supported Rubies include TruffleRuby through mini_racer's unchanged TruffleRuby backend, as listed in [STABILITY.md](STABILITY.md#platforms-rubies-and-v8).
272
315
 
273
316
  ## Documentation
274
317
 
275
318
  | Document | Covers |
276
319
  |---|---|
277
320
  | [ARCHITECTURE.md](ARCHITECTURE.md) | Crates, a call end to end, values, termination and limits, callbacks, promises and V8's tasks, snapshots, code cache, shared sources, fast calls, source maps, forks, fiber schedulers, rules that keep it safe, and how it is checked. |
278
- | [COMPATIBILITY.md](COMPATIBILITY.md) | Every public API item and deliberate difference from mini_racer 0.22.1, with its reason. |
321
+ | [COMPATIBILITY.md](COMPATIBILITY.md) | Every public API item and deliberate difference from mini_racer 0.22.2, with its reason. |
279
322
  | [BENCHMARKS.md](BENCHMARKS.md) | Benchmark method and full results. |
280
323
  | [STABILITY.md](STABILITY.md) | Versioning, the public API, unstable interfaces, and support policy. |
281
324
  | [SECURITY.md](SECURITY.md) | Vulnerability reporting, untrusted JavaScript, and supply-chain controls. |
@@ -18,11 +18,30 @@ use crate::process::platform::Mode;
18
18
  use crate::process::{self, platform, watchdog};
19
19
  use crate::runner::Start;
20
20
  use crate::spin::spin_until;
21
- use crate::{EngineError, InvalidSnapshot, SnapshotBlob, runner};
21
+ use crate::{EngineError, SnapshotBlob, runner};
22
22
 
23
23
  const MIN_RUNNER_STACK_BYTES: usize = 2 << 20;
24
24
  const STACK_HEADROOM_BYTES: usize = 1 << 20;
25
25
 
26
+ /// How a script dispatch runs.
27
+ #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
28
+ pub struct ScriptOptions {
29
+ /// Awaits a promise result, as `eval_await` and `call_await` do.
30
+ pub awaited: bool,
31
+ /// A timeout for this script alone. It only tightens the context's: the
32
+ /// script, and the microtasks it leaves, run under the shorter of the two.
33
+ pub timeout: Option<Duration>,
34
+ }
35
+
36
+ impl ScriptOptions {
37
+ const fn awaited(awaited: bool) -> Self {
38
+ Self {
39
+ awaited,
40
+ timeout: None,
41
+ }
42
+ }
43
+ }
44
+
26
45
  #[derive(Debug, Clone, Copy, PartialEq, Eq)]
27
46
  pub enum WaitOutcome {
28
47
  Ready,
@@ -258,7 +277,7 @@ impl ContextHandle {
258
277
  source: impl Into<JsText>,
259
278
  host: &mut impl Host,
260
279
  ) -> Result<Vec<u8>, EngineError> {
261
- self.evaluate((filename.into(), source.into()), false, host)
280
+ self.evaluate(filename, source, ScriptOptions::awaited(false), host)
262
281
  }
263
282
 
264
283
  /// `eval`, then awaits a promise result: runs microtasks and due tasks
@@ -269,29 +288,33 @@ impl ContextHandle {
269
288
  source: impl Into<JsText>,
270
289
  host: &mut impl Host,
271
290
  ) -> Result<Vec<u8>, EngineError> {
272
- self.evaluate((filename.into(), source.into()), true, host)
291
+ self.evaluate(filename, source, ScriptOptions::awaited(true), host)
273
292
  }
274
293
 
275
- fn evaluate(
294
+ /// `eval` or `eval_await`, as `options` says.
295
+ pub fn evaluate(
276
296
  &self,
277
- (filename, source): (JsText, JsText),
278
- awaited: bool,
297
+ filename: impl Into<JsText>,
298
+ source: impl Into<JsText>,
299
+ options: ScriptOptions,
279
300
  host: &mut impl Host,
280
301
  ) -> Result<Vec<u8>, EngineError> {
302
+ let (filename, source) = (filename.into(), source.into());
281
303
  self.dispatch(
282
304
  DispatchKind::Script,
283
305
  |depth| Request::Eval {
284
306
  filename,
285
307
  source,
286
308
  depth,
287
- awaited,
309
+ awaited: options.awaited,
310
+ timeout: options.timeout,
288
311
  },
289
312
  host,
290
313
  )
291
314
  }
292
315
 
293
316
  pub fn call(&self, request: CallRequest, host: &mut impl Host) -> Result<Vec<u8>, EngineError> {
294
- self.invoke(request, false, host)
317
+ self.invoke(request, ScriptOptions::awaited(false), host)
295
318
  }
296
319
 
297
320
  /// `call`, then awaits a promise result, as `eval_await` does.
@@ -300,13 +323,14 @@ impl ContextHandle {
300
323
  request: CallRequest,
301
324
  host: &mut impl Host,
302
325
  ) -> Result<Vec<u8>, EngineError> {
303
- self.invoke(request, true, host)
326
+ self.invoke(request, ScriptOptions::awaited(true), host)
304
327
  }
305
328
 
306
- fn invoke(
329
+ /// `call` or `call_await`, as `options` says.
330
+ pub fn invoke(
307
331
  &self,
308
332
  request: CallRequest,
309
- awaited: bool,
333
+ options: ScriptOptions,
310
334
  host: &mut impl Host,
311
335
  ) -> Result<Vec<u8>, EngineError> {
312
336
  self.dispatch(
@@ -314,7 +338,8 @@ impl ContextHandle {
314
338
  |depth| Request::Call {
315
339
  request,
316
340
  depth,
317
- awaited,
341
+ awaited: options.awaited,
342
+ timeout: options.timeout,
318
343
  },
319
344
  host,
320
345
  )
@@ -389,11 +414,6 @@ impl ContextHandle {
389
414
  base: Option<SnapshotBlob>,
390
415
  host: &mut impl Host,
391
416
  ) -> Result<Vec<u8>, EngineError> {
392
- // A warmup from no snapshot would build the read-only heap again, which
393
- // V8 aborts on once the process has one.
394
- if base.as_ref().is_some_and(SnapshotBlob::is_empty) {
395
- return Err(InvalidSnapshot::Empty.into());
396
- }
397
417
  let context = Self::spawn(ContextConfig::default(), host)?;
398
418
  let built = context.dispatch(
399
419
  DispatchKind::Script,
@@ -632,7 +652,10 @@ impl ContextHandle {
632
652
  result
633
653
  }
634
654
 
635
- // A script nested in an untimed dispatch gets a timeout of its own.
655
+ // A nested script gets a timeout of its own, the context's tightened by
656
+ // the script's, unless a script around it ends first: in an untimed
657
+ // dispatch always, as with `timeout:`, and otherwise when its own is the
658
+ // shortest.
636
659
  fn nested(
637
660
  &self,
638
661
  block: &Arc<ControlBlock>,
@@ -643,14 +666,14 @@ impl ContextHandle {
643
666
  if block.term.is_disposing() {
644
667
  return Err(EngineError::Disposed);
645
668
  }
646
- let timer = match (kind, block.config.timeout) {
647
- (DispatchKind::Script, Some(timeout)) => {
669
+ let timer = match (kind, block.config.timeout_within(request.timeout())) {
670
+ (DispatchKind::Script, Some(timeout)) if !watchdog::ends_within(block, timeout) => {
648
671
  block.term.time_nested().map(|id| (timeout, id))
649
672
  }
650
673
  _ => None,
651
674
  };
652
675
  if let Some((timeout, id)) = timer
653
- && let Err(error) = watchdog::schedule(timeout, block, id)
676
+ && let Err(error) = watchdog::schedule_nested(timeout, block, id)
654
677
  {
655
678
  block.term.untime_nested(id);
656
679
  return Err(error);
@@ -671,7 +694,7 @@ impl ContextHandle {
671
694
  if let Some((_, id)) = timer
672
695
  && !wait.forked()
673
696
  {
674
- watchdog::clear(block, id);
697
+ watchdog::clear_nested(block, id);
675
698
  block.term.untime_nested(id);
676
699
  }
677
700
  result
@@ -1,4 +1,4 @@
1
- use std::sync::atomic::{AtomicBool, Ordering};
1
+ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
2
2
  use std::sync::{Arc, Mutex, OnceLock};
3
3
  use std::time::{Duration, Instant};
4
4
 
@@ -92,16 +92,19 @@ pub enum Request {
92
92
  depth: Depth,
93
93
  },
94
94
  /// `awaited`: a promise result is awaited, as `eval_await` does.
95
+ /// `timeout`: the dispatch's own, which only tightens the context's.
95
96
  Eval {
96
97
  filename: JsText,
97
98
  source: JsText,
98
99
  depth: Depth,
99
100
  awaited: bool,
101
+ timeout: Option<Duration>,
100
102
  },
101
103
  Call {
102
104
  request: CallRequest,
103
105
  depth: Depth,
104
106
  awaited: bool,
107
+ timeout: Option<Duration>,
105
108
  },
106
109
  Attach {
107
110
  request: Vec<u8>,
@@ -136,6 +139,14 @@ pub enum Request {
136
139
  }
137
140
 
138
141
  impl Request {
142
+ /// The timeout a script request was given for itself.
143
+ pub const fn timeout(&self) -> Option<Duration> {
144
+ match self {
145
+ Self::Eval { timeout, .. } | Self::Call { timeout, .. } => *timeout,
146
+ _ => None,
147
+ }
148
+ }
149
+
139
150
  /// The bytes a counted dispatch hands JavaScript; `None` for the
140
151
  /// context's own setup and dispose, which no caller asked for.
141
152
  pub const fn payload(&self) -> Option<usize> {
@@ -216,13 +227,57 @@ pub struct ContextConfig {
216
227
  /// Has V8 report each exception that escapes a script, as `mini_racer`'s
217
228
  /// verbose `TryCatch` does: it prints where it happened to stdout.
218
229
  pub verbose_exceptions: bool,
230
+ /// The heap size, in bytes, V8 is given for the isolate. A script that
231
+ /// reaches it ends with `TerminationCause::HeapExhausted` where V8 would
232
+ /// abort the process, as long as what it allocates past the limit fits
233
+ /// in the room the runner lends V8 to end it.
234
+ pub heap_limit: Option<usize>,
235
+ }
236
+
237
+ /// What V8's near-heap-limit callback and the runner share for a context
238
+ /// with a heap limit. The callback touches nothing else but the termination
239
+ /// cell, so V8 may call it from any thread.
240
+ #[derive(Default)]
241
+ pub struct HeapWatch {
242
+ /// V8's limit for the old generation under the heap limit, which a hit
243
+ /// raises and the runner puts back.
244
+ pub old_generation: AtomicUsize,
245
+ /// V8's whole heap size limit under the heap limit, which the runner
246
+ /// checks once it has put the old generation's back.
247
+ pub reserved: AtomicUsize,
248
+ /// V8 called the callback since the runner last recovered.
249
+ pub hit: AtomicBool,
250
+ /// V8 terminated a script since the runner last recovered.
251
+ pub ended: AtomicBool,
252
+ /// The runner is collecting on its own, with no script to terminate.
253
+ pub collecting: AtomicBool,
254
+ /// A collection after a hit left the heap over its limit, so the context
255
+ /// runs no more JavaScript.
256
+ pub poisoned: AtomicBool,
257
+ }
258
+
259
+ impl HeapWatch {
260
+ /// For a forked child taking over the isolate this watched in its parent.
261
+ pub fn inherit(&self, parent: &Self) {
262
+ for (mine, theirs) in [
263
+ (&self.old_generation, &parent.old_generation),
264
+ (&self.reserved, &parent.reserved),
265
+ ] {
266
+ mine.store(theirs.load(Ordering::Relaxed), Ordering::Relaxed);
267
+ }
268
+ self.poisoned
269
+ .store(parent.poisoned.load(Ordering::Relaxed), Ordering::Relaxed);
270
+ }
219
271
  }
220
272
 
221
273
  /// The context's pending timeout and the earliest deadline the watchdog holds
222
274
  /// for it, so the watchdog keeps about one entry per context, not per dispatch.
275
+ /// Nested scripts timed on their own have slots apart, innermost last, so
276
+ /// the deadlines around each outlive it.
223
277
  #[derive(Default)]
224
278
  pub struct Timer {
225
279
  pub due: Option<(Instant, DispatchId)>,
280
+ pub nested: Vec<(Instant, DispatchId)>,
226
281
  pub queued: Option<Instant>,
227
282
  }
228
283
 
@@ -247,6 +302,7 @@ pub struct ControlBlock {
247
302
  // An idle single-threaded runner leaves its isolate here, its only owner
248
303
  // then, so a forked child can hand it to a runner of its own.
249
304
  pub custody: Mutex<Option<v8::SharedIsolate>>,
305
+ pub heap: HeapWatch,
250
306
  pub counters: Counters,
251
307
  }
252
308
 
@@ -267,6 +323,18 @@ impl Drop for ControlBlock {
267
323
  }
268
324
  }
269
325
 
326
+ impl ContextConfig {
327
+ /// The timeout a script runs under: the shorter of the context's and the
328
+ /// one the script was given, so a script's own only tightens it.
329
+ #[must_use]
330
+ pub fn timeout_within(&self, own: Option<Duration>) -> Option<Duration> {
331
+ match (self.timeout, own) {
332
+ (Some(context), Some(own)) => Some(context.min(own)),
333
+ (context, own) => context.or(own),
334
+ }
335
+ }
336
+ }
337
+
270
338
  impl ControlBlock {
271
339
  /// Asks the runner to park for a pending fork, in JavaScript or in a
272
340
  /// snapshot build, wherever V8 next checks for interrupts.
@@ -299,6 +367,7 @@ impl ControlBlock {
299
367
  isolate: OnceLock::new(),
300
368
  building: Mutex::new(None),
301
369
  custody: Mutex::new(None),
370
+ heap: HeapWatch::default(),
302
371
  counters,
303
372
  }
304
373
  }
@@ -8,20 +8,54 @@ pub enum FlagError {
8
8
  TooLong,
9
9
  #[error("platform already initialized")]
10
10
  AlreadyInitialized,
11
+ /// The flag sets a heap size V8 would use in place of the heap limit.
12
+ #[error("--{0} would override the heap limit")]
13
+ OverridesHeapLimit(&'static str),
11
14
  }
12
15
 
13
- /// Why a startup snapshot's blob is refused before V8 reads it, where V8
14
- /// itself would abort the process.
16
+ /// Why `platform::set_heap_limit` refused a limit.
17
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
18
+ pub enum HeapLimitError {
19
+ #[error(
20
+ "heap limit must be from {} to {} bytes",
21
+ crate::process::platform::MIN_HEAP_LIMIT,
22
+ crate::process::platform::MAX_HEAP_LIMIT
23
+ )]
24
+ Range,
25
+ /// A flag already set sizes the heap in its place.
26
+ #[error("the heap limit would be overridden by --{0}")]
27
+ Overridden(&'static str),
28
+ }
29
+
30
+ /// Why a startup snapshot's blob is refused before V8 reads it, in
31
+ /// `mini_racer`'s words.
15
32
  #[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
16
33
  pub enum InvalidSnapshot {
17
- /// Shorter than its own header, or its sections do not fit in it.
18
- #[error("invalid snapshot: truncated or corrupt")]
19
- Corrupt,
20
- #[error("invalid snapshot: not made by V8 {}", crate::process::v8_version())]
34
+ #[error("snapshot is too large")]
35
+ TooLarge,
36
+ #[error("snapshot is too short")]
37
+ TooShort,
38
+ #[error("snapshot version mismatch")]
21
39
  Version,
22
- /// Empty, where a warmup needs a snapshot to start from.
23
- #[error("invalid snapshot: empty")]
24
- Empty,
40
+ #[error("snapshot header is invalid")]
41
+ Header,
42
+ #[error("snapshot has no contexts")]
43
+ NoContexts,
44
+ #[error("snapshot context table is invalid")]
45
+ ContextTable,
46
+ /// The section before the one word 80 starts, V8 15.2's read-only one,
47
+ /// which V8 aborts on or reads past and `mini_racer` hands V8, named as
48
+ /// `mini_racer`'s messages name it.
49
+ #[error("snapshot startup section is invalid")]
50
+ Startup,
51
+ #[error("snapshot read-only section is invalid")]
52
+ ReadOnly,
53
+ #[error("snapshot shared-heap section is invalid")]
54
+ SharedHeap,
55
+ #[error("snapshot context section is invalid")]
56
+ Context,
57
+ #[error("snapshot checksum mismatch")]
58
+ Checksum,
25
59
  }
26
60
 
27
61
  /// Why `SourceMaps::register` refused a map.
@@ -67,6 +101,26 @@ impl JsError {
67
101
  message: message.to_owned(),
68
102
  }
69
103
  }
104
+
105
+ /// A script that reached the context's heap limit of `limit` bytes.
106
+ pub(crate) fn heap_limit_reached(limit: usize) -> Self {
107
+ Self {
108
+ kind: JsErrorKind::Terminated(TerminationCause::HeapExhausted),
109
+ message: format!("heap limit of {limit} bytes reached"),
110
+ }
111
+ }
112
+
113
+ /// Any later script in a context whose heap a collection after a hit left
114
+ /// over its limit of `limit` bytes.
115
+ pub(crate) fn heap_limit_exceeded(limit: usize) -> Self {
116
+ Self {
117
+ kind: JsErrorKind::Terminated(TerminationCause::HeapExhausted),
118
+ message: format!(
119
+ "heap still over its limit of {limit} bytes after a collection: \
120
+ this context runs no more JavaScript"
121
+ ),
122
+ }
123
+ }
70
124
  }
71
125
 
72
126
  #[derive(Debug, thiserror::Error)]
@@ -88,6 +142,9 @@ pub enum EngineError {
88
142
  InvalidSnapshot(#[from] InvalidSnapshot),
89
143
  #[error("internal error: {0}")]
90
144
  Internal(String),
145
+ /// V8's flags sized a context's heap past its heap limit.
146
+ #[error("the heap limit is overridden by a V8 flag")]
147
+ HeapLimitOverridden,
91
148
  }
92
149
 
93
150
  fn ebusy() -> String {
@@ -17,11 +17,12 @@ mod spin;
17
17
  mod sys;
18
18
  mod text;
19
19
 
20
- pub use context::{ContextHandle, Host, Unparker, WaitHandle, WaitOutcome};
20
+ pub use context::{ContextHandle, Host, ScriptOptions, Unparker, WaitHandle, WaitOutcome};
21
21
  pub use control::{CallRequest, CallbackReply, ContextConfig, JsText};
22
22
  pub use counters::{Counts, Terminations};
23
23
  pub use error::{
24
- EngineError, FlagError, InvalidSnapshot, JsError, JsErrorKind, SourceMapError, TerminationCause,
24
+ EngineError, FlagError, HeapLimitError, InvalidSnapshot, JsError, JsErrorKind, SourceMapError,
25
+ TerminationCause,
25
26
  };
26
27
  pub use snapshot::{SnapshotBlob, WeakSnapshotBlob};
27
28
  pub use text::{Decoded, Transcoder};