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
data/docs/quic.md ADDED
@@ -0,0 +1,268 @@
1
+ # QUIC
2
+
3
+ Raiha's QUIC core is sans-I/O: `Raiha::QUIC::Endpoint` and `Raiha::QUIC::Connection` never touch a socket, never read a clock and never wait. You hand them the datagrams that arrive and the current time, and they hand back the datagrams to send, the events that happened, and when they next need to be woken. The loop around them is yours, so a plain blocking `UDPSocket` is enough to run QUIC, with no Fiber scheduler.
4
+
5
+ Under a Fiber scheduler, `Raiha::Runtime` runs this loop for you with less code; see [fiber-scheduler.md](fiber-scheduler.md). The TLS and QUIC settings used below are described in [configuration.md](configuration.md).
6
+
7
+ ## The loop
8
+
9
+ An application owes the core four things, over and over:
10
+
11
+ 1. Send what it has to send: `each_transmit(now:)` yields `Raiha::QUIC::Transmit` values. Send each `payload` to its `destination` (`[host, port]`).
12
+ 2. Give it each datagram that arrives: `receive(data, from: [host, port], now:)`.
13
+ 3. Wake it at its deadline: `next_timeout` is a time on the monotonic clock, or `nil` when nothing is due. Once that time has come, call `handle_timeout(now:)`.
14
+ 4. Take its events: `each_event` yields what happened, such as a completed handshake or a stream with data to read. A connection holds at most 4,096 events nobody has taken; past that it closes with `INTERNAL_ERROR`.
15
+
16
+ Then wait on the socket until a datagram comes or the deadline passes, and go round again.
17
+
18
+ There are two clocks:
19
+
20
+ - `now:` is the monotonic clock in Float seconds, `Process.clock_gettime(Process::CLOCK_MONOTONIC)`. Every call that can make something happen takes it.
21
+ - `time:` is the wall clock, a `Time`, given once when an endpoint or connection is made. TLS needs it for certificates and tickets, and the core moves it on by the monotonic clock from then.
22
+
23
+ Because the core does no I/O, nothing inside it blocks: a call returns at once, and whatever has to wait (for a datagram, for flow control credit, for a timer) shows up later as an event or as a `next_timeout`.
24
+
25
+ ### A plain socket
26
+
27
+ Two settings of `Raiha::QUIC::Config` matter with a plain `UDPSocket`:
28
+
29
+ - `ecn_address_families: []`. A plain socket neither marks ECN nor reads it, so tell the core not to use it. Leaving `Transmit#ecn` unsent while the core counts its packets as ECT would only make the core find ECN broken.
30
+ - `enable_pmtud: false`. Path MTU probes need a socket that keeps IP from fragmenting, which a plain socket does not set up. The runtime turns this off itself where its socket cannot; see [platforms.md](platforms.md).
31
+
32
+ On a real network, sending can fail for one datagram, as with `Errno::ECONNREFUSED` after an ICMP unreachable or `Errno::EMSGSIZE`. The examples below do not rescue it; a loop that runs for long should rescue `SystemCallError` around each send and go on, since the core treats the datagram as lost. The runtime does the same.
33
+
34
+ With `max_transmit_size` left `nil` (the default), each `Transmit` is one datagram. `Transmit#source` is the local address to send from, `nil` to leave it to the OS; it matters only for a socket bound to a wildcard address on a host with several addresses.
35
+
36
+ ## A complete echo
37
+
38
+ A server in a thread, taking every client on one socket, and a client in the main thread that sends `hello` on a stream and reads it back. It needs `cert.pem` and `key.pem` for `localhost` in the current directory.
39
+
40
+ ```ruby
41
+ require "raiha"
42
+ require "socket"
43
+
44
+ def now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
45
+
46
+ # Waits for a datagram until `deadline` (nil for no limit): [data, [host, port]], or nil.
47
+ def wait(socket, deadline)
48
+ timeout = deadline && [deadline - now, 0].max
49
+ return nil unless socket.wait_readable(timeout)
50
+ data, addr = socket.recvfrom(65535)
51
+ [data, [addr[3], addr[1]]]
52
+ end
53
+
54
+ def send_all(socket, source)
55
+ source.each_transmit(now:) { |t| socket.send(t.payload, 0, *t.destination) }
56
+ end
57
+
58
+ registry = Raiha::TLS::Extension::Registry::BUILTIN.with(Raiha::QUIC::TransportParameters::Extension)
59
+ config = Raiha::QUIC::Config.new(ecn_address_families: [], enable_pmtud: false)
60
+
61
+ # The server: one Endpoint for its socket.
62
+ chain = OpenSSL::X509::Certificate.load(File.read("cert.pem")).map(&:to_der)
63
+ key = OpenSSL::PKey.read(File.read("key.pem")).private_to_der
64
+ identity = Raiha::TLS::Keyring::Identity.new(cert_der: chain, key_der: key)
65
+ server_tls = Raiha::TLS::Config.server(profile: Raiha::TLS::Profile::QUIC, alpn: ["echo"], registry:)
66
+ server_keyring = Raiha::TLS::Keyring.server(config: server_tls, identities: [identity])
67
+
68
+ server_socket = UDPSocket.new
69
+ server_socket.bind("127.0.0.1", 4433)
70
+ server = Raiha::QUIC::Endpoint.server(config:, random: SecureRandom, time: Time.now, now:)
71
+
72
+ Thread.new do
73
+ received = Hash.new { |hash, key| hash[key] = +"" }
74
+ loop do
75
+ send_all(server_socket, server)
76
+ if (datagram = wait(server_socket, server.next_timeout))
77
+ data, from = datagram
78
+ case (route = server.receive(data, from:, now:))
79
+ when Raiha::QUIC::Route::Incoming
80
+ route = server.admit(route.handle, now:)
81
+ server.accept(route.handle, tls_config: server_tls, keyring: server_keyring, now:) if route.is_a?(Raiha::QUIC::Route::ClientHello)
82
+ when Raiha::QUIC::Route::ClientHello
83
+ server.accept(route.handle, tls_config: server_tls, keyring: server_keyring, now:)
84
+ when Raiha::QUIC::Route::Respond
85
+ server_socket.send(route.transmit.payload, 0, *route.transmit.destination)
86
+ end
87
+ end
88
+ deadline = server.next_timeout
89
+ server.handle_timeout(now:) if deadline && now >= deadline
90
+ server.each_connection do |conn|
91
+ conn.each_event do |event|
92
+ next unless event.is_a?(Raiha::QUIC::Event::StreamReadable)
93
+ while (chunk = conn.stream_read(event.stream_id, 65536))
94
+ break if chunk.empty?
95
+ received[[conn, event.stream_id]] << chunk
96
+ end
97
+ # nil: the client ended the stream, so echo all of it back.
98
+ conn.stream_write(event.stream_id, received.delete([conn, event.stream_id]) || "", fin: true) if chunk.nil?
99
+ end
100
+ end
101
+ end
102
+ end
103
+
104
+ # The client: an Endpoint of its own with one connection.
105
+ client_tls = Raiha::TLS::Config.client(trust_anchors: chain, profile: Raiha::TLS::Profile::QUIC, alpn: ["echo"], registry:)
106
+ socket = UDPSocket.new
107
+ socket.bind("127.0.0.1", 0)
108
+ client = Raiha::QUIC::Endpoint.client(config:, random: SecureRandom, time: Time.now, now:)
109
+ conn = client.connect(tls_config: client_tls, keyring: Raiha::TLS::Keyring.client(config: client_tls), server_name: "localhost",
110
+ remote: ["127.0.0.1", 4433], now:)
111
+
112
+ reply = +""
113
+ done = false
114
+ until done || conn.closed?
115
+ send_all(socket, client)
116
+ if (datagram = wait(socket, client.next_timeout))
117
+ client.receive(datagram[0], from: datagram[1], now:)
118
+ end
119
+ deadline = client.next_timeout
120
+ client.handle_timeout(now:) if deadline && now >= deadline
121
+ conn.each_event do |event|
122
+ case event
123
+ when Raiha::QUIC::Event::Connected
124
+ stream = conn.open_stream
125
+ conn.stream_write(stream, "hello", fin: true)
126
+ when Raiha::QUIC::Event::StreamReadable
127
+ while (chunk = conn.stream_read(event.stream_id, 65536))
128
+ break if chunk.empty?
129
+ reply << chunk
130
+ end
131
+ done = chunk.nil?
132
+ end
133
+ end
134
+ end
135
+
136
+ conn.close(now:)
137
+ send_all(socket, client)
138
+ puts reply # => hello
139
+ ```
140
+
141
+ The echo writes each reply in one `stream_write`, which is enough for a short message; a longer one has to wait for credit, as [Streams](#streams) describes. [examples/udp_handshake.rb](../examples/udp_handshake.rb) and [examples/in_memory_handshake.rb](../examples/in_memory_handshake.rb) show the same loop in other shapes, the second with no socket at all.
142
+
143
+ ## Clients
144
+
145
+ `Raiha::QUIC::Endpoint.client(config:, random:, time:, now:)` makes a client's endpoint, and `connect` makes a connection on it, its first Initial waiting to be sent:
146
+
147
+ ```ruby
148
+ conn = endpoint.connect(tls_config:, keyring:, server_name: "localhost", remote: ["127.0.0.1", 4433], now:)
149
+ ```
150
+
151
+ `connect` also takes `tracer:` and `keylog:` (see [qlog.md](qlog.md)), and `session:`, `token:` and `early_data:` for [resumption](#resumption-and-0-rtt). Feed every datagram of the socket to `endpoint.receive`; it gives each to the connection it belongs to and returns a `Raiha::QUIC::Route::Deliver`, or a `Raiha::QUIC::Route::Drop` for one that belongs to none.
152
+
153
+ `Raiha::QUIC::Connection.client(config:, tls_config:, keyring:, server_name:, remote:, time:, now:)` makes a connection with no endpoint, which you feed with `conn.receive`. Such a connection issues no connection IDs of its own, so prefer an endpoint unless you need the bare connection.
154
+
155
+ The handshake is over when `Event::Connected` comes. `conn.handshake_complete?` tells the same, and `conn.handshake_confirmed?` turns true later, once the server's HANDSHAKE_DONE arrives. `Connected#handshake` is TLS's `HandshakeComplete`, with `server_name`, `alpn`, `cipher_suite`, `group`, `resumed`, `early_data_accepted`, `peer_certificates` and `peer_verified`.
156
+
157
+ ## Servers
158
+
159
+ `Raiha::QUIC::Endpoint.server(config:, random:, time:, now:)` serves every client of one socket. `receive` routes each datagram by its connection ID and returns what it did with it, as one of the `Raiha::QUIC::Route` values below (named here without their namespace, as are the `Raiha::QUIC::Event` values):
160
+
161
+ | Route | Meaning | What to do |
162
+ | --- | --- | --- |
163
+ | `Route::Deliver` | The datagram went to an existing connection (`connection`). | Nothing. |
164
+ | `Route::Incoming` | The first Initial of a new client (`handle`, `remote`, `address_validated`). | `admit`, `retry` or `refuse` the handle. |
165
+ | `Route::ClientHello` | The ClientHello of an admitted handle is whole (`handle`, `accepted`). | `accept` or `reject` the handle. |
166
+ | `Route::Respond` | The endpoint answers by itself: a Version Negotiation, a Stateless Reset, or a CONNECTION_CLOSE for a bad Retry token. | Send `transmit`. |
167
+ | `Route::Drop` | Nothing took the datagram (`reason`, such as `:unknown_connection_id`). | Nothing. |
168
+ | `nil` | The datagram was kept for, or read into, a handle that has no ClientHello to give: not admitted yet, admitted with the ClientHello still incomplete, or past its `Route::ClientHello`, which comes only once. | Nothing. |
169
+
170
+ `Route::Foreign` comes only with the connection IDs of `Runtime::Workers` and never from a plain endpoint.
171
+
172
+ A new connection takes two steps, so that turning a client down costs little:
173
+
174
+ - `admit(handle, now:)` reads the ClientHello out of the Initial packets the handle kept. It returns `Route::ClientHello` when the ClientHello is whole already, else `nil`, and a later `receive` returns the `Route::ClientHello`.
175
+ - `accept(handle, tls_config:, keyring:, now:)` makes the `Connection` and returns it. `accepted.info` tells what the ClientHello asked for (`server_name`, `alpn_protocols` and more), which you may choose the TLS config by. It also takes `tracer:`, `keylog:`, `anti_replay:` and `app_early_data_context:`.
176
+
177
+ The other answers:
178
+
179
+ - `retry(handle, now:)` sends a Retry, at the first step only. The client comes back with a token that shows it receives at its address, and that handle arrives with `address_validated` true.
180
+ - `refuse(handle, error_code: Raiha::QUIC::ErrorCode::CONNECTION_REFUSED)` closes the offer with a transport error, at either step.
181
+ - `reject(handle, description)` turns down a whole ClientHello with a TLS alert, one of `:unrecognized_name`, `:missing_extension`, `:no_application_protocol`, `:handshake_failure`, `:insufficient_security`, `:internal_error` and `:general_error`.
182
+
183
+ The endpoint bounds what each offer keeps, but not how many connections there are. Count your connections and offers whose address is not validated (`conn.address_validated?`, `route.address_validated`), and `retry` new clients once that count reaches a limit of your own: clients that spoof their address are never validated, and would otherwise take every connection you have room for. An offer nobody decides on goes after 10 seconds.
184
+
185
+ `each_connection` yields every connection of the endpoint and `connection_count` counts them. `endpoint.each_transmit`, `next_timeout` and `handle_timeout` cover all of them and the offers, and `handle_timeout` lets go of the connections that have closed.
186
+
187
+ ## Events
188
+
189
+ `each_event` (or `next_event`, one at a time) gives these `Raiha::QUIC::Event` values:
190
+
191
+ | Event | Fields | Meaning |
192
+ | --- | --- | --- |
193
+ | `Connected` | `handshake` | The handshake completed. |
194
+ | `StreamReadable` | `stream_id` | The stream has data to read, or its end. |
195
+ | `StreamWritable` | `stream_id` | A stream that took only part of a write can take more. |
196
+ | `StreamReset` | `stream_id`, `error_code`, `final_size` | The peer abandoned sending on the stream (RESET_STREAM). |
197
+ | `StopSending` | `stream_id`, `error_code` | The peer asks this end to stop sending on the stream. |
198
+ | `DatagramReceived` | `data` | A DATAGRAM frame arrived. |
199
+ | `KeyUpdated` | `phase` | The 1-RTT keys were updated. |
200
+ | `SessionTicket` | `session` | At a client, a `Raiha::QUIC::Session` to resume later. |
201
+ | `NewToken` | `token` | At a client, a token for later connections to this server. |
202
+ | `ZeroRttRejected` | `reason` | At a client, the server took no 0-RTT. |
203
+ | `TLSEvent` | `event` | A TLS event passed on as it came. |
204
+ | `Closed` | `error`, `by_peer` | The connection closed. `error` is a `Raiha::QUIC::ConnectionError`. |
205
+
206
+ ## Streams
207
+
208
+ Stream IDs are Integers, as QUIC numbers them. A connection opens streams, writes and reads them by ID:
209
+
210
+ | Method | What it does |
211
+ | --- | --- |
212
+ | `open_stream(direction: :bidi)` | Opens a stream, `:bidi` or `:uni`, and returns its ID, or `nil` while the peer allows no more. |
213
+ | `stream_write(id, data, fin: false)` | Takes as much of `data` as flow control and the send buffer allow and returns how many bytes it took. With `fin: true`, the stream ends once all of `data` is taken. |
214
+ | `stream_writable_bytes(id)` | How many bytes a write would take now. |
215
+ | `stream_read(id, max_bytes)` | Up to `max_bytes` that arrived: `""` when nothing is there yet, `nil` once the stream has ended. What is read goes back to the peer as flow control credit. |
216
+ | `readable_streams` | The IDs a read would give something on. |
217
+ | `writable_streams` | The IDs a write would take something on. |
218
+ | `stream_reset(id, error_code:)` | Abandons sending (RESET_STREAM); what was not acknowledged is not sent again. |
219
+ | `stream_stop_sending(id, error_code:)` | Asks the peer to stop sending (STOP_SENDING); what still comes is dropped. |
220
+ | `stream_priority(id, urgency:, incremental:)` | Sends streams of a lower urgency (0 to 7) first; within one urgency, incremental streams take turns. A stream is urgency 3 and incremental unless told. |
221
+
222
+ When `stream_write` takes less than all of `data`, keep the rest and write it when `Event::StreamWritable` comes for that stream. That event comes once per partial write. Read a stream on `Event::StreamReadable` until `stream_read` gives `""` (more later) or `nil` (the end). Data you do not read holds the peer back, as its credit comes back only as you read.
223
+
224
+ `conn.stream_early_data?(id)` tells, at a server, whether part of the stream came in 0-RTT and so may be a replay.
225
+
226
+ ## DATAGRAM frames
227
+
228
+ To exchange DATAGRAM frames (RFC 9221), both ends set `max_datagram_frame_size` in their `Raiha::QUIC::Config`; RFC 9221 suggests `65535`. Then:
229
+
230
+ - `datagram_send(data, expires_at: nil, urgency: 3)` queues `data` for one DATAGRAM frame, never sent again if lost, and returns whether it was queued. It is not queued when the peer takes no DATAGRAM frames, when `data` is over `datagram_max_size`, or when too many wait. With `expires_at` (a monotonic time), it is dropped unsent past that time.
231
+ - `datagram_max_size` is the largest `data` a frame can carry now, or `nil` while the peer has not agreed to DATAGRAM frames. It depends on the path, so it can change.
232
+ - `Event::DatagramReceived` carries each DATAGRAM that arrives.
233
+
234
+ ## Closing
235
+
236
+ `conn.close(error_code: 0, reason: "", now:)` closes with an application error code; `application: false` makes it a transport error. A CONNECTION_CLOSE goes out at the next `each_transmit`, and the connection stays closing for three PTOs, answering what still comes. Keep running the loop until `conn.closed?`; `closing?` and `draining?` tell the state on the way. An endpoint lets a connection go at the `handle_timeout` after it has closed.
237
+
238
+ `conn.close_reason` is `nil` while the connection is open, then the `Raiha::QUIC::ConnectionError` it closed with: `code`, `reason`, `application`, and `frame_type` (`nil` for an application error). `Event::Closed` carries the same, with `by_peer`. A connection also closes on its own at its idle timeout (`max_idle_timeout`), or on a stateless reset from the peer.
239
+
240
+ ## Versions
241
+
242
+ A connection is in one of the `versions` of its `Raiha::QUIC::Config`: version 1 (`Raiha::QUIC::Version::V1`) or version 2 (`Raiha::QUIC::Version::V2`, RFC 9369). [configuration.md](configuration.md#versions) tells how to choose them. `conn.version` is the version the connection is in. A client's is the one it started in until the server's Initial shows that the server chose another.
243
+
244
+ The versions are negotiated as RFC 9368 describes, with nothing for you to do:
245
+
246
+ - Compatible negotiation: a client offers the versions of its config in the `version_information` transport parameter, and a server switches the connection to the first of its own `versions` that the client offers and its `deployed_versions` holds, within the handshake.
247
+ - Incompatible negotiation: a server's endpoint answers an Initial of a version it does not take with a Version Negotiation packet (`Route::Respond`), listing `offered_versions`. The client starts again, in the same `Connection`, in the first of its `versions` that the packet lists. 0-RTT sent before is rejected (`Event::ZeroRttRejected` with reason `:version_negotiation`), and the new attempt neither resumes nor carries a token.
248
+ - Each end checks the version information of the other, and closes with `VERSION_NEGOTIATION_ERROR` when it shows that an attacker forced a version on the connection.
249
+
250
+
251
+ A client keeps what the server sends for later connections:
252
+
253
+ - `Event::SessionTicket` gives a `Raiha::QUIC::Session`. `session.to_h` and `Raiha::QUIC::Session.from_h` turn it into plain values and back, for storing.
254
+ - `Event::NewToken` gives a `Raiha::QUIC::Token`, which lets a later connection skip address validation. `token.to_h` and `Raiha::QUIC::Token.from_h` turn it into plain values and back.
255
+
256
+ Pass them to a later `connect(..., session:, token:)` to resume, and add `early_data: true` to send 0-RTT. What streams and DATAGRAM frames carry before the handshake completes then goes in 0-RTT packets. An attacker can replay 0-RTT, so send in it only what is safe to repeat. Use each ticket and token for one connection only.
257
+
258
+ A session and a token belong to the version of the connection they came on (`session.version`, `token.version`, RFC 9369). A client given a session starts in its version. When that version is not one of the config's `versions`, the session goes unused and the tracer's `session_ignored` hears of it. A token of another version than the one the client starts in goes unused too (`token_ignored`). A server that switches a resumed connection to another version rejects its 0-RTT, and the tickets it then gives are of the new version.
259
+
260
+ `conn.zero_rtt_state` is `:disabled`, `:pending` while 0-RTT goes, then `:accepted` or `:rejected`. On a rejection, `Event::ZeroRttRejected` comes and the streams opened in 0-RTT are gone; until you call `conn.acknowledge_zero_rtt_rejection`, those streams and `open_stream` raise `Raiha::QUIC::Error::ZeroRttRejected`. What to send again is up to you.
261
+
262
+ A server takes 0-RTT when its TLS config has ticket keys and `max_early_data_size` (see [configuration.md](configuration.md#tickets-and-0-rtt)). Its `accept` must then be given an `anti_replay:` record, such as `Raiha::TLS::AntiReplay::Memory.new(now: Time.now)`, so that each ClientHello's 0-RTT is taken at most once; without one, `accept` raises `Raiha::TLS::UsageError`.
263
+
264
+ ## Statistics and tracing
265
+
266
+ `conn.stats` returns a `Raiha::QUIC::Stats`: `rtt`, `rtt_var`, `min_rtt`, `congestion_window`, `bytes_in_flight`, `packets_sent`, `packets_received`, `packets_lost`, `packets_spuriously_lost`, `bytes_sent`, `bytes_received`, `path_mtu`, `handshake_duration`, `receive_window`, `send_buffer_bytes`, `blocked_sent` and `blocked_received`.
267
+
268
+ `tracer:` on `connect` and `accept` takes a qlog tracer, and `keylog:` a writer of TLS secrets; see [qlog.md](qlog.md).
data/docs/threads.md ADDED
@@ -0,0 +1,127 @@
1
+ # Threads
2
+
3
+ `Raiha::Runtime::Threaded` is the runtime of [Fiber scheduler](fiber-scheduler.md) on threads. It has the same classes by the same names, `Server`, `Client`, `Session`, `Stream`, `HTTP3::Server` and `HTTP3::Client`, with the same methods, and needs no scheduler gem: call it from any thread. Where the runtime of fibers starts a fiber, this one starts a thread: one for each connection's handler, each stream of `each_stream` and each HTTP/3 request.
4
+
5
+ Use it when a handler calls a library that blocks its whole thread, such as a C extension that does not cooperate with a Fiber scheduler. Under the runtime of fibers, such a call holds up every connection of that thread; here it holds up only its own. It is not faster: Ruby's GVL still runs one thread's Ruby code at a time.
6
+
7
+ ## Choosing the runtime
8
+
9
+ Use the namespace directly, or let `Raiha::Runtime.for` give it:
10
+
11
+ ```ruby
12
+ runtime = Raiha::Runtime.for(concurrency: :thread) # => Raiha::Runtime::Threaded
13
+ runtime::HTTP3::Server.new(config: Raiha::QUIC::Config.new, tls_config: tls, keyring:, port: 4433)
14
+
15
+ Raiha::Runtime.for # => Raiha::Runtime, the runtime of fibers
16
+ ```
17
+
18
+ `concurrency:` is `:fiber` (the default) or `:thread`; anything else raises `ArgumentError`.
19
+
20
+ ## HTTP/3 server
21
+
22
+ ```ruby
23
+ require "raiha"
24
+
25
+ registry = Raiha::TLS::Extension::Registry::BUILTIN.with(Raiha::QUIC::TransportParameters::Extension)
26
+ tls = Raiha::TLS::Config.server(profile: Raiha::TLS::Profile::QUIC, alpn: ["h3"], registry:)
27
+ identity = Raiha::TLS::Keyring::Identity.new(
28
+ cert_der: OpenSSL::X509::Certificate.load(File.read("fullchain.pem")).map(&:to_der),
29
+ key_der: OpenSSL::PKey.read(File.read("privkey.pem")).private_to_der
30
+ )
31
+ keyring = Raiha::TLS::Keyring.server(config: tls, identities: [identity])
32
+
33
+ server = Raiha::Runtime::Threaded::HTTP3::Server.new(config: Raiha::QUIC::Config.new, tls_config: tls, keyring:, host: "::", port: 4433)
34
+ trap("INT") { server.stop }
35
+
36
+ server.run do |request|
37
+ request.respond(200, [["content-type", "text/plain"]], "hello from #{request.path}\n")
38
+ end
39
+ ```
40
+
41
+ There is no `Sync`: `run` blocks the thread that calls it until the server stops. Each request runs in a thread of its own, so the block may block.
42
+
43
+ `Threaded::HTTP3::Server.new` and `Threaded::Server.new` take the keywords of the runtime of fibers (see [Server options](fiber-scheduler.md#server-options)), except that there is no `worker:`, and with these defaults and one more:
44
+
45
+ | Keyword | Default | Meaning |
46
+ | --- | --- | --- |
47
+ | `max_connections:` | `64` | The most connections at a time, counting the handlers that have not ended (see [How many threads](#how-many-threads)). The runtime of fibers takes 1024. |
48
+ | `max_threads:` | `256` | The most threads of streams and requests at a time. An Integer of 1 or more. |
49
+
50
+ Requests, responses, `stop`, `reconfigure` and 0-RTT work as [the HTTP/3 server of fibers](fiber-scheduler.md#http3-server) does.
51
+
52
+ ## HTTP/3 client
53
+
54
+ ```ruby
55
+ require "raiha"
56
+
57
+ registry = Raiha::TLS::Extension::Registry::BUILTIN.with(Raiha::QUIC::TransportParameters::Extension)
58
+ tls = Raiha::TLS::Config.client(trust_anchors: [File.read("ca.der")], profile: Raiha::TLS::Profile::QUIC, alpn: [Raiha::Runtime::Threaded::HTTP3::Client::ALPN], registry:)
59
+ keyring = Raiha::TLS::Keyring.client(config: tls)
60
+
61
+ response = Raiha::Runtime::Threaded::Client.connect("localhost", 4433, config: Raiha::QUIC::Config.new, tls_config: tls, keyring:) do |session|
62
+ Raiha::Runtime::Threaded::HTTP3::Client.new(session).get("/")
63
+ end
64
+ puts response.status, response.body
65
+ ```
66
+
67
+ `Threaded::Client.connect` takes the keywords of [the client of fibers](fiber-scheduler.md#connecting), and `max_threads:` (default 64), the most threads of the streams of `each_stream` at a time. The block runs in the thread that called `connect`.
68
+
69
+ One `Threaded::HTTP3::Client`, or one `Threaded::Session`, may be used from several threads at once: each request, or each stream, goes on a stream of its own.
70
+
71
+ ```ruby
72
+ Raiha::Runtime::Threaded::Client.connect("localhost", 4433, config: Raiha::QUIC::Config.new, tls_config: tls, keyring:) do |session|
73
+ client = Raiha::Runtime::Threaded::HTTP3::Client.new(session)
74
+ %w[/a /b /c].map { |path| Thread.new { client.get(path).body } }.map(&:value)
75
+ end
76
+ ```
77
+
78
+ Two threads must not read one `Stream`, or write one, at the same time.
79
+
80
+ ## QUIC
81
+
82
+ `Threaded::Server#run` gives the block each `Threaded::Session`, and `Threaded::Client.connect` gives its block one, as [the runtime of fibers](fiber-scheduler.md#quic) does. `each_stream` runs each stream in a thread of its own. The methods of `Session` and `Stream` are those of [Session](fiber-scheduler.md#session) and [Streams](fiber-scheduler.md#streams).
83
+
84
+ `session.connection` is the `QUIC::Connection` behind a lock: each of its methods takes the runtime's lock for the call, so `session.connection.stream_reset(stream.id, error_code: 7)` followed by `session.changed` works from any thread, as it does under the runtime of fibers. What a call returns, `session.connection.stats` for one, is read without the lock and may change while you read it.
85
+
86
+ ## How many threads
87
+
88
+ | Thread | How many |
89
+ | --- | --- |
90
+ | A socket's reader (`raiha-reader`) | One for each socket of a server or a client |
91
+ | The runner (`raiha-runner`) | One for each server, and for each connection of a client |
92
+ | The one that waits for `stop` (`raiha-wake`) | One for each server |
93
+ | A connection's handler (`raiha-conn`) | One for each connection, `max_connections` at most |
94
+ | A stream of `each_stream` (`raiha-stream`) | One for each stream, within `max_threads` |
95
+ | An HTTP/3 request (`raiha-request`) | One for each request, within `max_threads` |
96
+
97
+ A server starts at most `max_connections + max_threads` threads for the application, 320 by default. A handler counts toward `max_connections` until its thread ends, even after its connection has closed: a handler held up in a library keeps its place, and once `max_connections` places are taken, new connections are refused with CONNECTION_REFUSED. When `max_threads` threads of streams and requests are running, the next stream or request waits for one to end; its data waits in QUIC's flow control, and beyond that the peer waits. Threads the application starts itself are not counted.
98
+
99
+ The places are limited, so a request whose handler waits for the answer to another request to the same server can deadlock: if every place is taken by such handlers, the requests they wait for never get a thread.
100
+
101
+ ## Stopping
102
+
103
+ `stop` writes to a pipe and takes no lock, so a signal handler may call it, as under the runtime of fibers. The sessions are told they are `stopping?` and have the `timeout` to end their connections; those left are closed.
104
+
105
+ `run` then waits for the threads it started to end, until the time `stop` gave, or for `Threaded::Server::STOP_TIMEOUT` (30 seconds) when `run` is left by an exception such as `Interrupt`. A thread still running after that, held up in a library say, is not killed: `run` returns and leaves it running. Its connection has closed, so what it calls of the connection raises `Raiha::QUIC::ClosedError`. `Threaded::Client.connect` likewise waits for the threads of `each_stream` for `STOP_TIMEOUT` once its block is over.
106
+
107
+ ## Cancellation
108
+
109
+ No thread is interrupted with `Thread#raise`, which could stop it anywhere, in an `ensure` or with the runtime's lock held. When a server runs out of time to stop, it cancels the requests left with `H3_REQUEST_CANCELLED`; a thread that waits in a read or a write of its request raises `Raiha::Runtime::HTTP3::StreamReset` there, and one held up elsewhere raises it the next time it reads or writes. The runtime of fibers interrupts a fiber where it waits, when the scheduler can.
110
+
111
+ ## Exceptions
112
+
113
+ When a handler raises, its connection is closed with `INTERNAL_ERROR`, or its request answered with 500 or reset with `H3_INTERNAL_ERROR`, as under the runtime of fibers. The exception ends its thread, and Ruby reports it on standard error (`Thread#report_on_exception`).
114
+
115
+ ## The lock
116
+
117
+ Each server and client has one lock, a `Monitor`, that every thread takes before it touches a connection or HTTP/3: the methods of `Session`, `Stream` and `HTTP3` take it and let it go while they wait. No I/O and no code of the application runs under it.
118
+
119
+ A protocol over a `Session`, such as one of your own beside HTTP/3, is called under the lock: its `take` and `turn`, and the blocks of `session.wait_for`. They must not wait for anything, or every connection of the server waits with them. Code of the application called with the lock held raises `Raiha::Runtime::Error::Usage`, as `session.each_stream` called inside the block of `session.wait_for` does.
120
+
121
+ The two runtimes do not mix within a connection: `Threaded::HTTP3::Client.new` raises `Error::Usage` given a `Session` of the runtime of fibers, and `Raiha::Runtime::HTTP3::Client.new` given a `Threaded::Session`. A server of one and a client of the other speak QUIC to each other as usual.
122
+
123
+ ## Limits
124
+
125
+ - There is no Rack adapter and no `Workers` for the runtime on threads.
126
+ - It may be called inside a Fiber scheduler, from `Sync` say, and in a Ractor other than the main one, but neither is tested. A Ractor other than the main one runs its threads on Ruby's M:N scheduler, where OpenBSD with Ruby 4.0 has a bug that can crash the process (see [Workers and SO_REUSEPORT](platforms.md#workers-and-so_reuseport)).
127
+ - The qlog files are written as under the runtime of fibers (see [qlog.md](qlog.md)). The traces of the runtime on threads draw on a budget of their own, apart from that of the runtime of fibers in the same Ractor.
@@ -0,0 +1,55 @@
1
+ require "openssl"
2
+
3
+ # A CA and a server certificate it issues for "localhost", made each time an
4
+ # example runs, so that its client trusts the CA alone.
5
+ module ExampleCertificate
6
+ class << self
7
+ # The CA's certificate, DER-encoded, as a client's trust anchor.
8
+ def ca_der = ca.first.to_der
9
+
10
+ # The server's certificate chain and key, as a Keyring takes them.
11
+ def identity
12
+ @identity ||= begin
13
+ ca_cert, ca_key = ca
14
+ key = OpenSSL::PKey::EC.generate("prime256v1")
15
+ cert = certificate("localhost", key, issuer: ca_cert) do |factory|
16
+ [factory.create_extension("basicConstraints", "CA:FALSE", true),
17
+ factory.create_extension("extendedKeyUsage", "serverAuth"),
18
+ factory.create_extension("subjectAltName", "DNS:localhost")]
19
+ end
20
+ cert.sign(ca_key, "SHA256")
21
+ Raiha::TLS::Keyring::Identity.new(cert_der: [cert.to_der, ca_cert.to_der], key_der: key.private_to_der)
22
+ end
23
+ end
24
+
25
+ private def ca
26
+ @ca ||= begin
27
+ key = OpenSSL::PKey::EC.generate("prime256v1")
28
+ cert = certificate("Example CA", key) do |factory|
29
+ [factory.create_extension("basicConstraints", "CA:TRUE", true),
30
+ factory.create_extension("keyUsage", "keyCertSign,cRLSign", true)]
31
+ end
32
+ cert.sign(key, "SHA256")
33
+ [cert, key]
34
+ end
35
+ end
36
+
37
+ # A certificate of `key` for `name`, issued by `issuer` or by itself,
38
+ # with the extensions the block makes.
39
+ private def certificate(name, key, issuer: nil)
40
+ cert = OpenSSL::X509::Certificate.new
41
+ cert.version = 2
42
+ cert.serial = issuer ? 2 : 1
43
+ cert.subject = OpenSSL::X509::Name.new([["CN", name]])
44
+ cert.issuer = issuer ? issuer.subject : cert.subject
45
+ cert.public_key = key
46
+ cert.not_before = Time.now - 60
47
+ cert.not_after = Time.now + 3600
48
+ factory = OpenSSL::X509::ExtensionFactory.new
49
+ factory.subject_certificate = cert
50
+ factory.issuer_certificate = issuer || cert
51
+ yield(factory).each { |extension| cert.add_extension(extension) }
52
+ cert
53
+ end
54
+ end
55
+ end
@@ -0,0 +1,59 @@
1
+ # A server and a client of the runtime of raiha on the
2
+ # loopback interface, in fibers of the scheduler of the async gem: the
3
+ # server takes each connection and echoes each stream its client opens,
4
+ # and the client sends a payload on a stream of its own and reads it back.
5
+ # No loop of the application's own: the runtime waits on the sockets and
6
+ # the timers, and each call blocks only the fiber that makes it.
7
+ #
8
+ # Usage:
9
+ # bundle exec ruby -Ilib examples/high_level_loopback.rb
10
+ #
11
+ # Expected output:
12
+ # Raiha::Runtime::Server accepted 1 connection, stream echo OK
13
+
14
+ require "raiha/runtime"
15
+ # The scheduler of async reads with IO::Buffer, which Ruby 4.0 warns is
16
+ # experimental.
17
+ Warning[:experimental] = false
18
+ require "async"
19
+ require "securerandom"
20
+ require_relative "_certificate"
21
+
22
+ Runtime = Raiha::Runtime
23
+ QUIC = Raiha::QUIC
24
+ TLS = Raiha::TLS
25
+ REGISTRY = TLS::Extension::Registry::BUILTIN.with(QUIC::TransportParameters::Extension)
26
+ ALPN = ["hq-interop"].freeze
27
+
28
+ server_tls = TLS::Config.server(profile: TLS::Profile::QUIC, alpn: ALPN, registry: REGISTRY)
29
+ server = Runtime::Server.new(config: QUIC::Config.new, tls_config: server_tls,
30
+ keyring: TLS::Keyring.server(config: server_tls, identities: [ExampleCertificate.identity]), host: "127.0.0.1", port: 0)
31
+ client_tls = TLS::Config.client(trust_anchors: [ExampleCertificate.ca_der], profile: TLS::Profile::QUIC, alpn: ALPN, registry: REGISTRY)
32
+ payload = SecureRandom.random_bytes(256)
33
+ accepted = 0
34
+ echoed = nil
35
+
36
+ Async do
37
+ running = Async do
38
+ server.run do |session|
39
+ accepted += 1
40
+ session.each_stream { |stream| (stream << stream.read).close_write }
41
+ end
42
+ end
43
+ sleep 0.01 until server.local_address
44
+
45
+ Runtime::Client.connect("127.0.0.1", server.local_address[1], server_name: "localhost", config: QUIC::Config.new, tls_config: client_tls,
46
+ keyring: TLS::Keyring.client(config: client_tls)) do |session|
47
+ stream = session.open_stream
48
+ stream << payload
49
+ stream.close_write
50
+ echoed = stream.read
51
+ end
52
+
53
+ server.stop(timeout: 1)
54
+ running.wait
55
+ end
56
+
57
+ raise "Echo payload mismatch" unless echoed == payload
58
+
59
+ puts "Raiha::Runtime::Server accepted #{accepted} connection, stream echo OK"
@@ -0,0 +1,68 @@
1
+ # An HTTP/3 GET to a few public HTTP/3 servers with the runtime's client,
2
+ # printing each response's status, headers and the start of its body.
3
+ # With no arguments it asks a built-in list; URLs given as arguments take
4
+ # its place. The servers' certificates are verified against the system's
5
+ # trust store (OpenSSL::X509::DEFAULT_CERT_FILE). It needs the network, so
6
+ # no test runs it; a target that fails prints its error, and the next goes
7
+ # on.
8
+ #
9
+ # Usage:
10
+ # bundle exec ruby -Ilib examples/http3_get_public.rb
11
+ # bundle exec ruby -Ilib examples/http3_get_public.rb https://cloudflare-quic.com/
12
+ #
13
+ # Expected output (one block for each target):
14
+ # https://cloudflare-quic.com/
15
+ # status: 200
16
+ # headers:
17
+ # content-type: text/html
18
+ # ...
19
+ # body (... bytes, first 80): "..."
20
+
21
+ require "raiha/runtime"
22
+ # The scheduler of async reads with IO::Buffer, which Ruby 4.0 warns is
23
+ # experimental.
24
+ Warning[:experimental] = false
25
+ require "async"
26
+ require "openssl"
27
+ require "uri"
28
+
29
+ Runtime = Raiha::Runtime
30
+ QUIC = Raiha::QUIC
31
+ TLS = Raiha::TLS
32
+ REGISTRY = TLS::Extension::Registry::BUILTIN.with(QUIC::TransportParameters::Extension)
33
+
34
+ DEFAULT_TARGETS = [
35
+ "https://cloudflare-quic.com/",
36
+ "https://quic.nginx.org/",
37
+ "https://nghttp2.org/"
38
+ ].freeze
39
+
40
+ # The certificates of the system's trust store, DER-encoded.
41
+ def trust_anchors
42
+ pem = File.read(OpenSSL::X509::DEFAULT_CERT_FILE)
43
+ pem.scan(/-----BEGIN CERTIFICATE-----.+?-----END CERTIFICATE-----/m).map { |cert| OpenSSL::X509::Certificate.new(cert).to_der }
44
+ end
45
+
46
+ def print_response(url, response)
47
+ puts url
48
+ puts " status: #{response.status}"
49
+ puts " headers:"
50
+ response.headers.each { |name, value| puts " #{name}: #{value}" }
51
+ puts " body (#{response.body.bytesize} bytes, first 80): #{response.body.byteslice(0, 80).inspect}"
52
+ end
53
+
54
+ tls = TLS::Config.client(trust_anchors:, profile: TLS::Profile::QUIC, alpn: [Runtime::HTTP3::Client::ALPN], registry: REGISTRY)
55
+ targets = ARGV.empty? ? DEFAULT_TARGETS : ARGV
56
+
57
+ Async do
58
+ targets.each do |url|
59
+ uri = URI(url)
60
+ response = Runtime::Client.connect(uri.host, uri.port, config: QUIC::Config.new, tls_config: tls, keyring: TLS::Keyring.client(config: tls)) do |session|
61
+ Runtime::HTTP3::Client.new(session).get(uri.request_uri)
62
+ end
63
+ print_response(url, response)
64
+ rescue StandardError => error
65
+ puts url
66
+ puts " error: #{error.class}: #{error.message}"
67
+ end
68
+ end
@@ -0,0 +1,38 @@
1
+ # A QUIC handshake between a client and a server Connection in one
2
+ # process, with no socket: each side's datagrams are handed to the other
3
+ # by hand, at a time the example makes up. A Connection never reads a clock
4
+ # or touches the network, so this is all a test of the protocol needs.
5
+ #
6
+ # Usage:
7
+ # bundle exec ruby -Ilib examples/in_memory_handshake.rb
8
+ #
9
+ # Expected output:
10
+ # Handshake complete (client: true, server: true)
11
+
12
+ require "raiha/quic"
13
+ require_relative "_certificate"
14
+
15
+ QUIC = Raiha::QUIC
16
+ TLS = Raiha::TLS
17
+ REGISTRY = TLS::Extension::Registry::BUILTIN.with(QUIC::TransportParameters::Extension)
18
+ ALPN = ["hq-interop"].freeze
19
+ CLIENT = ["192.0.2.1", 50_000].freeze
20
+ SERVER = ["192.0.2.2", 443].freeze
21
+
22
+ client_tls = TLS::Config.client(trust_anchors: [ExampleCertificate.ca_der], profile: TLS::Profile::QUIC, alpn: ALPN, registry: REGISTRY)
23
+ server_tls = TLS::Config.server(profile: TLS::Profile::QUIC, alpn: ALPN, registry: REGISTRY)
24
+ now = 0.0
25
+ client = QUIC::Connection.client(config: QUIC::Config.new, tls_config: client_tls, keyring: TLS::Keyring.client(config: client_tls),
26
+ server_name: "localhost", remote: SERVER, time: Time.now, now:)
27
+ server = QUIC::Connection.server(config: QUIC::Config.new, tls_config: server_tls,
28
+ keyring: TLS::Keyring.server(config: server_tls, identities: [ExampleCertificate.identity]), time: Time.now, now:)
29
+
30
+ # A millisecond each way, until both have completed the handshake.
31
+ 20.times do
32
+ break if client.handshake_complete? && server.handshake_complete?
33
+ client.each_transmit(now:) { |transmit| server.receive(transmit.payload, from: CLIENT, now:) }
34
+ server.each_transmit(now:) { |transmit| client.receive(transmit.payload, from: SERVER, now:) }
35
+ now += 0.001
36
+ end
37
+
38
+ puts "Handshake complete (client: #{client.handshake_complete?}, server: #{server.handshake_complete?})"