kobako 0.31.0-aarch64-linux → 0.32.0-aarch64-linux

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 (44) hide show
  1. checksums.yaml +4 -4
  2. data/.githooks/linux-tests.sh +29 -0
  3. data/.release-please-manifest.json +1 -1
  4. data/CHANGELOG.md +125 -0
  5. data/README.md +2 -3
  6. data/ROADMAP.md +0 -1
  7. data/crates/kobako-runtime/CHANGELOG.md +90 -0
  8. data/crates/kobako-runtime/README.md +1 -1
  9. data/crates/kobako-transport/CHANGELOG.md +7 -0
  10. data/crates/kobako-transport/README.md +1 -1
  11. data/crates/kobako-wasmtime/CHANGELOG.md +47 -0
  12. data/crates/kobako-wasmtime/README.md +3 -3
  13. data/crates/kobako-wasmtime/witx/wasi_snapshot_preview1.witx +13 -0
  14. data/data/kobako.wasm +0 -0
  15. data/lib/kobako/3.3/kobako.so +0 -0
  16. data/lib/kobako/3.4/kobako.so +0 -0
  17. data/lib/kobako/4.0/kobako.so +0 -0
  18. data/lib/kobako/catalog/handles.rb +9 -5
  19. data/lib/kobako/codec/decoder.rb +1 -1
  20. data/lib/kobako/codec/state.rb +2 -18
  21. data/lib/kobako/codec/value_budget.rb +4 -4
  22. data/lib/kobako/codec.rb +5 -6
  23. data/lib/kobako/errors.rb +4 -7
  24. data/lib/kobako/filesystem.rb +1 -1
  25. data/lib/kobako/fork.rb +42 -0
  26. data/lib/kobako/handle.rb +1 -2
  27. data/lib/kobako/sandbox.rb +17 -36
  28. data/lib/kobako/sandbox_options.rb +7 -9
  29. data/lib/kobako/usage.rb +4 -2
  30. data/lib/kobako/version.rb +1 -1
  31. data/lib/kobako.rb +2 -2
  32. data/sig/kobako/catalog/handles.rbs +2 -0
  33. data/sig/kobako/codec/state.rbs +0 -4
  34. data/sig/kobako/codec/value_budget.rbs +1 -1
  35. data/sig/kobako/codec.rbs +2 -2
  36. data/sig/kobako/errors.rbs +0 -3
  37. data/sig/kobako/fork.rbs +17 -0
  38. data/sig/kobako/runtime.rbs +2 -2
  39. data/sig/kobako/sandbox.rbs +3 -12
  40. data/sig/kobako/sandbox_options.rbs +0 -2
  41. metadata +5 -5
  42. data/lib/kobako/pool.rb +0 -162
  43. data/sig/core/thread.rbs +0 -6
  44. data/sig/kobako/pool.rbs +0 -46
data/lib/kobako/errors.rb CHANGED
@@ -3,7 +3,7 @@
3
3
  module Kobako
4
4
  # Every Sandbox#eval or Sandbox#run that reaches the guest returns, or
5
5
  # raises exactly one of TrapError, SandboxError, or ServiceError. SetupError
6
- # and PoolTimeoutError arise outside any invocation. A mistake in a call
6
+ # arises outside any invocation. A mistake in a call
7
7
  # raises the TypeError, ArgumentError, RangeError, or FrozenError a CRuby
8
8
  # core method raises for it.
9
9
 
@@ -20,7 +20,8 @@ module Kobako
20
20
  end
21
21
 
22
22
  # The engine stopped the guest: a trap, a cap reached, or an outcome that
23
- # could not be read. The next invocation on the same Sandbox runs as usual.
23
+ # could not be read. Or the host could not start it, out of threads or
24
+ # address space. The next invocation on the same Sandbox runs as usual.
24
25
  # +execution+ is the failed run's Execution, so a rescue reads its captures
25
26
  # and usage as a successful caller would; it is +nil+ when the failure came
26
27
  # before the guest ran.
@@ -95,7 +96,7 @@ module Kobako
95
96
  # block never ran. Left unrescued, the Service call fails.
96
97
  class UnsupportedError < Error; end
97
98
 
98
- # One invocation issued more Handles than an id can number (2**31 - 1).
99
+ # One invocation issued more than the 1,000,000 Handles it may hold.
99
100
  class HandleExhaustedError < SandboxError; end
100
101
 
101
102
  # A <tt>preload(binary:)</tt> snippet failed to load. Bytecode that loads
@@ -118,8 +119,4 @@ module Kobako
118
119
  @available = available
119
120
  end
120
121
  end
121
-
122
- # Pool#with waited past +checkout_timeout+ with every slot held. Retrying
123
- # succeeds once a holder returns its Sandbox.
124
- class PoolTimeoutError < Error; end
125
122
  end
@@ -7,7 +7,7 @@ module Kobako
7
7
  #
8
8
  # sandbox.mount("/data", Kobako::Filesystem::Tmpfs.new("config.yml" => yaml))
9
9
  #
10
- # [<tt>Tmpfs.new(files = {}, size: 64 MiB, nr_inodes:)</tt>]
10
+ # [<tt>Tmpfs.new(files = {}, size: 4 MiB, nr_inodes:)</tt>]
11
11
  # Files held in memory for as long as the object lives, seeded from a
12
12
  # Hash of path to contents. Every invocation shares them; one that
13
13
  # should start empty mounts a new Tmpfs through Context#mount.
@@ -0,0 +1,42 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Kobako
4
+ # The check a fork through Ruby passes, defined by the ext: +prepare+ raises
5
+ # RuntimeError for a fork that cannot go on, as while a run is in progress,
6
+ # and otherwise holds new runs back, and +release+ lets them in again. This
7
+ # file hooks it into each fork Ruby makes.
8
+ module Fork # :nodoc:
9
+ # Prepended to Process's singleton class. +_fork+ is what Kernel#fork,
10
+ # Process.fork, and <tt>IO.popen("-")</tt> call, and Process.daemon
11
+ # forks without it. Only the main Ractor runs a Sandbox, so another
12
+ # Ractor's fork has nothing to check.
13
+ module Hook
14
+ def _fork
15
+ Fork.around { super }
16
+ end
17
+
18
+ def daemon(...)
19
+ Fork.around { super }
20
+ end
21
+ end
22
+
23
+ # Run +fork+ checked. A forked child holds no run back, so its +release+
24
+ # finds nothing to let in.
25
+ def self.around
26
+ return yield unless Ractor.current == Ractor.main
27
+
28
+ prepare
29
+ begin
30
+ yield
31
+ ensure
32
+ release
33
+ end
34
+ end
35
+
36
+ # Hook every fork from now on, once. A Sandbox installs it as it is
37
+ # built, so the hook stands outside the ones loaded before.
38
+ def self.install
39
+ Process.singleton_class.prepend(Hook) unless Process.singleton_class <= Hook
40
+ end
41
+ end
42
+ end
data/lib/kobako/handle.rb CHANGED
@@ -6,8 +6,7 @@ module Kobako
6
6
  class Handle < Data.define(:id)
7
7
  # The smallest id; 0 never names a Handle.
8
8
  MIN_ID = 1
9
- # The largest id, the bound the wire's Envelope holds every side to; an
10
- # invocation needing more raises HandleExhaustedError.
9
+ # The largest id, the bound the wire's Envelope holds every side to.
11
10
  MAX_ID = Kobako.max_handle_id
12
11
 
13
12
  def initialize(id:) # :nodoc:
@@ -45,6 +45,7 @@ module Kobako
45
45
  @grants = Catalog::Grants.new
46
46
  @sealed = false
47
47
  @runtime = build_runtime
48
+ Fork.install
48
49
  end
49
50
 
50
51
  # Make +object+ reachable from the guest as the constant at +path+, a
@@ -175,7 +176,7 @@ module Kobako
175
176
  # wire carries. A failed run raises as #eval does.
176
177
  def run(target, *args, **kwargs, &block)
177
178
  request = Transport::Run.new(entrypoint: target, args: args, kwargs: kwargs)
178
- Codec.within_value_budget(@options.value_budget) { begin_invocation.run(request, &block) }
179
+ begin_invocation.run(request, &block)
179
180
  end
180
181
 
181
182
  # Evaluate +code+, mruby source as a String, and return the Execution,
@@ -184,7 +185,8 @@ module Kobako
184
185
  #
185
186
  # Raises TypeError when +code+ is no String, and ArgumentError when it is
186
187
  # not UTF-8 text, before the guest runs; TrapError when the engine
187
- # stopped the guest, a deadline or memory budget included; SandboxError
188
+ # stopped the guest, a deadline or memory budget included, or the host
189
+ # could not start it; SandboxError
188
190
  # when the guest failed, the Guest Binary not starting the run included;
189
191
  # and ServiceError when a Service call failed and the guest left it
190
192
  # unrescued.
@@ -194,7 +196,17 @@ module Kobako
194
196
  source = code.dup.force_encoding(Encoding::UTF_8)
195
197
  raise ArgumentError, "code must be UTF-8 text" unless source.valid_encoding?
196
198
 
197
- Codec.within_value_budget(@options.value_budget) { begin_invocation.eval(source, &block) }
199
+ begin_invocation.eval(source, &block)
200
+ end
201
+
202
+ # What this Sandbox's runs are doing now, as a Hash, or the one value
203
+ # +key+ names, as GC.stat answers: +:runs_waiting+ counts the runs waiting
204
+ # on a lock or an event. Raises ArgumentError for a key it does not hold.
205
+ def stat(key = nil) # :nodoc:
206
+ stat = @runtime.stat
207
+ return stat if key.nil?
208
+
209
+ stat.fetch(key) { raise ArgumentError, "unknown key: #{key}" }
198
210
  end
199
211
 
200
212
  private
@@ -212,12 +224,7 @@ module Kobako
212
224
  # Registration closes at the first invocation, so every invocation ships
213
225
  # the same Services, snippets, flags, Extensions and mounts.
214
226
  def refuse_once_invoked(verb)
215
- raise FrozenError, "cannot #{verb} #{@sealed}" if @sealed
216
- end
217
-
218
- # Close registration, saying why for the refusal that follows.
219
- def seal(reason)
220
- @sealed = reason
227
+ raise FrozenError, "cannot #{verb} after first Sandbox invocation" if @sealed
221
228
  end
222
229
 
223
230
  # Sealing before the dependency check keeps a Sandbox whose check failed
@@ -226,37 +233,11 @@ module Kobako
226
233
  # the Context it answers, so nothing an invocation does is written back
227
234
  # onto the shared config.
228
235
  def begin_invocation
229
- warn_release_on_main_thread
230
- seal("after first Sandbox invocation")
236
+ @sealed = true
231
237
  @extensions.assert_dependencies
232
238
  @snippets.compile { |entries| @runtime.compile(preamble(entries)) }
233
239
  Context.new(runtime: @runtime, services: @services, extensions: @extensions, grants: @grants,
234
240
  preamble: preamble(@snippets.entries))
235
241
  end
236
-
237
- # Ruby runs a signal's trap handler, and a Ractor's +require+, on the main
238
- # Thread alone, and either raising as a run releasing the GVL takes it back
239
- # after a Service call leaves the run where it cannot unwind. The first such
240
- # run warns once.
241
- def warn_release_on_main_thread
242
- MainThreadRelease.warn_once if @options.gvl == :release && Thread.current == Thread.main
243
- end
244
-
245
- # The process's one warning that a run releasing the GVL ran on the main
246
- # Thread.
247
- module MainThreadRelease
248
- MESSAGE = "Kobako::Sandbox with gvl: :release runs on the main Thread, where a trap handler " \
249
- "that raises or exits, or another Ractor's require, can stop the run where it cannot " \
250
- "unwind; run it on another Thread, or keep trap handlers to setting a flag"
251
- @warned = false
252
-
253
- def self.warn_once
254
- return if @warned
255
-
256
- @warned = true
257
- warn(MESSAGE)
258
- end
259
- end
260
- private_constant :MainThreadRelease
261
242
  end
262
243
  end
@@ -17,21 +17,23 @@ module Kobako
17
17
  # Integer bytes kept from each output channel; 1 MiB.
18
18
  # [+open_file_limit+]
19
19
  # Integer descriptors one invocation may hold open, the
20
- # standard ones and each outermost mount's included; 1024.
20
+ # standard ones and the root's included; 16.
21
21
  # [+open_connection_limit+]
22
22
  # Integer connections one invocation holds open at once, each
23
23
  # socket once it dials, HTTP request, and name lookup in
24
24
  # flight one; 6.
25
25
  # [+connection_limit+]
26
26
  # Integer connections one invocation makes in all, each
27
- # socket's dial and HTTP request one; 50.
27
+ # lookup, dial, and HTTP request one, failed ones too,
28
+ # as a Worker counts its subrequests; 50.
28
29
  # [+profile+] The isolation the runtime must provide at least:
29
30
  # +:hermetic+, which denies the guest the clock and
30
31
  # entropy, or the weaker +:permissive+, which leaves them
31
32
  # live; +:hermetic+.
32
- # [+gvl+] How an invocation holds Ruby's GVL: +:hold+ through
33
- # the invocation, or +:release+ while the guest runs, so
34
- # Sandboxes on different Threads run in parallel; +:hold+.
33
+ # [+gvl+] How an invocation holds Ruby's GVL: +:hold+ while the
34
+ # guest runs, handing it over each quantum, or +:release+,
35
+ # giving it up while the guest runs, so Sandboxes on
36
+ # different Threads run in parallel; +:hold+.
35
37
  # [+network+] What the guest's network dials and looks names up
36
38
  # through, beneath every rule its entries make: +nil+
37
39
  # for the host's own, or a Kobako::Network::Mock a test
@@ -52,9 +54,5 @@ module Kobako
52
54
  open_file_limit:, open_connection_limit:, connection_limit: })
53
55
  super(**caps.merge(profile:, gvl:, network:))
54
56
  end
55
-
56
- def value_budget # :nodoc:
57
- Kobako::Runtime.value_budget_of(memory_limit)
58
- end
59
57
  end
60
58
  end
data/lib/kobako/usage.rb CHANGED
@@ -8,8 +8,10 @@ module Kobako
8
8
  # +timeout+ deadline governs; Service callbacks count, reading the
9
9
  # result and the captures afterwards does not.
10
10
  # * +memory_peak+ — Integer bytes of memory the invocation grew,
11
- # against the same baseline as +memory_limit+; it never exceeds the
12
- # cap, even when the cap was hit.
11
+ # against the same baseline as +memory_limit+. It can pass the cap by
12
+ # what a network queue had to take to move on or to keep a write's
13
+ # promised room, at most one read and one write per open connection,
14
+ # as Linux's +memory.peak+ records a forced charge.
13
15
  #
14
16
  # Filled on every outcome, traps included, so a Host App that rescues a
15
17
  # trap reads from the error's +execution+ how much of the budget the
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Kobako
4
- VERSION = "0.31.0"
4
+ VERSION = "0.32.0"
5
5
  end
data/lib/kobako.rb CHANGED
@@ -3,7 +3,7 @@
3
3
  # Inside +lib/+, the code sits in tiers: a tier may use the tiers below it
4
4
  # and never one above.
5
5
  #
6
- # Orchestration Sandbox, Pool, Runtime (+ ext), Context
6
+ # Orchestration Sandbox, Runtime (+ ext), Context
7
7
  # |
8
8
  # Catalog setup-time registries + the per-invocation Handle table
9
9
  # |
@@ -54,5 +54,5 @@ require_relative "kobako/extension"
54
54
  require_relative "kobako/transport"
55
55
  require_relative "kobako/catalog"
56
56
  require_relative "kobako/runtime"
57
+ require_relative "kobako/fork"
57
58
  require_relative "kobako/sandbox"
58
- require_relative "kobako/pool"
@@ -1,6 +1,8 @@
1
1
  module Kobako
2
2
  module Catalog
3
3
  class Handles
4
+ MAX_HANDLES: Integer
5
+
4
6
  def initialize: (?next_id: Integer) -> void
5
7
 
6
8
  def alloc: (untyped object) -> Kobako::Handle
@@ -6,13 +6,9 @@ module Kobako
6
6
  def self.current: () -> State
7
7
 
8
8
  @carried_handle: bool
9
- @value_budget: Integer?
10
-
11
- attr_reader value_budget: Integer?
12
9
 
13
10
  def track_handles: [T] { () -> T } -> [T, bool]
14
11
  def record_handle: () -> void
15
- def within_value_budget: [T] (Integer? budget) { () -> T } -> T
16
12
 
17
13
  private
18
14
 
@@ -15,7 +15,7 @@ module Kobako
15
15
 
16
16
  NAN_ENTRY: Integer
17
17
 
18
- def self.assert_within: (String bytes, Integer? budget) -> void
18
+ def self.assert_within: (String bytes, Integer budget) -> void
19
19
 
20
20
  class Count
21
21
  class OpenContainer < Struct[untyped]
data/sig/kobako/codec.rbs CHANGED
@@ -2,6 +2,8 @@ module Kobako
2
2
  module Codec
3
3
  MAX_NESTING_DEPTH: Integer
4
4
 
5
+ MAX_PAYLOAD_VALUES: Integer
6
+
5
7
  # A value in the closed wire type set: the scalar leaves, a Capability Handle, and Array / Hash
6
8
  # containers of the same. The by-value payloads that cross the wire —
7
9
  # dispatch arguments and success values — inhabit this type; a Fault is
@@ -13,8 +15,6 @@ module Kobako
13
15
 
14
16
  def self.track_handles: [T] { () -> T } -> [T, bool]
15
17
 
16
- def self.within_value_budget: [T] (Integer? budget) { () -> T } -> T
17
-
18
18
  # The Handle allocator/resolver a wire walk works against: alloc
19
19
  # registers a non-wire-representable object and returns its Handle,
20
20
  # fetch resolves a wire Handle id back to the live object. The
@@ -85,7 +85,4 @@ module Kobako
85
85
  ?backtrace_lines: Array[String]?
86
86
  ) -> void
87
87
  end
88
-
89
- class PoolTimeoutError < Error
90
- end
91
88
  end
@@ -0,0 +1,17 @@
1
+ module Kobako
2
+ module Fork
3
+ module Hook
4
+ def _fork: () -> Integer
5
+
6
+ def daemon: (?boolish nochdir, ?boolish noclose) -> 0
7
+ end
8
+
9
+ def self.around: [T] () { () -> T } -> T
10
+
11
+ def self.install: () -> void
12
+
13
+ def self.prepare: () -> void
14
+
15
+ def self.release: () -> void
16
+ end
17
+ end
@@ -27,8 +27,6 @@ module Kobako
27
27
  connection_limit: Integer?
28
28
  }
29
29
 
30
- def self.value_budget_of: (Integer? memory_limit) -> Integer?
31
-
32
30
  def self.from_path: (
33
31
  String path,
34
32
  timeout: (Float | Integer)?,
@@ -64,5 +62,7 @@ module Kobako
64
62
  def profile: () -> Symbol
65
63
 
66
64
  def compile: (Kobako::Context::preamble preamble) -> Array[String]?
65
+
66
+ def stat: () -> Hash[Symbol, Integer]
67
67
  end
68
68
  end
@@ -42,6 +42,9 @@ module Kobako
42
42
 
43
43
  def eval: (String code) ?{ (Kobako::Context) -> void } -> Kobako::Execution
44
44
 
45
+ def stat: () -> Hash[Symbol, Integer]
46
+ | (Symbol key) -> Integer
47
+
45
48
  private
46
49
 
47
50
  def build_runtime: () -> Kobako::Runtime
@@ -50,18 +53,6 @@ module Kobako
50
53
 
51
54
  def refuse_once_invoked: (String verb) -> void
52
55
 
53
- def seal: (String reason) -> String
54
-
55
56
  def begin_invocation: () -> Kobako::Context
56
-
57
- def warn_release_on_main_thread: () -> void
58
-
59
- module MainThreadRelease
60
- MESSAGE: String
61
-
62
- self.@warned: bool
63
-
64
- def self.warn_once: () -> void
65
- end
66
57
  end
67
58
  end
@@ -53,7 +53,5 @@ module Kobako
53
53
  gvl: Symbol,
54
54
  network: Network::Mock?
55
55
  }
56
-
57
- def value_budget: () -> Integer?
58
56
  end
59
57
  end
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: kobako
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.31.0
4
+ version: 0.32.0
5
5
  platform: aarch64-linux
6
6
  authors:
7
7
  - Aotokitsuruya
8
8
  autorequire:
9
9
  bindir: exe
10
10
  cert_chain: []
11
- date: 2026-11-18 00:00:00.000000000 Z
11
+ date: 2026-11-27 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: msgpack
@@ -39,6 +39,7 @@ executables: []
39
39
  extensions: []
40
40
  extra_rdoc_files: []
41
41
  files:
42
+ - ".githooks/linux-tests.sh"
42
43
  - ".release-please-manifest.json"
43
44
  - CHANGELOG.md
44
45
  - LICENSE
@@ -92,13 +93,13 @@ files:
92
93
  - lib/kobako/execution.rb
93
94
  - lib/kobako/extension.rb
94
95
  - lib/kobako/filesystem.rb
96
+ - lib/kobako/fork.rb
95
97
  - lib/kobako/handle.rb
96
98
  - lib/kobako/names.rb
97
99
  - lib/kobako/network.rb
98
100
  - lib/kobako/outcome.rb
99
101
  - lib/kobako/payload.rb
100
102
  - lib/kobako/payload/arguments.rb
101
- - lib/kobako/pool.rb
102
103
  - lib/kobako/runtime.rb
103
104
  - lib/kobako/sandbox.rb
104
105
  - lib/kobako/sandbox_options.rb
@@ -119,7 +120,6 @@ files:
119
120
  - lib/kobako/usage.rb
120
121
  - lib/kobako/version.rb
121
122
  - release-please-config.json
122
- - sig/core/thread.rbs
123
123
  - sig/kobako.rbs
124
124
  - sig/kobako/capture.rbs
125
125
  - sig/kobako/catalog.rbs
@@ -147,13 +147,13 @@ files:
147
147
  - sig/kobako/execution.rbs
148
148
  - sig/kobako/extension.rbs
149
149
  - sig/kobako/filesystem.rbs
150
+ - sig/kobako/fork.rbs
150
151
  - sig/kobako/guest_yielder.rbs
151
152
  - sig/kobako/handle.rbs
152
153
  - sig/kobako/network.rbs
153
154
  - sig/kobako/outcome.rbs
154
155
  - sig/kobako/payload.rbs
155
156
  - sig/kobako/payload/arguments.rbs
156
- - sig/kobako/pool.rbs
157
157
  - sig/kobako/runtime.rbs
158
158
  - sig/kobako/sandbox.rbs
159
159
  - sig/kobako/sandbox_options.rbs
data/lib/kobako/pool.rb DELETED
@@ -1,162 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- require_relative "errors"
4
- require_relative "sandbox"
5
-
6
- module Kobako
7
- # A bounded set of warm, identically set-up Sandboxes, handed out to one
8
- # holder at a time. Every Sandbox it builds is kept: an invocation leaves
9
- # nothing behind, whatever ended it.
10
- #
11
- # Deprecated: the next release removes Pool. A Sandbox keeps nothing
12
- # between runs, so Threads share one Sandbox instead.
13
- class Pool
14
- # The default +checkout_timeout+: 5 seconds.
15
- DEFAULT_CHECKOUT_TIMEOUT_SECONDS = 5.0
16
- # What building a Pool warns while deprecation warnings are shown.
17
- DEPRECATION = "Kobako::Pool is deprecated, removed next release; share a Kobako::Sandbox across Threads"
18
- private_constant :DEPRECATION
19
-
20
- # Build a Pool of up to +size+ Sandboxes, built on first demand with the
21
- # other keywords as Sandbox.new takes them. +checkout_timeout+ bounds how
22
- # many seconds #with waits, and +nil+ waits indefinitely. The block, if
23
- # given, sets up each Sandbox once, as with Sandbox#bind and
24
- # Sandbox#preload.
25
- #
26
- # Raises TypeError when +size+ is not an Integer or +checkout_timeout+
27
- # is not Numeric, and ArgumentError when either is not positive or
28
- # +checkout_timeout+ is not finite.
29
- def initialize(size:, checkout_timeout: DEFAULT_CHECKOUT_TIMEOUT_SECONDS, **sandbox_options, &setup)
30
- warn(DEPRECATION, category: :deprecated, uplevel: 1)
31
- validate_size(size)
32
- @size = size
33
- @checkout_timeout = normalize_checkout_timeout(checkout_timeout)
34
- @sandbox_options = sandbox_options
35
- @setup = setup
36
- @idle = [] # : Array[Kobako::Sandbox]
37
- @constructed = 0
38
- @mutex = Mutex.new
39
- @slot_freed = ConditionVariable.new
40
- end
41
-
42
- # Yield one exclusively-held Sandbox to the block and return the
43
- # block's value; the Sandbox returns to the pool however the block
44
- # exits. Raises PoolTimeoutError once every slot has stayed held past
45
- # +checkout_timeout+.
46
- #
47
- # An interrupt reaches the checkout only while it waits or builds, and
48
- # the block as it runs, as connection_pool's +with+ does, so none lands
49
- # between taking a Sandbox and handing it back.
50
- def with
51
- Thread.handle_interrupt(Exception => :never) do
52
- sandbox = acquire
53
- begin
54
- Thread.handle_interrupt(Exception => :immediate) { yield sandbox }
55
- ensure
56
- checkin(sandbox)
57
- end
58
- end
59
- end
60
-
61
- private
62
-
63
- def acquire
64
- timeout = @checkout_timeout
65
- deadline = timeout && (monotonic_now + timeout)
66
- loop do
67
- action, sandbox = claim_or_wait(deadline)
68
- return sandbox if action == :idle && sandbox
69
- return construct_slot if action == :build
70
- end
71
- end
72
-
73
- # Waiting happens inside the lock (so a checkin can wake it);
74
- # construction happens outside (so a slow setup block never holds the
75
- # lock) — capacity is reserved here and released by +construct_slot+
76
- # on failure.
77
- def claim_or_wait(deadline)
78
- @mutex.synchronize do
79
- return [:idle, @idle.pop] unless @idle.empty?
80
-
81
- if @constructed < @size
82
- @constructed += 1
83
- return [:build, nil]
84
- end
85
-
86
- await_slot(deadline)
87
- [:retry, nil]
88
- end
89
- end
90
-
91
- # Must run while holding +@mutex+.
92
- def await_slot(deadline)
93
- remaining = deadline && (deadline - monotonic_now)
94
- if remaining && remaining <= 0
95
- raise PoolTimeoutError,
96
- "no Sandbox returned within #{@checkout_timeout}s: all #{@size} Sandboxes are held"
97
- end
98
-
99
- Thread.handle_interrupt(Exception => :immediate) { @slot_freed.wait(@mutex, remaining) }
100
- end
101
-
102
- # A failed construction releases its reserved capacity so a later
103
- # checkout can retry. Setup closes registration, so each holder gets
104
- # the Sandbox as the setup block left it.
105
- def construct_slot
106
- done = false
107
- sandbox = Thread.handle_interrupt(Exception => :immediate) { build_slot }
108
- done = true
109
- sandbox
110
- ensure
111
- release_capacity unless done
112
- end
113
-
114
- def build_slot
115
- sandbox = Sandbox.new(**@sandbox_options)
116
- @setup&.call(sandbox)
117
- sandbox.send(:seal, "on a pooled Sandbox once its setup ran")
118
- sandbox
119
- end
120
-
121
- def checkin(sandbox)
122
- @mutex.synchronize do
123
- @idle.push(sandbox)
124
- @slot_freed.broadcast
125
- end
126
- end
127
-
128
- def release_capacity
129
- @mutex.synchronize do
130
- @constructed -= 1
131
- @slot_freed.broadcast
132
- end
133
- end
134
-
135
- # The wait deadline runs on the monotonic clock so a wall-clock jump
136
- # cannot stretch or cut the checkout wait.
137
- def monotonic_now
138
- Process.clock_gettime(Process::CLOCK_MONOTONIC)
139
- end
140
-
141
- def validate_size(size)
142
- raise TypeError, "size must be an Integer, got #{size.class}" unless size.is_a?(Integer)
143
- return if size.positive?
144
-
145
- raise ArgumentError, "size must be a positive Integer, got #{size.inspect}"
146
- end
147
-
148
- def normalize_checkout_timeout(checkout_timeout)
149
- return nil if checkout_timeout.nil?
150
- unless checkout_timeout.is_a?(Numeric)
151
- raise TypeError, "checkout_timeout must be Numeric or nil, got #{checkout_timeout.inspect}"
152
- end
153
-
154
- seconds = checkout_timeout.to_f
155
- unless seconds.positive? && seconds.finite?
156
- raise ArgumentError, "checkout_timeout must be > 0 and finite (got #{checkout_timeout})"
157
- end
158
-
159
- seconds
160
- end
161
- end
162
- end
data/sig/core/thread.rbs DELETED
@@ -1,6 +0,0 @@
1
- # The block form rbs 4.2.0 leaves out. ruby/rbs types it after that release
2
- # (7c396890); this goes once a release carrying it is the floor.
3
- class Thread
4
- def self.handle_interrupt: [T] (Hash[Class, :immediate | :on_blocking | :never] hash) { (nil) -> T } -> T
5
- | ...
6
- end