kobako 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. checksums.yaml +4 -4
  2. data/.release-please-manifest.json +1 -0
  3. data/CHANGELOG.md +29 -0
  4. data/Cargo.lock +1 -1
  5. data/README.md +0 -1
  6. data/data/kobako.wasm +0 -0
  7. data/ext/kobako/Cargo.toml +1 -1
  8. data/ext/kobako/src/lib.rs +4 -2
  9. data/ext/kobako/src/{wasm → runtime}/cache.rs +12 -16
  10. data/ext/kobako/src/runtime/capture.rs +91 -0
  11. data/ext/kobako/src/runtime/config.rs +26 -0
  12. data/ext/kobako/src/runtime/dispatch.rs +211 -0
  13. data/ext/kobako/src/runtime/exports.rs +51 -0
  14. data/ext/kobako/src/runtime/guest_mem.rs +228 -0
  15. data/ext/kobako/src/{wasm/host_state.rs → runtime/invocation.rs} +94 -86
  16. data/ext/kobako/src/runtime/trap.rs +134 -0
  17. data/ext/kobako/src/runtime.rs +782 -0
  18. data/ext/kobako/src/snapshot.rs +110 -0
  19. data/lib/kobako/capture.rb +11 -16
  20. data/lib/kobako/catalog/handles.rb +107 -0
  21. data/lib/kobako/catalog/namespaces.rb +99 -0
  22. data/lib/kobako/{snippet/table.rb → catalog/snippets.rb} +37 -62
  23. data/lib/kobako/catalog.rb +18 -0
  24. data/lib/kobako/codec/decoder.rb +13 -5
  25. data/lib/kobako/codec/factory.rb +12 -12
  26. data/lib/kobako/codec/utils.rb +56 -59
  27. data/lib/kobako/codec.rb +6 -3
  28. data/lib/kobako/errors.rb +45 -28
  29. data/lib/kobako/fault.rb +40 -0
  30. data/lib/kobako/handle.rb +4 -6
  31. data/lib/kobako/namespace.rb +67 -0
  32. data/lib/kobako/outcome.rb +31 -35
  33. data/lib/kobako/runtime.rb +30 -0
  34. data/lib/kobako/sandbox.rb +83 -72
  35. data/lib/kobako/sandbox_options.rb +6 -9
  36. data/lib/kobako/snapshot.rb +40 -0
  37. data/lib/kobako/snippet/binary.rb +6 -7
  38. data/lib/kobako/snippet/source.rb +8 -8
  39. data/lib/kobako/snippet.rb +7 -9
  40. data/lib/kobako/transport/dispatcher.rb +195 -0
  41. data/lib/kobako/{rpc/wire_error.rb → transport/error.rb} +7 -6
  42. data/lib/kobako/transport/request.rb +78 -0
  43. data/lib/kobako/transport/response.rb +69 -0
  44. data/lib/kobako/transport/run.rb +141 -0
  45. data/lib/kobako/transport/yield.rb +91 -0
  46. data/lib/kobako/transport/yielder.rb +89 -0
  47. data/lib/kobako/transport.rb +24 -0
  48. data/lib/kobako/version.rb +1 -1
  49. data/lib/kobako.rb +4 -4
  50. data/release-please-config.json +24 -0
  51. data/sig/kobako/capture.rbs +0 -2
  52. data/sig/kobako/catalog/handles.rbs +19 -0
  53. data/sig/kobako/catalog/namespaces.rbs +17 -0
  54. data/sig/kobako/{snippet/table.rbs → catalog/snippets.rbs} +2 -11
  55. data/sig/kobako/{rpc.rbs → catalog.rbs} +1 -1
  56. data/sig/kobako/codec/decoder.rbs +2 -1
  57. data/sig/kobako/codec/factory.rbs +2 -2
  58. data/sig/kobako/codec/utils.rbs +5 -5
  59. data/sig/kobako/errors.rbs +7 -7
  60. data/sig/kobako/fault.rbs +19 -0
  61. data/sig/kobako/handle.rbs +2 -3
  62. data/sig/kobako/namespace.rbs +19 -0
  63. data/sig/kobako/outcome.rbs +2 -2
  64. data/sig/kobako/runtime.rbs +23 -0
  65. data/sig/kobako/sandbox.rbs +5 -8
  66. data/sig/kobako/snapshot.rbs +15 -0
  67. data/sig/kobako/transport/dispatcher.rbs +34 -0
  68. data/sig/kobako/transport/error.rbs +6 -0
  69. data/sig/kobako/transport/request.rbs +32 -0
  70. data/sig/kobako/transport/response.rbs +30 -0
  71. data/sig/kobako/transport/run.rbs +27 -0
  72. data/sig/kobako/transport/yield.rbs +34 -0
  73. data/sig/kobako/transport/yielder.rbs +21 -0
  74. data/sig/kobako/transport.rbs +4 -0
  75. metadata +48 -30
  76. data/ext/kobako/src/wasm/dispatch.rs +0 -162
  77. data/ext/kobako/src/wasm/instance.rs +0 -873
  78. data/ext/kobako/src/wasm.rs +0 -126
  79. data/lib/kobako/handle_table.rb +0 -119
  80. data/lib/kobako/invocation.rb +0 -143
  81. data/lib/kobako/rpc/dispatcher.rb +0 -171
  82. data/lib/kobako/rpc/envelope.rb +0 -118
  83. data/lib/kobako/rpc/fault.rb +0 -41
  84. data/lib/kobako/rpc/namespace.rb +0 -74
  85. data/lib/kobako/rpc/server.rb +0 -146
  86. data/lib/kobako/rpc.rb +0 -11
  87. data/lib/kobako/wasm.rb +0 -25
  88. data/sig/kobako/handle_table.rbs +0 -23
  89. data/sig/kobako/invocation.rbs +0 -25
  90. data/sig/kobako/rpc/dispatcher.rbs +0 -33
  91. data/sig/kobako/rpc/envelope.rbs +0 -51
  92. data/sig/kobako/rpc/fault.rbs +0 -20
  93. data/sig/kobako/rpc/namespace.rbs +0 -24
  94. data/sig/kobako/rpc/server.rbs +0 -31
  95. data/sig/kobako/rpc/wire_error.rbs +0 -6
  96. data/sig/kobako/wasm.rbs +0 -41
@@ -0,0 +1,110 @@
1
+ //! `Kobako::Snapshot` — per-invocation observable bundle.
2
+ //!
3
+ //! Every successful `Kobako::Runtime#eval` / `#run` returns one of these.
4
+ //! It carries every observable the host needs to surface after a guest
5
+ //! invocation: the OUTCOME_BUFFER bytes (`return_bytes`), the captured
6
+ //! stdout / stderr byte slices with their truncation flags (B-04), and
7
+ //! the wall-clock + memory-peak figures from `Kobako::Usage` (B-35).
8
+ //!
9
+ //! Ruby callers see the seven raw readers registered below; the helper
10
+ //! methods that pack them into `Kobako::Capture` / `Kobako::Usage`
11
+ //! (`Kobako::Snapshot#stdout` / `#stderr` / `#usage`) live in
12
+ //! `lib/kobako/snapshot.rb`. The split keeps the ext side a pure value
13
+ //! carrier and lets Ruby own the convenience surface.
14
+
15
+ use std::cell::Cell;
16
+ use std::time::Duration;
17
+
18
+ use magnus::{method, prelude::*, Error as MagnusError, RModule, RString, Ruby};
19
+
20
+ /// Per-invocation snapshot value. Magnus wraps it so a single ext call
21
+ /// from `Runtime::eval` / `Runtime::run` returns the whole bundle —
22
+ /// the Sandbox layer can decompose it without round-tripping into ext
23
+ /// again. All fields are private; the seven public methods registered
24
+ /// in `init` read them out one by one. The wall-clock duration is
25
+ /// held as a `Cell<Duration>` only because magnus' `#[magnus::wrap]`
26
+ /// macro requires interior mutability — every field is set once at
27
+ /// construction time and never mutated again.
28
+ #[magnus::wrap(class = "Kobako::Snapshot", free_immediately, size)]
29
+ pub(crate) struct Snapshot {
30
+ return_bytes: Vec<u8>,
31
+ stdout_bytes: Vec<u8>,
32
+ stdout_truncated: bool,
33
+ stderr_bytes: Vec<u8>,
34
+ stderr_truncated: bool,
35
+ wall_time: Cell<Duration>,
36
+ memory_peak: usize,
37
+ }
38
+
39
+ impl Snapshot {
40
+ /// Construct a fresh Snapshot from the per-invocation data the
41
+ /// Runtime has just collected. Called from
42
+ /// `crate::runtime::Runtime::build_snapshot` once the
43
+ /// guest export has returned, the OUTCOME_BUFFER has been drained,
44
+ /// and the capture pipes have been clipped to their caps.
45
+ pub(crate) fn new(
46
+ return_bytes: Vec<u8>,
47
+ stdout_bytes: Vec<u8>,
48
+ stdout_truncated: bool,
49
+ stderr_bytes: Vec<u8>,
50
+ stderr_truncated: bool,
51
+ wall_time: Duration,
52
+ memory_peak: usize,
53
+ ) -> Self {
54
+ Self {
55
+ return_bytes,
56
+ stdout_bytes,
57
+ stdout_truncated,
58
+ stderr_bytes,
59
+ stderr_truncated,
60
+ wall_time: Cell::new(wall_time),
61
+ memory_peak,
62
+ }
63
+ }
64
+
65
+ fn return_bytes(&self) -> RString {
66
+ let ruby = Ruby::get().expect("Ruby thread");
67
+ ruby.str_from_slice(&self.return_bytes)
68
+ }
69
+
70
+ fn stdout_bytes(&self) -> RString {
71
+ let ruby = Ruby::get().expect("Ruby thread");
72
+ ruby.str_from_slice(&self.stdout_bytes)
73
+ }
74
+
75
+ fn stdout_truncated(&self) -> bool {
76
+ self.stdout_truncated
77
+ }
78
+
79
+ fn stderr_bytes(&self) -> RString {
80
+ let ruby = Ruby::get().expect("Ruby thread");
81
+ ruby.str_from_slice(&self.stderr_bytes)
82
+ }
83
+
84
+ fn stderr_truncated(&self) -> bool {
85
+ self.stderr_truncated
86
+ }
87
+
88
+ fn wall_time(&self) -> f64 {
89
+ self.wall_time.get().as_secs_f64()
90
+ }
91
+
92
+ fn memory_peak(&self) -> usize {
93
+ self.memory_peak
94
+ }
95
+ }
96
+
97
+ /// Register `Kobako::Snapshot` plus its seven raw readers under the
98
+ /// `Kobako` module. Called from `crate::init` after `Kobako::Runtime`
99
+ /// is registered so the magnus wrap macro can resolve the class name.
100
+ pub(crate) fn init(ruby: &Ruby, kobako: RModule) -> Result<(), MagnusError> {
101
+ let snapshot = kobako.define_class("Snapshot", ruby.class_object())?;
102
+ snapshot.define_method("return_bytes", method!(Snapshot::return_bytes, 0))?;
103
+ snapshot.define_method("stdout_bytes", method!(Snapshot::stdout_bytes, 0))?;
104
+ snapshot.define_method("stdout_truncated", method!(Snapshot::stdout_truncated, 0))?;
105
+ snapshot.define_method("stderr_bytes", method!(Snapshot::stderr_bytes, 0))?;
106
+ snapshot.define_method("stderr_truncated", method!(Snapshot::stderr_truncated, 0))?;
107
+ snapshot.define_method("wall_time", method!(Snapshot::wall_time, 0))?;
108
+ snapshot.define_method("memory_peak", method!(Snapshot::memory_peak, 0))?;
109
+ Ok(())
110
+ }
@@ -8,18 +8,23 @@ module Kobako
8
8
  #
9
9
  # Immutable value object: the captured bytes and the truncation flag
10
10
  # always travel together and the instance is frozen on construction.
11
- # Construct via +Capture.from_ext+ for ext-provided binary bytes (handles
12
- # UTF-8 / ASCII-8BIT fallback) or reach +Capture::EMPTY+ for the pre-
13
- # invocation sentinel that +Sandbox+ uses before any invocation has
14
- # executed.
11
+ # Construct via +Capture.new(bytes:, truncated:)+ for the ext-provided
12
+ # binary bytes (the constructor handles the UTF-8 / ASCII-8BIT fallback)
13
+ # or reach +Capture::EMPTY+ for the pre-invocation sentinel that
14
+ # +Sandbox+ uses before any invocation has executed.
15
15
  class Capture
16
16
  attr_reader :bytes
17
17
 
18
18
  # Build a Capture wrapping +bytes+ (the captured prefix as a String) and
19
19
  # +truncated+ (whether the originating WASI pipe reported the cap was
20
- # hit). Freezes the instance so callers cannot mutate the pair.
20
+ # hit). Coerces +bytes+ to UTF-8 when they are valid UTF-8, otherwise
21
+ # falls back to ASCII-8BIT so invalid sequences remain inspectable
22
+ # without raising; +bytes+ is duplicated, never mutated. Freezes the
23
+ # instance so callers cannot mutate the pair.
21
24
  def initialize(bytes:, truncated:)
22
- @bytes = bytes
25
+ copy = bytes.dup.force_encoding(Encoding::UTF_8)
26
+ copy.force_encoding(Encoding::ASCII_8BIT) unless copy.valid_encoding?
27
+ @bytes = copy
23
28
  @truncated = truncated
24
29
  freeze
25
30
  end
@@ -29,16 +34,6 @@ module Kobako
29
34
  # ({docs/behavior.md B-04}[link:../../docs/behavior.md]).
30
35
  def truncated? = @truncated
31
36
 
32
- # Construct a Capture from ext-provided binary bytes. Coerces +bytes+
33
- # to UTF-8 when the bytes are valid UTF-8, otherwise falls back to
34
- # ASCII-8BIT so invalid sequences remain inspectable without raising.
35
- # +bytes+ is not mutated.
36
- def self.from_ext(bytes, truncated)
37
- copy = bytes.dup.force_encoding(Encoding::UTF_8)
38
- copy.force_encoding(Encoding::ASCII_8BIT) unless copy.valid_encoding?
39
- new(bytes: copy, truncated: truncated)
40
- end
41
-
42
37
  # Pre-invocation sentinel ({docs/behavior.md B-05}[link:../../docs/behavior.md]).
43
38
  # Empty UTF-8 bytes and +truncated? == false+; reused by every fresh
44
39
  # +Sandbox+ and by +Sandbox+ between invocations to denote "no capture
@@ -0,0 +1,107 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../handle"
4
+
5
+ module Kobako
6
+ module Catalog
7
+ # Host-side mapping from opaque integer Handle IDs to Ruby objects.
8
+ # The table is owned by +Kobako::Sandbox+
9
+ # ({docs/behavior.md B-19}[link:../../../docs/behavior.md]) and injected
10
+ # into the per-Sandbox +Kobako::Catalog::Namespaces+ so guest→host dispatch
11
+ # resolves Handle targets and arguments against the same table that
12
+ # host→guest wire encoding allocates into
13
+ # ({docs/behavior.md B-14, B-34}[link:../../../docs/behavior.md]).
14
+ #
15
+ # Lifecycle invariants ({docs/behavior.md}[link:../../../docs/behavior.md]):
16
+ #
17
+ # - {docs/behavior.md B-15}[link:../../../docs/behavior.md] — Handle IDs
18
+ # are allocated by a monotonically increasing counter scoped to a
19
+ # single invocation. The first ID issued in an invocation is 1; ID 0
20
+ # is reserved as the invalid sentinel and is never returned by
21
+ # +#alloc+.
22
+ #
23
+ # - {docs/behavior.md B-19}[link:../../../docs/behavior.md] — At every
24
+ # invocation boundary (via +#reset!+), every Handle issued under the
25
+ # old state becomes invalid. Reset applies uniformly regardless of
26
+ # allocation source (B-14 Service return or B-34 host-injected
27
+ # argument).
28
+ #
29
+ # - {docs/behavior.md B-21}[link:../../../docs/behavior.md] — The cap is
30
+ # +0x7fff_ffff+ (2³¹ − 1). Allocation beyond the cap raises
31
+ # immediately — no silent truncation, no wrap, no ID reuse.
32
+ class Handles
33
+ # Build a fresh, empty table. +next_id+ is an internal seam that
34
+ # sets the starting value of the monotonic counter (defaults to 1 per
35
+ # B-15); tests pass a value near +Kobako::Handle::MAX_ID+ to exercise
36
+ # the cap-exhaustion path without 2³¹ allocations.
37
+ def initialize(next_id: 1)
38
+ @entries = {} # : Hash[Integer, untyped]
39
+ @next_id = next_id
40
+ end
41
+
42
+ # Bind +object+ in the table and return a +Kobako::Handle+ token
43
+ # for it. +object+ is any host-side Ruby object to bind. Returns a
44
+ # freshly-allocated +Kobako::Handle+ whose +#id+ falls in
45
+ # +[Kobako::Handle::MIN_ID, Kobako::Handle::MAX_ID]+. Raises
46
+ # +Kobako::HandlerExhaustedError+ if the next ID would exceed the
47
+ # cap. The cap is anchored on +Kobako::Handle+ — the wire codec
48
+ # and the allocator share the same invariant
49
+ # ({docs/behavior.md B-21}[link:../../../docs/behavior.md]).
50
+ #
51
+ # Returning a Handle (rather than a bare Integer id) keeps the
52
+ # allocator's output a domain entity; +Kobako::Handle.restore+
53
+ # is reserved for the codec's wire-decode path, where the id is
54
+ # the only thing the bytes carry.
55
+ def alloc(object)
56
+ id = @next_id
57
+ cap = Kobako::Handle::MAX_ID
58
+ if id > cap
59
+ raise HandlerExhaustedError,
60
+ "Out of handle allocations: too many host objects were referenced " \
61
+ "in a single invocation (limit #{cap})"
62
+ end
63
+
64
+ @entries[id] = object
65
+ @next_id = id + 1
66
+ Kobako::Handle.restore(id)
67
+ end
68
+
69
+ # Resolve a Handle ID to its bound object. +id+ is a Handle ID previously
70
+ # returned by +#alloc+. Returns the bound object. Raises
71
+ # +Kobako::SandboxError+ if +id+ is not currently bound.
72
+ def fetch(id)
73
+ require_bound!(id)
74
+ @entries[id]
75
+ end
76
+
77
+ # Clear all entries AND reset the counter to 1. Called at the per-invocation
78
+ # boundary by +Kobako::Sandbox+ — see
79
+ # {docs/behavior.md B-19}[link:../../../docs/behavior.md]. Returns +self+.
80
+ def reset!
81
+ @entries.clear
82
+ @next_id = 1
83
+ self
84
+ end
85
+
86
+ # Number of currently-bound entries. Used by tests of the Dispatcher
87
+ # and Codec::Utils#deep_wrap to observe whether each path allocates
88
+ # exactly the Handle entries it should — the +Handles+ table itself never
89
+ # consults its own size, but the surrounding code's allocation
90
+ # contract is part of the observable boundary.
91
+ def size
92
+ @entries.size
93
+ end
94
+
95
+ private
96
+
97
+ # Single source of truth for the "unknown Handle id" raise used by
98
+ # {#fetch}. Returns +nil+ on success; raises +Kobako::SandboxError+
99
+ # when +id+ is not currently bound.
100
+ def require_bound!(id)
101
+ return if @entries.key?(id)
102
+
103
+ raise SandboxError, "unknown Handle id: #{id.inspect}"
104
+ end
105
+ end
106
+ end
107
+ end
@@ -0,0 +1,99 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "handles"
4
+ require_relative "../codec"
5
+ require_relative "../errors"
6
+ require_relative "../transport/request"
7
+ require_relative "../namespace"
8
+
9
+ module Kobako
10
+ module Catalog
11
+ # Kobako::Catalog::Namespaces — per-Sandbox registry of
12
+ # +Kobako::Namespace+ entities. Holds the Namespace / Member bindings
13
+ # and the preamble emitted on Frame 1
14
+ # ({docs/behavior.md B-07..B-11}[link:../../../docs/behavior.md]).
15
+ #
16
+ # Public API:
17
+ #
18
+ # namespaces = Kobako::Catalog::Namespaces.new
19
+ # namespace = namespaces.define(:MyService) # => Kobako::Namespace
20
+ # namespace.bind(:KV, kv_object) # => namespace (chainable)
21
+ # namespaces.encode # => msgpack bytes for Frame 1
22
+ # namespaces.lookup("MyService::KV") # => kv_object
23
+ #
24
+ # Namespaces live at +Kobako::Namespace+. Per-dispatch routing is
25
+ # +Kobako::Transport::Dispatcher+'s responsibility — the Dispatcher
26
+ # receives this registry and the +Catalog::Handles+ as arguments from
27
+ # the +Runtime#on_dispatch+ Proc that +Kobako::Sandbox#initialize+
28
+ # installs ({docs/behavior.md B-12}[link:../../../docs/behavior.md]).
29
+ # The registry holds an injected +Catalog::Handles+ reference so
30
+ # dispatch target resolution and host→guest auto-wrap share the same
31
+ # Sandbox-owned allocator (docs/behavior.md B-19).
32
+ class Namespaces
33
+ # Build a fresh registry. +handler+ is an internal seam that injects
34
+ # a pre-configured +Catalog::Handles+; tests pass one whose +next_id+
35
+ # is pinned near +MAX_ID+ to exercise the B-21 cap-exhaustion path
36
+ # without 2³¹ allocations. Production callers leave it at the default.
37
+ def initialize(handler: Catalog::Handles.new)
38
+ @namespaces = {} # : Hash[String, Kobako::Namespace]
39
+ @handler = handler
40
+ @sealed = false
41
+ end
42
+
43
+ # Declare or retrieve the Namespace named +name+ (idempotent — docs/behavior.md B-10).
44
+ # +name+ is a constant-form name as a +Symbol+ or +String+ (must satisfy
45
+ # +Namespace::NAME_PATTERN+). Returns the +Kobako::Namespace+ for that
46
+ # name, creating it if it does not exist. Raises +ArgumentError+ when
47
+ # +name+ is malformed, or when called after the owning Sandbox has been
48
+ # sealed by its first invocation
49
+ # ({docs/behavior.md B-07}[link:../../../docs/behavior.md]).
50
+ def define(name)
51
+ raise ArgumentError, "cannot define after first Sandbox invocation" if @sealed
52
+
53
+ name_str = name.to_s
54
+ unless Namespace::NAME_PATTERN.match?(name_str)
55
+ raise ArgumentError,
56
+ "Namespace name must match #{Namespace::NAME_PATTERN.inspect} (got #{name.inspect})"
57
+ end
58
+
59
+ @namespaces[name_str] ||= Namespace.new(name_str)
60
+ end
61
+
62
+ # Resolve a +target+ path of the form +"Namespace::Member"+ to the
63
+ # bound Host object. +target+ is a two-level path using the +::+
64
+ # separator. Returns the bound Host object. Raises +KeyError+ when the
65
+ # namespace or the member is not bound.
66
+ def lookup(target)
67
+ namespace_name, member_name = target.to_s.split("::", 2)
68
+ namespace = @namespaces[namespace_name]
69
+ raise KeyError, "no namespace named #{namespace_name.inspect}" if namespace.nil?
70
+ raise KeyError, "no member in target #{target.inspect}" unless member_name
71
+
72
+ namespace.fetch(member_name)
73
+ end
74
+
75
+ # Encode the preamble as msgpack bytes for stdin Frame 1 delivery
76
+ # ({docs/behavior.md B-02}[link:../../../docs/behavior.md]). Routes through
77
+ # {Kobako::Codec::Encoder} like every other host-side wire encode so
78
+ # there is a single codec path; the preamble carries only Strings and
79
+ # Arrays, so none of the kobako ext types actually fire. Structure:
80
+ # +[["Namespace", ["MemberA", "MemberB"]], ...]+. Returns a binary
81
+ # +String+ of msgpack bytes.
82
+ def encode
83
+ Codec::Encoder.encode(@namespaces.values.map(&:to_preamble))
84
+ end
85
+
86
+ # Mark the registry as sealed. Called by +Sandbox+ on the first
87
+ # invocation. After sealing, #define raises ArgumentError. Idempotent.
88
+ def seal!
89
+ @sealed = true
90
+ self
91
+ end
92
+
93
+ # Returns +true+ when {#seal!} has been called, +false+ otherwise.
94
+ def sealed?
95
+ @sealed
96
+ end
97
+ end
98
+ end
99
+ end
@@ -1,32 +1,30 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require "msgpack"
4
-
5
- require_relative "binary"
6
- require_relative "source"
3
+ require_relative "../codec"
4
+ require_relative "../snippet"
7
5
 
8
6
  module Kobako
9
- module Snippet
10
- # Kobako::Snippet::Table — per-Sandbox insertion-ordered registry of
11
- # preloaded snippets
7
+ module Catalog
8
+ # Kobako::Catalog::Snippets — per-Sandbox insertion-ordered registry
9
+ # of preloaded snippets
12
10
  # ({docs/behavior.md B-32 / B-33}[link:../../../docs/behavior.md]).
13
11
  #
14
12
  # Entries replay against the fresh +mrb_state+ before per-invocation
15
- # source / entrypoint resolution. Each +Source+ entry's +name+ is its
16
- # canonical identity — the filename baked into the loaded IREP's
17
- # +debug_info+ that surfaces in every backtrace frame originating
18
- # from the snippet as +(snippet:Name):line+. Duplicate names within
19
- # the +code:+ form would produce ambiguous attribution and are
20
- # rejected at registration time
13
+ # source / entrypoint resolution. Each +Snippet::Source+ entry's +name+
14
+ # is its canonical identity — the filename baked into the loaded IREP's
15
+ # +debug_info+ that surfaces in every backtrace frame originating from
16
+ # the snippet as +(snippet:Name):line+. Duplicate names within the
17
+ # +code:+ form would produce ambiguous attribution and are rejected at
18
+ # registration time
21
19
  # ({docs/behavior.md E-33}[link:../../../docs/behavior.md]).
22
- # +Binary+ entries carry no host-side name — their canonical name
23
- # lives in the bytecode's +debug_info+ and is read by the guest at
20
+ # +Snippet::Binary+ entries carry no host-side name — their canonical
21
+ # name lives in the bytecode's +debug_info+ and is read by the guest at
24
22
  # load time; the host does not extract it.
25
23
  #
26
- # Sealing (B-33) is governed by the owning Sandbox — the table itself
24
+ # Sealing (B-33) is governed by the owning Sandbox — the registry itself
27
25
  # is append-only and exposes no mutation API beyond +#register+; the
28
26
  # Sandbox guards +#register+ behind the seal check before delegating.
29
- class Table
27
+ class Snippets
30
28
  # Ruby constant-name pattern enforced on snippet names
31
29
  # ({docs/behavior.md E-34}[link:../../../docs/behavior.md]).
32
30
  NAME_PATTERN = /\A[A-Z]\w*\z/
@@ -37,14 +35,15 @@ module Kobako
37
35
 
38
36
  # Serialize the registered snippets to wire bytes. Each entry
39
37
  # contributes a msgpack map shape; the collection rides as a single
40
- # msgpack array. An empty table serializes to an empty array, never
38
+ # msgpack array. An empty registry serializes to an empty array, never
41
39
  # absent. The wire codec is an implementation detail — callers
42
- # receive a binary +String+ that the +Kobako::Wasm+ layer ships
43
- # through the invocation channel. Mirrors the
44
- # +Kobako::RPC.encode_request+ pattern: entry value objects stay
45
- # pure carriers, this method reads their attributes externally.
40
+ # receive a binary +String+ that the +Kobako::Runtime+ layer ships
41
+ # through the invocation channel. The entry value objects stay pure
42
+ # carriers this collection-tier method reads their attributes
43
+ # externally via +entry_payload+ rather than asking each entry to
44
+ # self-encode.
46
45
  def encode
47
- MessagePack.pack(@entries.map { |entry| entry_payload(entry) })
46
+ Codec::Encoder.encode(@entries.map { |entry| entry_payload(entry) })
48
47
  end
49
48
 
50
49
  # Register one preloaded snippet in either of two forms
@@ -78,43 +77,20 @@ module Kobako
78
77
  end
79
78
  end
80
79
 
81
- # Iterate over registered entries in insertion order. Yields each
82
- # entry (a +Kobako::Snippet::Source+ or +Kobako::Snippet::Binary+).
83
- # Returns an Enumerator when no block is given.
84
- def each(&)
85
- @entries.each(&)
86
- end
87
-
88
- # Canonical names of every registered +Source+ entry, in insertion
89
- # order. +Binary+ entries are skipped — their names live in
90
- # bytecode +debug_info+ on the guest side and are not extracted by
91
- # the host.
92
- def names
93
- @entries.filter_map { |entry| entry.name if entry.is_a?(Source) }
94
- end
95
-
96
- # Number of registered snippets.
97
- def size
98
- @entries.size
99
- end
100
-
101
- # Whether no snippets are registered.
102
- def empty?
103
- @entries.empty?
104
- end
105
-
106
80
  private
107
81
 
108
82
  # Source-form register path. Delegates argument-shape checks to
109
- # +ensure_source_args!+ (which returns the narrowed
110
- # +[code, name]+ pair), normalises +name+ to a Symbol, rejects
111
- # duplicates (E-33), and appends the Source entry.
83
+ # +ensure_source_args!+ (which returns the narrowed +[code, name]+
84
+ # pair), normalises +name+ to a Symbol, rejects duplicates (E-33),
85
+ # and appends the Source entry.
112
86
  def register_source!(code, name)
113
87
  code, name = ensure_source_args!(code, name)
114
88
  name_sym = normalize_name(name)
115
- raise ArgumentError, "snippet #{name_sym.inspect} already preloaded" if names.include?(name_sym)
89
+ if @entries.any? { |e| e.is_a?(Snippet::Source) && e.name == name_sym }
90
+ raise ArgumentError, "snippet #{name_sym.inspect} already preloaded"
91
+ end
116
92
 
117
- @entries << Source.new(name: name_sym, body: code.dup.force_encoding(Encoding::UTF_8))
93
+ @entries << Snippet::Source.new(name: name_sym, body: code.dup.force_encoding(Encoding::UTF_8))
118
94
  name_sym
119
95
  end
120
96
 
@@ -131,14 +107,13 @@ module Kobako
131
107
  [code, name]
132
108
  end
133
109
 
134
- # Binary-form register path. Validates the +binary:+ payload
135
- # type and appends the Binary entry. The bytes are duplicated and
136
- # forced to ASCII-8BIT so msgpack-ruby picks the +bin+ family on
137
- # the wire.
110
+ # Binary-form register path. Validates the +binary:+ payload type
111
+ # and appends the Binary entry. The bytes are duplicated and forced
112
+ # to ASCII-8BIT so msgpack-ruby picks the +bin+ family on the wire.
138
113
  def register_binary!(bytes)
139
114
  raise ArgumentError, "binary must be a String, got #{bytes.class}" unless bytes.is_a?(String)
140
115
 
141
- @entries << Binary.new(body: bytes.dup.force_encoding(Encoding::ASCII_8BIT))
116
+ @entries << Snippet::Binary.new(body: bytes.dup.force_encoding(Encoding::ASCII_8BIT))
142
117
  nil
143
118
  end
144
119
 
@@ -149,10 +124,10 @@ module Kobako
149
124
  # ({docs/wire-codec.md Invocation channels}[link:../../../docs/wire-codec.md]).
150
125
  def entry_payload(entry)
151
126
  case entry
152
- when Source
153
- { "name" => entry.name.to_s, "kind" => Source::KIND, "body" => entry.body }
154
- when Binary
155
- { "kind" => Binary::KIND, "body" => entry.body }
127
+ when Snippet::Source
128
+ { "name" => entry.name.to_s, "kind" => Snippet::Source::KIND, "body" => entry.body }
129
+ when Snippet::Binary
130
+ { "kind" => Snippet::Binary::KIND, "body" => entry.body }
156
131
  end
157
132
  end
158
133
 
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "catalog/handles"
4
+ require_relative "catalog/namespaces"
5
+ require_relative "catalog/snippets"
6
+
7
+ module Kobako
8
+ # Kobako::Catalog — Sandbox-level configuration and per-invocation
9
+ # allocation tables. Houses the three host-side registries the Sandbox
10
+ # owns: +Catalog::Namespaces+ (Namespace / Member registry),
11
+ # +Catalog::Snippets+ (preloaded source / bytecode entries), and
12
+ # +Catalog::Handles+ (per-invocation Handle ID allocator).
13
+ #
14
+ # See {SPEC.md Refinement → Internal Concepts}[link:../../SPEC.md] for
15
+ # how Catalog fits alongside Transport and Runtime.
16
+ module Catalog
17
+ end
18
+ end
@@ -23,13 +23,21 @@ module Kobako
23
23
  # Decode +bytes+ into one Ruby value and validate transitively
24
24
  # against the SPEC type mapping. Raises {Truncated}, {InvalidType},
25
25
  # or {InvalidEncoding} on wire violations.
26
+ #
27
+ # When a block is given, the decoded value is yielded and the block's
28
+ # result is returned — wire Value Objects use this to build themselves
29
+ # from the decoded payload. The block runs inside this method's
30
+ # rescue, so a Value Object's +ArgumentError+ invariant failure
31
+ # surfaces as {InvalidType} without a separate {Utils.with_boundary}
32
+ # wrapper at the call site.
26
33
  def self.decode(bytes)
27
34
  value = Factory.load(bytes.b)
28
35
  validate_utf8!(value)
29
- value
30
- # msgpack gem raises these for type/format violations; +ArgumentError+
31
- # also comes from our ext-type validators (Handle id range, Exception
32
- # type whitelist).
36
+ block_given? ? yield(value) : value
37
+ # msgpack gem raises the format/type errors below; +ArgumentError+
38
+ # comes from our ext-type validators (Handle id range, Exception type
39
+ # whitelist) and from a yielded block's Value Object invariants — both
40
+ # are wire violations, so both map to {InvalidType}.
33
41
  rescue ::MessagePack::UnknownExtTypeError, ::MessagePack::MalformedFormatError,
34
42
  ::MessagePack::StackError, ::ArgumentError => e
35
43
  raise InvalidType, e.message
@@ -45,7 +53,7 @@ module Kobako
45
53
  # Encoding Rules). The msgpack gem returns UTF-8-tagged Strings for
46
54
  # str family but does not validate the bytes; +bin+ family decodes
47
55
  # to ASCII-8BIT. Walk the tree once and reject invalid UTF-8 in any
48
- # str-typed leaf via {Utils.assert_utf8!}. {Kobako::RPC::Fault}
56
+ # str-typed leaf via {Utils.assert_utf8!}. {Kobako::Fault}
49
57
  # payloads are validated transitively: +Factory.unpack_fault+
50
58
  # feeds the inner ext-0x02 bytes back through this Decoder, so their
51
59
  # +str+ fields are already covered by the time control returns here.
@@ -7,7 +7,7 @@ require "msgpack"
7
7
  require_relative "error"
8
8
  require_relative "utils"
9
9
  require_relative "../handle"
10
- require_relative "../rpc/fault"
10
+ require_relative "../fault"
11
11
 
12
12
  module Kobako
13
13
  module Codec
@@ -108,16 +108,16 @@ module Kobako
108
108
 
109
109
  def register_fault
110
110
  @factory.register_type(
111
- EXT_ERRENV, RPC::Fault,
111
+ EXT_ERRENV, Kobako::Fault,
112
112
  packer: ->(fault) { pack_fault(fault) },
113
113
  unpacker: ->(payload) { unpack_fault(payload) }
114
114
  )
115
115
  end
116
116
 
117
117
  # Peel off the fixext-4 frame, hand the bytes to the
118
- # Host-Gem-internal +Kobako::Handle.from_wire+ factory, and
118
+ # Host-Gem-internal +Kobako::Handle.restore+ factory, and
119
119
  # translate the +ArgumentError+ raised by Handle's invariants
120
- # into a wire-layer +InvalidType+ via {Codec::Utils.wire_boundary}.
120
+ # into a wire-layer +InvalidType+ via {Codec::Utils.with_boundary}.
121
121
  # The Value Object owns the id-range contract; this method only
122
122
  # owns the frame shape.
123
123
  def unpack_handle(payload)
@@ -125,7 +125,7 @@ module Kobako
125
125
  raise InvalidType, "Handle payload must be 4 bytes, got #{bytes.bytesize}" unless bytes.bytesize == 4
126
126
 
127
127
  id = bytes.unpack1("N") # : Integer
128
- Codec::Utils.wire_boundary { Kobako::Handle.from_wire(id) }
128
+ Codec::Utils.with_boundary { Kobako::Handle.restore(id) }
129
129
  end
130
130
 
131
131
  # Encode the inner ext-0x02 map via {Encoder} (not +factory.dump+) so
@@ -136,9 +136,10 @@ module Kobako
136
136
  Encoder.encode("type" => fault.type, "message" => fault.message, "details" => fault.details)
137
137
  end
138
138
 
139
- # Peel the embedded msgpack map and hand it to +RPC::Fault.new+;
140
- # translate the value-object's +ArgumentError+ into +InvalidType+
141
- # at the wire boundary. Inner decode goes through {Decoder} (not
139
+ # Peel the embedded msgpack map and hand it to +Kobako::Fault.new+
140
+ # inside {Decoder.decode}'s block form, so the value-object's
141
+ # +ArgumentError+ invariants surface as +InvalidType+ through the
142
+ # decoder boundary. Inner decode goes through {Decoder} (not
142
143
  # +factory.load+) so the embedded +str+ payloads flow through the
143
144
  # same UTF-8 validation as a top-level decode.
144
145
  #
@@ -150,11 +151,10 @@ module Kobako
150
151
  # +factory.load+ to "simplify": that path bypasses UTF-8 validation
151
152
  # and re-opens the Decoder's special case for Fault (removed in M5).
152
153
  def unpack_fault(payload)
153
- map = Decoder.decode(payload)
154
- raise InvalidType, "Fault payload must be a map" unless map.is_a?(Hash)
154
+ Decoder.decode(payload) do |map|
155
+ raise InvalidType, "Fault payload must be a map" unless map.is_a?(Hash)
155
156
 
156
- Codec::Utils.wire_boundary do
157
- RPC::Fault.new(type: map["type"], message: map["message"], details: map["details"])
157
+ Kobako::Fault.new(type: map["type"], message: map["message"], details: map["details"])
158
158
  end
159
159
  end
160
160
  end