raiha 0.1.0 → 0.2.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 (347) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +33 -0
  3. data/LICENSE +202 -0
  4. data/README.md +94 -22
  5. data/docs/configuration.md +227 -0
  6. data/docs/development.md +99 -0
  7. data/docs/fiber-scheduler.md +591 -0
  8. data/docs/getting-started.md +190 -0
  9. data/docs/http3-client.md +303 -0
  10. data/docs/http3-server.md +301 -0
  11. data/docs/platforms.md +98 -0
  12. data/docs/qlog.md +86 -0
  13. data/docs/quic.md +268 -0
  14. data/docs/threads.md +127 -0
  15. data/examples/_certificate.rb +55 -0
  16. data/examples/high_level_loopback.rb +59 -0
  17. data/examples/http3_get_public.rb +68 -0
  18. data/examples/in_memory_handshake.rb +38 -0
  19. data/examples/qlog_output.rb +58 -0
  20. data/examples/qlog_roundtrips.rb +66 -0
  21. data/examples/quic_gem_loopback.rb +62 -0
  22. data/examples/stream_echo.rb +68 -0
  23. data/examples/udp_handshake.rb +76 -0
  24. data/lib/raiha/http3/action.rb +21 -0
  25. data/lib/raiha/http3/capsule.rb +86 -0
  26. data/lib/raiha/http3/connection.rb +983 -0
  27. data/lib/raiha/http3/error.rb +24 -0
  28. data/lib/raiha/http3/error_code.rb +27 -0
  29. data/lib/raiha/http3/event.rb +63 -0
  30. data/lib/raiha/http3/frame.rb +148 -0
  31. data/lib/raiha/http3/frame_reader.rb +114 -0
  32. data/lib/raiha/http3/message.rb +137 -0
  33. data/lib/raiha/http3/output.rb +61 -0
  34. data/lib/raiha/http3/priority.rb +52 -0
  35. data/lib/raiha/http3/qlog.rb +145 -0
  36. data/lib/raiha/http3/qpack/decoder.rb +302 -0
  37. data/lib/raiha/http3/qpack/dynamic_table.rb +83 -0
  38. data/lib/raiha/http3/qpack/encoder.rb +94 -0
  39. data/lib/raiha/http3/qpack/error.rb +39 -0
  40. data/lib/raiha/http3/qpack/error_code.rb +13 -0
  41. data/lib/raiha/http3/qpack/field.rb +15 -0
  42. data/lib/raiha/http3/qpack/huffman.rb +397 -0
  43. data/lib/raiha/http3/qpack/reader.rb +82 -0
  44. data/lib/raiha/http3/qpack/result.rb +26 -0
  45. data/lib/raiha/http3/qpack/static_table.rb +139 -0
  46. data/lib/raiha/http3/qpack/writer.rb +44 -0
  47. data/lib/raiha/http3/qpack.rb +26 -0
  48. data/lib/raiha/http3/receiving.rb +46 -0
  49. data/lib/raiha/http3/sending.rb +23 -0
  50. data/lib/raiha/http3/session.rb +31 -0
  51. data/lib/raiha/http3/settings.rb +81 -0
  52. data/lib/raiha/http3/structured_field.rb +120 -0
  53. data/lib/raiha/http3/tracer.rb +26 -0
  54. data/lib/raiha/http3/varint.rb +45 -0
  55. data/lib/raiha/http3.rb +19 -0
  56. data/lib/raiha/http3_binding.rb +139 -0
  57. data/lib/raiha/namespace.rb +11 -0
  58. data/lib/raiha/quic/config.rb +229 -0
  59. data/lib/raiha/quic/congestion/algorithms.rb +17 -0
  60. data/lib/raiha/quic/congestion/cubic.rb +258 -0
  61. data/lib/raiha/quic/congestion/new_reno.rb +161 -0
  62. data/lib/raiha/quic/congestion/pacing.rb +21 -0
  63. data/lib/raiha/quic/congestion/startup/rapid_start.rb +249 -0
  64. data/lib/raiha/quic/congestion/startup.rb +13 -0
  65. data/lib/raiha/quic/congestion.rb +15 -0
  66. data/lib/raiha/quic/connection.rb +2022 -0
  67. data/lib/raiha/quic/connection_ids.rb +62 -0
  68. data/lib/raiha/quic/crypto/aead.rb +68 -0
  69. data/lib/raiha/quic/crypto/header_protection.rb +42 -0
  70. data/lib/raiha/quic/crypto/initial.rb +23 -0
  71. data/lib/raiha/quic/crypto/keys.rb +32 -0
  72. data/lib/raiha/quic/crypto/mac.rb +15 -0
  73. data/lib/raiha/quic/crypto/random.rb +13 -0
  74. data/lib/raiha/quic/crypto.rb +18 -0
  75. data/lib/raiha/quic/crypto_stream.rb +161 -0
  76. data/lib/raiha/quic/datagrams.rb +91 -0
  77. data/lib/raiha/quic/endpoint.rb +785 -0
  78. data/lib/raiha/quic/error.rb +61 -0
  79. data/lib/raiha/quic/error_code.rb +34 -0
  80. data/lib/raiha/quic/event.rb +59 -0
  81. data/lib/raiha/quic/issued_connection_ids.rb +137 -0
  82. data/lib/raiha/quic/kept_packets.rb +41 -0
  83. data/lib/raiha/quic/mtu_search.rb +75 -0
  84. data/lib/raiha/quic/negotiation.rb +143 -0
  85. data/lib/raiha/quic/new_token.rb +55 -0
  86. data/lib/raiha/quic/pacer.rb +52 -0
  87. data/lib/raiha/quic/packet_protection.rb +310 -0
  88. data/lib/raiha/quic/path.rb +473 -0
  89. data/lib/raiha/quic/peer_connection_ids.rb +160 -0
  90. data/lib/raiha/quic/qlog.rb +260 -0
  91. data/lib/raiha/quic/ranges.rb +32 -0
  92. data/lib/raiha/quic/recovery/duty.rb +102 -0
  93. data/lib/raiha/quic/recovery/packet_number_space.rb +420 -0
  94. data/lib/raiha/quic/recovery/rate_meter.rb +95 -0
  95. data/lib/raiha/quic/recovery/rtt_estimator.rb +57 -0
  96. data/lib/raiha/quic/recovery/sent_packet.rb +16 -0
  97. data/lib/raiha/quic/recovery.rb +641 -0
  98. data/lib/raiha/quic/remembered_transport_parameters.rb +29 -0
  99. data/lib/raiha/quic/retry_token.rb +54 -0
  100. data/lib/raiha/quic/route.rb +37 -0
  101. data/lib/raiha/quic/scheduler.rb +112 -0
  102. data/lib/raiha/quic/session.rb +47 -0
  103. data/lib/raiha/quic/stateless_reset.rb +38 -0
  104. data/lib/raiha/quic/stats.rb +24 -0
  105. data/lib/raiha/quic/streams/receive_window.rb +119 -0
  106. data/lib/raiha/quic/streams/receiver.rb +217 -0
  107. data/lib/raiha/quic/streams/sender.rb +200 -0
  108. data/lib/raiha/quic/streams.rb +687 -0
  109. data/lib/raiha/quic/test/bottleneck.rb +55 -0
  110. data/lib/raiha/quic/test/congestion_contract.rb +106 -0
  111. data/lib/raiha/quic/test/network.rb +244 -0
  112. data/lib/raiha/quic/test/random_loss.rb +34 -0
  113. data/lib/raiha/quic/test/reorder.rb +51 -0
  114. data/lib/raiha/quic/test/server.rb +54 -0
  115. data/lib/raiha/quic/test/vectors.rb +337 -0
  116. data/lib/raiha/quic/test/virtual_clock.rb +21 -0
  117. data/lib/raiha/quic/test.rb +17 -0
  118. data/lib/raiha/quic/tls_binding.rb +179 -0
  119. data/lib/raiha/quic/token.rb +28 -0
  120. data/lib/raiha/quic/tracer.rb +127 -0
  121. data/lib/raiha/quic/transmit.rb +14 -0
  122. data/lib/raiha/quic/transport_parameters.rb +244 -0
  123. data/lib/raiha/quic/version.rb +63 -0
  124. data/lib/raiha/quic/wire/codec.rb +136 -0
  125. data/lib/raiha/quic/wire/frame.rb +521 -0
  126. data/lib/raiha/quic/wire/header.rb +90 -0
  127. data/lib/raiha/quic/wire/packet.rb +130 -0
  128. data/lib/raiha/quic/wire/packet_number.rb +47 -0
  129. data/lib/raiha/quic/wire/retry.rb +62 -0
  130. data/lib/raiha/quic/wire/version_negotiation.rb +53 -0
  131. data/lib/raiha/quic/wire.rb +9 -0
  132. data/lib/raiha/quic.rb +46 -0
  133. data/lib/raiha/runtime/addresses.rb +35 -0
  134. data/lib/raiha/runtime/admission.rb +37 -0
  135. data/lib/raiha/runtime/client.rb +190 -0
  136. data/lib/raiha/runtime/driver.rb +165 -0
  137. data/lib/raiha/runtime/error.rb +16 -0
  138. data/lib/raiha/runtime/http3.rb +363 -0
  139. data/lib/raiha/runtime/http3_fields.rb +38 -0
  140. data/lib/raiha/runtime/http3_server.rb +416 -0
  141. data/lib/raiha/runtime/kept.rb +36 -0
  142. data/lib/raiha/runtime/qlog.rb +204 -0
  143. data/lib/raiha/runtime/rack.rb +180 -0
  144. data/lib/raiha/runtime/server.rb +334 -0
  145. data/lib/raiha/runtime/session.rb +447 -0
  146. data/lib/raiha/runtime/threaded/client.rb +161 -0
  147. data/lib/raiha/runtime/threaded/driver.rb +230 -0
  148. data/lib/raiha/runtime/threaded/http3.rb +287 -0
  149. data/lib/raiha/runtime/threaded/http3_server.rb +432 -0
  150. data/lib/raiha/runtime/threaded/server.rb +290 -0
  151. data/lib/raiha/runtime/threaded/session.rb +604 -0
  152. data/lib/raiha/runtime/threaded.rb +45 -0
  153. data/lib/raiha/runtime/udp.rb +410 -0
  154. data/lib/raiha/runtime/worker.rb +138 -0
  155. data/lib/raiha/runtime/workers.rb +248 -0
  156. data/lib/raiha/runtime.rb +37 -0
  157. data/lib/raiha/tls/anti_replay.rb +139 -0
  158. data/lib/raiha/tls/cipher_suite.rb +62 -0
  159. data/lib/raiha/tls/codec/error.rb +43 -0
  160. data/lib/raiha/tls/codec/reader.rb +95 -0
  161. data/lib/raiha/tls/codec/writer.rb +81 -0
  162. data/lib/raiha/tls/codec.rb +5 -0
  163. data/lib/raiha/tls/config.rb +318 -0
  164. data/lib/raiha/tls/crypto/aead.rb +64 -0
  165. data/lib/raiha/tls/crypto/certificate.rb +28 -0
  166. data/lib/raiha/tls/crypto/digest.rb +30 -0
  167. data/lib/raiha/tls/crypto/ecdh.rb +74 -0
  168. data/lib/raiha/tls/crypto/hash.rb +22 -0
  169. data/lib/raiha/tls/crypto/hkdf.rb +28 -0
  170. data/lib/raiha/tls/crypto/signature.rb +87 -0
  171. data/lib/raiha/tls/crypto.rb +19 -0
  172. data/lib/raiha/tls/error.rb +36 -0
  173. data/lib/raiha/tls/event.rb +45 -0
  174. data/lib/raiha/tls/extension/alpn.rb +35 -0
  175. data/lib/raiha/tls/extension/certificate_authorities.rb +35 -0
  176. data/lib/raiha/tls/extension/compress_certificate.rb +33 -0
  177. data/lib/raiha/tls/extension/cookie.rb +27 -0
  178. data/lib/raiha/tls/extension/early_data.rb +54 -0
  179. data/lib/raiha/tls/extension/key_share.rb +90 -0
  180. data/lib/raiha/tls/extension/list.rb +49 -0
  181. data/lib/raiha/tls/extension/opaque.rb +21 -0
  182. data/lib/raiha/tls/extension/placement.rb +55 -0
  183. data/lib/raiha/tls/extension/post_handshake_auth.rb +22 -0
  184. data/lib/raiha/tls/extension/pre_shared_key.rb +81 -0
  185. data/lib/raiha/tls/extension/psk_key_exchange_modes.rb +32 -0
  186. data/lib/raiha/tls/extension/record_size_limit.rb +30 -0
  187. data/lib/raiha/tls/extension/registry.rb +50 -0
  188. data/lib/raiha/tls/extension/server_name.rb +63 -0
  189. data/lib/raiha/tls/extension/signature_algorithms.rb +39 -0
  190. data/lib/raiha/tls/extension/signature_algorithms_cert.rb +21 -0
  191. data/lib/raiha/tls/extension/supported_groups.rb +32 -0
  192. data/lib/raiha/tls/extension/supported_versions.rb +53 -0
  193. data/lib/raiha/tls/extension.rb +32 -0
  194. data/lib/raiha/tls/handshake/acceptor.rb +164 -0
  195. data/lib/raiha/tls/handshake/authentication_messages.rb +127 -0
  196. data/lib/raiha/tls/handshake/certificate.rb +56 -0
  197. data/lib/raiha/tls/handshake/certificate_request.rb +39 -0
  198. data/lib/raiha/tls/handshake/certificate_verify.rb +40 -0
  199. data/lib/raiha/tls/handshake/client_hello.rb +208 -0
  200. data/lib/raiha/tls/handshake/client_hello_builder.rb +144 -0
  201. data/lib/raiha/tls/handshake/client_side.rb +578 -0
  202. data/lib/raiha/tls/handshake/conductor.rb +390 -0
  203. data/lib/raiha/tls/handshake/encrypted_extensions.rb +33 -0
  204. data/lib/raiha/tls/handshake/end_of_early_data.rb +28 -0
  205. data/lib/raiha/tls/handshake/finished.rb +36 -0
  206. data/lib/raiha/tls/handshake/key_update.rb +38 -0
  207. data/lib/raiha/tls/handshake/key_update_handling.rb +88 -0
  208. data/lib/raiha/tls/handshake/machine.rb +238 -0
  209. data/lib/raiha/tls/handshake/message.rb +25 -0
  210. data/lib/raiha/tls/handshake/new_session_ticket.rb +48 -0
  211. data/lib/raiha/tls/handshake/reassembler.rb +88 -0
  212. data/lib/raiha/tls/handshake/server_hello.rb +98 -0
  213. data/lib/raiha/tls/handshake/server_side.rb +672 -0
  214. data/lib/raiha/tls/handshake/violation.rb +12 -0
  215. data/lib/raiha/tls/handshake.rb +62 -0
  216. data/lib/raiha/tls/iana.rb +113 -0
  217. data/lib/raiha/tls/key_exchange.rb +58 -0
  218. data/lib/raiha/tls/key_schedule.rb +269 -0
  219. data/lib/raiha/tls/keylog.rb +40 -0
  220. data/lib/raiha/tls/keyring.rb +180 -0
  221. data/lib/raiha/tls/masked_inspect.rb +33 -0
  222. data/lib/raiha/tls/output.rb +32 -0
  223. data/lib/raiha/tls/profile.rb +82 -0
  224. data/lib/raiha/tls/record/layer.rb +228 -0
  225. data/lib/raiha/tls/record/protection.rb +67 -0
  226. data/lib/raiha/tls/record.rb +11 -0
  227. data/lib/raiha/tls/server_name.rb +42 -0
  228. data/lib/raiha/tls/session.rb +106 -0
  229. data/lib/raiha/tls/signature_scheme.rb +35 -0
  230. data/lib/raiha/tls/tcp/acceptor.rb +121 -0
  231. data/lib/raiha/tls/tcp/connection.rb +371 -0
  232. data/lib/raiha/tls/tcp/event.rb +15 -0
  233. data/lib/raiha/tls/tcp/socket.rb +161 -0
  234. data/lib/raiha/tls/tcp.rb +14 -0
  235. data/lib/raiha/tls/test/fixed_kem.rb +30 -0
  236. data/lib/raiha/tls/test/fixed_random.rb +18 -0
  237. data/lib/raiha/tls/test/rfc8448.rb +923 -0
  238. data/lib/raiha/tls/test/rfc8448_handshakes.rb +118 -0
  239. data/lib/raiha/tls/test.rb +13 -0
  240. data/lib/raiha/tls/ticket.rb +184 -0
  241. data/lib/raiha/tls/ticket_keys.rb +206 -0
  242. data/lib/raiha/tls/trace.rb +58 -0
  243. data/lib/raiha/tls/transcript.rb +94 -0
  244. data/lib/raiha/tls/verifier/default.rb +72 -0
  245. data/lib/raiha/tls/verifier/host_name.rb +75 -0
  246. data/lib/raiha/tls/verifier/none.rb +14 -0
  247. data/lib/raiha/tls/verifier.rb +24 -0
  248. data/lib/raiha/tls.rb +34 -0
  249. data/lib/raiha/version.rb +3 -1
  250. data/lib/raiha.rb +8 -5
  251. data/sig/patches/array.rbs +9 -0
  252. data/sig/patches/io_buffer.rbs +13 -0
  253. data/sig/patches/openssl.rbs +25 -0
  254. data/sig/patches/socket.rbs +29 -0
  255. data/sig/patches/string.rbs +26 -0
  256. data/sig/patches/strscan.rbs +12 -0
  257. data/sig/raiha/http3/capsule.rbs +32 -0
  258. data/sig/raiha/http3/connection.rbs +324 -0
  259. data/sig/raiha/http3/frame.rbs +138 -0
  260. data/sig/raiha/http3/frame_reader.rbs +39 -0
  261. data/sig/raiha/http3/message.rbs +23 -0
  262. data/sig/raiha/http3/priority.rbs +40 -0
  263. data/sig/raiha/http3/qlog.rbs +54 -0
  264. data/sig/raiha/http3/qpack.rbs +246 -0
  265. data/sig/raiha/http3/session.rbs +11 -0
  266. data/sig/raiha/http3/settings.rbs +26 -0
  267. data/sig/raiha/http3.rbs +2 -0
  268. data/sig/raiha/http3_binding.rbs +26 -0
  269. data/sig/raiha/namespace.rbs +2 -0
  270. data/sig/raiha/quic/config.rbs +89 -0
  271. data/sig/raiha/quic/congestion.rbs +213 -0
  272. data/sig/raiha/quic/connection.rbs +249 -0
  273. data/sig/raiha/quic/connection_ids.rbs +34 -0
  274. data/sig/raiha/quic/crypto.rbs +78 -0
  275. data/sig/raiha/quic/crypto_stream.rbs +34 -0
  276. data/sig/raiha/quic/datagrams.rbs +32 -0
  277. data/sig/raiha/quic/endpoint.rbs +179 -0
  278. data/sig/raiha/quic/frame.rbs +387 -0
  279. data/sig/raiha/quic/issued_connection_ids.rbs +47 -0
  280. data/sig/raiha/quic/kept_packets.rbs +25 -0
  281. data/sig/raiha/quic/mtu_search.rbs +21 -0
  282. data/sig/raiha/quic/negotiation.rbs +33 -0
  283. data/sig/raiha/quic/new_token.rbs +14 -0
  284. data/sig/raiha/quic/pacer.rbs +16 -0
  285. data/sig/raiha/quic/packet_protection.rbs +63 -0
  286. data/sig/raiha/quic/path.rbs +106 -0
  287. data/sig/raiha/quic/peer_connection_ids.rbs +42 -0
  288. data/sig/raiha/quic/qlog.rbs +74 -0
  289. data/sig/raiha/quic/ranges.rbs +7 -0
  290. data/sig/raiha/quic/recovery.rbs +376 -0
  291. data/sig/raiha/quic/retry_token.rbs +21 -0
  292. data/sig/raiha/quic/route.rbs +51 -0
  293. data/sig/raiha/quic/scheduler.rbs +36 -0
  294. data/sig/raiha/quic/session.rbs +17 -0
  295. data/sig/raiha/quic/stateless_reset.rbs +10 -0
  296. data/sig/raiha/quic/streams.rbs +244 -0
  297. data/sig/raiha/quic/test.rbs +354 -0
  298. data/sig/raiha/quic/tls_binding.rbs +58 -0
  299. data/sig/raiha/quic/token.rbs +11 -0
  300. data/sig/raiha/quic/tracer.rbs +71 -0
  301. data/sig/raiha/quic/transport_parameters.rbs +113 -0
  302. data/sig/raiha/quic/values.rbs +200 -0
  303. data/sig/raiha/quic/version.rbs +30 -0
  304. data/sig/raiha/quic/wire.rbs +199 -0
  305. data/sig/raiha/quic.rbs +2 -0
  306. data/sig/raiha/runtime/threaded.rbs +616 -0
  307. data/sig/raiha/runtime.rbs +982 -0
  308. data/sig/raiha/tls/anti_replay.rbs +41 -0
  309. data/sig/raiha/tls/cipher_suite.rbs +41 -0
  310. data/sig/raiha/tls/codec.rbs +66 -0
  311. data/sig/raiha/tls/config.rbs +122 -0
  312. data/sig/raiha/tls/crypto.rbs +86 -0
  313. data/sig/raiha/tls/error.rbs +21 -0
  314. data/sig/raiha/tls/event.rbs +61 -0
  315. data/sig/raiha/tls/extension.rbs +331 -0
  316. data/sig/raiha/tls/handshake.rbs +311 -0
  317. data/sig/raiha/tls/iana.rbs +13 -0
  318. data/sig/raiha/tls/key_exchange.rbs +33 -0
  319. data/sig/raiha/tls/key_schedule.rbs +58 -0
  320. data/sig/raiha/tls/keylog.rbs +20 -0
  321. data/sig/raiha/tls/keyring.rbs +64 -0
  322. data/sig/raiha/tls/machine.rbs +429 -0
  323. data/sig/raiha/tls/masked_inspect.rbs +12 -0
  324. data/sig/raiha/tls/output.rbs +37 -0
  325. data/sig/raiha/tls/profile.rbs +26 -0
  326. data/sig/raiha/tls/record.rbs +79 -0
  327. data/sig/raiha/tls/server_name.rbs +10 -0
  328. data/sig/raiha/tls/session.rbs +48 -0
  329. data/sig/raiha/tls/signature_scheme.rbs +20 -0
  330. data/sig/raiha/tls/tcp.rbs +134 -0
  331. data/sig/raiha/tls/test.rbs +143 -0
  332. data/sig/raiha/tls/ticket.rbs +68 -0
  333. data/sig/raiha/tls/ticket_keys.rbs +67 -0
  334. data/sig/raiha/tls/trace.rbs +99 -0
  335. data/sig/raiha/tls/transcript.rbs +22 -0
  336. data/sig/raiha/tls/verifier.rbs +54 -0
  337. data/sig/raiha/tls.rbs +5 -0
  338. data/sig/raiha.rbs +3 -0
  339. metadata +355 -57
  340. data/.gitignore +0 -10
  341. data/CODE_OF_CONDUCT.md +0 -74
  342. data/Gemfile +0 -4
  343. data/Gemfile.lock +0 -22
  344. data/Rakefile +0 -10
  345. data/bin/console +0 -14
  346. data/bin/setup +0 -8
  347. data/raiha.gemspec +0 -40
@@ -0,0 +1,410 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "socket"
4
+
5
+ module Raiha::Runtime
6
+ # A UDP socket that carries QUIC: the datagrams of a Transmit go out, on
7
+ # Linux, in one `sendmsg` that the kernel cuts at the segment size (GSO,
8
+ # UDP_SEGMENT), elsewhere each with its own, marked with its ECN
9
+ # codepoint; each datagram that comes in is read with `recvmsg` along with
10
+ # the codepoint it was marked with and the address it came to (IP_PKTINFO,
11
+ # or IP_RECVDSTADDR on the BSDs, and IPV6_PKTINFO), so far as the OS
12
+ # tells them (UDP#features), and one sent from an address of the
13
+ # Transmit's goes from there by a control message too. Bound to "::",
14
+ # one socket takes IPv4 as well where the OS lets it (not OpenBSD); the
15
+ # addresses of IPv4 it tells are IPv4's ("192.0.2.1", not the IPv4-mapped
16
+ # "::ffff:192.0.2.1"), so that a peer is the same address whichever
17
+ # socket it came on, and it maps them back to send.
18
+ #
19
+ # On Linux, IP fragments nothing it sends and the kernel's idea of the
20
+ # path MTU is left aside (PMTUDISC_PROBE), so that a probe for a larger
21
+ # datagram is lost or refused (EMSGSIZE) rather than pass in pieces;
22
+ # elsewhere, the runtime sends no probe (UDP.pmtud).
23
+ #
24
+ # Where the kernel will not cut them, a path with no checksum offload
25
+ # (EIO, as ns-3's simulator has it) or a kernel without UDP_SEGMENT
26
+ # (ENOPROTOOPT), the datagrams go one by one and the socket no longer
27
+ # tries; it gives up on EINVAL or EMSGSIZE too, unless one by one they
28
+ # fail all the same, when the destination is at fault, not GSO.
29
+ class UDP
30
+ # The most datagrams taken from the socket at once.
31
+ RECEIVE_BATCH = 64
32
+ # The largest datagram UDP carries.
33
+ MAX_DATAGRAM = 65_535
34
+ # The Linux default for the buffers (about 212 KB) is too small for a
35
+ # burst: the kernel drops what overflows before it is read. Linux cuts
36
+ # a larger size down to its limit; OpenBSD refuses one over its limit
37
+ # (2 MiB) with ENOBUFS, and the socket asks for half as much, and half
38
+ # again, while it is more than the buffer has.
39
+ BUFFER = 8 * 1024 * 1024
40
+ # The low two bits of the traffic class, the ECN field (RFC 3168).
41
+ ECN = { 0b00 => :not_ect, 0b01 => :ect1, 0b10 => :ect0, 0b11 => :ce }.freeze
42
+ MARKS = { ect0: 0b10, ect1: 0b01 }.freeze
43
+ # A peer gone or a datagram too big for the path is no reason to stop,
44
+ # nor an address the OS will not send to, as port 0 (EINVAL), a
45
+ # broadcast (EACCES) or one of a family the socket does not send to
46
+ # (EAFNOSUPPORT): a peer that spoofs its source chooses where the
47
+ # responses of an Endpoint go. A firewall that refuses (EPERM) or a
48
+ # kernel short of buffers (ENOBUFS) loses one datagram.
49
+ DROPPED = [Errno::ECONNREFUSED, Errno::EMSGSIZE, Errno::ENETUNREACH, Errno::EHOSTUNREACH, Errno::EADDRNOTAVAIL,
50
+ Errno::EINVAL, Errno::EACCES, Errno::EPERM, Errno::ENOBUFS, Errno::EAFNOSUPPORT].freeze
51
+ # Linux's UDP_SEGMENT, a control message at the level of UDP, which
52
+ # Socket does not name.
53
+ UDP_SEGMENT = 103
54
+ # Linux's IP_PMTUDISC_PROBE and IPV6_PMTUDISC_PROBE, which Socket does
55
+ # not name either.
56
+ PMTUDISC_PROBE = 3
57
+ # What GSO refuses with; the first two say it never works here.
58
+ GSO_REFUSED = [Errno::EIO, Errno::ENOPROTOOPT, Errno::EINVAL, Errno::EMSGSIZE].freeze
59
+ GSO_UNAVAILABLE = [Errno::EIO, Errno::ENOPROTOOPT].freeze
60
+ # What sendmsg refuses a control message it does not take with; the
61
+ # datagram goes again without it (UDP#without_controls), which is left
62
+ # out for good unless it was EINVAL.
63
+ CONTROLS_REFUSED = [Errno::EINVAL, Errno::ENOPROTOOPT, Errno::EOPNOTSUPP].freeze
64
+ # The most a Transmit carries for GSO: the largest UDP payload over
65
+ # IPv4, a Config's max_transmit_size when the application leaves it.
66
+ MAX_TRANSMIT = 65_507
67
+
68
+ # What a socket has here: the sizes of its buffers as the OS keeps
69
+ # them, whether it takes IPv4, and the control messages it uses now,
70
+ # those it reads (the ECN codepoint and the address a datagram came
71
+ # to) and those it sends (the address and the ECN mark a datagram goes
72
+ # with). The runtime logs none of this; it is there to look at a socket
73
+ # on an OS that differs.
74
+ Features = Data.define(:receive_buffer, :send_buffer, :ipv4, :ecn_in, :destination, :source, :ecn_out)
75
+
76
+ # `config` with MAX_TRANSMIT for max_transmit_size, unless it has one:
77
+ # a socket here sends the datagrams of a Transmit as they are cut.
78
+ def self.batching(config) = config.max_transmit_size ? config : config.with(max_transmit_size: MAX_TRANSMIT)
79
+
80
+ # Whether a socket here keeps IP from fragmenting what it sends.
81
+ def self.unfragmented? = RUBY_PLATFORM.include?("linux") && Socket.const_defined?(:IP_MTU_DISCOVER) &&
82
+ Socket.const_defined?(:IPV6_MTU_DISCOVER)
83
+
84
+ # `config` with enable_pmtud false where a socket cannot keep IP from
85
+ # fragmenting, so that no probe passes in pieces.
86
+ def self.pmtud(config) = unfragmented? || !config.enable_pmtud ? config : config.with(enable_pmtud: false)
87
+
88
+ # `config` without ECN on IPv4 where the OS has no IP_RECVTOS, so that
89
+ # QUIC sends Not-ECT there: such an OS, OpenBSD, also skips an IP_TOS
90
+ # control message without a word, and QUIC would take what it sent for
91
+ # ECT(0).
92
+ def self.ecn(config)
93
+ return config if Socket.const_defined?(:IP_RECVTOS)
94
+ config.with(ecn_address_families: config.ecn_address_families - %i[ipv4])
95
+ end
96
+
97
+ # A socket bound to `host` and `port` (0 for one the OS chooses); with
98
+ # `reuse_port`, one of several that share the address (UDP.open).
99
+ def self.bind(host, port, reuse_port: false) = new(open(host, port, reuse_port:))
100
+
101
+ # A plain UDPSocket bound to `host` and `port`, as `bind` wraps, which
102
+ # can be moved to another Ractor and wrapped there. With `reuse_port`
103
+ # (SO_REUSEPORT, set before binding), other sockets with it may bind
104
+ # the same address, and the kernel gives each the datagrams of some
105
+ # 4-tuples, as the workers of a server take theirs.
106
+ def self.open(host, port, reuse_port: false)
107
+ family = Addrinfo.udp(host, port).afamily
108
+ socket = UDPSocket.new(family)
109
+ if family == Socket::AF_INET6
110
+ begin
111
+ socket.setsockopt(Socket::IPPROTO_IPV6, Socket::IPV6_V6ONLY, 0)
112
+ rescue Errno::EINVAL, Errno::ENOPROTOOPT
113
+ # OpenBSD's IPv6 sockets are IPv6's alone (ip6(4)), and the socket
114
+ # takes no IPv4 (UDP.takes_ipv4?).
115
+ end
116
+ end
117
+ socket.setsockopt(Socket::SOL_SOCKET, Socket::SO_REUSEPORT, 1) if reuse_port
118
+ socket.bind(host, port)
119
+ socket
120
+ rescue StandardError
121
+ socket&.close
122
+ raise
123
+ end
124
+
125
+ def initialize(socket)
126
+ @socket = socket
127
+ local = socket.local_address
128
+ @family = local.afamily
129
+ @port = local.ip_port
130
+ enlarge(Socket::SO_RCVBUF)
131
+ enlarge(Socket::SO_SNDBUF)
132
+ # What a datagram comes with, at both levels on a socket that takes
133
+ # both, the options Socket names here alone: an IPv6 socket that
134
+ # takes IPv4 tells the codepoint and the address of an IPv4 datagram
135
+ # the IPv4 way. The IPv4 options go only on a socket that takes IPv4,
136
+ # as OpenBSD's IPv6 sockets refuse them (EINVAL). Its IPv4 has no
137
+ # IP_RECVTOS, and IP_RECVDSTADDR in place of IP_PKTINFO.
138
+ ipv4 = takes_ipv4?
139
+ ipv6 = @family == Socket::AF_INET6
140
+ @ipv4_destination = if !ipv4 then nil
141
+ elsif enable(Socket::IPPROTO_IP, :IP_PKTINFO) then Socket::IP_PKTINFO
142
+ elsif enable(Socket::IPPROTO_IP, :IP_RECVDSTADDR) then Socket::IP_RECVDSTADDR
143
+ end
144
+ ipv6_destination = ipv6 && enable(Socket::IPPROTO_IPV6, :IPV6_RECVPKTINFO)
145
+ ipv4_ecn = ipv4 && enable(Socket::IPPROTO_IP, :IP_RECVTOS)
146
+ ipv6_ecn = ipv6 && enable(Socket::IPPROTO_IPV6, :IPV6_RECVTCLASS)
147
+ @destination = (!ipv4 || !@ipv4_destination.nil?) && (!ipv6 || ipv6_destination)
148
+ @ecn_in = (!ipv4 || ipv4_ecn) && (!ipv6 || ipv6_ecn)
149
+ # No fragments, at both levels on a socket that sends both.
150
+ if UDP.unfragmented?
151
+ @socket.setsockopt(Socket::IPPROTO_IP, Socket::IP_MTU_DISCOVER, PMTUDISC_PROBE)
152
+ @socket.setsockopt(Socket::IPPROTO_IPV6, Socket::IPV6_MTU_DISCOVER, PMTUDISC_PROBE) if @family == Socket::AF_INET6
153
+ end
154
+ @gso = RUBY_PLATFORM.include?("linux")
155
+ @stripped = false
156
+ # The control messages a datagram goes with: the ECN mark of IPv4
157
+ # only where the codepoint is read too (UDP.ecn), and the source of
158
+ # IPv4 by IP_PKTINFO or else IP_SENDSRCADDR. A kind sendmsg refuses
159
+ # is left out for good (without_controls).
160
+ @sends = { tos: ipv4 && Socket.const_defined?(:IP_RECVTOS), tclass: ipv6,
161
+ ip_source: ipv4 && (Socket.const_defined?(:IP_PKTINFO) || Socket.const_defined?(:IP_SENDSRCADDR)),
162
+ ipv6_source: ipv6 }
163
+ end
164
+
165
+ # The Features of this socket now.
166
+ def features
167
+ Features.new(receive_buffer: @socket.getsockopt(Socket::SOL_SOCKET, Socket::SO_RCVBUF).int,
168
+ send_buffer: @socket.getsockopt(Socket::SOL_SOCKET, Socket::SO_SNDBUF).int, ipv4: takes_ipv4?,
169
+ ecn_in: @ecn_in, destination: @destination, source: @sends[@family == Socket::AF_INET6 ? :ipv6_source : :ip_source],
170
+ ecn_out: (!takes_ipv4? || @sends[:tos]) && (@family != Socket::AF_INET6 || @sends[:tclass]))
171
+ end
172
+
173
+ # [address, port] the socket is bound to.
174
+ def local_address
175
+ address = @socket.local_address
176
+ [address.ip_address, address.ip_port]
177
+ end
178
+
179
+ # Whether a datagram from `address` ([address, port]) goes from this
180
+ # socket: the port is the socket's, and so is the address, or the
181
+ # socket is bound to any of its family, IPv4 too for "::" where IPv4
182
+ # comes to it.
183
+ def sends_from?(address) = UDP.covers?(@socket, address)
184
+
185
+ # Whether `socket`, a socket wrapped or not yet, sends from `address`,
186
+ # as `sends_from?` tells of one.
187
+ def self.covers?(socket, address)
188
+ host, port = address
189
+ bound = socket.local_address
190
+ return false unless port == bound.ip_port
191
+ return host.include?(":") || takes_ipv4?(socket) if bound.ipv6? && bound.ipv6_unspecified?
192
+ return !host.include?(":") if bound.ip_address == "0.0.0.0"
193
+ UDP.unmapped(bound.ip_address) == host
194
+ end
195
+
196
+ # Whether IPv4 comes to this socket (UDP.takes_ipv4?).
197
+ def takes_ipv4? = UDP.takes_ipv4?(@socket)
198
+
199
+ # Sends each datagram of `transmit`; whether all of them went. The ECN
200
+ # mark of an IPv4 destination, IPv4-mapped included, goes as IP_TOS:
201
+ # Linux leaves IPV6_TCLASS off a datagram that leaves as IPv4. The
202
+ # Transmit's source, when it has one, is the address the datagrams go
203
+ # from; the port is the socket's. When GSO
204
+ # fails, the datagrams go one by one, each lost alone; GSO goes for
205
+ # good when it is unavailable here, or when it refused what went one by
206
+ # one, so that the fault was not the destination's.
207
+ def send(transmit)
208
+ host, port = transmit.destination
209
+ host = mapped(host)
210
+ destination = Socket.sockaddr_in(port, host)
211
+ controls = [mark(transmit.ecn, host), source(transmit.source)].compact
212
+ size = transmit.segment_size
213
+ if @gso && size && size < transmit.payload.bytesize
214
+ failed = send_segments(transmit.payload, size, destination, controls.map(&:last))
215
+ return true unless failed
216
+ end
217
+ @stripped = false
218
+ sent = datagrams(transmit).map { |datagram| send_datagram(datagram, destination, controls) }
219
+ # A control message the datagrams went without was at fault, not GSO.
220
+ if failed && GSO_REFUSED.any? { failed.is_a?(_1) } && !@stripped
221
+ @gso = false if sent.any? || GSO_UNAVAILABLE.any? { failed.is_a?(_1) }
222
+ end
223
+ sent.all?
224
+ end
225
+
226
+ # The datagrams there now, RECEIVE_BATCH at most, each as [data,
227
+ # [address, port] it came from, [address, port] it came to, ecn]; the
228
+ # address it came to is nil where the OS does not tell it. None when
229
+ # there are none.
230
+ def receive
231
+ received = [] #: Array[[String, address, address?, ecn]]
232
+ while received.size < RECEIVE_BATCH
233
+ result = @socket.recvmsg_nonblock(MAX_DATAGRAM, 0, exception: false)
234
+ break unless result.is_a?(Array)
235
+ data, from = result
236
+ # The control messages follow the flags one by one, not as an Array
237
+ # as the bundled declaration has it.
238
+ controls = result.drop(3) #: Array[Socket::AncillaryData]
239
+ received << [data, [unmapped(from.ip_address), from.ip_port], destination(controls), ecn(controls)]
240
+ end
241
+ received
242
+ rescue *DROPPED
243
+ received || []
244
+ end
245
+
246
+ # Waits until a datagram is there or `timeout` seconds have gone
247
+ # (forever when nil); whether one is there. Under a Fiber scheduler only
248
+ # the fiber waits.
249
+ def wait_readable(timeout = nil) = @socket.wait_readable(timeout) ? true : false
250
+
251
+ def close = @socket.close
252
+
253
+ def closed? = @socket.closed?
254
+
255
+ # The socket, so that IO.select waits on this with others, as a loop of
256
+ # an application's own that reads several does.
257
+ def to_io = @socket
258
+
259
+ # Sets the buffer `option` to BUFFER, or to the most of its halves the
260
+ # OS takes; never less than the buffer has.
261
+ private def enlarge(option)
262
+ size = BUFFER
263
+ default = @socket.getsockopt(Socket::SOL_SOCKET, option).int
264
+ while size > default && size.positive?
265
+ begin
266
+ return @socket.setsockopt(Socket::SOL_SOCKET, option, size)
267
+ rescue Errno::ENOBUFS, Errno::EINVAL
268
+ size /= 2
269
+ end
270
+ end
271
+ end
272
+
273
+ # Turns on the option `name` at `level` where Socket names it; whether
274
+ # it did.
275
+ private def enable(level, name)
276
+ return false unless Socket.const_defined?(name)
277
+ @socket.setsockopt(level, Socket.const_get(name), 1)
278
+ true
279
+ end
280
+
281
+ # Whether IPv4 comes to `socket`: one bound to an address of IPv4, or
282
+ # of IPv6 bound to "::" (or an IPv4-mapped address) and not IPv6 alone,
283
+ # which OpenBSD does not allow.
284
+ def self.takes_ipv4?(socket)
285
+ local = socket.local_address
286
+ return true if local.ipv4?
287
+ return false unless local.ipv6_unspecified? || local.ipv6_v4mapped?
288
+ socket.getsockopt(Socket::IPPROTO_IPV6, Socket::IPV6_V6ONLY).int.zero?
289
+ end
290
+
291
+ # All the datagrams in one sendmsg: nil when they went, else what it
292
+ # failed with.
293
+ private def send_segments(payload, size, destination, controls)
294
+ segment = Socket::AncillaryData.new(@family, Socket::IPPROTO_UDP, UDP_SEGMENT, [size].pack("S"))
295
+ @socket.sendmsg(payload, 0, destination, *controls, segment)
296
+ nil
297
+ rescue *GSO_REFUSED, *CONTROLS_REFUSED, *DROPPED => error
298
+ error
299
+ end
300
+
301
+ # `controls` are [kind, control message], those of a kind left out
302
+ # since dropped.
303
+ private def send_datagram(datagram, destination, controls)
304
+ controls = controls.select { |kind, _| @sends[kind] }
305
+ @socket.sendmsg(datagram, 0, destination, *controls.map(&:last))
306
+ true
307
+ rescue *CONTROLS_REFUSED => error
308
+ without_controls(datagram, destination, controls, error)
309
+ rescue *DROPPED
310
+ false
311
+ end
312
+
313
+ # Sends `datagram`, which sendmsg refused with `controls` and `error`.
314
+ # A control message the OS does not know (ENOPROTOOPT, EOPNOTSUPP): the
315
+ # datagram goes without the ECN mark, then without the source, then
316
+ # without both, and what it went without is left out for good. EINVAL
317
+ # may be the source's alone, an address the host no longer has (Linux,
318
+ # of IPv6): the datagram goes without the mark only, and nothing is
319
+ # left out. When it never goes, the destination is at fault.
320
+ private def without_controls(datagram, destination, controls, error)
321
+ marks, sources = controls.partition { |kind, _| kind == :tos || kind == :tclass }
322
+ forget = !error.is_a?(Errno::EINVAL)
323
+ trials = [] #: Array[[Array[[Symbol, Socket::AncillaryData]], Array[[Symbol, Socket::AncillaryData]]]]
324
+ trials << [sources, marks] unless marks.empty?
325
+ trials << [marks, sources] if forget && !sources.empty?
326
+ trials << [[], controls] if forget && !(marks.empty? || sources.empty?)
327
+ trials.each do |kept, left|
328
+ @socket.sendmsg(datagram, 0, destination, *kept.map(&:last))
329
+ left.each { |kind, _| @sends[kind] = false } if forget
330
+ @stripped = true
331
+ return true
332
+ rescue *CONTROLS_REFUSED
333
+ next
334
+ rescue *DROPPED
335
+ return false
336
+ end
337
+ false
338
+ end
339
+
340
+ private def datagrams(transmit)
341
+ payload = transmit.payload
342
+ size = transmit.segment_size
343
+ return [payload] unless size && size < payload.bytesize
344
+ (0...payload.bytesize).step(size).map { |offset| payload.byteslice(offset, size) || "".b }
345
+ end
346
+
347
+ # [kind, control message] that marks a datagram to `host` with `ecn`,
348
+ # none when it goes without.
349
+ private def mark(ecn, host)
350
+ value = MARKS[ecn] or return nil
351
+ if @family == Socket::AF_INET6 && !(host.start_with?("::ffff:") && host.include?("."))
352
+ [:tclass, Socket::AncillaryData.int(:INET6, :IPV6, :TCLASS, value)] if @sends[:tclass]
353
+ elsif @sends[:tos]
354
+ [:tos, Socket::AncillaryData.int(:INET, :IP, :TOS, value)]
355
+ end
356
+ end
357
+
358
+ # [kind, control message] that sends from the address of `source`,
359
+ # none to leave it to the OS. IP_SENDSRCADDR carries the in_addr alone.
360
+ private def source(source)
361
+ return nil unless source
362
+ address = Addrinfo.ip(mapped(source[0]))
363
+ if @family == Socket::AF_INET6
364
+ [:ipv6_source, Socket::AncillaryData.ipv6_pktinfo(address, 0)] if @sends[:ipv6_source]
365
+ elsif !@sends[:ip_source] then nil
366
+ elsif Socket.const_defined?(:IP_PKTINFO)
367
+ [:ip_source, Socket::AncillaryData.ip_pktinfo(address, 0, address)]
368
+ else
369
+ [:ip_source, Socket::AncillaryData.new(:INET, :IP, Socket::IP_SENDSRCADDR, address.ip_address.split(".").map(&:to_i).pack("C4"))]
370
+ end
371
+ end
372
+
373
+ # The address a datagram came to, from its control messages, with the
374
+ # socket's port.
375
+ private def destination(controls)
376
+ controls.each do |control|
377
+ return [unmapped(control.ipv6_pktinfo[0].ip_address), @port] if control.cmsg_is?(Socket::IPPROTO_IPV6, Socket::IPV6_PKTINFO)
378
+ return [ipv4_destination(control), @port] if @ipv4_destination && control.cmsg_is?(Socket::IPPROTO_IP, @ipv4_destination) # steep:ignore
379
+ end
380
+ nil
381
+ end
382
+
383
+ # The address of IP_PKTINFO's in_pktinfo, or IP_RECVDSTADDR's in_addr,
384
+ # which is the address alone.
385
+ private def ipv4_destination(control)
386
+ data = control.data
387
+ data.bytesize == 4 ? data.unpack("C4").join(".") : control.ip_pktinfo[0].ip_address
388
+ end
389
+
390
+ # An IPv4 address as an IPv6 socket sends to or from it, IPv4-mapped,
391
+ # which also marks it the IPv4 way.
392
+ private def mapped(host) = @family == Socket::AF_INET6 && !host.include?(":") ? "::ffff:#{host}" : host
393
+
394
+ # An IPv4-mapped address as the IPv4 address it maps.
395
+ private def unmapped(host) = UDP.unmapped(host)
396
+
397
+ # `host` as IPv4's when it is IPv4-mapped.
398
+ def self.unmapped(host) = host.start_with?("::ffff:") && host.include?(".") ? host.delete_prefix("::ffff:") : host
399
+
400
+ # The codepoint of a datagram from its control messages: IP_TOS is one
401
+ # byte, IPV6_TCLASS an int.
402
+ private def ecn(controls)
403
+ controls.each do |control|
404
+ return ECN.fetch(control.data.getbyte(0).to_i & 0b11) if control.cmsg_is?(Socket::IPPROTO_IP, Socket::IP_TOS)
405
+ return ECN.fetch(control.int & 0b11) if control.cmsg_is?(Socket::IPPROTO_IPV6, Socket::IPV6_TCLASS)
406
+ end
407
+ :not_ect
408
+ end
409
+ end
410
+ end
@@ -0,0 +1,138 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Raiha::Runtime
4
+ # One of the workers of a server, as Workers gives each its own Ractor:
5
+ # its ID of `count`, the sockets bound for it, its `inbox`, where other
6
+ # workers hand on what came for its connections, the `control` port
7
+ # Workers asks it things through, and `peers`, the inboxes of all the
8
+ # workers by ID, its own included. Its QUIC `config` has the Retry token
9
+ # and stateless reset keys every worker uses, so that each takes the
10
+ # tokens and reads the connection IDs another issued, and `anti_replay`
11
+ # is the record
12
+ # of 0-RTT they share, so that each ClientHello's 0-RTT is taken once by
13
+ # them all rather than once by each.
14
+ #
15
+ # A Ractor::Port waits for what comes without yielding to the Fiber
16
+ # scheduler, so `listen` starts a thread of its own that waits on the
17
+ # inbox and the control port: what is handed on goes into a queue the
18
+ # driver takes from (`take`), up to QUEUE datagrams and QUEUE_BYTES of
19
+ # them, past which the newest is dropped; what comes to the control port
20
+ # goes to the block. `forward`
21
+ # hands a datagram on to another worker, and never waits.
22
+ class Worker
23
+ # The most datagrams handed on that a worker keeps before taking them,
24
+ # and the most bytes of them: a datagram may be 64 KiB, and a peer that
25
+ # sends large ones for another worker's connections would otherwise
26
+ # make a worker that falls behind keep 64 MiB.
27
+ QUEUE = 1024
28
+ QUEUE_BYTES = 4 * 1024 * 1024
29
+ # What `close` sends the listening thread to end it.
30
+ CLOSE = :close
31
+
32
+ # What a worker counts of what it hands on and is handed: sent to
33
+ # another worker, received from one, and dropped as the queue was full.
34
+ Stats = Data.define(:id, :sent, :received, :dropped)
35
+
36
+ attr_reader :id, :count, :config, :sockets, :inbox, :control, :peers, :anti_replay
37
+
38
+ def initialize(id:, count:, config:, sockets:, inbox:, control:, peers:, anti_replay:)
39
+ @id = id
40
+ @config = config
41
+ @anti_replay = anti_replay
42
+ @count = count
43
+ @sockets = sockets
44
+ @inbox = inbox
45
+ @control = control
46
+ @peers = peers
47
+ @queue = Thread::Queue.new
48
+ # The bytes queued, which the listening thread adds to and `take`
49
+ # takes from.
50
+ @queued_bytes = 0
51
+ @lock = Thread::Mutex.new
52
+ @sent = 0
53
+ @received = 0
54
+ @dropped = 0
55
+ @listener = nil #: Thread?
56
+ end
57
+
58
+ # Starts the thread that waits on the inbox and the control port: it
59
+ # calls `changed` once a datagram handed on is queued, the block with
60
+ # each message to the control port but a request for `stats`, which it
61
+ # answers itself, and `failed` with what it raises, if anything. It ends
62
+ # at the CLOSE `close` sends, as closing a port does not wake
63
+ # Ractor.select. The control port goes first: Ractor.select takes the
64
+ # first port that has something, and datagrams handed on without end
65
+ # would keep a stop waiting.
66
+ def listen(changed:, failed:, &control)
67
+ raise Error::Usage, "the worker listens already" if @listener
68
+ @listener = Thread.new do
69
+ loop do
70
+ port, message = Ractor.select(@control, @inbox)
71
+ break if message == CLOSE && port.equal?(@control)
72
+ port.equal?(@inbox) ? queue(message, changed) : answer(message, control)
73
+ end
74
+ rescue StandardError => error
75
+ failed.call(error)
76
+ end
77
+ self
78
+ end
79
+
80
+ # Hands `forwarded`, [datagram, from, to, ecn, received_at], on to the
81
+ # worker `worker`; one that has ended already gets nothing, and nothing
82
+ # is answered for it.
83
+ def forward(worker, forwarded)
84
+ @peers.fetch(worker).send(Ractor.make_shareable(forwarded))
85
+ @sent += 1
86
+ rescue Ractor::ClosedError
87
+ nil
88
+ end
89
+
90
+ # The datagrams handed on to this worker since the last `take`.
91
+ def take
92
+ taken = [] #: Array[forwarded]
93
+ while (forwarded = @queue.pop(timeout: 0))
94
+ bytes = forwarded.fetch(0).bytesize
95
+ @lock.synchronize { @queued_bytes -= bytes }
96
+ taken << forwarded
97
+ end
98
+ taken
99
+ end
100
+
101
+ def stats = Stats.new(id: @id, sent: @sent, received: @received, dropped: @dropped)
102
+
103
+ # Ends the listening thread and waits for it, then closes the inbox and
104
+ # the control port, so that what other workers hand on from then is
105
+ # dropped where it is sent.
106
+ def close
107
+ if (listener = @listener)
108
+ @control.send(CLOSE) unless @control.closed?
109
+ listener.join
110
+ end
111
+ [@inbox, @control].each(&:close)
112
+ nil
113
+ end
114
+
115
+ private def queue(forwarded, changed)
116
+ bytes = forwarded.fetch(0).bytesize
117
+ room = @lock.synchronize do
118
+ next false if @queue.size >= QUEUE || @queued_bytes + bytes > QUEUE_BYTES
119
+ @queued_bytes += bytes
120
+ end
121
+ unless room
122
+ @dropped += 1
123
+ return
124
+ end
125
+ @received += 1
126
+ @queue << forwarded
127
+ changed.call
128
+ end
129
+
130
+ private def answer(message, control)
131
+ return control.call(message) unless message.is_a?(Array) && message.first == :stats
132
+ reply = message.fetch(1) #: Ractor::Port[Stats?]
133
+ reply.send(stats)
134
+ rescue Ractor::ClosedError
135
+ nil
136
+ end
137
+ end
138
+ end