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
@@ -0,0 +1,626 @@
1
+ //! The one thread that waits on every host socket of the process, as Linux's
2
+ //! softirq hands each arriving segment to the socket it belongs to: an event
3
+ //! calls its socket's `on_event`, which moves what it can without blocking and
4
+ //! wakes the socket's wait queue. The same thread wakes a waker whose timer is
5
+ //! due, so no socket holds a thread of its own. It only wakes: an HTTP
6
+ //! exchange or a name lookup moves on the thread that waits for it. A forked
7
+ //! child, which inherits no thread, starts a reactor of its own.
8
+
9
+ use std::collections::HashMap;
10
+ use std::io;
11
+ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
12
+ use std::sync::{Arc, Mutex, MutexGuard, PoisonError, Weak};
13
+ use std::task::Waker;
14
+ use std::thread;
15
+ use std::time::{Duration, Instant};
16
+
17
+ use mio::event::Source;
18
+ use mio::{Events, Interest, Registry, Token};
19
+
20
+ use crate::fork::{Pid, ProcessLocal};
21
+ use crate::vfs::PollMask;
22
+
23
+ /// The poll mask `event` reports: a hang-up once both directions closed, as
24
+ /// a reset or two FINs leave a socket, which Windows' AFD reports alone.
25
+ fn poll_mask_of(event: &mio::event::Event) -> PollMask {
26
+ let mut mask = PollMask::default();
27
+ if event.is_readable() {
28
+ mask = mask | PollMask::IN;
29
+ }
30
+ if event.is_writable() {
31
+ mask = mask | PollMask::OUT;
32
+ }
33
+ if event.is_error() {
34
+ mask = mask | PollMask::ERR;
35
+ }
36
+ if event.is_read_closed() && event.is_write_closed() {
37
+ mask = mask | PollMask::HUP;
38
+ }
39
+ mask
40
+ }
41
+
42
+ /// What a host socket does once the reactor saw it change, as a socket's
43
+ /// `sk_data_ready` and `sk_write_space` do: move what it can without blocking,
44
+ /// then wake whoever waits on it. `events` is what the change reported, as a
45
+ /// wakeup's key carries the poll mask; a repoll reports nothing. A socket
46
+ /// that stops short of `WouldBlock` hears of the host socket again only
47
+ /// through `events`, a repoll, or its guest's next call.
48
+ pub(crate) trait Ready: Send + Sync {
49
+ fn on_event(&self, events: PollMask);
50
+
51
+ /// Fail the socket from outside, as the reactor stopping does, and wake
52
+ /// whoever waits on it, as `tcp_abort` and `udp_abort` end one.
53
+ fn abort(&self);
54
+ }
55
+
56
+ /// What the reactor watches a socket for: what arrives, always, and room to
57
+ /// write only while a writer found none, as Linux wakes a socket's writers
58
+ /// once `SOCK_NOSPACE` marks it. A socket that always has room would
59
+ /// otherwise be reported again each time a host re-arms its watch, as
60
+ /// Windows' AFD does after every read that would block.
61
+ fn interest(nospace: bool) -> Interest {
62
+ match nospace {
63
+ true => Interest::READABLE | Interest::WRITABLE,
64
+ false => Interest::READABLE,
65
+ }
66
+ }
67
+
68
+ /// The token that wakes the reactor to read its timers and repolls again.
69
+ const WAKE_TOKEN: Token = Token(0);
70
+
71
+ pub(crate) struct Reactor {
72
+ registry: Registry,
73
+ waker: mio::Waker,
74
+ next: AtomicUsize,
75
+ /// The socket each token belongs to, held weakly so the reactor keeps no
76
+ /// socket alive past its release.
77
+ sockets: Mutex<HashMap<Token, Weak<dyn Ready>>>,
78
+ /// The sockets whose last turn ended at its bound with more waiting, each
79
+ /// once, run again after the next round of events, as NAPI puts a poll
80
+ /// that spent its weight back at the tail of `poll_list`.
81
+ repoll: Mutex<Vec<Weak<dyn Ready>>>,
82
+ /// Whether the thread stopped, its poll having failed or a callback
83
+ /// panicked, so the next socket starts another reactor rather than
84
+ /// register on one nobody waits on.
85
+ stopped: AtomicBool,
86
+ /// The wakers due at an instant, as hrtimers wake a task whose timeout
87
+ /// ends.
88
+ timers: Mutex<Vec<(Instant, Waker)>>,
89
+ }
90
+
91
+ /// The process's reactor.
92
+ static CURRENT: ProcessLocal<Arc<Reactor>> = ProcessLocal::new();
93
+
94
+ impl Reactor {
95
+ /// The process's reactor, started at the first socket; a forked child
96
+ /// starts its own, since its parent's thread never came along, and so does
97
+ /// the socket after a reactor that stopped.
98
+ pub(crate) fn current() -> io::Result<Arc<Self>> {
99
+ CURRENT.with(|current| {
100
+ if let Some(reactor) = current.as_ref() {
101
+ if !reactor.stopped.load(Ordering::Acquire) {
102
+ return Ok(reactor.clone());
103
+ }
104
+ }
105
+ let reactor = Self::start()?;
106
+ *current = Some(reactor.clone());
107
+ Ok(reactor)
108
+ })
109
+ }
110
+
111
+ fn start() -> io::Result<Arc<Self>> {
112
+ let mut poll = mio::Poll::new()?;
113
+ let reactor = Self::on(&poll)?;
114
+ let running = reactor.clone();
115
+ thread::Builder::new()
116
+ .name("kobako-reactor".into())
117
+ .spawn(move || running.run(|events, wait| poll.poll(events, wait)))?;
118
+ Ok(reactor)
119
+ }
120
+
121
+ /// A reactor registering on `poll`, whose events nobody reads yet.
122
+ fn on(poll: &mio::Poll) -> io::Result<Arc<Self>> {
123
+ Ok(Arc::new(Self {
124
+ registry: poll.registry().try_clone()?,
125
+ waker: mio::Waker::new(poll.registry(), WAKE_TOKEN)?,
126
+ next: AtomicUsize::new(1),
127
+ sockets: Mutex::default(),
128
+ repoll: Mutex::default(),
129
+ stopped: AtomicBool::new(false),
130
+ timers: Mutex::default(),
131
+ }))
132
+ }
133
+
134
+ /// Serve each round of the events `poll` waits for, until it fails.
135
+ fn run(&self, mut poll: impl FnMut(&mut Events, Option<Duration>) -> io::Result<()>) {
136
+ let _stopping = Stopping(self);
137
+ let mut events = Events::with_capacity(256);
138
+ loop {
139
+ let wait = match self.repoll().is_empty() {
140
+ true => self.poll_timeout(),
141
+ false => Some(Duration::ZERO),
142
+ };
143
+ if let Err(err) = poll(&mut events, wait) {
144
+ if err.kind() == io::ErrorKind::Interrupted {
145
+ continue;
146
+ }
147
+ return;
148
+ }
149
+ // What asked for another turn before this round runs after its
150
+ // events, as `net_rx_action` takes the polls newly scheduled
151
+ // ahead of its repoll list; what asks during the round waits for
152
+ // the next. A poll a signal interrupted takes none, so each
153
+ // waits on in place, as `poll_list` keeps its entries.
154
+ let again = std::mem::take(&mut *self.repoll());
155
+ let ready: Vec<(Arc<dyn Ready>, PollMask)> = {
156
+ let sockets = self.sockets.lock().unwrap_or_else(PoisonError::into_inner);
157
+ events
158
+ .iter()
159
+ .filter_map(|event| {
160
+ let socket = sockets.get(&event.token()).and_then(Weak::upgrade)?;
161
+ Some((socket, poll_mask_of(event)))
162
+ })
163
+ .collect()
164
+ };
165
+ ready
166
+ .iter()
167
+ .for_each(|(socket, events)| socket.on_event(*events));
168
+ again
169
+ .iter()
170
+ .filter_map(Weak::upgrade)
171
+ .for_each(|socket| socket.on_event(PollMask::default()));
172
+ self.wake_due_timers();
173
+ }
174
+ }
175
+
176
+ /// Wake `waker` once `at` passes, in place of any instant its task asked
177
+ /// for before, as `hrtimer_start` moves a task's one timer. The timer
178
+ /// lasts until it is due or its `Timer` drops, so a wait that ends or is
179
+ /// cancelled leaves none behind.
180
+ #[cfg(any(test, all(unix, not(target_os = "macos"))))]
181
+ pub(crate) fn wake_at(self: &Arc<Self>, at: Instant, waker: Waker) -> Timer {
182
+ self.disarm(&waker);
183
+ self.timers
184
+ .lock()
185
+ .unwrap_or_else(PoisonError::into_inner)
186
+ .push((at, waker.clone()));
187
+ let _ = self.waker.wake();
188
+ // A reactor that stopped never reads its timers again.
189
+ if self.stopped.load(Ordering::Acquire) {
190
+ self.disarm(&waker);
191
+ waker.wake_by_ref();
192
+ }
193
+ Timer {
194
+ reactor: self.clone(),
195
+ waker,
196
+ }
197
+ }
198
+
199
+ /// Drop the timer `waker`'s task holds, as `hrtimer_cancel` does.
200
+ #[cfg(any(test, all(unix, not(target_os = "macos"))))]
201
+ fn disarm(&self, waker: &Waker) {
202
+ self.timers
203
+ .lock()
204
+ .unwrap_or_else(PoisonError::into_inner)
205
+ .retain(|(_, armed)| !armed.will_wake(waker));
206
+ }
207
+
208
+ fn repoll(&self) -> MutexGuard<'_, Vec<Weak<dyn Ready>>> {
209
+ self.repoll.lock().unwrap_or_else(PoisonError::into_inner)
210
+ }
211
+
212
+ /// How long the poll may wait before the soonest timer is due.
213
+ fn poll_timeout(&self) -> Option<Duration> {
214
+ let timers = self.timers.lock().unwrap_or_else(PoisonError::into_inner);
215
+ let soonest = timers.iter().map(|(at, _)| *at).min()?;
216
+ Some(soonest.saturating_duration_since(Instant::now()))
217
+ }
218
+
219
+ fn wake_due_timers(&self) {
220
+ let now = Instant::now();
221
+ let due: Vec<Waker> = {
222
+ let mut timers = self.timers.lock().unwrap_or_else(PoisonError::into_inner);
223
+ let (due, pending) = std::mem::take(&mut *timers)
224
+ .into_iter()
225
+ .partition(|(at, _)| *at <= now);
226
+ *timers = pending;
227
+ due.into_iter().map(|(_, waker)| waker).collect()
228
+ };
229
+ due.into_iter().for_each(Waker::wake);
230
+ }
231
+
232
+ /// Watch `source` for what arrives, and for room to write while `nospace`
233
+ /// holds, handing each change to `ready`'s `on_event`; a reactor that
234
+ /// stopped refuses it with `ECONNABORTED`, as nobody would wake its
235
+ /// socket.
236
+ pub(crate) fn register(
237
+ self: &Arc<Self>,
238
+ source: &mut impl Source,
239
+ ready: Weak<dyn Ready>,
240
+ nospace: bool,
241
+ ) -> io::Result<Registration> {
242
+ let token = Token(self.next.fetch_add(1, Ordering::Relaxed));
243
+ self.sockets
244
+ .lock()
245
+ .unwrap_or_else(PoisonError::into_inner)
246
+ .insert(token, ready);
247
+ if let Err(err) = self.registry.register(source, token, interest(nospace)) {
248
+ self.forget(token);
249
+ return Err(err);
250
+ }
251
+ // Read after the token is in place, so a reactor stopping meanwhile
252
+ // either aborts the socket or is seen here.
253
+ if self.stopped.load(Ordering::Acquire) {
254
+ let _ = self.registry.deregister(source);
255
+ self.forget(token);
256
+ return Err(io::ErrorKind::ConnectionAborted.into());
257
+ }
258
+ Ok(Registration {
259
+ token,
260
+ reactor: self.clone(),
261
+ pid: Pid::current(),
262
+ nospace,
263
+ })
264
+ }
265
+
266
+ fn forget(&self, token: Token) {
267
+ self.sockets
268
+ .lock()
269
+ .unwrap_or_else(PoisonError::into_inner)
270
+ .remove(&token);
271
+ }
272
+ }
273
+
274
+ /// Stops the reactor as its thread leaves the loop, by a failed poll or a
275
+ /// panic alike: no socket registers on it again, and each socket and timer
276
+ /// it watched is aborted or woken, so no waiter waits on a thread that is
277
+ /// gone.
278
+ struct Stopping<'a>(&'a Reactor);
279
+
280
+ impl Drop for Stopping<'_> {
281
+ fn drop(&mut self) {
282
+ let reactor = self.0;
283
+ reactor.stopped.store(true, Ordering::Release);
284
+ let watched: Vec<Arc<dyn Ready>> = reactor
285
+ .sockets
286
+ .lock()
287
+ .unwrap_or_else(PoisonError::into_inner)
288
+ .values()
289
+ .filter_map(Weak::upgrade)
290
+ .collect();
291
+ watched.iter().for_each(|socket| socket.abort());
292
+ let timers = std::mem::take(
293
+ &mut *reactor
294
+ .timers
295
+ .lock()
296
+ .unwrap_or_else(PoisonError::into_inner),
297
+ );
298
+ timers.into_iter().for_each(|(_, waker)| waker.wake());
299
+ }
300
+ }
301
+
302
+ /// One host socket the reactor watches; the socket deregisters it as it
303
+ /// lets the host socket go.
304
+ pub(crate) struct Registration {
305
+ token: Token,
306
+ reactor: Arc<Reactor>,
307
+ pid: Pid,
308
+ nospace: bool,
309
+ }
310
+
311
+ impl Registration {
312
+ /// Watch `source` for room to write while `nospace` holds, as a writer
313
+ /// that found none sets `SOCK_NOSPACE` and one that wrote clears it. A
314
+ /// forked child leaves its parent's watch as it was, as `deregister` does.
315
+ pub(crate) fn set_nospace(&mut self, source: &mut impl Source, nospace: bool) {
316
+ if self.nospace == nospace || !self.pid.is_current() {
317
+ return;
318
+ }
319
+ if self
320
+ .reactor
321
+ .registry
322
+ .reregister(source, self.token, interest(nospace))
323
+ .is_ok()
324
+ {
325
+ self.nospace = nospace;
326
+ }
327
+ }
328
+
329
+ /// Stop watching `source`, which the socket closes next; the token goes
330
+ /// once the registration drops. A forked child leaves its parent's
331
+ /// registration be: the epoll instance is shared, and removing the one
332
+ /// `<fd, file>` entry would stop the parent watching its own socket.
333
+ pub(crate) fn deregister(&self, source: &mut impl Source) {
334
+ if self.pid.is_current() {
335
+ let _ = self.reactor.registry.deregister(source);
336
+ }
337
+ }
338
+
339
+ /// Run `ready`'s `on_event` again after the reactor's next round of
340
+ /// events, once however often it asks, as NAPI repolls a device that
341
+ /// spent its weight with more to take and `NAPI_STATE_SCHED` keeps it
342
+ /// queued once; no further event may come for what already waits.
343
+ pub(crate) fn repoll(&self, ready: Weak<dyn Ready>) {
344
+ let mut repoll = self.reactor.repoll();
345
+ if !repoll.iter().any(|queued| queued.ptr_eq(&ready)) {
346
+ repoll.push(ready);
347
+ }
348
+ drop(repoll);
349
+ let _ = self.reactor.waker.wake();
350
+ }
351
+ }
352
+
353
+ impl Drop for Registration {
354
+ fn drop(&mut self) {
355
+ self.reactor.forget(self.token);
356
+ }
357
+ }
358
+
359
+ /// A task's armed timer, disarmed as it drops.
360
+ #[cfg(any(test, all(unix, not(target_os = "macos"))))]
361
+ pub(crate) struct Timer {
362
+ reactor: Arc<Reactor>,
363
+ waker: Waker,
364
+ }
365
+
366
+ #[cfg(any(test, all(unix, not(target_os = "macos"))))]
367
+ impl Drop for Timer {
368
+ fn drop(&mut self) {
369
+ self.reactor.disarm(&self.waker);
370
+ }
371
+ }
372
+
373
+ #[cfg(test)]
374
+ mod tests {
375
+ use std::sync::mpsc;
376
+ use std::task::{Poll, Wake};
377
+ use std::time::Duration;
378
+
379
+ use super::super::task::Task;
380
+ use super::*;
381
+
382
+ // A reactor started in another process, as a forked child inherits its
383
+ // parent's, is never handed out: the child starts its own.
384
+ #[test]
385
+ fn a_reactor_started_in_another_process_is_replaced() {
386
+ let inherited = Reactor::current().expect("a reactor starts");
387
+ CURRENT.inherit();
388
+ let own = Reactor::current().expect("a reactor starts");
389
+ assert!(
390
+ !Arc::ptr_eq(&inherited, &own),
391
+ "Reactor::current must start a reactor of its own once the one it holds was started \
392
+ in another process"
393
+ );
394
+ }
395
+
396
+ /// A socket the reactor tells of each change through a channel.
397
+ struct Tells(Mutex<mpsc::Sender<()>>);
398
+
399
+ impl Ready for Tells {
400
+ fn on_event(&self, _events: PollMask) {
401
+ let _ = self.0.lock().unwrap().send(());
402
+ }
403
+
404
+ fn abort(&self) {}
405
+ }
406
+
407
+ /// A socket that tells only of its abort.
408
+ struct TellsAbort(Mutex<mpsc::Sender<&'static str>>);
409
+
410
+ impl Ready for TellsAbort {
411
+ fn on_event(&self, _events: PollMask) {}
412
+
413
+ fn abort(&self) {
414
+ let _ = self.0.lock().unwrap().send("the socket");
415
+ }
416
+ }
417
+
418
+ /// A socket whose callback fails once armed, as a panic in the code it
419
+ /// runs would. Unarmed, it lets pass the event its registration brings,
420
+ /// as a socket is writable the moment it registers.
421
+ struct PanicsOnceArmed(AtomicBool);
422
+
423
+ impl Ready for PanicsOnceArmed {
424
+ fn on_event(&self, _events: PollMask) {
425
+ if self.0.load(Ordering::Acquire) {
426
+ panic!("a socket's callback failed on the reactor");
427
+ }
428
+ }
429
+
430
+ fn abort(&self) {}
431
+ }
432
+
433
+ /// A timer's task that tells as it wakes.
434
+ struct TellsWake(Mutex<mpsc::Sender<&'static str>>);
435
+
436
+ impl Wake for TellsWake {
437
+ fn wake(self: Arc<Self>) {
438
+ let _ = self.0.lock().unwrap().send("the timer");
439
+ }
440
+ }
441
+
442
+ // A reactor whose thread stops, here as a socket's callback panics,
443
+ // aborts each socket still registered and wakes each timer at once,
444
+ // rather than leave their waiters to their deadlines, and is handed out
445
+ // no more. A poll that fails leaves the loop through the same guard.
446
+ // @behavior NW-235
447
+ #[test]
448
+ fn a_reactor_that_stops_aborts_every_socket_and_timer_it_watches() {
449
+ let reactor = Reactor::start().expect("a reactor starts");
450
+ let (tx, rx) = mpsc::channel();
451
+ let waiting: Arc<dyn Ready> = Arc::new(TellsAbort(Mutex::new(tx.clone())));
452
+ let panics = Arc::new(PanicsOnceArmed(AtomicBool::new(false)));
453
+ let failing: Arc<dyn Ready> = panics.clone();
454
+ let addr = "127.0.0.1:0".parse().unwrap();
455
+ let mut watched = mio::net::UdpSocket::bind(addr).expect("a UDP socket binds");
456
+ let mut failed = mio::net::UdpSocket::bind(addr).expect("a UDP socket binds");
457
+ let _watching = reactor
458
+ .register(&mut watched, Arc::downgrade(&waiting), false)
459
+ .expect("the socket registers");
460
+ let _failing = reactor
461
+ .register(&mut failed, Arc::downgrade(&failing), false)
462
+ .expect("the socket registers");
463
+ let _timer = reactor.wake_at(
464
+ Instant::now() + Duration::from_secs(30),
465
+ Waker::from(Arc::new(TellsWake(Mutex::new(tx)))),
466
+ );
467
+ panics.0.store(true, Ordering::Release);
468
+ std::net::UdpSocket::bind(addr)
469
+ .expect("a UDP socket binds")
470
+ .send_to(b"x", failed.local_addr().unwrap())
471
+ .expect("the datagram goes");
472
+ let mut told: Vec<_> = (0..2)
473
+ .filter_map(|_| rx.recv_timeout(Duration::from_secs(5)).ok())
474
+ .collect();
475
+ told.sort_unstable();
476
+ assert_eq!(
477
+ (told, reactor.stopped.load(Ordering::Acquire)),
478
+ (vec!["the socket", "the timer"], true),
479
+ "a reactor whose thread stops must abort each socket registered on it, wake each \
480
+ timer at once, and mark itself stopped so no later socket registers on it"
481
+ );
482
+ }
483
+
484
+ /// A socket that counts each turn it is given.
485
+ #[derive(Default)]
486
+ struct CountsTurns(AtomicUsize);
487
+
488
+ impl Ready for CountsTurns {
489
+ fn on_event(&self, _events: PollMask) {
490
+ self.0.fetch_add(1, Ordering::SeqCst);
491
+ }
492
+
493
+ fn abort(&self) {}
494
+ }
495
+
496
+ // A socket that spent its turn's bound waits for its next turn, and a
497
+ // signal interrupting the reactor's wait in between must not drop it:
498
+ // with no further event to come, it would wait until its deadline.
499
+ // @behavior NW-174
500
+ #[test]
501
+ fn a_repoll_runs_once_past_an_interrupted_wait() {
502
+ let poll = mio::Poll::new().expect("a poll opens");
503
+ let reactor = Reactor::on(&poll).expect("a reactor is made");
504
+ let counts = Arc::new(CountsTurns::default());
505
+ let ready: Arc<dyn Ready> = counts.clone();
506
+ reactor.repoll().push(Arc::downgrade(&ready));
507
+ // Interrupted, then a round with no event, then a failure that stops
508
+ // the thread.
509
+ let mut waits = [
510
+ Err(io::ErrorKind::Interrupted.into()),
511
+ Ok(()),
512
+ Err(io::ErrorKind::Other.into()),
513
+ ]
514
+ .into_iter();
515
+ reactor.run(|_, _| waits.next().expect("the reactor stopped at the failure"));
516
+ assert_eq!(
517
+ counts.0.load(Ordering::SeqCst),
518
+ 1,
519
+ "a socket asking for another turn must get it once in the round after a reactor \
520
+ wait a signal interrupted"
521
+ );
522
+ }
523
+
524
+ // A forked child shares its parent's epoll instance, where an inherited
525
+ // socket's `<fd, file>` entry stands once for both, so a child letting the
526
+ // socket go must leave the parent watching it.
527
+ // @behavior NW-232
528
+ #[test]
529
+ fn a_registration_made_in_another_process_stays_watched_once_let_go() {
530
+ let reactor = Reactor::current().expect("a reactor starts");
531
+ let (tx, rx) = mpsc::channel();
532
+ let ready: Arc<dyn Ready> = Arc::new(Tells(Mutex::new(tx)));
533
+ let addr = "127.0.0.1:0".parse().unwrap();
534
+ let mut socket = mio::net::UdpSocket::bind(addr).expect("a UDP socket binds");
535
+ let mut registration = reactor
536
+ .register(&mut socket, Arc::downgrade(&ready), false)
537
+ .expect("the socket registers");
538
+ while rx.recv_timeout(Duration::from_millis(50)).is_ok() {}
539
+ registration.pid = Pid::parent();
540
+ registration.deregister(&mut socket);
541
+ let sender = std::net::UdpSocket::bind(addr).expect("a UDP socket binds");
542
+ sender
543
+ .send_to(b"x", socket.local_addr().unwrap())
544
+ .expect("the datagram goes");
545
+ assert!(
546
+ rx.recv_timeout(Duration::from_secs(5)).is_ok(),
547
+ "a forked child letting go of a guest's socket its parent watches must leave the \
548
+ parent woken by that socket's events"
549
+ );
550
+ }
551
+
552
+ // A waker asked to be woken at an instant is woken once it passes, with
553
+ // nothing else waking it.
554
+ #[test]
555
+ fn a_timer_wakes_its_waker_once_due() {
556
+ let reactor = Reactor::current().expect("a reactor starts");
557
+ let (tx, rx) = mpsc::channel();
558
+ let _timer = reactor.wake_at(
559
+ Instant::now() + Duration::from_millis(50),
560
+ Waker::from(Arc::new(TellsWake(Mutex::new(tx)))),
561
+ );
562
+ assert!(
563
+ rx.recv_timeout(Duration::from_secs(5)).is_ok(),
564
+ "a waker the reactor was asked to wake at an instant must be woken once it passes"
565
+ );
566
+ }
567
+
568
+ // A waker asked to be woken again holds one timer, the newest, however
569
+ // often it asked before.
570
+ #[test]
571
+ fn a_waker_asking_again_holds_one_timer() {
572
+ let reactor = Reactor::current().expect("a reactor starts");
573
+ let waker = Waker::noop().clone();
574
+ let later = Instant::now() + Duration::from_secs(30);
575
+ let armed: Vec<Timer> = (0..3)
576
+ .map(|_| reactor.wake_at(later, waker.clone()))
577
+ .collect();
578
+ let held = timers_of(&reactor, &waker);
579
+ drop(armed);
580
+ assert_eq!(
581
+ (held, timers_of(&reactor, &waker)),
582
+ (1, 0),
583
+ "a waker asked to be woken three times must hold one timer, the newest, and none \
584
+ once its timers drop"
585
+ );
586
+ }
587
+
588
+ /// How many timers `reactor` holds for `waker`.
589
+ fn timers_of(reactor: &Reactor, waker: &Waker) -> usize {
590
+ reactor
591
+ .timers
592
+ .lock()
593
+ .unwrap()
594
+ .iter()
595
+ .filter(|(_, armed)| armed.will_wake(waker))
596
+ .count()
597
+ }
598
+
599
+ // A request cancelled while its timer is armed leaves no timer behind, so
600
+ // a guest dropping lookups never fills the reactor's timers.
601
+ #[test]
602
+ fn a_cancelled_request_leaves_no_timer() {
603
+ let reactor = Reactor::start().expect("a reactor starts");
604
+ let timing = reactor.clone();
605
+ let later = Instant::now() + Duration::from_secs(30);
606
+ let task = Task::new(
607
+ async move {
608
+ let mut timer = None;
609
+ std::future::poll_fn(|cx| {
610
+ timer.get_or_insert_with(|| timing.wake_at(later, cx.waker().clone()));
611
+ Poll::<()>::Pending
612
+ })
613
+ .await;
614
+ },
615
+ Arc::default(),
616
+ );
617
+ task.poll();
618
+ let held = reactor.timers.lock().unwrap().len();
619
+ task.cancel();
620
+ assert_eq!(
621
+ (held, reactor.timers.lock().unwrap().len()),
622
+ (1, 0),
623
+ "a cancelled lookup's timer must leave the reactor with the lookup, not stay until due"
624
+ );
625
+ }
626
+ }