mini_racer_rs 1.2.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 11094220c1f6f76dd8a40c25b8ced649e6c6fa5297d2463eb9f6f1b1308d157c
4
- data.tar.gz: bc299816d05331614b98d727ec43996bb714dab7a8ad36d553e1a81e55a10a35
3
+ metadata.gz: 5fa48ce83f4ac181230edd5df5a490007698ead30ba777abd6d9ab5c0816cdeb
4
+ data.tar.gz: a397d43582531e16d1b0f21b4eeee1026ee261e01af57f62f6019894ded53c0a
5
5
  SHA512:
6
- metadata.gz: a21607878aa930c6ee9a0281b48f21af7457ea6142672a2339937cf0c0098a7215e1a7f512e847351e39831d6642f786d125e9e9843d572c718cb1dc8a4f7926
7
- data.tar.gz: b096d9cbc42855cc07bb30bb98c9a533b898da9ebc38e63f87c540412f67bcabe888fed71d70b44a700ae74fc31c4b6f0cb793980554c316eed4e1aa6ae5c494
6
+ metadata.gz: 1faa024992d863cd72c866cdc7b23db3608a2c0c1b19f31cb1cc9d9a4cf71ead36ea55507b1de8e2613e341202a027b0eb14fa7cf8e09e0b7f433c6d93b14521
7
+ data.tar.gz: 46134cb7a25b3c4e2aab913d0b6faafd84a7042d61c01ae092b01a4206ef09e8b59056c881788d3e5e03996fc12260f30dc69e7899076c2223cdde03a5613f5d
data/CHANGELOG.md CHANGED
@@ -1,5 +1,21 @@
1
1
  # Changelog
2
2
 
3
+ ## [1.4.0](https://github.com/andymai/mini_racer_rs/compare/v1.3.0...v1.4.0) (2026-10-23)
4
+
5
+
6
+ ### Features
7
+
8
+ * add MiniRacerRs::Pool for ready contexts replaced off the request path ([#131](https://github.com/andymai/mini_racer_rs/issues/131)) ([9087488](https://github.com/andymai/mini_racer_rs/commit/9087488faacc37d362a28efd6181b972f9ee0d30))
9
+ * add MiniRacerRs.heap_limit so heap exhaustion raises instead of aborting ([#130](https://github.com/andymai/mini_racer_rs/issues/130)) ([f58d1e0](https://github.com/andymai/mini_racer_rs/commit/f58d1e052b2e93b9d750d08b058f769abc81c471))
10
+ * add MiniRacerRs.timeout for per-call time budgets ([#128](https://github.com/andymai/mini_racer_rs/issues/128)) ([da4b529](https://github.com/andymai/mini_racer_rs/commit/da4b529c5ee685df57b3b35b26cbf41518aa667e))
11
+
12
+ ## [1.3.0](https://github.com/andymai/mini_racer_rs/compare/v1.2.0...v1.3.0) (2026-10-23)
13
+
14
+
15
+ ### Features
16
+
17
+ * add MiniRacerRs.counters for per-context activity counts ([#126](https://github.com/andymai/mini_racer_rs/issues/126)) ([d482a3f](https://github.com/andymai/mini_racer_rs/commit/d482a3fb9fb4ac5ba3c077e6d2deffe25402ef3d))
18
+
3
19
  ## [1.2.0](https://github.com/andymai/mini_racer_rs/compare/v1.1.1...v1.2.0) (2026-10-22)
4
20
 
5
21
 
data/COMPATIBILITY.md CHANGED
@@ -82,6 +82,33 @@
82
82
  | `smethod:MiniRacer::Platform.set_flags!` | done | done |
83
83
  | `smethod:MiniRacer::Snapshot.load` | done | n/a |
84
84
 
85
+ ## Additions
86
+
87
+ What mini_racer_rs adds under `MiniRacerRs`. An internal id is not for callers.
88
+
89
+ | Id | CRuby | TruffleRuby |
90
+ |---|---|---|
91
+ | `class:MiniRacerRs::HeapLimitError < MiniRacer::V8OutOfMemoryError` | done | n/a |
92
+ | `class:MiniRacerRs::Pins < Object` | internal | n/a |
93
+ | `class:MiniRacerRs::Pool < Object` | done | n/a |
94
+ | `class:MiniRacerRs::Pool::ShutdownError < MiniRacer::Error` | done | n/a |
95
+ | `class:MiniRacerRs::Spill < Object` | internal | n/a |
96
+ | `class:MiniRacerRs::TimeoutScope < Object` | internal | n/a |
97
+ | `const:MiniRacerRs::NATIVE_VERSION` | done | n/a |
98
+ | `const:MiniRacerRs::V8_VERSION` | done | n/a |
99
+ | `const:MiniRacerRs::VERSION` | done | done |
100
+ | `imethod:MiniRacerRs::ForkHook#_fork` | internal | n/a |
101
+ | `imethod:MiniRacerRs::ForkHook#daemon` | internal | n/a |
102
+ | `imethod:MiniRacerRs::Pool#shutdown` | done | n/a |
103
+ | `imethod:MiniRacerRs::Pool#with` | done | n/a |
104
+ | `module:MiniRacerRs` | done | done |
105
+ | `module:MiniRacerRs::ForkHook` | internal | n/a |
106
+ | `smethod:MiniRacerRs.counters` | done | n/a |
107
+ | `smethod:MiniRacerRs.heap_limit` | done | n/a |
108
+ | `smethod:MiniRacerRs.heap_limit=` | done | n/a |
109
+ | `smethod:MiniRacerRs.register_source_map` | done | n/a |
110
+ | `smethod:MiniRacerRs.timeout` | done | n/a |
111
+
85
112
  ## Deviations
86
113
 
87
114
  ### `behavior:bigint-objects@ruby`
data/Cargo.lock CHANGED
@@ -593,7 +593,7 @@ checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
593
593
 
594
594
  [[package]]
595
595
  name = "mini_racer_engine"
596
- version = "1.2.0"
596
+ version = "1.4.0"
597
597
  dependencies = [
598
598
  "deno_core_icudata",
599
599
  "libc",
@@ -606,7 +606,7 @@ dependencies = [
606
606
 
607
607
  [[package]]
608
608
  name = "mini_racer_rs"
609
- version = "1.2.0"
609
+ version = "1.4.0"
610
610
  dependencies = [
611
611
  "magnus",
612
612
  "mini_racer_engine",
@@ -617,7 +617,7 @@ dependencies = [
617
617
 
618
618
  [[package]]
619
619
  name = "mini_racer_sourcemap"
620
- version = "1.2.0"
620
+ version = "1.4.0"
621
621
  dependencies = [
622
622
  "memchr",
623
623
  "serde",
@@ -627,7 +627,7 @@ dependencies = [
627
627
 
628
628
  [[package]]
629
629
  name = "mini_racer_sync"
630
- version = "1.2.0"
630
+ version = "1.4.0"
631
631
  dependencies = [
632
632
  "loom",
633
633
  "thiserror",
@@ -635,7 +635,7 @@ dependencies = [
635
635
 
636
636
  [[package]]
637
637
  name = "mini_racer_wire"
638
- version = "1.2.0"
638
+ version = "1.4.0"
639
639
  dependencies = [
640
640
  "criterion",
641
641
  "proptest",
data/Cargo.toml CHANGED
@@ -15,7 +15,7 @@ license = "MIT"
15
15
  publish = false
16
16
  repository = "https://github.com/andymai/mini_racer_rs"
17
17
  rust-version = "1.91"
18
- version = "1.2.0"
18
+ version = "1.4.0"
19
19
 
20
20
  [workspace.dependencies]
21
21
  criterion = {version = "0.8", default-features = false, features = ["cargo_bench_support"]}
data/README.md CHANGED
@@ -101,7 +101,11 @@ ExecJS.eval("[1, 2].map(x => x * 2)") # => [2, 4]
101
101
  | `Context#pump_message_loop`, `#perform_microtask_checkpoint` | Runs pending V8 tasks and microtasks. |
102
102
  | `Snapshot.new`, `#warmup!`, `#dump`, `Snapshot.load` | Creates, warms, serializes, and loads startup snapshots. |
103
103
  | `Platform.set_flags!(*flags)` | Sets V8 flags before the first context. |
104
- | `MiniRacerRs.register_source_map(bundle, map)` | Registers a source map for a bundle, so `MiniRacer::RuntimeError` backtraces show its original files and positions. |
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
+ | `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. |
105
109
 
106
110
  `Context.new` accepts these options:
107
111
 
@@ -112,7 +116,7 @@ ExecJS.eval("[1, 2].map(x => x * 2)") # => [2, 4]
112
116
  | `ensure_gc_after_idle:` | Idle milliseconds before one full garbage collection. `0` disables it. |
113
117
  | `snapshot:` | A `MiniRacer::Snapshot` used to initialize the context. |
114
118
 
115
- Errors are `MiniRacer::ParseError`, `MiniRacer::RuntimeError`, `MiniRacer::ScriptTerminatedError`, `MiniRacer::V8OutOfMemoryError`, `MiniRacer::ContextDisposedError`, `MiniRacer::SnapshotError`, and `MiniRacer::PlatformAlreadyInitialized`. `MiniRacer::RuntimeError` includes JavaScript frames in its backtrace. All descend from `MiniRacer::Error`.
119
+ `MiniRacer::EvalError` is the parent of `MiniRacer::ParseError`, `MiniRacer::ScriptTerminatedError`, `MiniRacer::V8OutOfMemoryError`, `MiniRacer::RuntimeError`, and `MiniRacer::ScriptError`. On CRuby, `MiniRacer::InternalError` also descends from `MiniRacer::EvalError` and reports a failure inside the gem rather than in JavaScript. `MiniRacer::ContextDisposedError`, `MiniRacer::SnapshotError`, and `MiniRacer::PlatformAlreadyInitialized` descend directly from `MiniRacer::Error`. Everything descends from `MiniRacer::Error`. `MiniRacer::RuntimeError` includes JavaScript frames in its backtrace.
116
120
 
117
121
  **Source maps.** Bundles must be UTF-8 Strings of at least 1,024 bytes. Maps must be JSON Strings in source map v3 format. When a context evaluates UTF-8 source containing a registered bundle, mini_racer_rs rewrites `MiniRacer::RuntimeError` backtraces. V8 positions inside the bundle become mapped original file, line, and column positions. V8 function names remain.
118
122
 
@@ -120,6 +124,47 @@ V8 positions remain for async frames and frames after the tenth. They also remai
120
124
 
121
125
  Detailed stack capture makes creating and throwing errors more expensive in affected contexts. Measured React and MUI server renders were unchanged. Registration is process wide and holds at most eight bundles. Maps cannot be removed. Registering a bundle again replaces its map. Trust bundles and maps like application code because source names appear in Ruby backtraces.
122
126
 
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.
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
+
123
168
  ## Switching from mini_racer
124
169
 
125
170
  ### What changes
@@ -148,7 +193,7 @@ See [COMPATIBILITY.md](COMPATIBILITY.md) for every difference.
148
193
 
149
194
  ### Stay on mini_racer if
150
195
 
151
- - Download size matters more than compile time. The largest native gem is 65.6 MB because it contains three Ruby extensions. mini_racer downloads 47.1 MB on x86_64 Linux, then compiles.
196
+ - Download size matters more than compile time. The largest native gem is 66.2 MB because it contains three Ruby extensions. mini_racer downloads 47.1 MB on x86_64 Linux, then compiles.
152
197
 
153
198
  ### Gems that depend on mini_racer
154
199
 
@@ -159,11 +204,11 @@ gem "mini_racer_rs"
159
204
  gem "mini_racer", github: "andymai/mini_racer_rs", tag: "vX.Y.Z", glob: "shim/*.gemspec"
160
205
  ```
161
206
 
162
- The repository tests `path:` shim resolution with rtlcss in `test/consumers/transitive/`. The `github:` form has not run end to end. 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.1 cannot use the shim.
163
208
 
164
209
  ### Forking servers such as Puma
165
210
 
166
- Before forking, evaluate each bundle of 1 MB 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.
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.
167
212
 
168
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 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.
169
214
 
@@ -185,7 +230,7 @@ With `mini_racer` 0.22.1, each worker compiles the bundle from source on its fir
185
230
 
186
231
  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.
187
232
 
188
- 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 MB 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 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.
189
234
 
190
235
  | Measure | mini_racer 0.22.1 | mini_racer_rs |
191
236
  |---|---:|---:|
@@ -237,12 +282,13 @@ mini_racer_rs uses the `v8` crate, rusty_v8 152.2.0, with magnus and rb-sys Ruby
237
282
 
238
283
  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.
239
284
 
240
- One watchdog thread per process enforces every context's `timeout:`. In `:single_threaded` mode, forks quiesce runners. Children take over idle contexts; contexts in use raise there. 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. Default multi-threaded children reject inherited contexts.
285
+ 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.
241
286
 
242
- The implementation has four crates:
287
+ The implementation has five crates:
243
288
 
244
289
  - `mini_racer_wire`: the wire codec, with no unsafe code.
245
290
  - `mini_racer_sync`: the thread protocol, with no unsafe code and loom checking.
291
+ - `mini_racer_sourcemap`: source maps for JavaScript backtraces, with no unsafe code.
246
292
  - `mini_racer_engine`: V8 process state and runners, and the only crate naming `v8`.
247
293
  - `mini_racer_rs`: the Ruby extension, and the only crate naming magnus or rb-sys.
248
294
 
@@ -270,7 +316,7 @@ Supported implementations are CRuby 3.3, 3.4, and 4.0, plus TruffleRuby through
270
316
 
271
317
  | Document | Covers |
272
318
  |---|---|
273
- | [ARCHITECTURE.md](ARCHITECTURE.md) | Crates, a call end to end, values, termination, callbacks, promises, snapshots, forks, fiber schedulers, safety rules, and verification. |
319
+ | [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. |
274
320
  | [COMPATIBILITY.md](COMPATIBILITY.md) | Every public API item and deliberate difference from mini_racer 0.22.1, with its reason. |
275
321
  | [BENCHMARKS.md](BENCHMARKS.md) | Benchmark method and full results. |
276
322
  | [STABILITY.md](STABILITY.md) | Versioning, the public API, unstable interfaces, and support policy. |
@@ -11,6 +11,7 @@ use mini_racer_sync::{
11
11
  use crate::control::{
12
12
  CallRequest, CallbackReply, ContextConfig, ControlBlock, Depth, JsText, Request, Wire,
13
13
  };
14
+ use crate::counters::{Counters, Counts};
14
15
  use crate::notify::NotifyFd;
15
16
  use crate::process::fork::{self, Generation};
16
17
  use crate::process::platform::Mode;
@@ -22,6 +23,25 @@ use crate::{EngineError, InvalidSnapshot, SnapshotBlob, runner};
22
23
  const MIN_RUNNER_STACK_BYTES: usize = 2 << 20;
23
24
  const STACK_HEADROOM_BYTES: usize = 1 << 20;
24
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
+
25
45
  #[derive(Debug, Clone, Copy, PartialEq, Eq)]
26
46
  pub enum WaitOutcome {
27
47
  Ready,
@@ -257,7 +277,7 @@ impl ContextHandle {
257
277
  source: impl Into<JsText>,
258
278
  host: &mut impl Host,
259
279
  ) -> Result<Vec<u8>, EngineError> {
260
- self.evaluate((filename.into(), source.into()), false, host)
280
+ self.evaluate(filename, source, ScriptOptions::awaited(false), host)
261
281
  }
262
282
 
263
283
  /// `eval`, then awaits a promise result: runs microtasks and due tasks
@@ -268,29 +288,33 @@ impl ContextHandle {
268
288
  source: impl Into<JsText>,
269
289
  host: &mut impl Host,
270
290
  ) -> Result<Vec<u8>, EngineError> {
271
- self.evaluate((filename.into(), source.into()), true, host)
291
+ self.evaluate(filename, source, ScriptOptions::awaited(true), host)
272
292
  }
273
293
 
274
- fn evaluate(
294
+ /// `eval` or `eval_await`, as `options` says.
295
+ pub fn evaluate(
275
296
  &self,
276
- (filename, source): (JsText, JsText),
277
- awaited: bool,
297
+ filename: impl Into<JsText>,
298
+ source: impl Into<JsText>,
299
+ options: ScriptOptions,
278
300
  host: &mut impl Host,
279
301
  ) -> Result<Vec<u8>, EngineError> {
302
+ let (filename, source) = (filename.into(), source.into());
280
303
  self.dispatch(
281
304
  DispatchKind::Script,
282
305
  |depth| Request::Eval {
283
306
  filename,
284
307
  source,
285
308
  depth,
286
- awaited,
309
+ awaited: options.awaited,
310
+ timeout: options.timeout,
287
311
  },
288
312
  host,
289
313
  )
290
314
  }
291
315
 
292
316
  pub fn call(&self, request: CallRequest, host: &mut impl Host) -> Result<Vec<u8>, EngineError> {
293
- self.invoke(request, false, host)
317
+ self.invoke(request, ScriptOptions::awaited(false), host)
294
318
  }
295
319
 
296
320
  /// `call`, then awaits a promise result, as `eval_await` does.
@@ -299,13 +323,14 @@ impl ContextHandle {
299
323
  request: CallRequest,
300
324
  host: &mut impl Host,
301
325
  ) -> Result<Vec<u8>, EngineError> {
302
- self.invoke(request, true, host)
326
+ self.invoke(request, ScriptOptions::awaited(true), host)
303
327
  }
304
328
 
305
- fn invoke(
329
+ /// `call` or `call_await`, as `options` says.
330
+ pub fn invoke(
306
331
  &self,
307
332
  request: CallRequest,
308
- awaited: bool,
333
+ options: ScriptOptions,
309
334
  host: &mut impl Host,
310
335
  ) -> Result<Vec<u8>, EngineError> {
311
336
  self.dispatch(
@@ -313,7 +338,8 @@ impl ContextHandle {
313
338
  |depth| Request::Call {
314
339
  request,
315
340
  depth,
316
- awaited,
341
+ awaited: options.awaited,
342
+ timeout: options.timeout,
317
343
  },
318
344
  host,
319
345
  )
@@ -498,6 +524,26 @@ impl ContextHandle {
498
524
  }
499
525
  }
500
526
 
527
+ /// Read from atomics, without a dispatch or taking an inherited context
528
+ /// over: in a forked child that has not, the counts it inherited, and
529
+ /// after a dispose, the last ones.
530
+ #[must_use]
531
+ pub fn counters(&self) -> Counts {
532
+ let epoch = fork::epoch();
533
+ let mut lineage = &self.lineage;
534
+ let mut counted = None;
535
+ loop {
536
+ if let Held::Block(block) = &lineage.held {
537
+ counted = Some(&block.counters);
538
+ }
539
+ match lineage.next.get() {
540
+ Some(next) if lineage.epoch != epoch => lineage = next,
541
+ _ => break,
542
+ }
543
+ }
544
+ counted.map_or_else(Counts::default, Counters::read)
545
+ }
546
+
501
547
  /// Answers without taking an inherited context over.
502
548
  #[must_use]
503
549
  pub fn is_disposed(&self) -> bool {
@@ -588,8 +634,15 @@ impl ContextHandle {
588
634
  self.session.owner.store(thread, Ordering::Release);
589
635
  let owning = Owning(&self.session.owner);
590
636
  let wait = WaitHandle::new(block);
591
- let result = match block.channel.request(request(Depth::Outermost(dispatch))) {
592
- Ok(()) => self.await_response(block, &wait, false, host),
637
+ let request = request(Depth::Outermost(dispatch));
638
+ let payload = request.payload();
639
+ let result = match block.channel.request(request) {
640
+ Ok(()) => {
641
+ if let Some(bytes) = payload {
642
+ block.counters.dispatched(bytes);
643
+ }
644
+ self.await_response(block, &wait, false, host)
645
+ }
593
646
  Err(error) => Err(channel(error)),
594
647
  };
595
648
  drop(owning);
@@ -604,7 +657,10 @@ impl ContextHandle {
604
657
  result
605
658
  }
606
659
 
607
- // A script nested in an untimed dispatch gets a timeout of its own.
660
+ // A nested script gets a timeout of its own, the context's tightened by
661
+ // the script's, unless a script around it ends first: in an untimed
662
+ // dispatch always, as with `timeout:`, and otherwise when its own is the
663
+ // shortest.
608
664
  fn nested(
609
665
  &self,
610
666
  block: &Arc<ControlBlock>,
@@ -615,31 +671,35 @@ impl ContextHandle {
615
671
  if block.term.is_disposing() {
616
672
  return Err(EngineError::Disposed);
617
673
  }
618
- let timer = match (kind, block.config.timeout) {
619
- (DispatchKind::Script, Some(timeout)) => {
674
+ let timer = match (kind, block.config.timeout_within(request.timeout())) {
675
+ (DispatchKind::Script, Some(timeout)) if !watchdog::ends_within(block, timeout) => {
620
676
  block.term.time_nested().map(|id| (timeout, id))
621
677
  }
622
678
  _ => None,
623
679
  };
624
680
  if let Some((timeout, id)) = timer
625
- && let Err(error) = watchdog::schedule(timeout, block, id)
681
+ && let Err(error) = watchdog::schedule_nested(timeout, block, id)
626
682
  {
627
683
  block.term.untime_nested(id);
628
684
  return Err(error);
629
685
  }
630
686
  let wait = WaitHandle::new(block);
687
+ let payload = request.payload();
631
688
  let result = block
632
689
  .channel
633
690
  .request(request)
634
691
  .map_err(channel)
635
692
  .and_then(|()| {
693
+ if let Some(bytes) = payload {
694
+ block.counters.dispatched(bytes);
695
+ }
636
696
  let _waiting = Counted::enter(&self.session.waits);
637
697
  self.await_response(block, &wait, true, host)
638
698
  });
639
699
  if let Some((_, id)) = timer
640
700
  && !wait.forked()
641
701
  {
642
- watchdog::clear(block, id);
702
+ watchdog::clear_nested(block, id);
643
703
  block.term.untime_nested(id);
644
704
  }
645
705
  result
@@ -687,17 +747,21 @@ impl ContextHandle {
687
747
  if nested && cancelled {
688
748
  block.term.release();
689
749
  }
690
- return if disposed {
750
+ let response = if disposed {
691
751
  Err(EngineError::Disposed)
692
752
  } else {
693
753
  response
694
754
  };
755
+ block.counters.answered(&response, nested && cancelled);
756
+ return response;
695
757
  }
696
758
  Ok(Some(ToRuby::Callback(request))) => {
759
+ block.counters.asked(request.len());
697
760
  let reply = if cancelled {
698
761
  CallbackReply::Abort
699
762
  } else {
700
763
  let _running = Counted::enter(&self.session.callbacks);
764
+ block.counters.called_back();
701
765
  let reply = host.callback(&request);
702
766
  if wait.forked() {
703
767
  return Err(EngineError::Orphaned);
@@ -712,6 +776,7 @@ impl ContextHandle {
712
776
  if matches!(reply, CallbackReply::Abort) && !cancelled {
713
777
  abandon(&mut cancelled);
714
778
  }
779
+ block.counters.replied(&reply);
715
780
  block.channel.reply(reply).map_err(channel)?;
716
781
  }
717
782
  Ok(None) => {}
@@ -781,7 +846,11 @@ fn adopt(inherited: &ControlBlock, carried: Inherited) -> Held {
781
846
  else {
782
847
  return orphaned(true, false);
783
848
  };
784
- let block = Arc::new(ControlBlock::with_tasks(inherited.config.clone(), tasks));
849
+ let block = Arc::new(ControlBlock::adopted(
850
+ inherited.config.clone(),
851
+ tasks,
852
+ inherited.counters.inherited(),
853
+ ));
785
854
  *lock(&block.custody) = Some(isolate);
786
855
  block.term.adopt(carried);
787
856
  // The isolate keeps whatever termination V8 still held for it.