kobako 0.30.0 → 0.32.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 (288) hide show
  1. checksums.yaml +4 -4
  2. data/.githooks/linux-tests.sh +29 -0
  3. data/.release-please-manifest.json +1 -1
  4. data/CHANGELOG.md +460 -0
  5. data/Cargo.lock +868 -447
  6. data/README.md +43 -4
  7. data/ROADMAP.md +1 -2
  8. data/crates/kobako-runtime/CHANGELOG.md +309 -0
  9. data/crates/kobako-runtime/Cargo.toml +58 -11
  10. data/crates/kobako-runtime/README.md +7 -4
  11. data/crates/kobako-runtime/src/cred.rs +136 -0
  12. data/crates/kobako-runtime/src/dispatch.rs +4 -5
  13. data/crates/kobako-runtime/src/endpoint/buffer.rs +153 -44
  14. data/crates/kobako-runtime/src/endpoint/dispatch.rs +80 -41
  15. data/crates/kobako-runtime/src/endpoint/invoke.rs +23 -36
  16. data/crates/kobako-runtime/src/endpoint.rs +137 -36
  17. data/crates/kobako-runtime/src/errno.rs +391 -0
  18. data/crates/kobako-runtime/src/error.rs +31 -10
  19. data/crates/kobako-runtime/src/filesystem/anon_inodes.rs +52 -0
  20. data/crates/kobako-runtime/src/filesystem/bind/fid.rs +300 -22
  21. data/crates/kobako-runtime/src/filesystem/bind/lookup.rs +101 -29
  22. data/crates/kobako-runtime/src/filesystem/bind/unicode.rs +109 -0
  23. data/crates/kobako-runtime/src/filesystem/bind/walk.rs +52 -34
  24. data/crates/kobako-runtime/src/filesystem/bind.rs +812 -447
  25. data/crates/kobako-runtime/src/filesystem/overlay/file.rs +6 -6
  26. data/crates/kobako-runtime/src/filesystem/overlay/path.rs +43 -65
  27. data/crates/kobako-runtime/src/filesystem/overlay/stack/copy_up.rs +11 -16
  28. data/crates/kobako-runtime/src/filesystem/overlay/stack/dir.rs +47 -72
  29. data/crates/kobako-runtime/src/filesystem/overlay/stack/namei.rs +12 -12
  30. data/crates/kobako-runtime/src/filesystem/overlay/stack/readdir.rs +4 -7
  31. data/crates/kobako-runtime/src/filesystem/overlay/stack.rs +120 -37
  32. data/crates/kobako-runtime/src/filesystem/overlay.rs +578 -388
  33. data/crates/kobako-runtime/src/filesystem/pipe.rs +12 -9
  34. data/crates/kobako-runtime/src/filesystem/rdir.rs +14 -50
  35. data/crates/kobako-runtime/src/filesystem/testing.rs +31 -0
  36. data/crates/kobako-runtime/src/filesystem/tmpfs/seed.rs +32 -0
  37. data/crates/kobako-runtime/src/filesystem/tmpfs/tmpfile.rs +3 -3
  38. data/crates/kobako-runtime/src/filesystem/tmpfs/whiteout.rs +57 -35
  39. data/crates/kobako-runtime/src/filesystem/tmpfs/xattr.rs +2 -2
  40. data/crates/kobako-runtime/src/filesystem/tmpfs.rs +219 -173
  41. data/crates/kobako-runtime/src/filesystem/wrap.rs +36 -52
  42. data/crates/kobako-runtime/src/filesystem.rs +8 -3
  43. data/crates/kobako-runtime/src/fork.rs +319 -0
  44. data/crates/kobako-runtime/src/grant.rs +3 -0
  45. data/crates/kobako-runtime/src/hashtable.rs +4 -2
  46. data/crates/kobako-runtime/src/lib.rs +18 -7
  47. data/crates/kobako-runtime/src/limits.rs +171 -0
  48. data/crates/kobako-runtime/src/locking/seqlock.rs +29 -3
  49. data/crates/kobako-runtime/src/locking.rs +518 -113
  50. data/crates/kobako-runtime/src/memcg.rs +306 -0
  51. data/crates/kobako-runtime/src/mount.rs +37 -9
  52. data/crates/kobako-runtime/src/net/backends.rs +43 -0
  53. data/crates/kobako-runtime/src/net/connections.rs +219 -0
  54. data/crates/kobako-runtime/src/net/credential.rs +125 -0
  55. data/crates/kobako-runtime/src/net/egress.rs +180 -0
  56. data/crates/kobako-runtime/src/net/family.rs +181 -0
  57. data/crates/kobako-runtime/src/net/http.rs +3165 -0
  58. data/crates/kobako-runtime/src/net/lookup.rs +385 -0
  59. data/crates/kobako-runtime/src/net/mock.rs +251 -0
  60. data/crates/kobako-runtime/src/net/namespace.rs +1368 -0
  61. data/crates/kobako-runtime/src/net/reactor.rs +626 -0
  62. data/crates/kobako-runtime/src/net/resolv/darwin.rs +280 -0
  63. data/crates/kobako-runtime/src/net/resolv/stub/tests.rs +519 -0
  64. data/crates/kobako-runtime/src/net/resolv/stub.rs +542 -0
  65. data/crates/kobako-runtime/src/net/resolv/windows.rs +218 -0
  66. data/crates/kobako-runtime/src/net/resolv.rs +251 -0
  67. data/crates/kobako-runtime/src/net/skbuff.rs +109 -0
  68. data/crates/kobako-runtime/src/net/socket.rs +869 -0
  69. data/crates/kobako-runtime/src/net/task.rs +223 -0
  70. data/crates/kobako-runtime/src/net/tcp.rs +1840 -0
  71. data/crates/kobako-runtime/src/net/tls.rs +120 -0
  72. data/crates/kobako-runtime/src/net/transport.rs +304 -0
  73. data/crates/kobako-runtime/src/net/udp.rs +1105 -0
  74. data/crates/kobako-runtime/src/net.rs +45 -0
  75. data/crates/kobako-runtime/src/network/builder.rs +177 -0
  76. data/crates/kobako-runtime/src/network/ruleset.rs +777 -0
  77. data/crates/kobako-runtime/src/network.rs +551 -0
  78. data/crates/kobako-runtime/src/policy.rs +16 -0
  79. data/crates/kobako-runtime/src/profile.rs +29 -144
  80. data/crates/kobako-runtime/src/runtime.rs +3 -5
  81. data/crates/kobako-runtime/src/sched.rs +338 -51
  82. data/crates/kobako-runtime/src/security/entry_policy.rs +22 -0
  83. data/crates/kobako-runtime/src/{vfs/cred.rs → security/hooks.rs} +52 -144
  84. data/crates/kobako-runtime/src/security/mount_policy.rs +158 -0
  85. data/crates/kobako-runtime/src/security.rs +125 -209
  86. data/crates/kobako-runtime/src/snapshot.rs +121 -2
  87. data/crates/kobako-runtime/src/vfs/attr.rs +5 -5
  88. data/crates/kobako-runtime/src/vfs/dentry.rs +210 -117
  89. data/crates/kobako-runtime/src/vfs/file.rs +243 -248
  90. data/crates/kobako-runtime/src/vfs/inode.rs +41 -45
  91. data/crates/kobako-runtime/src/vfs/kern_path.rs +62 -53
  92. data/crates/kobako-runtime/src/vfs/mount.rs +10 -9
  93. data/crates/kobako-runtime/src/vfs/namei.rs +1162 -818
  94. data/crates/kobako-runtime/src/vfs/namespace.rs +245 -0
  95. data/crates/kobako-runtime/src/vfs/open_files.rs +69 -0
  96. data/crates/kobako-runtime/src/vfs/openat2.rs +3 -3
  97. data/crates/kobako-runtime/src/vfs/path.rs +6 -6
  98. data/crates/kobako-runtime/src/vfs/readdir.rs +6 -6
  99. data/crates/kobako-runtime/src/vfs/stat.rs +248 -23
  100. data/crates/kobako-runtime/src/vfs/super_block.rs +18 -14
  101. data/crates/kobako-runtime/src/vfs/utimes.rs +37 -27
  102. data/crates/kobako-runtime/src/vfs.rs +10 -6
  103. data/crates/kobako-runtime/src/wait.rs +381 -0
  104. data/crates/kobako-transport/CHANGELOG.md +38 -0
  105. data/crates/kobako-transport/Cargo.toml +1 -1
  106. data/crates/kobako-transport/README.md +3 -4
  107. data/crates/kobako-transport/src/abi.rs +78 -72
  108. data/crates/kobako-transport/src/envelope/bytes.rs +17 -6
  109. data/crates/kobako-transport/src/envelope/call.rs +32 -4
  110. data/crates/kobako-transport/src/envelope/error_record.rs +21 -0
  111. data/crates/kobako-transport/src/envelope/name.rs +99 -0
  112. data/crates/kobako-transport/src/envelope/outcome.rs +9 -9
  113. data/crates/kobako-transport/src/envelope/preamble.rs +24 -21
  114. data/crates/kobako-transport/src/envelope/reply.rs +27 -27
  115. data/crates/kobako-transport/src/envelope/unsupported.rs +10 -10
  116. data/crates/kobako-transport/src/envelope.rs +13 -8
  117. data/crates/kobako-wasmtime/CHANGELOG.md +208 -0
  118. data/crates/kobako-wasmtime/Cargo.toml +47 -7
  119. data/crates/kobako-wasmtime/README.md +4 -3
  120. data/crates/kobako-wasmtime/build/preview2.rs +1339 -0
  121. data/crates/kobako-wasmtime/build.rs +16 -0
  122. data/crates/kobako-wasmtime/src/abi.rs +18 -37
  123. data/crates/kobako-wasmtime/src/ambient.rs +43 -19
  124. data/crates/kobako-wasmtime/src/cache/unix.rs +95 -0
  125. data/crates/kobako-wasmtime/src/cache/windows.rs +359 -0
  126. data/crates/kobako-wasmtime/src/cache.rs +106 -113
  127. data/crates/kobako-wasmtime/src/config.rs +52 -68
  128. data/crates/kobako-wasmtime/src/driver.rs +80 -82
  129. data/crates/kobako-wasmtime/src/exports.rs +143 -17
  130. data/crates/kobako-wasmtime/src/guest.rs +12 -6
  131. data/crates/kobako-wasmtime/src/guest_binary.rs +14 -0
  132. data/crates/kobako-wasmtime/src/imports.rs +42 -18
  133. data/crates/kobako-wasmtime/src/instance_pre.rs +4 -4
  134. data/crates/kobako-wasmtime/src/invocation.rs +91 -15
  135. data/crates/kobako-wasmtime/src/lib.rs +7 -3
  136. data/crates/kobako-wasmtime/src/limiter.rs +130 -12
  137. data/crates/kobako-wasmtime/src/preview1/descriptors.rs +305 -0
  138. data/crates/kobako-wasmtime/src/preview1/differential/mount.rs +9 -20
  139. data/crates/kobako-wasmtime/src/preview1/differential.rs +27 -31
  140. data/crates/kobako-wasmtime/src/preview1/errno.rs +55 -66
  141. data/crates/kobako-wasmtime/src/preview1/fd.rs +347 -312
  142. data/crates/kobako-wasmtime/src/preview1/memory.rs +21 -12
  143. data/crates/kobako-wasmtime/src/preview1/mount_view/wrap.rs +34 -53
  144. data/crates/kobako-wasmtime/src/preview1/mount_view.rs +335 -388
  145. data/crates/kobako-wasmtime/src/preview1/path.rs +56 -121
  146. data/crates/kobako-wasmtime/src/preview1/poll.rs +255 -125
  147. data/crates/kobako-wasmtime/src/preview1/random.rs +125 -0
  148. data/crates/kobako-wasmtime/src/preview1/sock.rs +10 -8
  149. data/crates/kobako-wasmtime/src/preview1/testing.rs +31 -0
  150. data/crates/kobako-wasmtime/src/preview1/testsuite.rs +5 -15
  151. data/crates/kobako-wasmtime/src/preview1.rs +131 -51
  152. data/crates/kobako-wasmtime/src/preview2/abi.rs +227 -0
  153. data/crates/kobako-wasmtime/src/preview2/error.rs +118 -0
  154. data/crates/kobako-wasmtime/src/preview2/filesystem.rs +122 -0
  155. data/crates/kobako-wasmtime/src/preview2/host.rs +4319 -0
  156. data/crates/kobako-wasmtime/src/preview2/http.rs +1587 -0
  157. data/crates/kobako-wasmtime/src/preview2/io.rs +328 -0
  158. data/crates/kobako-wasmtime/src/preview2/sockets.rs +379 -0
  159. data/crates/kobako-wasmtime/src/preview2/table.rs +257 -0
  160. data/crates/kobako-wasmtime/src/preview2.rs +57 -0
  161. data/crates/kobako-wasmtime/src/trap.rs +88 -28
  162. data/crates/kobako-wasmtime/src/waits.rs +59 -0
  163. data/crates/kobako-wasmtime/src/wasi.rs +291 -81
  164. data/crates/kobako-wasmtime/wit/deps/cli.wit +233 -0
  165. data/crates/kobako-wasmtime/wit/deps/clocks.wit +162 -0
  166. data/crates/kobako-wasmtime/wit/deps/filesystem.wit +589 -0
  167. data/crates/kobako-wasmtime/wit/deps/http.wit +733 -0
  168. data/crates/kobako-wasmtime/wit/deps/io.wit +299 -0
  169. data/crates/kobako-wasmtime/wit/deps/random.wit +92 -0
  170. data/crates/kobako-wasmtime/wit/deps/sockets.wit +949 -0
  171. data/crates/kobako-wasmtime/witx/wasi_snapshot_preview1.witx +13 -0
  172. data/data/kobako.wasm +0 -0
  173. data/ext/kobako/Cargo.toml +6 -2
  174. data/ext/kobako/src/{runtime/errors.rs → errors.rs} +34 -26
  175. data/ext/kobako/src/escape.rs +404 -0
  176. data/ext/kobako/src/{runtime/filesystem → filesystem}/grants.rs +34 -32
  177. data/ext/kobako/src/{runtime/filesystem → filesystem}/ruby.rs +158 -170
  178. data/ext/kobako/src/{runtime/filesystem.rs → filesystem.rs} +71 -23
  179. data/ext/kobako/src/fork.rs +72 -0
  180. data/ext/kobako/src/gvl.rs +729 -0
  181. data/ext/kobako/src/handoff.rs +490 -0
  182. data/ext/kobako/src/lib.rs +74 -3
  183. data/ext/kobako/src/network/mock.rs +187 -0
  184. data/ext/kobako/src/network.rs +593 -0
  185. data/ext/kobako/src/pinned_value.rs +44 -0
  186. data/ext/kobako/src/runtime/bridge.rs +58 -50
  187. data/ext/kobako/src/runtime/snapshot.rs +4 -4
  188. data/ext/kobako/src/runtime.rs +272 -163
  189. data/ext/kobako/src/wire.rs +42 -0
  190. data/lib/kobako/catalog/extensions.rb +14 -2
  191. data/lib/kobako/catalog/flags.rb +3 -5
  192. data/lib/kobako/catalog/grants.rb +5 -4
  193. data/lib/kobako/catalog/handles.rb +14 -32
  194. data/lib/kobako/catalog/mount.rb +11 -3
  195. data/lib/kobako/catalog/network.rb +35 -0
  196. data/lib/kobako/catalog/replacements.rb +28 -0
  197. data/lib/kobako/catalog/services.rb +5 -19
  198. data/lib/kobako/catalog/snippets.rb +3 -18
  199. data/lib/kobako/catalog.rb +3 -0
  200. data/lib/kobako/codec/{utils.rb → boundary.rb} +4 -2
  201. data/lib/kobako/codec/decoder.rb +5 -5
  202. data/lib/kobako/codec/ext_types.rb +3 -3
  203. data/lib/kobako/codec/handle_walk.rb +3 -43
  204. data/lib/kobako/codec/state.rb +2 -18
  205. data/lib/kobako/codec/value_budget.rb +133 -41
  206. data/lib/kobako/codec.rb +6 -7
  207. data/lib/kobako/context.rb +24 -11
  208. data/lib/kobako/errors.rb +18 -18
  209. data/lib/kobako/extension.rb +3 -2
  210. data/lib/kobako/filesystem.rb +10 -3
  211. data/lib/kobako/fork.rb +42 -0
  212. data/lib/kobako/handle.rb +2 -3
  213. data/lib/kobako/names.rb +28 -0
  214. data/lib/kobako/network.rb +210 -0
  215. data/lib/kobako/outcome.rb +7 -7
  216. data/lib/kobako/runtime.rb +3 -2
  217. data/lib/kobako/sandbox.rb +73 -35
  218. data/lib/kobako/sandbox_options.rb +42 -109
  219. data/lib/kobako/transport/argument_wrap.rb +64 -0
  220. data/lib/kobako/transport/block_failure.rb +1 -1
  221. data/lib/kobako/transport/dispatcher.rb +6 -6
  222. data/lib/kobako/transport/exposure.rb +26 -15
  223. data/lib/kobako/transport/reflection.rb +21 -4
  224. data/lib/kobako/transport/run.rb +8 -23
  225. data/lib/kobako/transport/yielder.rb +2 -9
  226. data/lib/kobako/transport.rb +1 -0
  227. data/lib/kobako/usage.rb +4 -2
  228. data/lib/kobako/version.rb +1 -1
  229. data/lib/kobako.rb +8 -4
  230. data/release-please-config.json +15 -0
  231. data/sig/kobako/catalog/extensions.rbs +2 -0
  232. data/sig/kobako/catalog/grants.rbs +7 -4
  233. data/sig/kobako/catalog/handles.rbs +2 -2
  234. data/sig/kobako/catalog/mount.rbs +3 -1
  235. data/sig/kobako/catalog/network.rbs +20 -0
  236. data/sig/kobako/catalog/replacements.rbs +14 -0
  237. data/sig/kobako/catalog/services.rbs +0 -4
  238. data/sig/kobako/catalog/snippets.rbs +0 -2
  239. data/sig/kobako/codec/{utils.rbs → boundary.rbs} +2 -2
  240. data/sig/kobako/codec/handle_walk.rbs +0 -6
  241. data/sig/kobako/codec/state.rbs +0 -4
  242. data/sig/kobako/codec/value_budget.rbs +48 -5
  243. data/sig/kobako/codec.rbs +2 -2
  244. data/sig/kobako/context.rbs +3 -1
  245. data/sig/kobako/errors.rbs +4 -7
  246. data/sig/kobako/filesystem.rbs +21 -3
  247. data/sig/kobako/fork.rbs +17 -0
  248. data/sig/kobako/network.rbs +115 -0
  249. data/sig/kobako/outcome.rbs +1 -1
  250. data/sig/kobako/runtime.rbs +32 -3
  251. data/sig/kobako/sandbox.rbs +10 -2
  252. data/sig/kobako/sandbox_options.rbs +29 -40
  253. data/sig/kobako/transport/argument_wrap.rbs +15 -0
  254. data/sig/kobako/transport/error.rbs +1 -1
  255. data/sig/kobako/transport/exposure.rbs +2 -4
  256. data/sig/kobako/transport/reflection.rbs +10 -0
  257. data/sig/kobako/transport/run.rbs +0 -2
  258. data/sig/kobako/transport/yielder.rbs +0 -3
  259. data/sig/kobako/transport.rbs +1 -1
  260. data/sig/kobako.rbs +13 -0
  261. metadata +97 -37
  262. data/crates/kobako-runtime/src/endpoint/capture.rs +0 -115
  263. data/crates/kobako-runtime/src/endpoint/memory_cap.rs +0 -238
  264. data/crates/kobako-runtime/src/filesystem/path.rs +0 -21
  265. data/crates/kobako-runtime/src/vfs/errno.rs +0 -153
  266. data/crates/kobako-runtime/tests/linux_baseline/calls.rs +0 -171
  267. data/crates/kobako-runtime/tests/linux_baseline/concurrent.rs +0 -276
  268. data/crates/kobako-runtime/tests/linux_baseline/kobako.rs +0 -323
  269. data/crates/kobako-runtime/tests/linux_baseline/linux-baseline-expected.txt +0 -16
  270. data/crates/kobako-runtime/tests/linux_baseline/linux.rs +0 -449
  271. data/crates/kobako-runtime/tests/linux_baseline/main.rs +0 -611
  272. data/crates/kobako-runtime/tests/linux_baseline/permissions.rs +0 -236
  273. data/crates/kobako-wasmtime/src/descriptors.rs +0 -200
  274. data/crates/kobako-wasmtime/tests/integration/compile_posture.rs +0 -43
  275. data/crates/kobako-wasmtime/tests/integration/guest_file.rs +0 -1085
  276. data/crates/kobako-wasmtime/tests/integration/main.rs +0 -29
  277. data/crates/kobako-wasmtime/tests/integration/preamble_flags.rs +0 -70
  278. data/crates/kobako-wasmtime/tests/integration/snippet_compile.rs +0 -95
  279. data/crates/kobako-wasmtime/tests/integration/support/mod.rs +0 -30
  280. data/crates/kobako-wasmtime/tests/integration/unanswered_call.rs +0 -86
  281. data/crates/kobako-wasmtime/tests/integration/unsupported_call.rs +0 -51
  282. data/ext/kobako/src/runtime/escape.rs +0 -67
  283. data/ext/kobako/src/runtime/gvl.rs +0 -147
  284. data/ext/kobako/src/runtime/pinned_value.rs +0 -31
  285. data/lib/kobako/constant_name.rb +0 -8
  286. data/lib/kobako/pool.rb +0 -140
  287. data/sig/kobako/constant_name.rbs +0 -3
  288. data/sig/kobako/pool.rbs +0 -42
@@ -1,8 +1,9 @@
1
- //! Host-side magnus shell over the extracted wasmtime driver.
1
+ //! The Ruby handle of the contract `Runtime` a Sandbox runs each
2
+ //! invocation on.
2
3
  //!
3
4
  //! The Ruby-visible classes are
4
5
  //!
5
- //! Kobako::Runtime — wraps a `kobako_wasmtime::Driver`
6
+ //! Kobako::Runtime — holds one contract `Runtime`
6
7
  //! Kobako::Snapshot — one invocation's completion + captures + usage
7
8
  //!
8
9
  //! `Kobako::Runtime` is constructed via `Kobako::Runtime.from_path(path,
@@ -11,48 +12,38 @@
11
12
  //! argument, instantiates a fresh instance, and returns a `Snapshot` — the
12
13
  //! whole per-invocation result — so the Runtime holds no per-invocation
13
14
  //! state and one Runtime is safe to drive concurrently. The run mechanics —
14
- //! engine/module caches, caps, trap classification — live in the
15
- //! `kobako-wasmtime` crate behind the `kobako_runtime` contract; no wasm
15
+ //! engine/module caches, caps, trap classification — live in the Wasm
16
+ //! Driver `from_path` builds, behind the `kobako_runtime` contract; no wasm
16
17
  //! engine type reaches this crate or the Host App.
17
18
  //!
18
19
  //! Each module holds one responsibility and opens with its own doc.
19
20
 
20
21
  mod bridge;
21
- mod errors;
22
- mod escape;
23
- mod filesystem;
24
- mod gvl;
25
- mod pinned_value;
26
22
  mod snapshot;
27
23
 
28
24
  use magnus::{
29
- function, method, prelude::*, scan_args::get_kwargs, typed_data::DataTypeFunctions,
30
- value::Opaque, Error as MagnusError, RArray, RHash, RModule, RString, Ruby, Symbol, TypedData,
31
- Value,
25
+ function, method, prelude::*, typed_data::DataTypeFunctions, value::Opaque,
26
+ Error as MagnusError, RArray, RHash, RModule, RString, Ruby, Symbol, TypedData, Value,
32
27
  };
33
28
 
34
29
  use std::path::Path;
30
+ use std::sync::atomic::{AtomicUsize, Ordering};
35
31
  use std::sync::Arc;
36
32
  use std::time::Duration;
37
33
 
38
34
  use kobako_runtime::dispatch::DispatchHandler;
35
+ use kobako_runtime::limits::{Cap, Limits};
36
+ use kobako_runtime::net::Backends;
39
37
  use kobako_runtime::profile::Profile;
40
38
  use kobako_runtime::runtime::{Entry, Runtime as ContractRuntime};
41
39
  use kobako_transport::envelope::{Bindings, Flag, Preamble, Snippet, Snippets};
42
40
  use kobako_wasmtime::{Config, Driver};
43
41
 
42
+ use crate::{errors, filesystem, gvl, name_of, network, symbol_name_of, to_bytes, value_by_name};
44
43
  use snapshot::Snapshot;
45
44
 
46
- /// The one place the boundary borrows an RString's bytes: the borrow does
47
- /// not outlive this call, so no Ruby allocation can move the RString
48
- /// between the borrow and the copy.
49
- fn rstring_to_vec(s: RString) -> Vec<u8> {
50
- // SAFETY: see item doc.
51
- unsafe { s.as_slice() }.to_vec()
52
- }
53
-
54
45
  /// `kind` arrives as a Symbol so the registry never names the wire's
55
- /// discriminant; an off-ladder kind raises rather than defaulting.
46
+ /// discriminant; an unknown kind raises rather than defaulting.
56
47
  fn to_snippets(ruby: &Ruby, entries: RArray) -> Result<Snippets, MagnusError> {
57
48
  let mut snippets = Snippets {
58
49
  entries: Vec::with_capacity(entries.len()),
@@ -66,7 +57,7 @@ fn to_snippets(ruby: &Ruby, entries: RArray) -> Result<Snippets, MagnusError> {
66
57
  body: entry.entry(2)?,
67
58
  },
68
59
  "bytecode" => Snippet::Bytecode {
69
- body: rstring_to_vec(entry.entry(2)?),
60
+ body: to_bytes(entry.entry(2)?),
70
61
  },
71
62
  other => {
72
63
  return Err(MagnusError::new(
@@ -106,27 +97,20 @@ fn to_preamble(ruby: &Ruby, parts: RArray) -> Result<Preamble, MagnusError> {
106
97
  // Ruby init
107
98
  // ---------------------------------------------------------------------------
108
99
 
109
- pub fn init(ruby: &Ruby, kobako: RModule) -> Result<(), MagnusError> {
110
- // Error hierarchy lives in `lib/kobako/errors.rb`; the ext raises
111
- // directly into those classes through the constructors and mappers
112
- // in `runtime/errors.rs` — no intermediate hierarchy is registered.
113
-
114
- // This extension is the only frontend in its process, so the first
115
- // registration is the one that stands.
116
- let _ = kobako_runtime::sched::register_blocking(Box::new(gvl::GvlFreeWait));
117
-
100
+ pub(crate) fn register(ruby: &Ruby, kobako: RModule) -> Result<(), MagnusError> {
118
101
  let runtime = kobako.define_class("Runtime", ruby.class_object())?;
119
102
  runtime.define_singleton_method("from_path", function!(Runtime::from_path, 2))?;
103
+ runtime.define_singleton_method("default_options", function!(Runtime::default_options, 0))?;
104
+ runtime.define_singleton_method("normalize_caps", function!(normalize_caps, 1))?;
120
105
  runtime.define_method("eval", method!(Runtime::eval, 3))?;
121
106
  runtime.define_method("run", method!(Runtime::run, 4))?;
122
107
  runtime.define_method("profile", method!(Runtime::profile, 0))?;
123
108
  runtime.define_method("compile", method!(Runtime::compile, 1))?;
124
- runtime.define_singleton_method("validate_mount", function!(filesystem::validate_mount, 3))?;
109
+ runtime.define_method("stat", method!(Runtime::stat, 0))?;
125
110
  // The guest re-enters for a block yield through a frame-scoped
126
111
  // `Kobako::GuestYielder` the dispatcher hands the Proc, not a method on
127
112
  // Runtime.
128
113
  bridge::register(kobako)?;
129
- filesystem::register(ruby, kobako)?;
130
114
 
131
115
  // Snapshot — the per-invocation result object each entry point returns.
132
116
  snapshot::register(ruby, kobako)?;
@@ -141,120 +125,230 @@ pub fn init(ruby: &Ruby, kobako: RModule) -> Result<(), MagnusError> {
141
125
  Ok(())
142
126
  }
143
127
 
128
+ /// Each cap in `caps`, read as `to_limits` reads it and keyed as
129
+ /// `Kobako::SandboxOptions` names it.
130
+ fn normalize_caps(caps: RHash) -> Result<RHash, MagnusError> {
131
+ let ruby = Ruby::get().expect("Ruby thread");
132
+ caps_of(&ruby, &to_limits(&ruby, caps)?)
133
+ }
134
+
135
+ /// The caps in `caps`, keyed as `Kobako::SandboxOptions` names them, each read
136
+ /// as its kind: a deadline as seconds, a positive finite Numeric, and every
137
+ /// other cap as a positive Integer, `nil` asking for none. One outside its
138
+ /// kind is refused as an argument error, and a zero by the runtime's own
139
+ /// check, which the Rust SDK asks too.
140
+ fn to_limits(ruby: &Ruby, caps: RHash) -> Result<Limits, MagnusError> {
141
+ let mut limits = Limits::default();
142
+ for (name, cap) in limits.caps_mut() {
143
+ let value = caps.fetch(ruby.to_symbol(name))?;
144
+ match cap {
145
+ Cap::Deadline(deadline) => *deadline = to_deadline(ruby, name, value)?,
146
+ Cap::Count(count) => *count = to_count(ruby, name, value)?,
147
+ }
148
+ }
149
+ limits
150
+ .check()
151
+ .map_err(|zero| MagnusError::new(ruby.exception_arg_error(), zero.to_string()))?;
152
+ Ok(limits)
153
+ }
154
+
155
+ /// Each cap `limits` holds, keyed as `Kobako::SandboxOptions` names it, a
156
+ /// deadline in seconds.
157
+ fn caps_of(ruby: &Ruby, limits: &Limits) -> Result<RHash, MagnusError> {
158
+ let caps = ruby.hash_new();
159
+ let mut limits = *limits;
160
+ for (name, cap) in limits.caps_mut() {
161
+ let key = ruby.to_symbol(name);
162
+ match cap {
163
+ Cap::Deadline(deadline) => caps.aset(key, deadline.map(|d| d.as_secs_f64()))?,
164
+ Cap::Count(count) => caps.aset(key, *count)?,
165
+ }
166
+ }
167
+ Ok(caps)
168
+ }
169
+
170
+ /// The deadline `value` names in seconds for `name`, none for `nil`. A
171
+ /// deadline that never arrives, is past what a `Duration` counts, or is not a
172
+ /// number, is refused: the way to ask for none is `nil`.
173
+ fn to_deadline(ruby: &Ruby, name: &str, value: Value) -> Result<Option<Duration>, MagnusError> {
174
+ if value.is_nil() {
175
+ return Ok(None);
176
+ }
177
+ if !value.is_kind_of(ruby.class_numeric()) {
178
+ return Err(MagnusError::new(
179
+ ruby.exception_type_error(),
180
+ format!(
181
+ "{name} must be Numeric or nil, got {}",
182
+ value.class().inspect()
183
+ ),
184
+ ));
185
+ }
186
+ let seconds: f64 = value.funcall("to_f", ())?;
187
+ let refusal = if seconds > 0.0 && seconds.is_finite() {
188
+ ruby.exception_range_error()
189
+ } else {
190
+ ruby.exception_arg_error()
191
+ };
192
+ match Duration::try_from_secs_f64(seconds) {
193
+ Ok(deadline) if seconds.is_finite() => Ok(Some(deadline)),
194
+ _ => Err(MagnusError::new(
195
+ refusal,
196
+ format!(
197
+ "{name} must be > 0 and at most {} seconds (got {})",
198
+ Duration::MAX.as_secs(),
199
+ value.inspect()
200
+ ),
201
+ )),
202
+ }
203
+ }
204
+
205
+ /// The count `value` names for the cap `name`, none for `nil`; anything but
206
+ /// an Integer a `usize` holds is refused.
207
+ fn to_count(ruby: &Ruby, name: &str, value: Value) -> Result<Option<usize>, MagnusError> {
208
+ if value.is_nil() {
209
+ return Ok(None);
210
+ }
211
+ let Some(integer) = magnus::Integer::from_value(value) else {
212
+ return Err(MagnusError::new(
213
+ ruby.exception_type_error(),
214
+ format!(
215
+ "{name} must be an Integer or nil, got {}",
216
+ value.class().inspect()
217
+ ),
218
+ ));
219
+ };
220
+ let refusal = if value.funcall::<_, _, bool>("negative?", ())? {
221
+ ruby.exception_arg_error()
222
+ } else {
223
+ ruby.exception_range_error()
224
+ };
225
+ match integer.to_usize().ok() {
226
+ Some(count) => Ok(Some(count)),
227
+ None => Err(MagnusError::new(
228
+ refusal,
229
+ format!(
230
+ "{name} must be a positive Integer or nil, got {}",
231
+ value.inspect()
232
+ ),
233
+ )),
234
+ }
235
+ }
236
+
237
+ /// What an invocation runs, owned so the guest's thread holds it.
238
+ enum Verb {
239
+ Eval(Vec<u8>),
240
+ Run(String, Vec<u8>),
241
+ }
242
+
243
+ impl Verb {
244
+ fn name(&self) -> &'static str {
245
+ match self {
246
+ Self::Eval(_) => "eval",
247
+ Self::Run(..) => "run",
248
+ }
249
+ }
250
+
251
+ /// Hand `invoke` the Entry this verb names.
252
+ fn invoke<T>(self, invoke: impl FnOnce(Entry<'_>) -> T) -> T {
253
+ match self {
254
+ Self::Eval(source) => invoke(Entry::Eval { source: &source }),
255
+ Self::Run(entrypoint, payload) => invoke(Entry::Run {
256
+ entrypoint: &entrypoint,
257
+ payload,
258
+ }),
259
+ }
260
+ }
261
+ }
262
+
144
263
  #[derive(TypedData)]
145
264
  #[magnus(class = "Kobako::Runtime", free_immediately, size)]
146
265
  struct Runtime {
147
- // The magnus-free wasmtime driver that runs every invocation; the
148
- // shell only shuttles Ruby values across its boundary. The Runtime
149
- // holds no per-invocation state — each `#eval` / `#run` takes its
150
- // dispatch handler as an argument and returns its whole result as a
151
- // `Snapshot` — so `Driver`'s own `Send + Sync` carries the type with no
152
- // interior mutability to guard.
153
- driver: Driver,
266
+ // The runtime every invocation runs on, held behind the contract so the
267
+ // driver is named only where it is built. The Runtime holds no
268
+ // per-invocation state — each `#eval` / `#run` takes its dispatch
269
+ // handler as an argument and returns its whole result as a `Snapshot`
270
+ // — so the contract's `Send + Sync` carries the type with no interior
271
+ // mutability to guard. A run's guest holds it too, as a guest outlives a
272
+ // caller that never came back for it.
273
+ runtime: Arc<dyn ContractRuntime + Send + Sync>,
154
274
  // Whether each invocation releases Ruby's GVL for its guest span
155
275
  // (`gvl: :release`) or holds it throughout (`gvl: :hold`). Fixed at
156
276
  // construction; a `bool` carries no interior mutability, so the type
157
277
  // stays `Send + Sync`.
158
278
  release_gvl: bool,
279
+ // How many of its runs wait now, on a lock or an event, as each run's
280
+ // guest counts while it waits. An atomic, so the type stays `Send + Sync`.
281
+ waiting: Arc<AtomicUsize>,
159
282
  }
160
283
 
161
284
  impl DataTypeFunctions for Runtime {}
162
285
 
163
286
  impl Runtime {
287
+ /// Each option `from_path` takes, keyed as `Kobako::SandboxOptions` names
288
+ /// it, at the runtime's default, so every frontend applies one set. A
289
+ /// run holds the GVL unless the Host App asks to release it.
290
+ fn default_options() -> Result<RHash, MagnusError> {
291
+ let ruby = Ruby::get().expect("Ruby thread");
292
+ let options = caps_of(&ruby, &Limits::default())?;
293
+ options.aset(
294
+ ruby.to_symbol("profile"),
295
+ to_profile_name(&ruby, Profile::default()),
296
+ )?;
297
+ options.aset(ruby.to_symbol("gvl"), ruby.to_symbol("hold"))?;
298
+ options.aset(ruby.to_symbol("network"), ruby.qnil())?;
299
+ Ok(options)
300
+ }
301
+
164
302
  /// The only Ruby-facing constructor, so Engine and Module are never
165
- /// visible to Ruby. Every option is a required keyword: the defaults
166
- /// belong to `Kobako::SandboxOptions`, which names the keys.
303
+ /// visible to Ruby. Every option is a required keyword, as
304
+ /// `default_options` answers each.
167
305
  fn from_path(path: String, options: RHash) -> Result<Self, MagnusError> {
168
306
  let ruby = Ruby::get().expect("Ruby thread");
169
- type Options = (
170
- Option<f64>,
171
- Option<f64>,
172
- Option<usize>,
173
- Option<usize>,
174
- Option<usize>,
175
- Option<usize>,
176
- Symbol,
177
- Symbol,
178
- );
179
- let options = get_kwargs::<_, Options, (), ()>(
180
- options,
181
- &[
182
- "timeout",
183
- "setup_timeout",
184
- "memory_limit",
185
- "stdout_limit",
186
- "stderr_limit",
187
- "open_file_limit",
188
- "profile",
189
- "gvl",
190
- ],
191
- &[],
192
- )?;
193
- let (
194
- timeout_seconds,
195
- setup_timeout_seconds,
196
- memory_limit,
197
- stdout_limit,
198
- stderr_limit,
199
- open_file_limit,
200
- profile,
201
- gvl,
202
- ) = options.required;
203
- // An invalid cap argument is a Host App programming error and
204
- // raises `ArgumentError`, outside the construction-failure
205
- // `SetupError` branch. `SandboxOptions` is the primary guard (it
206
- // never lets a bad timeout reach here); this is defence-in-depth
207
- // for direct `from_path` calls.
208
- let to_duration = |seconds: Option<f64>, name: &str| match seconds {
209
- None => Ok(None),
210
- Some(secs) if secs.is_finite() && secs > 0.0 => Ok(Some(Duration::from_secs_f64(secs))),
211
- Some(secs) => Err(MagnusError::new(
307
+ let limits = to_limits(&ruby, options)?;
308
+ let profile: Value = options.fetch(ruby.to_symbol("profile"))?;
309
+ let gvl: Value = options.fetch(ruby.to_symbol("gvl"))?;
310
+ // A value kobako does not name a profile has no profile to stand
311
+ // for, so it is refused rather than read as a weaker one.
312
+ let Some(profile) =
313
+ symbol_name_of(profile)?.and_then(|name| value_by_name(&PROFILE_NAMES, &name))
314
+ else {
315
+ return Err(MagnusError::new(
212
316
  ruby.exception_arg_error(),
213
- format!("{name} must be > 0 and finite, got {secs} seconds"),
214
- )),
317
+ format!(
318
+ "profile must be :permissive or :hermetic, got {}",
319
+ profile.inspect()
320
+ ),
321
+ ));
215
322
  };
216
- let timeout = to_duration(timeout_seconds, "timeout")?;
217
- let setup_timeout = to_duration(setup_timeout_seconds, "setup_timeout")?;
218
- // Fail closed on an off-ladder rung: an unrecognized posture must
219
- // never fall back to a weaker posture. Same defence in depth as the
220
- // timeout guard above — `SandboxOptions` is the primary validator.
221
- let profile = match profile.name()?.as_ref() {
222
- "hermetic" => Profile::Hermetic,
223
- "permissive" => Profile::Permissive,
224
- other => {
323
+ // A mode kobako does not name is refused as a profile is.
324
+ let release_gvl = match symbol_name_of(gvl)?.as_deref() {
325
+ Some("hold") => false,
326
+ Some("release") => true,
327
+ _ => {
225
328
  return Err(MagnusError::new(
226
329
  ruby.exception_arg_error(),
227
- format!("profile must be :permissive or :hermetic, got :{other}"),
330
+ format!("gvl must be :hold or :release, got {}", gvl.inspect()),
228
331
  ));
229
332
  }
230
333
  };
231
- // Same fail-closed posture as `profile`: an unrecognized mode raises
232
- // rather than defaulting. `SandboxOptions` is the primary validator;
233
- // this guards direct `from_path` calls.
234
- let release_gvl = match gvl.name()?.as_ref() {
235
- "hold" => false,
236
- "release" => true,
237
- other => {
238
- return Err(MagnusError::new(
239
- ruby.exception_arg_error(),
240
- format!("gvl must be :hold or :release, got :{other}"),
241
- ));
242
- }
334
+
335
+ // `nil` is the host's own network; anything else must be a Mock.
336
+ let mock: Value = options.fetch(ruby.to_symbol("network"))?;
337
+ let backends = match mock.is_nil() {
338
+ true => Backends::default(),
339
+ false => <&network::MockNet>::try_convert(mock)?.backends(),
243
340
  };
244
341
 
245
342
  let mut config = Config::default();
246
- config.timeout = timeout;
247
- config.setup_timeout = setup_timeout;
248
- config.memory_limit = memory_limit;
249
- config.stdout_limit = stdout_limit;
250
- config.stderr_limit = stderr_limit;
251
- config.open_file_limit = open_file_limit;
343
+ config.limits = limits;
252
344
  config.profile = profile;
253
- let driver =
254
- Driver::new(Path::new(&path), config).map_err(|e| errors::setup_to_magnus(&ruby, e))?;
345
+ config.network = backends;
346
+ let driver = Driver::from_file(Path::new(&path), config)
347
+ .map_err(|e| errors::from_setup(&ruby, e))?;
255
348
  Ok(Self {
256
- driver,
349
+ runtime: Arc::new(driver),
257
350
  release_gvl,
351
+ waiting: Arc::default(),
258
352
  })
259
353
  }
260
354
 
@@ -263,11 +357,12 @@ impl Runtime {
263
357
  // argument and returns a `Snapshot` for any completed invocation —
264
358
  // success or trap alike. Only a could-not-start fault (a missing export
265
359
  // or a fault before the export call) raises directly, as the class
266
- // `errors::to_magnus` gives its cause, since it yields no `Snapshot`.
360
+ // `errors::from_invoke` gives its cause, since it yields no `Snapshot`.
267
361
  //
268
- // `setup` is the invocation's `[paths, snippets, flags, mounts]`: the
269
- // Preamble's three parts, then the Mounts as
270
- // `filesystem::to_grants` reads them.
362
+ // `setup` is the invocation's `[paths, snippets, flags, mounts,
363
+ // networks]`: the Preamble's three parts, then the Mounts as
364
+ // `filesystem::to_grants` reads them and the network entries as
365
+ // `network::to_grants` reads them.
271
366
  // -----------------------------------------------------------------
272
367
 
273
368
  fn eval(
@@ -276,8 +371,7 @@ impl Runtime {
276
371
  setup: RArray,
277
372
  source: RString,
278
373
  ) -> Result<Snapshot, MagnusError> {
279
- let source = rstring_to_vec(source);
280
- self.invoke(dispatch, setup, Entry::Eval { source: &source })
374
+ self.invoke(dispatch, setup, Verb::Eval(to_bytes(source)))
281
375
  }
282
376
 
283
377
  fn run(
@@ -287,55 +381,63 @@ impl Runtime {
287
381
  entrypoint: String,
288
382
  payload: RString,
289
383
  ) -> Result<Snapshot, MagnusError> {
290
- self.invoke(
291
- dispatch,
292
- setup,
293
- Entry::Run {
294
- entrypoint: &entrypoint,
295
- payload: rstring_to_vec(payload),
296
- },
297
- )
384
+ self.invoke(dispatch, setup, Verb::Run(entrypoint, to_bytes(payload)))
298
385
  }
299
386
 
300
387
  /// One owner for the wiring both verbs share, so a Preamble, a Grant,
301
388
  /// or a handler change cannot drift between them.
302
- fn invoke(
303
- &self,
304
- dispatch: Value,
305
- setup: RArray,
306
- entry: Entry<'_>,
307
- ) -> Result<Snapshot, MagnusError> {
389
+ fn invoke(&self, dispatch: Value, setup: RArray, verb: Verb) -> Result<Snapshot, MagnusError> {
308
390
  let ruby = Ruby::get().expect("Ruby thread");
309
- let verb = match entry {
310
- Entry::Eval { .. } => "eval",
311
- Entry::Run { .. } => "run",
312
- };
391
+ let name = verb.name();
313
392
  let handler = build_handler(dispatch);
314
393
  let preamble = to_preamble(&ruby, setup)?;
315
- let (grants, _pins) = filesystem::to_grants(&ruby, setup.entry(3)?)?;
316
- // Release the GVL around the guest span iff this Sandbox asks for it;
317
- // the closure touches no Ruby VALUE (the driver is magnus-free, and a
318
- // guest→host dispatch, or a mount's block, re-acquires the GVL).
319
- let result = gvl::region(self.release_gvl, || {
320
- self.driver.invoke(entry, &preamble, handler, &grants)
321
- });
322
- escape::resume()?;
323
- result
324
- .map(|snapshot| Snapshot::new(snapshot, verb))
325
- .map_err(|e| errors::to_magnus(&ruby, e))
394
+ let runtime = self.runtime.clone();
395
+ gvl::run(&ruby, self.release_gvl, &self.waiting, || {
396
+ let (mut grants, mut pins) = filesystem::to_grants(setup.entry(3)?)?;
397
+ let (networks, network_pins) = network::to_grants(&ruby, setup.entry(4)?)?;
398
+ grants.extend(networks);
399
+ pins.extend(network_pins);
400
+ // The closure touches no Ruby VALUE (the runtime is magnus-free, and
401
+ // a guest→host dispatch, or a mount's block, comes back to this
402
+ // Fiber), and owns all it reads, as the guest's thread runs it. It
403
+ // lets the pins go once the Store, which reaches them, is gone.
404
+ Ok(move || {
405
+ let snapshot =
406
+ verb.invoke(|entry| runtime.invoke(entry, &preamble, handler, &grants));
407
+ drop(grants);
408
+ drop(pins);
409
+ snapshot
410
+ })
411
+ })?
412
+ .map(|snapshot| Snapshot::new(snapshot, name))
413
+ .map_err(|e| errors::from_invoke(&ruby, e))
414
+ }
415
+
416
+ /// What this Runtime's runs are doing now, as `GC.stat` answers the
417
+ /// collector's: how many wait, on a lock or an event.
418
+ fn stat(&self) -> Result<RHash, MagnusError> {
419
+ let ruby = Ruby::get().expect("Ruby thread");
420
+ let stat = ruby.hash_new();
421
+ stat.aset(
422
+ ruby.to_symbol("runs_waiting"),
423
+ self.waiting.load(Ordering::SeqCst),
424
+ )?;
425
+ Ok(stat)
326
426
  }
327
427
 
328
428
  /// The bytecode of the source snippets, one binary String each in
329
429
  /// order, or `nil` when the guest compiled nothing; no failure raises,
330
430
  /// since the Sandbox keeps the source either way. Takes the Preamble an
331
- /// invocation sends, `paths` included, so the driver can tell whether
431
+ /// invocation sends, `paths` included, so the runtime can tell whether
332
432
  /// the bytecode still fits it; no dispatch handler is bound, since
333
433
  /// compiling runs no script.
334
434
  fn compile(&self, preamble: RArray) -> Result<Option<RArray>, MagnusError> {
335
435
  let ruby = Ruby::get().expect("Ruby thread");
336
436
  let preamble = to_preamble(&ruby, preamble)?;
337
- let bytecodes = gvl::region(self.release_gvl, || self.driver.compile(&preamble));
338
- escape::resume()?;
437
+ let runtime = self.runtime.clone();
438
+ let bytecodes = gvl::run(&ruby, self.release_gvl, &self.waiting, || {
439
+ Ok(move || runtime.compile(&preamble))
440
+ })?;
339
441
  Ok(bytecodes.map(|bytecodes| {
340
442
  ruby.ary_from_iter(
341
443
  bytecodes
@@ -345,19 +447,26 @@ impl Runtime {
345
447
  }))
346
448
  }
347
449
 
348
- /// The driver's declaration, which the Sandbox checks against the
349
- /// posture its `profile:` option requested.
450
+ /// The isolation profile the runtime declares it built.
350
451
  fn profile(&self) -> Symbol {
351
452
  let ruby = Ruby::get().expect("Ruby thread");
352
- match self.driver.profile() {
353
- Profile::Hermetic => ruby.to_symbol("hermetic"),
354
- Profile::Permissive => ruby.to_symbol("permissive"),
355
- }
453
+ to_profile_name(&ruby, self.runtime.profile())
356
454
  }
357
455
  }
358
456
 
457
+ /// Each profile beside the name the `profile:` option takes it by.
458
+ const PROFILE_NAMES: [(Profile, &str); 2] = [
459
+ (Profile::Hermetic, "hermetic"),
460
+ (Profile::Permissive, "permissive"),
461
+ ];
462
+
463
+ /// `profile` as the Symbol the `profile:` option names it by.
464
+ fn to_profile_name(ruby: &Ruby, profile: Profile) -> Symbol {
465
+ ruby.to_symbol(name_of(&PROFILE_NAMES, &profile).expect("every profile has a name"))
466
+ }
467
+
359
468
  /// The Proc stays GC-rooted for the synchronous `#eval` / `#run` call as a
360
- /// live method argument on the Ruby stack, so the driver only borrows it
469
+ /// live method argument on the Ruby stack, so the runtime only borrows it
361
470
  /// (the safety contract on `kobako_runtime::runtime::Runtime`).
362
471
  fn build_handler(dispatch: Value) -> Option<Arc<dyn DispatchHandler>> {
363
472
  if dispatch.is_nil() {
@@ -0,0 +1,42 @@
1
+ //! The Wire's rules a Ruby frontend asks before it writes a name the guest
2
+ //! interns or issues a Capability Handle id, so both frontends hold to the
3
+ //! one rule the Envelope tier keeps.
4
+
5
+ use magnus::{function, prelude::*, Error as MagnusError, RModule, RString};
6
+
7
+ use kobako_transport::envelope::name::{collides, is_constant_name, is_constant_path, is_reserved};
8
+ use kobako_transport::envelope::MAX_HANDLE_ID;
9
+
10
+ pub(crate) fn register(kobako: RModule) -> Result<(), MagnusError> {
11
+ kobako.define_singleton_method("max_handle_id", function!(|| MAX_HANDLE_ID, 0))?;
12
+ kobako.define_singleton_method(
13
+ "constant_name?",
14
+ function!(|name: RString| holds(name, is_constant_name), 1),
15
+ )?;
16
+ kobako.define_singleton_method(
17
+ "constant_path?",
18
+ function!(|path: RString| holds(path, is_constant_path), 1),
19
+ )?;
20
+ kobako.define_singleton_method(
21
+ "reserved_path?",
22
+ function!(|path: RString| holds(path, is_reserved), 1),
23
+ )?;
24
+ kobako.define_singleton_method("paths_collide?", function!(paths_collide, 2))?;
25
+ Ok(())
26
+ }
27
+
28
+ /// Whether the paths `path` and `bound` spell cannot both be bound; bytes
29
+ /// that spell no text are no name at all, so they collide with nothing.
30
+ fn paths_collide(path: RString, bound: RString) -> bool {
31
+ let (path, bound) = (crate::to_bytes(path), crate::to_bytes(bound));
32
+ match (std::str::from_utf8(&path), std::str::from_utf8(&bound)) {
33
+ (Ok(path), Ok(bound)) => collides(path, bound),
34
+ _ => false,
35
+ }
36
+ }
37
+
38
+ /// Whether `rule` holds for the text `s` spells; bytes that spell no text
39
+ /// are no name at all.
40
+ fn holds(s: RString, rule: fn(&str) -> bool) -> bool {
41
+ std::str::from_utf8(&crate::to_bytes(s)).is_ok_and(rule)
42
+ }
@@ -66,13 +66,25 @@ module Kobako
66
66
 
67
67
  def validate(extension)
68
68
  source = extension.source
69
- raise ArgumentError, "Extension #source must be a String, got #{source.class}" unless source.is_a?(String)
69
+ raise TypeError, "Extension #source must be a String, got #{source.class}" unless source.is_a?(String)
70
70
 
71
+ validate_dependencies(extension.depends_on)
71
72
  backend = extension.backend
72
73
  return if backend.nil?
73
74
  return if backend.respond_to?(:path) && backend.respond_to?(:object) && backend.respond_to?(:provider)
74
75
 
75
- raise ArgumentError, "Extension #backend must expose #path, #object, and #provider"
76
+ raise TypeError, "Extension #backend must expose #path, #object, and #provider"
77
+ end
78
+
79
+ # Each dependency names an Extension as its +name+ does.
80
+ def validate_dependencies(dependencies)
81
+ return if dependencies.nil?
82
+ unless dependencies.is_a?(Array)
83
+ raise TypeError,
84
+ "Extension #depends_on must be an Array, got #{dependencies.class}"
85
+ end
86
+
87
+ dependencies.each { |dependency| Kobako.to_name(dependency, "Extension #depends_on entry") }
76
88
  end
77
89
 
78
90
  def unmet_dependency
@@ -13,12 +13,10 @@ module Kobako
13
13
  end
14
14
 
15
15
  def register(name, value, advisory:)
16
- unless name.is_a?(Symbol) || name.is_a?(String)
17
- raise ArgumentError, "flag name must be a Symbol or String, got #{name.class}"
18
- end
19
- raise ArgumentError, "flag value must be a String, got #{value.class}" unless value.is_a?(String)
16
+ name = Kobako.to_name(name, "flag name")
17
+ raise TypeError, "flag value must be a String, got #{value.class}" unless value.is_a?(String)
20
18
 
21
- key = Catalog.to_utf8(name.to_s, "flag name")
19
+ key = Catalog.to_utf8(name, "flag name")
22
20
  raise ArgumentError, "flag #{key.inspect} already set" if @entries.key?(key)
23
21
 
24
22
  @entries[key] = [Catalog.to_utf8(value, "flag value"), !advisory]