kobako 0.19.0-aarch64-linux → 0.21.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 (92) hide show
  1. checksums.yaml +4 -4
  2. data/.release-please-manifest.json +1 -1
  3. data/CHANGELOG.md +127 -0
  4. data/README.md +96 -44
  5. data/ROADMAP.md +1 -1
  6. data/crates/kobako-runtime/CHANGELOG.md +44 -0
  7. data/crates/kobako-runtime/README.md +1 -1
  8. data/crates/kobako-transport/CHANGELOG.md +31 -0
  9. data/crates/kobako-transport/README.md +43 -0
  10. data/crates/kobako-wasmtime/CHANGELOG.md +30 -0
  11. data/crates/kobako-wasmtime/README.md +1 -1
  12. data/data/kobako.wasm +0 -0
  13. data/lib/kobako/3.3/kobako.so +0 -0
  14. data/lib/kobako/3.4/kobako.so +0 -0
  15. data/lib/kobako/4.0/kobako.so +0 -0
  16. data/lib/kobako/catalog/extensions.rb +50 -43
  17. data/lib/kobako/catalog/handles.rb +7 -16
  18. data/lib/kobako/catalog/services.rb +24 -46
  19. data/lib/kobako/catalog/snippets.rb +16 -33
  20. data/lib/kobako/codec/decoder.rb +10 -13
  21. data/lib/kobako/codec/encoder.rb +7 -7
  22. data/lib/kobako/codec/error.rb +6 -6
  23. data/lib/kobako/codec/ext_types.rb +12 -72
  24. data/lib/kobako/codec/handle_walk.rb +6 -6
  25. data/lib/kobako/codec/state.rb +4 -56
  26. data/lib/kobako/codec/utils.rb +4 -4
  27. data/lib/kobako/codec.rb +11 -21
  28. data/lib/kobako/context.rb +208 -0
  29. data/lib/kobako/errors.rb +59 -16
  30. data/lib/kobako/execution.rb +52 -0
  31. data/lib/kobako/extension.rb +24 -10
  32. data/lib/kobako/outcome.rb +71 -128
  33. data/lib/kobako/payload/arguments.rb +59 -0
  34. data/lib/kobako/payload.rb +19 -0
  35. data/lib/kobako/pool.rb +1 -7
  36. data/lib/kobako/sandbox.rb +51 -191
  37. data/lib/kobako/sandbox_options.rb +24 -3
  38. data/lib/kobako/snippet/binary.rb +3 -4
  39. data/lib/kobako/snippet/source.rb +5 -6
  40. data/lib/kobako/snippet.rb +2 -2
  41. data/lib/kobako/transport/call.rb +21 -0
  42. data/lib/kobako/transport/dispatcher.rb +94 -142
  43. data/lib/kobako/transport/error.rb +21 -5
  44. data/lib/kobako/transport/reflection.rb +82 -0
  45. data/lib/kobako/transport/run.rb +25 -33
  46. data/lib/kobako/transport/yielder.rb +27 -36
  47. data/lib/kobako/transport.rb +11 -8
  48. data/lib/kobako/unresolved.rb +17 -0
  49. data/lib/kobako/usage.rb +7 -7
  50. data/lib/kobako/version.rb +1 -1
  51. data/lib/kobako.rb +1 -0
  52. data/release-please-config.json +47 -2
  53. data/sig/kobako/catalog/extensions.rbs +4 -6
  54. data/sig/kobako/catalog/handles.rbs +0 -2
  55. data/sig/kobako/catalog/services.rbs +4 -4
  56. data/sig/kobako/catalog/snippets.rbs +4 -2
  57. data/sig/kobako/codec/error.rbs +4 -4
  58. data/sig/kobako/codec/ext_types.rbs +0 -7
  59. data/sig/kobako/codec/state.rbs +0 -4
  60. data/sig/kobako/codec.rbs +4 -5
  61. data/sig/kobako/context.rbs +36 -0
  62. data/sig/kobako/errors.rbs +27 -6
  63. data/sig/kobako/execution.rbs +24 -0
  64. data/sig/kobako/extension.rbs +4 -2
  65. data/sig/kobako/outcome.rbs +12 -13
  66. data/sig/kobako/payload/arguments.rbs +26 -0
  67. data/sig/kobako/payload.rbs +4 -0
  68. data/sig/kobako/pool.rbs +0 -2
  69. data/sig/kobako/runtime.rbs +44 -14
  70. data/sig/kobako/sandbox.rbs +5 -24
  71. data/sig/kobako/sandbox_options.rbs +9 -2
  72. data/sig/kobako/snippet/binary.rbs +1 -1
  73. data/sig/kobako/snippet/source.rbs +1 -1
  74. data/sig/kobako/transport/call.rbs +21 -0
  75. data/sig/kobako/transport/dispatcher.rbs +9 -11
  76. data/sig/kobako/transport/error.rbs +11 -0
  77. data/sig/kobako/transport/reflection.rbs +15 -0
  78. data/sig/kobako/transport/run.rbs +1 -1
  79. data/sig/kobako/transport/yielder.rbs +2 -2
  80. data/sig/kobako/transport.rbs +8 -2
  81. data/sig/kobako/unresolved.rbs +4 -0
  82. metadata +18 -12
  83. data/lib/kobako/fault.rb +0 -38
  84. data/lib/kobako/outcome/panic.rb +0 -42
  85. data/lib/kobako/transport/request.rb +0 -76
  86. data/lib/kobako/transport/response.rb +0 -83
  87. data/lib/kobako/transport/yield.rb +0 -94
  88. data/sig/kobako/fault.rbs +0 -19
  89. data/sig/kobako/outcome/panic.rbs +0 -34
  90. data/sig/kobako/transport/request.rbs +0 -29
  91. data/sig/kobako/transport/response.rbs +0 -33
  92. data/sig/kobako/transport/yield.rbs +0 -34
@@ -6,45 +6,39 @@ require_relative "error"
6
6
  require_relative "utils"
7
7
  require_relative "state"
8
8
  require_relative "../handle"
9
- require_relative "../fault"
10
9
 
11
10
  module Kobako
12
11
  module Codec
13
12
  # The kobako wire ext-type conversions
14
- # ({docs/wire-codec.md}[link:../../../docs/wire-codec.md] § Ext Types)
13
+ # ({docs/wire/payload-msgpack.md}[link:../../../docs/wire/payload-msgpack.md] § Ext Types)
15
14
  # as pure functions: per-operation decode state is threaded in as an
16
15
  # argument, so the module itself holds nothing. #build_factory assembles
17
16
  # the one +MessagePack::Factory+ these conversions are registered on.
18
17
  module ExtTypes
19
18
  # MessagePack ext type code reserved for Symbol
20
- # ({docs/wire-codec.md}[link:../../../docs/wire-codec.md] § Ext Types
19
+ # ({docs/wire/payload-msgpack.md}[link:../../../docs/wire/payload-msgpack.md] § Ext Types
21
20
  # → ext 0x00). Module-private — mirrors +codec::EXT_SYMBOL+ on the
22
21
  # Rust side.
23
22
  EXT_SYMBOL = 0x00
24
23
  # MessagePack ext type code reserved for Capability Handle
25
- # ({docs/wire-codec.md}[link:../../../docs/wire-codec.md] § Ext Types
24
+ # ({docs/wire/payload-msgpack.md}[link:../../../docs/wire/payload-msgpack.md] § Ext Types
26
25
  # → ext 0x01). Module-private — mirrors +codec::EXT_HANDLE+ on the
27
26
  # Rust side.
28
27
  EXT_HANDLE = 0x01
29
- # MessagePack ext type code reserved for Exception envelope
30
- # ({docs/wire-codec.md}[link:../../../docs/wire-codec.md] § Ext Types
31
- # → ext 0x02). Module-private — mirrors +codec::EXT_ERRENV+ on the
32
- # Rust side.
33
- EXT_ERRENV = 0x02
34
- private_constant :EXT_SYMBOL, :EXT_HANDLE, :EXT_ERRENV
28
+ private_constant :EXT_SYMBOL, :EXT_HANDLE
35
29
 
36
30
  # Inert ext id the unrepresentable-value guard registers under. It is
37
31
  # never emitted (the guard's packer always raises) and never decoded
38
32
  # (no unpacker is registered, so the id stays an UnknownExtTypeError on
39
33
  # the wire), so it is not a wire ext type: deliberately not named
40
- # +EXT_*+ like the three real ext codes, since it has no Rust-side mirror
34
+ # +EXT_*+ like the two real ext codes, since it has no Rust-side mirror
41
35
  # and must stay outside the wire-symmetry inventory.
42
36
  UNREPRESENTABLE_GUARD_ID = 0x7F
43
37
  private_constant :UNREPRESENTABLE_GUARD_ID
44
38
 
45
39
  module_function
46
40
 
47
- # Assemble a +MessagePack::Factory+ with the three kobako ext types plus
41
+ # Assemble a +MessagePack::Factory+ with the two kobako ext types plus
48
42
  # the unrepresentable-value guard registered, frozen because
49
43
  # registration is its only mutation and happens exactly once. The
50
44
  # stateful conversions resolve their per-operation state at call time,
@@ -53,7 +47,6 @@ module Kobako
53
47
  factory = MessagePack::Factory.new
54
48
  register_symbol(factory)
55
49
  register_handle(factory)
56
- register_fault(factory)
57
50
  register_unrepresentable(factory)
58
51
  factory.freeze
59
52
  end
@@ -64,7 +57,7 @@ module Kobako
64
57
  end
65
58
 
66
59
  # Validate the ext-0x00 payload as UTF-8 and intern. Raises
67
- # InvalidEncoding on invalid bytes — SPEC forbids the
60
+ # InvalidEncodingError on invalid bytes — SPEC forbids the
68
61
  # binary-encoding fallback that msgpack-gem's default unpacker
69
62
  # would otherwise apply. The re-tag step lives here because the
70
63
  # msgpack ext-type unpacker hands us binary bytes; the assertion
@@ -86,64 +79,19 @@ module Kobako
86
79
  # Peel off the fixext-4 frame, hand the bytes to the
87
80
  # Host-Gem-internal +Kobako::Handle.restore+ factory, and
88
81
  # translate the +ArgumentError+ raised by Handle's invariants
89
- # into a wire-layer +InvalidType+ via Codec::Utils.with_boundary.
82
+ # into a wire-layer +InvalidTypeError+ via Codec::Utils.with_boundary.
90
83
  # The Value Object owns the id-range contract; this method only
91
84
  # owns the frame shape. Records the Handle sighting on +state+ so a
92
85
  # Handle-free decode can skip the downstream resolution walk.
93
86
  def unpack_handle(payload, state)
94
87
  state.record_handle!
95
88
  bytes = payload.b
96
- raise InvalidType, "Handle payload must be 4 bytes, got #{bytes.bytesize}" unless bytes.bytesize == 4
89
+ raise InvalidTypeError, "Handle payload must be 4 bytes, got #{bytes.bytesize}" unless bytes.bytesize == 4
97
90
 
98
91
  id = bytes.unpack1("N") # : Integer
99
92
  Codec::Utils.with_boundary { Kobako::Handle.restore(id) }
100
93
  end
101
94
 
102
- # Encode the inner ext-0x02 map via Encoder (not the raw factory) so
103
- # the embedded payload flows through the same boundary as a top-level
104
- # encode — nested kobako values (Handle, nested Fault) reach the
105
- # registered ext-type packers. A +details+ chain nested past the
106
- # +state+ depth cap has no wire representation and surfaces as
107
- # +UnsupportedType+. In a payload position (+state+ inside a
108
- # forbid_faults bracket) the envelope has no wire representation at
109
- # all, so the refusal routes the value into the position's
110
- # non-representable handling — the Dispatcher's auto-wrap rescue,
111
- # or a raise at the yield site.
112
- def pack_fault(fault, state)
113
- if state.faults_forbidden?
114
- raise UnsupportedType, "Kobako::Fault has no wire representation in a payload position"
115
- end
116
-
117
- state.within_ext_frame(UnsupportedType) do
118
- Encoder.encode("type" => fault.type, "message" => fault.message, "details" => fault.details)
119
- end
120
- end
121
-
122
- # Peel the embedded msgpack map and hand it to +Kobako::Fault.new+
123
- # inside Decoder.decode's block form, so the value-object's
124
- # +ArgumentError+ invariants surface as +InvalidType+ through the
125
- # decoder boundary. Inner decode goes through Decoder (not the raw
126
- # factory) so the embedded +str+ payloads flow through the same
127
- # UTF-8 validation as a top-level decode. A nested ext 0x02 in
128
- # +details+ re-enters this method, so the +state+ ext-frame guard
129
- # bounds the chain depth to keep it from exhausting the native stack.
130
- # In a payload position (+state+ inside a forbid_faults bracket) the
131
- # envelope is a wire violation outright — its sole legal position is
132
- # the Response fault field.
133
- def unpack_fault(payload, state)
134
- if state.faults_forbidden?
135
- raise InvalidType, "Fault envelope (ext 0x02) is not a legal value in a payload position"
136
- end
137
-
138
- state.within_ext_frame(InvalidType) do
139
- Decoder.decode(payload) do |map|
140
- raise InvalidType, "Fault payload must be a map" unless map.is_a?(Hash)
141
-
142
- Kobako::Fault.new(type: map["type"], message: map["message"], details: map["details"])
143
- end
144
- end
145
- end
146
-
147
95
  def register_symbol(factory)
148
96
  factory.register_type(
149
97
  EXT_SYMBOL, Symbol,
@@ -160,17 +108,9 @@ module Kobako
160
108
  )
161
109
  end
162
110
 
163
- def register_fault(factory)
164
- factory.register_type(
165
- EXT_ERRENV, Kobako::Fault,
166
- packer: ->(fault) { ExtTypes.pack_fault(fault, State.current) },
167
- unpacker: ->(payload) { ExtTypes.unpack_fault(payload, State.current) }
168
- )
169
- end
170
-
171
111
  # A catch-all packer that rejects any value with no wire representation
172
- # as +UnsupportedType+. Registered on +BasicObject+ so it also covers
173
- # BasicObject-based proxies; the narrower Symbol / Handle / Fault
112
+ # as +UnsupportedTypeError+. Registered on +BasicObject+ so it also covers
113
+ # BasicObject-based proxies; the narrower Symbol / Handle
174
114
  # registrations still win by most-specific match, and native types never
175
115
  # reach it. Packer-only: the guard never writes bytes, so its id is inert
176
116
  # and the decode surface stays fail-closed.
@@ -184,7 +124,7 @@ module Kobako
184
124
  def register_unrepresentable(factory)
185
125
  factory.register_type(
186
126
  UNREPRESENTABLE_GUARD_ID, BasicObject,
187
- packer: ->(_value) { raise UnsupportedType, "value has no wire representation" }
127
+ packer: ->(_value) { raise UnsupportedTypeError, "value has no wire representation" }
188
128
  )
189
129
  end
190
130
  end
@@ -11,8 +11,8 @@ module Kobako
11
11
  # path; #deep_restore resolves each wire-decoded Handle back to its
12
12
  # host object on every guest→host value path. #representable? is the
13
13
  # by-value codec-type predicate that decides which leaves #deep_wrap
14
- # must wrap: the closed 12-entry wire type set
15
- # ({docs/wire-codec.md}[link:../../../docs/wire-codec.md] § Type
14
+ # must wrap: the closed 11-entry wire type set
15
+ # ({docs/wire/payload-msgpack.md}[link:../../../docs/wire/payload-msgpack.md] § Type
16
16
  # Mapping).
17
17
  #
18
18
  # All helpers are pure except #deep_wrap, whose only side effect is
@@ -23,7 +23,7 @@ module Kobako
23
23
  # Inclusive Integer range the msgpack gem encodes without raising
24
24
  # +RangeError+ at encode time — signed +int 64+ minimum through
25
25
  # unsigned +uint 64+ maximum
26
- # ({docs/wire-codec.md}[link:../../../docs/wire-codec.md] § Type
26
+ # ({docs/wire/payload-msgpack.md}[link:../../../docs/wire/payload-msgpack.md] § Type
27
27
  # Mapping #3, the +fixint+ / +int 8..64+ / +uint 8..64+ union).
28
28
  # Anchored as a +Range+ so #primitive_type? stays a single
29
29
  # dispatch line. This is the codec's encode domain — not to
@@ -33,16 +33,16 @@ module Kobako
33
33
  MSGPACK_INT_RANGE = (-(2**63)..((2**64) - 1))
34
34
 
35
35
  # Codec-type predicate
36
- # ({docs/wire-codec.md}[link:../../../docs/wire-codec.md] § Type
36
+ # ({docs/wire/payload-msgpack.md}[link:../../../docs/wire/payload-msgpack.md] § Type
37
37
  # Mapping). Returns +true+ when +value+ belongs to the closed
38
- # 12-entry codec type set — +nil+, +TrueClass+, +FalseClass+,
38
+ # 11-entry codec type set — +nil+, +TrueClass+, +FalseClass+,
39
39
  # +Integer+ (in the +i64..u64+ value domain), +Float+, +String+,
40
40
  # +Symbol+, +Kobako::Handle+, +Array+ whose every element is itself
41
41
  # representable, or +Hash+ whose every key and value are
42
42
  # representable. Integers outside the codec's signed-64 /
43
43
  # unsigned-64 union are rejected so the predicate agrees with the
44
44
  # msgpack gem's encode-time +RangeError+ behaviour the codec
45
- # already surfaces as UnsupportedType.
45
+ # already surfaces as UnsupportedTypeError.
46
46
  #
47
47
  # The optional +depth+ bounds the recursive descent at the wire's
48
48
  # structural nesting cap so a self-referential container — reachable
@@ -2,23 +2,11 @@
2
2
 
3
3
  module Kobako
4
4
  module Codec
5
- # Codec-internal, per-thread state of the operation in flight: the
6
- # ext-envelope nesting depth and whether a Capability Handle crossed
7
- # the current decode. Thread scoping is what makes plain instance
8
- # variables sound — host codec calls run synchronously on their
9
- # owning thread, and a nested decode (an ext 0x02 Fault re-entering
10
- # through its +details+) reuses the same thread instance, so the
11
- # depth counter accumulates across the re-entry instead of resetting.
5
+ # Codec-internal, per-thread state of the operation in flight: whether
6
+ # a Capability Handle crossed the current decode. Thread scoping is
7
+ # what makes plain instance variables sound — host codec calls run
8
+ # synchronously on their owning thread.
12
9
  class State
13
- # An ext 0x02 (Fault) envelope nests through its +details+ field, and
14
- # each level re-enters the codec with a fresh +MessagePack+ unpacker
15
- # whose built-in stack guard resets — so ext-envelope depth is tracked
16
- # here instead. The cap matches the wire's overall nesting bound and
17
- # keeps a nested chain from exhausting the native stack: an over-deep
18
- # chain fails as a clean wire error, never a stack-level trap.
19
- MAX_EXT_DEPTH = 128
20
- private_constant :MAX_EXT_DEPTH
21
-
22
10
  # Thread-local slot holding the calling thread's State.
23
11
  STATE_KEY = :__kobako_codec_state__
24
12
  private_constant :STATE_KEY
@@ -31,9 +19,7 @@ module Kobako
31
19
  private_class_method :new
32
20
 
33
21
  def initialize
34
- @ext_depth = 0
35
22
  @carried_handle = false
36
- @faults_forbidden = false
37
23
  end
38
24
 
39
25
  # Bracket a decode and return the block's result together with
@@ -53,44 +39,6 @@ module Kobako
53
39
  def record_handle!
54
40
  @carried_handle = true
55
41
  end
56
-
57
- # Bracket a codec operation in a payload position, where an ext 0x02
58
- # Fault envelope has no legal wire representation: the fault field of
59
- # an error Response is its only home. The ext-type conversions
60
- # consult #faults_forbidden? and refuse the envelope in both
61
- # directions while the bracket is open. Save/restore keeps a nested
62
- # legal operation on the same thread unaffected.
63
- def forbid_faults
64
- previous = @faults_forbidden
65
- @faults_forbidden = true
66
- yield
67
- ensure
68
- @faults_forbidden = previous
69
- end
70
-
71
- # Whether the operation in flight sits inside a #forbid_faults
72
- # bracket — i.e. in a payload position where ext 0x02 is a wire
73
- # violation.
74
- def faults_forbidden?
75
- @faults_forbidden
76
- end
77
-
78
- # Track ext-envelope re-entry depth and refuse a chain past
79
- # MAX_EXT_DEPTH, raising +over_limit+ so the failure lands in the
80
- # caller's existing wire-error class. The next depth is checked before
81
- # it is committed, so an over-deep rejection leaves the counter
82
- # untouched, and the +ensure+ restores the entry value on the way out.
83
- def within_ext_frame(over_limit)
84
- depth = @ext_depth + 1
85
- raise over_limit, "ext envelope nesting exceeds #{MAX_EXT_DEPTH} levels" if depth > MAX_EXT_DEPTH
86
-
87
- @ext_depth = depth
88
- begin
89
- yield
90
- ensure
91
- @ext_depth = depth - 1
92
- end
93
- end
94
42
  end
95
43
 
96
44
  private_constant :State
@@ -21,18 +21,18 @@ module Kobako
21
21
  module Utils
22
22
  module_function
23
23
 
24
- # Raise InvalidEncoding unless +string+'s bytes are valid under
24
+ # Raise InvalidEncodingError unless +string+'s bytes are valid under
25
25
  # its current encoding tag. +label+ is the caller-supplied prefix
26
26
  # for the error message (e.g. +"str payload"+, +"Symbol payload"+).
27
27
  def assert_utf8!(string, label)
28
28
  return if string.valid_encoding?
29
29
 
30
- raise InvalidEncoding, "#{label} is not valid UTF-8"
30
+ raise InvalidEncodingError, "#{label} is not valid UTF-8"
31
31
  end
32
32
 
33
33
  # Run +block+ at the codec boundary: a value object raises
34
34
  # +ArgumentError+ when an invariant is violated at construction, and
35
- # this helper surfaces that as InvalidType so the public taxonomy
35
+ # this helper surfaces that as InvalidTypeError so the public taxonomy
36
36
  # stays Kobako::Codec::Error and never leaks +ArgumentError+ from
37
37
  # the Ruby standard library.
38
38
  #
@@ -45,7 +45,7 @@ module Kobako
45
45
  def with_boundary
46
46
  yield
47
47
  rescue ::ArgumentError => e
48
- raise InvalidType, e.message
48
+ raise InvalidTypeError, e.message
49
49
  end
50
50
  end
51
51
  end
data/lib/kobako/codec.rb CHANGED
@@ -11,22 +11,21 @@ require_relative "codec/decoder"
11
11
  module Kobako
12
12
  # Host-side MessagePack codec for the kobako wire contract — the
13
13
  # byte-level layer ({docs/wire-codec.md}[link:../../docs/wire-codec.md]).
14
- # Two consumers sit on top:
15
- # +Kobako::Transport+ pins the host↔guest framing (Request / Response /
16
- # Run / Yield) and +Kobako::Outcome+ owns the per-+#run+ outcome
17
- # envelope (Result body / Panic map). The ext-type leaves this layer
18
- # carries — +Kobako::Handle+ (0x01) and +Kobako::Fault+ (0x02) — live at
19
- # the kobako root so the codec can register them without depending
20
- # upward on Transport.
14
+ # This is the payload codec: the core envelope is framed natively, so
15
+ # what reaches here is one codec document — an invocation's arguments
16
+ # (+Kobako::Payload::Arguments+), a dispatch or yield value, or an
17
+ # invocation's value and a Panic's diagnostics
18
+ # (+Kobako::Outcome+). The ext-type leaves this layer
19
+ # carries — +Kobako::Handle+ (0x01) — lives at the kobako root so the
20
+ # codec can register it without depending upward on Transport.
21
21
  #
22
- # Backed by the official +msgpack+ gem: ExtTypes registers the three
23
- # kobako-specific ext types (0x00 Symbol, 0x01 Capability Handle,
24
- # 0x02 Exception envelope) on one process-wide +MessagePack::Factory+,
22
+ # Backed by the official +msgpack+ gem: ExtTypes registers the two
23
+ # kobako-specific ext types (0x00 Symbol, 0x01 Capability Handle) on
24
+ # one process-wide +MessagePack::Factory+,
25
25
  # and Encoder / Decoder are thin wrappers over it. The Rust side
26
26
  # mirrors this layer as the +codec+ module in the +kobako-codec+ crate;
27
27
  # the ext-code constants live as module-private values on ExtTypes
28
- # alongside +codec::EXT_SYMBOL+ / +codec::EXT_HANDLE+ /
29
- # +codec::EXT_ERRENV+ on that side.
28
+ # alongside +codec::EXT_SYMBOL+ / +codec::EXT_HANDLE+ on that side.
30
29
  module Codec
31
30
  # The maximum structural nesting depth the wire represents (the
32
31
  # MessagePack ecosystem's bound), shared with the guest +kobako_codec+
@@ -41,14 +40,5 @@ module Kobako
41
40
  def self.track_handles(&block)
42
41
  State.current.track_handles(&block)
43
42
  end
44
-
45
- # Bracket a codec operation in a payload position: an ext 0x02 Fault
46
- # envelope is only legal in the Response fault field, so the envelope
47
- # layers open this bracket around every other encode / decode and the
48
- # ext-type conversions refuse the envelope while it is open — a wire
49
- # violation on decode, no wire representation on encode.
50
- def self.forbid_faults(&block)
51
- State.current.forbid_faults(&block)
52
- end
53
43
  end
54
44
  end
@@ -0,0 +1,208 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "capture"
4
+ require_relative "codec"
5
+ require_relative "errors"
6
+ require_relative "execution"
7
+ require_relative "unresolved"
8
+ require_relative "outcome"
9
+ require_relative "usage"
10
+ require_relative "transport"
11
+ require_relative "catalog"
12
+
13
+ module Kobako
14
+ # Kobako::Context — the per-invocation driver behind a single +Sandbox#eval+
15
+ # / +#run+. Each Context owns a fresh +Catalog::Handles+ table and drives one
16
+ # guest invocation: it builds the dispatch handler, runs the guest, records
17
+ # the run's captures and usage, and decodes the outcome. One Context per
18
+ # invocation owns all per-invocation state, so the reusable +Sandbox+ holds
19
+ # none and overlapping evals never touch each other's state.
20
+ class Context
21
+ # Build a Context over the Sandbox-owned config — the +Runtime+, the
22
+ # sealed +Catalog::Services+ / +Catalog::Snippets+ registries, and the
23
+ # +Catalog::Extensions+ whose callable backends this Context resolves for
24
+ # its own run. The +Catalog::Handles+ table is this invocation's own, so
25
+ # guest→host dispatch and host→guest auto-wrap share one allocator scoped
26
+ # to the run; the resolved provider map is likewise per-invocation, so
27
+ # concurrent invocations never share mutable state.
28
+ def initialize(runtime:, services:, snippets:, extensions:)
29
+ @runtime = runtime
30
+ @services = services
31
+ @snippets = snippets
32
+ @extensions = extensions
33
+ @resolved = {} # : Hash[String, untyped]
34
+ @overrides = {} # : Hash[String, untyped]
35
+ @spent = false
36
+ @handler = Catalog::Handles.new
37
+ @stdout_capture = @stderr_capture = Capture::EMPTY
38
+ @usage = Usage::EMPTY
39
+ end
40
+
41
+ # Override the object bound at an already-declared +path+ for this
42
+ # invocation only — the per-eval hook the +#eval+ / +#run+ block uses to
43
+ # fill a fillable or shadow any static / per-invocation binding. +path+
44
+ # must name a declared (Frame 1) binding; overriding an undeclared path
45
+ # raises +ArgumentError+ so the Frame 1 key set stays fixed. Valid only
46
+ # while the block runs — the Context is spent once the block returns, so a
47
+ # captured +ctx+ used afterward raises +ArgumentError+ too, putting both
48
+ # misuses on one rescuable channel. Returns +self+.
49
+ def bind(path, object)
50
+ raise ArgumentError, "Kobako::Context is spent; ctx.bind is only valid inside the #eval / #run block" if @spent
51
+
52
+ key = path.to_s
53
+ raise ArgumentError, "cannot override undeclared path #{key.inspect}" unless @services.bound?(key)
54
+
55
+ @overrides[key] = object
56
+ self
57
+ end
58
+
59
+ # Resolve a Service +path+ to the object backing it this invocation,
60
+ # layering the per-eval +ctx.bind+ overrides over this Context's
61
+ # per-invocation provider results over the Sandbox's static base bindings.
62
+ # An unbound path raises +KeyError+; a fillable left unfilled resolves to
63
+ # +Kobako::Unresolved+ and is reported the same way, so an unresolved
64
+ # capability fails closed as an undefined target rather than dispatching to
65
+ # the sentinel. The Dispatcher maps either +KeyError+ to an
66
+ # undefined-target wire fault. Internal — the per-invocation dispatch
67
+ # handler is the sole caller.
68
+ def lookup(path)
69
+ key = path.to_s
70
+ object = @overrides.fetch(key) { @resolved.fetch(key) { @services.lookup(path) } }
71
+ raise KeyError, "service #{path} is declared but unresolved this invocation" if Unresolved.equal?(object)
72
+
73
+ object
74
+ end
75
+
76
+ # Execute a guest mruby source string in a fresh +mrb_state+ and return the
77
+ # decoded last expression. A given +block+ runs first, receiving this
78
+ # Context to collect +ctx.bind+ overrides before the guest drives.
79
+ def eval(code, &block)
80
+ collect_overrides(&block) if block
81
+ invoke!(:eval) do
82
+ @runtime.eval(dispatch_handler, @services.paths, code.b, @snippets.entries)
83
+ end
84
+ end
85
+
86
+ # Dispatch a +Transport::Run+ into a preloaded entrypoint and return the
87
+ # decoded result. A given +block+ runs first, receiving this Context to
88
+ # collect +ctx.bind+ overrides before the guest drives.
89
+ def run(request, &block)
90
+ collect_overrides(&block) if block
91
+ invoke!(:run, entrypoint: request.entrypoint) do
92
+ @runtime.run(dispatch_handler, @services.paths, @snippets.entries,
93
+ request.entrypoint.to_s, request.payload(@handler))
94
+ end
95
+ end
96
+
97
+ private
98
+
99
+ # Run the per-eval override +block+, handing it this Context so it can call
100
+ # +ctx.bind+, then spend the Context so a captured +ctx+ used after the
101
+ # block raises. A block that raises propagates before the guest drives, so
102
+ # the guest never runs and no Execution is produced.
103
+ def collect_overrides
104
+ yield self
105
+ ensure
106
+ @spent = true
107
+ end
108
+
109
+ # Build this invocation's guest→host dispatch handler — a +Proc+ routing
110
+ # each guest→host call through the stateless +Transport::Dispatcher+,
111
+ # capturing this Context as the path resolver (its +#lookup+ layers the
112
+ # per-invocation providers over the static bindings) plus +@handler+. Handed to
113
+ # +Runtime#eval+ / +#run+ as a call argument, so the Runtime holds no
114
+ # dispatch state and the +Proc+ stays GC-rooted as a live argument for the
115
+ # synchronous call. The ext hands the +Proc+ a per-dispatch +guest_yielder+
116
+ # — a +String → String+ callable that re-enters the in-flight guest to run
117
+ # a yielded block — which the +Dispatcher+ forwards to the
118
+ # +Transport::Yielder+ it builds for the call.
119
+ def dispatch_handler
120
+ lambda do |target, method_name, block_given, payload, guest_yielder|
121
+ call = Transport::Call.new(target: target, method_name: method_name,
122
+ block_given: block_given, payload: payload)
123
+ Transport::Dispatcher.dispatch(call, self, @handler, guest_yielder)
124
+ end
125
+ end
126
+
127
+ # Record this invocation's usage and both output captures from the ext
128
+ # +Snapshot+. Every Snapshot carries them — value return or trap alike — so
129
+ # +#usage+ / +#stdout+ / +#stderr+ stay readable after a rescued trap.
130
+ def populate_observability!(snapshot)
131
+ @usage = Usage.new(wall_time: snapshot.wall_time, memory_peak: snapshot.memory_peak)
132
+ @stdout_capture = Capture.new(bytes: snapshot.stdout, truncated: snapshot.stdout_truncated?)
133
+ @stderr_capture = Capture.new(bytes: snapshot.stderr, truncated: snapshot.stderr_truncated?)
134
+ end
135
+
136
+ # Pick the +TrapError+ subclass to re-raise based on +err+'s actual class.
137
+ # Cap-trap subclasses (+TimeoutError+ / +MemoryLimitError+) preserve their
138
+ # named identity; everything else collapses to the base +Kobako::TrapError+,
139
+ # so #invoke! can add the verb prefix without erasing the named subclass.
140
+ def trap_class_for(err)
141
+ case err
142
+ when TimeoutError then TimeoutError
143
+ when MemoryLimitError then MemoryLimitError
144
+ else TrapError
145
+ end
146
+ end
147
+
148
+ # Build the +TrapError+-family exception for a trapped +Snapshot+ from its
149
+ # neutral trap kind, tagged with the verb — the cap subclasses
150
+ # (+TimeoutError+ / +MemoryLimitError+) keep their identity, every other
151
+ # engine fault is the base +TrapError+.
152
+ def trap_error_for(snapshot, verb)
153
+ klass = case snapshot.trap_kind
154
+ when :timeout then TimeoutError
155
+ when :memory_limit then MemoryLimitError
156
+ else TrapError
157
+ end
158
+ klass.new("Sandbox##{verb} failed: #{snapshot.trap_message}")
159
+ end
160
+
161
+ # Freeze this run's observables plus +value+ (+nil+ on a failed run) into
162
+ # the read-only +Execution+ the caller receives or the error carries.
163
+ # +failed+ records the two apart so a +nil+ +value+ from a successful run
164
+ # stays distinct from a failed one.
165
+ def build_execution(value, failed:)
166
+ Execution.new(value: value, usage: @usage, stdout: @stdout_capture, stderr: @stderr_capture, failed: failed)
167
+ end
168
+
169
+ # Settle a completed run's outcome into its +Execution+. A Capability
170
+ # Handle in the result is restored to its host object first. The settle
171
+ # sits in the rescue so a wire-violation trap or a Panic both attach this
172
+ # run's Execution, just like a guest-call trap does. +entrypoint+ is the
173
+ # name +#run+ asked for, which the host knows and the wire never carries,
174
+ # so an unresolved one names itself on the error it raises.
175
+ def settle_outcome(snapshot, verb, entrypoint)
176
+ kind, payload, panic = snapshot.outcome
177
+ value, carried = Codec.track_handles { Outcome.reify(kind, payload, panic, entrypoint: entrypoint) }
178
+ value = Codec::HandleWalk.deep_restore(value, @handler) if carried
179
+ build_execution(value, failed: false)
180
+ rescue Kobako::TrapError => e
181
+ raise trap_class_for(e).new("Sandbox##{verb} failed: #{e.message}").with_execution(build_execution(nil,
182
+ failed: true))
183
+ rescue Kobako::SandboxError, Kobako::ServiceError => e
184
+ raise e.with_execution(build_execution(nil, failed: true))
185
+ end
186
+
187
+ # Drive one invocation and settle it into a frozen +Execution+. +verb+
188
+ # tags the TrapError message so the failing export is identifiable. This
189
+ # invocation's callable Extension backends are resolved first — before the
190
+ # guest runs — so a provider that raises propagates unwrapped and leaves
191
+ # the guest unrun. Usage and captures are recorded before the trap check,
192
+ # so a trapped Snapshot's error carries them just like a completed run's
193
+ # return value. A could-not-start fault ran no invocation at all, so it
194
+ # carries no Execution and gains only the verb prefix.
195
+ def invoke!(verb, entrypoint: nil)
196
+ @resolved = @extensions.resolve
197
+ begin
198
+ snapshot = yield
199
+ rescue Kobako::TrapError => e
200
+ raise trap_class_for(e), "Sandbox##{verb} failed: #{e.message}"
201
+ end
202
+ populate_observability!(snapshot)
203
+ return settle_outcome(snapshot, verb, entrypoint) unless snapshot.trapped?
204
+
205
+ raise trap_error_for(snapshot, verb).with_execution(build_execution(nil, failed: true))
206
+ end
207
+ end
208
+ end