kobako 0.20.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 (78) hide show
  1. checksums.yaml +4 -4
  2. data/.release-please-manifest.json +1 -1
  3. data/CHANGELOG.md +107 -0
  4. data/README.md +96 -44
  5. data/ROADMAP.md +1 -1
  6. data/crates/kobako-runtime/CHANGELOG.md +37 -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 +23 -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/services.rb +13 -21
  17. data/lib/kobako/catalog/snippets.rb +16 -34
  18. data/lib/kobako/codec/decoder.rb +10 -13
  19. data/lib/kobako/codec/encoder.rb +7 -7
  20. data/lib/kobako/codec/error.rb +6 -6
  21. data/lib/kobako/codec/ext_types.rb +12 -72
  22. data/lib/kobako/codec/handle_walk.rb +6 -6
  23. data/lib/kobako/codec/state.rb +4 -56
  24. data/lib/kobako/codec/utils.rb +4 -4
  25. data/lib/kobako/codec.rb +11 -21
  26. data/lib/kobako/context.rb +23 -17
  27. data/lib/kobako/errors.rb +32 -11
  28. data/lib/kobako/outcome.rb +71 -128
  29. data/lib/kobako/payload/arguments.rb +59 -0
  30. data/lib/kobako/payload.rb +19 -0
  31. data/lib/kobako/sandbox.rb +12 -13
  32. data/lib/kobako/sandbox_options.rb +1 -1
  33. data/lib/kobako/snippet/binary.rb +3 -4
  34. data/lib/kobako/snippet/source.rb +5 -6
  35. data/lib/kobako/snippet.rb +2 -2
  36. data/lib/kobako/transport/call.rb +21 -0
  37. data/lib/kobako/transport/dispatcher.rb +86 -135
  38. data/lib/kobako/transport/error.rb +21 -5
  39. data/lib/kobako/transport/reflection.rb +82 -0
  40. data/lib/kobako/transport/run.rb +25 -33
  41. data/lib/kobako/transport/yielder.rb +27 -36
  42. data/lib/kobako/transport.rb +11 -8
  43. data/lib/kobako/usage.rb +1 -1
  44. data/lib/kobako/version.rb +1 -1
  45. data/release-please-config.json +47 -2
  46. data/sig/kobako/catalog/services.rbs +1 -1
  47. data/sig/kobako/catalog/snippets.rbs +4 -4
  48. data/sig/kobako/codec/error.rbs +4 -4
  49. data/sig/kobako/codec/ext_types.rbs +0 -7
  50. data/sig/kobako/codec/state.rbs +0 -4
  51. data/sig/kobako/codec.rbs +4 -5
  52. data/sig/kobako/context.rbs +4 -4
  53. data/sig/kobako/errors.rbs +15 -3
  54. data/sig/kobako/outcome.rbs +12 -13
  55. data/sig/kobako/payload/arguments.rbs +26 -0
  56. data/sig/kobako/payload.rbs +4 -0
  57. data/sig/kobako/pool.rbs +0 -2
  58. data/sig/kobako/runtime.rbs +15 -13
  59. data/sig/kobako/snippet/binary.rbs +1 -1
  60. data/sig/kobako/snippet/source.rbs +1 -1
  61. data/sig/kobako/transport/call.rbs +21 -0
  62. data/sig/kobako/transport/dispatcher.rbs +8 -10
  63. data/sig/kobako/transport/error.rbs +11 -0
  64. data/sig/kobako/transport/reflection.rbs +15 -0
  65. data/sig/kobako/transport/run.rbs +1 -1
  66. data/sig/kobako/transport/yielder.rbs +2 -2
  67. data/sig/kobako/transport.rbs +8 -2
  68. metadata +12 -12
  69. data/lib/kobako/fault.rb +0 -38
  70. data/lib/kobako/outcome/panic.rb +0 -42
  71. data/lib/kobako/transport/request.rb +0 -76
  72. data/lib/kobako/transport/response.rb +0 -83
  73. data/lib/kobako/transport/yield.rb +0 -94
  74. data/sig/kobako/fault.rbs +0 -19
  75. data/sig/kobako/outcome/panic.rbs +0 -34
  76. data/sig/kobako/transport/request.rbs +0 -29
  77. data/sig/kobako/transport/response.rbs +0 -33
  78. data/sig/kobako/transport/yield.rbs +0 -34
@@ -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
@@ -79,17 +79,18 @@ module Kobako
79
79
  def eval(code, &block)
80
80
  collect_overrides(&block) if block
81
81
  invoke!(:eval) do
82
- @runtime.eval(dispatch_handler, @services.encode, code.b, @snippets.encode)
82
+ @runtime.eval(dispatch_handler, @services.paths, code.b, @snippets.entries)
83
83
  end
84
84
  end
85
85
 
86
- # Dispatch a +Transport::Run+ envelope into a preloaded entrypoint and
87
- # return the decoded result. A given +block+ runs first, receiving this
88
- # Context to collect +ctx.bind+ overrides before the guest drives.
89
- def run(run_envelope, &block)
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
90
  collect_overrides(&block) if block
91
- invoke!(:run) do
92
- @runtime.run(dispatch_handler, @services.encode, @snippets.encode, run_envelope.encode(@handler))
91
+ invoke!(:run, entrypoint: request.entrypoint) do
92
+ @runtime.run(dispatch_handler, @services.paths, @snippets.entries,
93
+ request.entrypoint.to_s, request.payload(@handler))
93
94
  end
94
95
  end
95
96
 
@@ -116,8 +117,10 @@ module Kobako
116
117
  # a yielded block — which the +Dispatcher+ forwards to the
117
118
  # +Transport::Yielder+ it builds for the call.
118
119
  def dispatch_handler
119
- lambda do |request_bytes, guest_yielder|
120
- Transport::Dispatcher.dispatch(request_bytes, self, @handler, guest_yielder)
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)
121
124
  end
122
125
  end
123
126
 
@@ -163,12 +166,15 @@ module Kobako
163
166
  Execution.new(value: value, usage: @usage, stdout: @stdout_capture, stderr: @stderr_capture, failed: failed)
164
167
  end
165
168
 
166
- # Decode a completed run's outcome into its +Execution+. A Capability
167
- # Handle in the result is restored to its host object first. Decode sits in
168
- # the rescue so a wire-violation trap or a Panic envelope both attach this
169
- # run's Execution, just like a guest-call trap does.
170
- def settle_outcome(snapshot, verb)
171
- value, carried = Codec.track_handles { Outcome.decode(snapshot.outcome) }
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) }
172
178
  value = Codec::HandleWalk.deep_restore(value, @handler) if carried
173
179
  build_execution(value, failed: false)
174
180
  rescue Kobako::TrapError => e
@@ -186,7 +192,7 @@ module Kobako
186
192
  # so a trapped Snapshot's error carries them just like a completed run's
187
193
  # return value. A could-not-start fault ran no invocation at all, so it
188
194
  # carries no Execution and gains only the verb prefix.
189
- def invoke!(verb)
195
+ def invoke!(verb, entrypoint: nil)
190
196
  @resolved = @extensions.resolve
191
197
  begin
192
198
  snapshot = yield
@@ -194,7 +200,7 @@ module Kobako
194
200
  raise trap_class_for(e), "Sandbox##{verb} failed: #{e.message}"
195
201
  end
196
202
  populate_observability!(snapshot)
197
- return settle_outcome(snapshot, verb) unless snapshot.trapped?
203
+ return settle_outcome(snapshot, verb, entrypoint) unless snapshot.trapped?
198
204
 
199
205
  raise trap_error_for(snapshot, verb).with_execution(build_execution(nil, failed: true))
200
206
  end
data/lib/kobako/errors.rb CHANGED
@@ -36,8 +36,8 @@ module Kobako
36
36
 
37
37
  # Wasm engine layer. Raised when the Wasm execution engine crashed
38
38
  # (trap, OOM, unreachable) or when the wire layer detected a structural
39
- # violation that signals a corrupted guest execution environment
40
- # (zero-length OUTCOME_BUFFER, unknown outcome tag).
39
+ # violation that signals a corrupted guest execution environment (an
40
+ # outcome the core envelope cannot frame, an absent one included).
41
41
  #
42
42
  # Two named subclasses cover the configured per-invocation caps:
43
43
  #
@@ -85,26 +85,30 @@ module Kobako
85
85
  class ModuleNotBuiltError < SetupError; end
86
86
 
87
87
  # The structured attribution the two invocation-failure classes carry
88
- # from a decoded guest exception — its +origin+, original +klass+,
89
- # +backtrace_lines+, and +details+ — so a Host App can inspect a failure
90
- # beyond its message. Mixed into both rather than promoted to a shared
91
- # superclass because +SandboxError+ and +ServiceError+ sit in distinct
92
- # branches of the invocation-outcome taxonomy under +Kobako::Error+.
88
+ # from a decoded guest exception — its +origin+, original +klass+, and
89
+ # +backtrace_lines+ — so a Host App can inspect a failure beyond its
90
+ # message. Mixed into both rather than promoted to a shared superclass
91
+ # because +SandboxError+ and +ServiceError+ sit in distinct branches of
92
+ # the invocation-outcome taxonomy under +Kobako::Error+.
93
+ #
94
+ # Data specific to one kind of failure rides a named reader on the
95
+ # subclass that failure raises, the way Ruby pairs NameError#name with
96
+ # +NameError#local_variables+ — see UndefinedEntrypointError.
93
97
  module Diagnosable
94
- attr_reader :origin, :klass, :backtrace_lines, :details
98
+ attr_reader :origin, :klass, :backtrace_lines
95
99
 
96
- def initialize(message, origin: nil, klass: nil, backtrace_lines: nil, details: nil)
100
+ def initialize(message, origin: nil, klass: nil, backtrace_lines: nil)
97
101
  super(message)
98
102
  @origin = origin
99
103
  @klass = klass
100
104
  @backtrace_lines = backtrace_lines
101
- @details = details
102
105
  end
103
106
  end
104
107
 
105
108
  # Sandbox / wire layer. Raised when the guest ran to completion but
106
109
  # execution failed due to a mruby script error, a protocol fault, or a
107
- # host-side wire decode failure on an otherwise valid outcome tag.
110
+ # payload the host's codec could not decode out of a well-framed
111
+ # outcome.
108
112
  class SandboxError < Error
109
113
  include Diagnosable
110
114
  include CarriesExecution
@@ -135,6 +139,23 @@ module Kobako
135
139
  # can +rescue Kobako::BytecodeError+ directly.
136
140
  class BytecodeError < SandboxError; end
137
141
 
142
+ # UndefinedEntrypointError is the SandboxError subclass raised when a
143
+ # +#run+ target names no top-level constant in the guest. It carries the
144
+ # +#name+ that was asked for and the +#available+ names it could have
145
+ # been — the top-level constants the preloaded snippets contributed — so
146
+ # a caller corrects the name from the error rather than by reading the
147
+ # guest source. Ruby pairs NameError#name with
148
+ # +NameError#local_variables+ for the same reason.
149
+ class UndefinedEntrypointError < SandboxError
150
+ attr_reader :name, :available
151
+
152
+ def initialize(message, name: nil, available: [], **)
153
+ super(message, **)
154
+ @name = name
155
+ @available = available
156
+ end
157
+ end
158
+
138
159
  # Pool checkout layer. Raised by +Kobako::Pool#with+ when the checkout
139
160
  # wait exceeded the configured +checkout_timeout+ while every slot was
140
161
  # held. No Sandbox state is touched — retrying succeeds as soon as a holder
@@ -1,163 +1,106 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative "codec"
4
- require_relative "outcome/panic"
5
4
  require_relative "transport/error"
6
5
 
7
6
  module Kobako
8
- # Host-facing boundary for the OUTCOME_BUFFER produced by
9
- # +__kobako_eval+. Takes raw outcome bytes — a one-byte tag followed by
10
- # the msgpack-encoded body — and maps them to either the unwrapped
11
- # mruby return value or a raised three-layer exception.
7
+ # Host-facing boundary for the invocation outcome the native side split
8
+ # off the core envelope. Takes the arm it named plus the fields that arm
9
+ # carries, and settles the invocation the way a host does: return the
10
+ # value, or raise the exception the failure attributes to.
12
11
  #
13
- # Self-contained: this module owns the wire framing (tag bytes,
14
- # body decoding), and the +Panic+ wire record lives at
15
- # +Kobako::Outcome::Panic+. The byte-level msgpack codec at
16
- # +Kobako::Codec+ is invoked for the body itself; otherwise
17
- # nothing in +Transport+ participates.
12
+ # This is the two-step attribution decision. The wire framing belongs to
13
+ # the native side; the payload codec at +Kobako::Codec+ decodes only
14
+ # the one arm that carries a value.
18
15
  module Outcome
19
- # First byte of the OUTCOME_BUFFER for the success branch — body is
20
- # the bare msgpack encoding of the returned value
21
- # ({docs/wire-contract.md Outcome Envelope}[link:../../docs/wire-contract.md]).
22
- TYPE_VALUE = 0x01
23
- # First byte of the OUTCOME_BUFFER for the failure branch — body is
24
- # the msgpack Panic map.
25
- TYPE_PANIC = 0x02
16
+ # The two +origin+ values a Panic attributes with.
17
+ ORIGIN_SANDBOX = "sandbox"
18
+ ORIGIN_SERVICE = "service"
19
+
20
+ # The guest-written class names that select a +SandboxError+ subclass.
21
+ # A name absent here settles as plain +SandboxError+, so the guest
22
+ # widens the taxonomy only by naming a class the host already defines.
23
+ SUBCLASSES = {
24
+ "Kobako::BytecodeError" => BytecodeError,
25
+ "Kobako::UndefinedEntrypointError" => UndefinedEntrypointError
26
+ }.freeze
26
27
 
27
28
  module_function
28
29
 
29
- def decode(bytes)
30
- tag, body = split_tag(bytes)
31
- case tag
32
- when TYPE_VALUE
33
- decode_value(body)
34
- when TYPE_PANIC
35
- decode_panic(body)
36
- else
37
- raise build_trap_error(tag)
38
- end
39
- end
30
+ # Settle one invocation. +kind+ names the arm, +payload+ is the
31
+ # codec-encoded value the +:ok+ arm carries, and +panic+ carries
32
+ # the Panic's fields +[origin, class, message, backtrace, available]+ —
33
+ # present on the panic arm and absent on every other, which is what
34
+ # tells the failure that has a record to attribute from apart from the
35
+ # two that do not. +entrypoint+ is the name this invocation asked for,
36
+ # which the host knows and the wire therefore never carries.
37
+ def reify(kind, payload, panic, entrypoint: nil)
38
+ return decode_value(payload) if kind == :ok
40
39
 
41
- # TrapError for unknown or absent tag
42
- # ({docs/wire-codec.md ABI Signatures}[link:../../docs/wire-codec.md]:
43
- # zero-length output and unrecognised first byte both walk the trap
44
- # path). The absent-vs-present distinction selects the message;
45
- # the raw byte is not actionable to a caller and is not surfaced.
46
- def build_trap_error(tag)
47
- if tag.nil?
48
- TrapError.new("Sandbox exited without producing a result")
49
- else
50
- TrapError.new(
51
- "Sandbox produced an unrecognised result; the runtime is corrupted, " \
52
- "discard this Sandbox before another invocation"
53
- )
54
- end
40
+ raise panic ? panic_error(panic, entrypoint) : trap_error(kind)
55
41
  end
56
42
 
57
- def split_tag(bytes)
58
- bytes = bytes.b
59
- return [nil, "".b] if bytes.empty?
43
+ # Map a Panic's fields onto the three-layer taxonomy. The fields land
44
+ # on the exception verbatim — it carries the record rather than a
45
+ # translation of one.
46
+ def panic_error(panic, entrypoint)
47
+ origin, klass, message, backtrace, available = panic
48
+ selected = error_class(origin, klass)
49
+ attribution = { origin: origin, klass: klass, backtrace_lines: backtrace }
50
+ return selected.new(message, **attribution) unless selected == UndefinedEntrypointError
60
51
 
61
- tag = bytes.getbyte(0) # : Integer
62
- body = bytes.byteslice(1, bytes.bytesize - 1) # : String
63
- [tag, body]
52
+ UndefinedEntrypointError.new(message, name: entrypoint, available: available.map(&:to_sym), **attribution)
64
53
  end
65
54
 
66
- # Decode failure on the success tag is a SandboxError: the
67
- # framing was fine, but the carried value is unrepresentable. The
68
- # specific codec fault is stashed in +details+ rather
69
- # than spliced into the message — callers cannot act on the inner
70
- # "Symbol payload must be …" wording, but operators triaging a
71
- # corrupted Sandbox runtime still need it.
72
- def decode_value(body)
73
- # The Result envelope is a payload position: an ext 0x02 Fault in it
74
- # is a wire violation routed into the invalid-result rescue below.
75
- Kobako::Codec.forbid_faults { Kobako::Codec::Decoder.decode(body) }
76
- rescue Kobako::Codec::Error => e
77
- raise build_transport_error(
78
- "Sandbox produced an invalid result value",
79
- detail: e.message
80
- )
81
- end
55
+ # +origin == "service"+ selects ServiceError; a sandbox-origin failure
56
+ # naming one of the guest-written subclass names selects that subclass
57
+ # so callers can rescue that path specifically.
58
+ def error_class(origin, klass)
59
+ return ServiceError if origin == ORIGIN_SERVICE
82
60
 
83
- # Decode failure on the panic tag is a SandboxError. Either
84
- # path raises — on success the decoded Panic is mapped to its three-
85
- # layer exception via +build_panic_error+ and raised; on wire-decode
86
- # failure the rescue path raises the wire-violation +SandboxError+.
87
- def decode_panic(body)
88
- raise build_panic_error(build_panic_record(body))
89
- rescue Kobako::Codec::Error => e
90
- raise build_transport_error(
91
- "Sandbox produced an invalid panic record",
92
- detail: e.message
93
- )
61
+ SUBCLASSES.fetch(klass, SandboxError)
94
62
  end
95
63
 
96
- # Build a +Panic+ value object from the msgpack-decoded body. Raises
97
- # +Kobako::Codec::InvalidType+ when the body is not a map or when
98
- # required keys are missing — both routed by +decode_panic+ to
99
- # +build_transport_error+. The decode runs in block form so
100
- # +Panic.new+'s +ArgumentError+ invariants surface as +InvalidType+
101
- # through the decoder boundary; the message itself is never user-
102
- # facing — it lands in +details+ via the rescue chain above.
103
- def build_panic_record(body)
104
- # The Panic envelope is a payload position: an ext 0x02 Fault in its
105
- # +details+ is a wire violation routed into the invalid-panic rescue.
106
- Kobako::Codec.forbid_faults do
107
- Kobako::Codec::Decoder.decode(body) do |map|
108
- raise Kobako::Codec::InvalidType, "panic body must be a map, got #{map.class}" unless map.is_a?(Hash)
109
-
110
- Panic.new(
111
- origin: map["origin"], klass: map["class"], message: map["message"],
112
- backtrace: map["backtrace"] || [], details: map["details"]
113
- )
114
- end
115
- end
116
- end
64
+ # An arm the host cannot settle: the guest wrote nothing, or wrote
65
+ # bytes the envelope cannot frame. Either leaves nothing to attribute
66
+ # to, so both walk the trap path; only the absent-versus-present
67
+ # distinction selects the message.
68
+ def trap_error(kind)
69
+ return TrapError.new("Sandbox exited without producing a result") if kind == :absent
117
70
 
118
- # Map a decoded Panic record into the corresponding three-layer
119
- # Ruby exception. +origin == "service"+ → ServiceError; everything
120
- # else → SandboxError.
121
- def build_panic_error(panic)
122
- panic_target_class(panic).new(
123
- panic.message,
124
- origin: panic.origin,
125
- klass: panic.klass,
126
- backtrace_lines: panic.backtrace,
127
- details: panic.details
71
+ TrapError.new(
72
+ "Sandbox produced an unrecognised result; the runtime is corrupted, " \
73
+ "discard this Sandbox before another invocation"
128
74
  )
129
75
  end
130
76
 
131
- # Map the panic +class+ field to the matching Ruby exception subclass
132
- # so callers can rescue specific failure paths. +origin="service"+ →
133
- # +ServiceError+; +origin="sandbox"+ plus
134
- # +class="Kobako::BytecodeError"+ selects the +BytecodeError+
135
- # subclass. Everything else falls back to the base class for the
136
- # origin.
137
- def panic_target_class(panic)
138
- case panic.origin
139
- when Panic::ORIGIN_SERVICE
140
- ServiceError
141
- else
142
- panic.klass == "Kobako::BytecodeError" ? BytecodeError : SandboxError
143
- end
77
+ # The ok arm's value — the one position a payload codec still
78
+ # owns on this path. A decode fault means the framing was fine but the
79
+ # carried value is unrepresentable.
80
+ def decode_value(payload)
81
+ Kobako::Codec::Decoder.decode(payload)
82
+ rescue Kobako::Codec::Error => e
83
+ raise wire_error("Sandbox produced an invalid result value", diagnostic: e.message)
144
84
  end
145
85
 
146
- # Lift the wire-violation fallback to the real
86
+ # Lift a wire violation the host detected to the real
147
87
  # +Kobako::Transport::Error+ class so callers can +rescue+ it
148
88
  # specifically instead of pattern-matching on +error.klass+. The
149
- # +klass+ field is still populated so existing operator-side
150
- # tooling that greps on the string continues to work.
151
- # +detail+ carries the inner codec / framing message, stashed
152
- # directly into +details+ for operator diagnosis without polluting
153
- # the user-facing +#message+.
154
- def build_transport_error(message, detail: nil)
89
+ # +klass+ field is still populated so existing operator-side tooling
90
+ # that greps on the string continues to work.
91
+ def wire_error(message, diagnostic: nil)
155
92
  Kobako::Transport::Error.new(
156
93
  message,
157
- origin: Panic::ORIGIN_SANDBOX,
94
+ origin: ORIGIN_SANDBOX,
158
95
  klass: "Kobako::Transport::Error",
159
- details: detail
96
+ diagnostic: diagnostic
160
97
  )
161
98
  end
99
+
100
+ # +reify+ is the whole seam: one call settles one invocation, matching
101
+ # the single entry point the Rust frontend's twin exposes. Everything
102
+ # else here is how that decision is reached.
103
+ private_class_method :panic_error, :error_class, :trap_error, :decode_value, :wire_error
104
+ private_constant :ORIGIN_SANDBOX, :ORIGIN_SERVICE, :SUBCLASSES
162
105
  end
163
106
  end
@@ -0,0 +1,59 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../codec"
4
+
5
+ module Kobako
6
+ module Payload
7
+ # The invocation arguments a Call or a Run carries: a 2-element
8
+ # msgpack array, +args+ then +kwargs+. Both elements are always
9
+ # present, so field positions stay stable when either is empty.
10
+ #
11
+ # The positional-versus-keyword split lives here rather than in the
12
+ # core envelope because it is Ruby's call semantics, not the wire's.
13
+ # SPEC pins +kwargs+ keys to Symbols; the invariant is enforced at
14
+ # construction so the value object is the single source of truth.
15
+ #
16
+ # Built on the +class X < Data.define(...)+ subclass form so the class
17
+ # body is fully Steep-visible; see +.rubocop.yml+ for the
18
+ # rationale.
19
+ class Arguments < Data.define(:args, :kwargs)
20
+ def initialize(args: [], kwargs: {})
21
+ raise ArgumentError, "payload args must be Array" unless args.is_a?(Array)
22
+
23
+ validate_kwargs!(kwargs)
24
+ super
25
+ end
26
+
27
+ # Encode to the +[args, kwargs]+ msgpack bytes. The value object's
28
+ # own invariants are the contract; this does not re-check the shape.
29
+ def encode
30
+ Codec::Encoder.encode([args, kwargs])
31
+ end
32
+
33
+ # Decode +bytes+ into an Arguments. Raises +Codec::InvalidTypeError+ when
34
+ # the payload is not the expected 2-element msgpack array, or when the
35
+ # construction invariants reject the decoded fields.
36
+ def self.decode(bytes)
37
+ Codec::Decoder.decode(bytes) do |frame|
38
+ unless frame.is_a?(Array) && frame.length == 2
39
+ raise Codec::InvalidTypeError,
40
+ "an invocation payload is malformed (expected a 2-element array)"
41
+ end
42
+
43
+ args, kwargs = frame
44
+ new(args: args, kwargs: kwargs)
45
+ end
46
+ end
47
+
48
+ private
49
+
50
+ def validate_kwargs!(kwargs)
51
+ raise ArgumentError, "payload kwargs must be Hash" unless kwargs.is_a?(Hash)
52
+
53
+ kwargs.each_key do |key|
54
+ raise ArgumentError, "payload kwargs keys must be Symbol, got #{key.class}" unless key.is_a?(Symbol)
55
+ end
56
+ end
57
+ end
58
+ end
59
+ end
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "payload/arguments"
4
+
5
+ module Kobako
6
+ # The payload shapes that ride inside a core envelope's opaque payload
7
+ # field. The envelope routes a message and the native side decodes it;
8
+ # this layer decides what the resolved method receives, and the byte-level
9
+ # encoding of that shape belongs to +Kobako::Codec+ beneath it.
10
+ #
11
+ # Keeping the two apart is what lets an endpoint with its own schema
12
+ # replace this layer and keep the envelope, so nothing here may reach for
13
+ # a routing field.
14
+ #
15
+ # +Kobako::Payload::Arguments+ is the wire-symmetric peer of
16
+ # +kobako_codec::payload::Arguments+.
17
+ module Payload
18
+ end
19
+ end