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,591 @@
1
+ # Fiber scheduler
2
+
3
+ The pages on [QUIC](quic.md), the [HTTP/3 server](http3-server.md) and the [HTTP/3 client](http3-client.md) drive the protocols with a loop of your own: send what the connection has to send, feed it the datagrams that arrive, and call it again at its next timeout. `Raiha::Runtime` is that loop written once, for a Fiber scheduler. It owns the UDP sockets and the timers, runs each connection, stream and request in a fiber of its own, and gives the application calls that read as if they blocked: `stream.read` waits for data, `request.respond` waits while flow control holds the response back. Only the fiber that makes a call waits; the others go on.
4
+
5
+ ## The scheduler
6
+
7
+ The runtime waits through `Fiber.scheduler`, which Ruby leaves to a gem. The examples here use the [async](https://github.com/socketry/async) gem, which Raiha does not depend on; add it to your Gemfile:
8
+
9
+ ```ruby
10
+ gem "async"
11
+ ```
12
+
13
+ Call the runtime inside `Sync do ... end` or `Async do ... end`. `Runtime::Server#run`, `Runtime::HTTP3::Server#run` and `Runtime::Client.connect` raise `Raiha::Runtime::Error::Usage` on a thread with no scheduler. To run with no scheduler, on threads, use `Raiha::Runtime::Threaded`; see [Threads](threads.md).
14
+
15
+ The async gem reads sockets with `IO::Buffer`, which Ruby 4.0 warns is experimental. Set `Warning[:experimental] = false` before `require "async"` to silence it.
16
+
17
+ The server and the client share the scheduler with the rest of the application: run a server in an `Async` task and other tasks go on beside it, as the [QUIC echo](#a-minimal-echo) below does with a server and a client in one process. `stop` takes no lock and does not block, so it can be called from a signal handler or from another fiber.
18
+
19
+ ## HTTP/3 server
20
+
21
+ ### A minimal server
22
+
23
+ ```ruby
24
+ require "raiha"
25
+ require "async"
26
+
27
+ registry = Raiha::TLS::Extension::Registry::BUILTIN.with(Raiha::QUIC::TransportParameters::Extension)
28
+ tls = Raiha::TLS::Config.server(profile: Raiha::TLS::Profile::QUIC, alpn: ["h3"], registry:)
29
+ identity = Raiha::TLS::Keyring::Identity.new(
30
+ cert_der: OpenSSL::X509::Certificate.load(File.read("fullchain.pem")).map(&:to_der),
31
+ key_der: OpenSSL::PKey.read(File.read("privkey.pem")).private_to_der
32
+ )
33
+ keyring = Raiha::TLS::Keyring.server(config: tls, identities: [identity])
34
+
35
+ server = Raiha::Runtime::HTTP3::Server.new(config: Raiha::QUIC::Config.new, tls_config: tls, keyring:, host: "::", port: 4433)
36
+ trap("INT") { server.stop }
37
+
38
+ Sync do
39
+ server.run do |request|
40
+ request.respond(200, [["content-type", "text/plain"]], "hello from #{request.path}\n")
41
+ end
42
+ end
43
+ ```
44
+
45
+ What each piece is:
46
+
47
+ - The TLS `Config` uses the QUIC profile, offers `"h3"` by ALPN, and carries the extension registry with QUIC's transport parameters. See [configuration.md](configuration.md) for the TLS and QUIC settings.
48
+ - A `Keyring::Identity` is a certificate chain, leaf first, and its private key. `OpenSSL::X509::Certificate.load` reads every certificate of a PEM file. A `Keyring` holds the parsed identities; build one per process or Ractor, not per connection.
49
+ - `host` defaults to `"::"` and `port` to `443`. On a system where `"::"` does not take IPv4, the server binds `"0.0.0.0"` on the same port as well (see [platforms.md](platforms.md)).
50
+ - `run` blocks until the server stops. `stop` may be called from a signal handler.
51
+
52
+ ### Server options
53
+
54
+ `Runtime::HTTP3::Server.new` takes:
55
+
56
+ | Keyword | Default | Meaning |
57
+ | --- | --- | --- |
58
+ | `config:` | required | The `QUIC::Config` of the connections. |
59
+ | `tls_config:` | required | A server `TLS::Config` with `"h3"` in `alpn`. |
60
+ | `keyring:` | required | `TLS::Keyring.server` for that config. |
61
+ | `host:` | `"::"` | Address to bind. |
62
+ | `port:` | `443` | Port to bind; `0` picks a free one. |
63
+ | `max_connections:` | `1024` | Connections served at once. More are refused with `CONNECTION_REFUSED`. |
64
+ | `max_unvalidated:` | half of `max_connections` | Once this many connections have unvalidated addresses, new clients are sent a Retry first. `0` sends one to every client without a token. |
65
+ | `qlog_dir:` | `nil` | A directory to write a qlog of each connection to. See [qlog.md](qlog.md). |
66
+ | `settings:` | `Raiha::HTTP3::Settings.new` | The server's HTTP/3 SETTINGS. |
67
+ | `anti_replay:` | a `TLS::AntiReplay::Memory` of its own | The record of 0-RTT ClientHellos, so that each is taken at most once. |
68
+ | `worker:` | `nil` | The `Worker` given by `Workers`. See [Workers](#several-ractors-with-workers). Do not give `host` or `port` with it. |
69
+
70
+ `Raiha::HTTP3::Settings.new` takes `qpack_max_table_capacity:` (0), `qpack_blocked_streams:` (0), `max_field_section_size:` (65,536), `h3_datagram:` (false) and `enable_connect_protocol:` (false).
71
+
72
+ Other methods:
73
+
74
+ - `local_address` is `[address, port]` once `run` has bound the socket, and `nil` before. With `port: 0`, use it to learn the port.
75
+ - `stop(timeout: 30)` stops the server. See [Stopping](#stopping).
76
+ - `reconfigure(tls_config:, keyring:)` makes connections from now on use another TLS config and keyring, for a renewed certificate. Connections already taken keep theirs.
77
+
78
+ ### Requests
79
+
80
+ The block is called once per request, in a fiber of its own, with a `Runtime::HTTP3::Request`. A slow request does not hold up the others.
81
+
82
+ | Method | Value |
83
+ | --- | --- |
84
+ | `method`, `path` | The `:method` and `:path` pseudo-header fields (`""` if absent). |
85
+ | `authority`, `scheme`, `protocol` | `:authority`, `:scheme` and `:protocol`, or `nil`. `protocol` is set only for an Extended CONNECT. |
86
+ | `headers` | The header fields without the pseudo-header ones, as `[[name, value], ...]`. Names are lowercase. A field that appears more than once stays as separate pairs. |
87
+ | `body` | The request body as it arrives (below). |
88
+ | `trailers` | The trailer fields, once the body has been read to its end; `[]` until then or if there are none. |
89
+ | `stream_id` | The QUIC stream of the request. |
90
+ | `early_data?` | Whether the request may be a replay. See [Early data](#early-data-0-rtt). |
91
+ | `responded?` | Whether `respond` has been called. |
92
+
93
+ The body is read as it comes:
94
+
95
+ - `request.body.read_chunk` returns the next chunk, waiting for it, and `nil` at the end.
96
+ - `request.body.each { |chunk| ... }` yields each chunk until the end.
97
+ - `request.body.read` returns everything that is left as one String.
98
+
99
+ The server keeps at most 256 KiB of the body unread. Past that, it stops reading the stream and QUIC flow control holds the client back. A body you never read is not buffered without limit. When the request is over, the client is told to stop sending what is left of the body.
100
+
101
+ ```ruby
102
+ server.run do |request|
103
+ case [request.method, request.path]
104
+ in ["POST", "/upload"]
105
+ size = 0
106
+ request.body.each { |chunk| size += chunk.bytesize }
107
+ request.respond(200, [["content-type", "text/plain"]], "#{size} bytes, trailers #{request.trailers.inspect}\n")
108
+ in ["GET", "/stream"]
109
+ request.priority = { urgency: 5, incremental: true }
110
+ request.respond(200, [["content-type", "text/plain"]]) do |body|
111
+ 3.times { |i| body << "part #{i}\n" }
112
+ body.trailers = [["x-parts", "3"]]
113
+ end
114
+ in ["POST", "/order"] if request.early_data?
115
+ request.respond(425)
116
+ else
117
+ request.respond(404, [], "not found\n")
118
+ end
119
+ end
120
+ ```
121
+
122
+ ### Responses
123
+
124
+ `request.respond(status, headers = [], body = nil)` sends a whole response:
125
+
126
+ - `status` is an Integer from 200 to 599. Anything else raises `ArgumentError`. Interim (1xx) responses cannot be sent.
127
+ - `headers` is an Array of `[name, value]` pairs. Do not include `:status`; it is added for you.
128
+ - `body` is a String or `nil`. It is written as fast as flow control allows; `respond` waits until all of it has been handed to QUIC.
129
+
130
+ A request takes one response. A second `respond` raises `Raiha::Runtime::Error::Usage`.
131
+
132
+ #### Writing the body as you go
133
+
134
+ Give `respond` a block, and the block gets a `Runtime::HTTP3::ResponseBody` to write to:
135
+
136
+ - `write(data)` or `body << data` writes a chunk. Each write waits while the client's flow control holds the stream back.
137
+ - `trailers = [[name, value], ...]` sets trailer fields, sent after the body.
138
+ - `close` ends the response, with the trailers set so far, before the block is over. After that, `write` and `trailers=` raise `Error::Usage`. `closed?` tells whether it has ended.
139
+
140
+ The response ends when the block returns, if `close` has not ended it already.
141
+
142
+ #### Priority
143
+
144
+ `request.priority = { urgency: 0..7, incremental: true/false }` sets the priority of the response (RFC 9218). The parameters given override those the request asked for; those left out keep the request's.
145
+
146
+ #### When the block does not answer
147
+
148
+ - If the block returns without calling `respond`, the request is answered with 500. An Extended CONNECT request is answered with 501.
149
+ - If the block raises before responding, the request is answered with 500. If it raises in the middle of a response, the stream is reset with `H3_INTERNAL_ERROR`. A response that was already complete is left alone. In both cases the exception goes on to the scheduler (async logs it), and the other requests and the connection go on.
150
+ - If the client resets the request, or stops reading the response, the call that is waiting on it (a body read or a write) raises `Runtime::HTTP3::StreamReset`, with `stream_id` and the HTTP/3 `error_code`. The server catches it when it leaves your block, so you need to rescue it only to clean up.
151
+ - If the connection closes, waiting calls raise `Raiha::QUIC::ClosedError`. The server catches that too.
152
+
153
+ ### Early data (0-RTT)
154
+
155
+ The server takes 0-RTT only when its TLS config issues tickets and allows early data (`ticket_keys:` or `ticket_key:`, and `max_early_data_size:`; see [configuration.md](configuration.md)). It takes 0-RTT only from a ticket issued with the same HTTP/3 `settings`. Each ClientHello's 0-RTT is taken at most once, as recorded in `anti_replay:`. The default `TLS::AntiReplay::Memory` takes no 0-RTT for its first 11 seconds, so that a ClientHello taken before a restart is not taken again.
156
+
157
+ 0-RTT can still be replayed by an attacker to another server, or arrive again by way of a proxy. `request.early_data?` is true when any part of the request came in 0-RTT, or when it carries an `Early-Data` header field, which a proxy adds to a request it forwarded from early data. Answering 425 (Too Early) to a request that is not safe to repeat is up to you.
158
+
159
+ ### Stopping
160
+
161
+ `server.stop(timeout: 30)` asks the server to stop. Only the first call counts. It does not wait, so a signal handler may call it.
162
+
163
+ 1. No new connections are taken.
164
+ 2. Each connection is sent a GOAWAY, then after twice its RTT a second GOAWAY that names the first request not yet seen. Requests after that are rejected with `H3_REQUEST_REJECTED`.
165
+ 3. Requests already taken are let finish, and what was sent is let be acknowledged. Then the connection closes with `H3_NO_ERROR`.
166
+ 4. When `timeout` seconds have passed, requests not yet given to the block are rejected, and those in progress are cancelled with `H3_REQUEST_CANCELLED`. Their fibers get `StreamReset` where they wait, if the scheduler can interrupt fibers. Then the remaining connections close.
167
+
168
+ `run` returns once every connection has closed.
169
+
170
+ ### Rack
171
+
172
+ `Raiha::Runtime::Rack` runs a Rack 3 application on the server. It is not loaded by `require "raiha"`, and it does not depend on the rack gem.
173
+
174
+ ```ruby
175
+ require "raiha/runtime/rack"
176
+
177
+ app = lambda do |env|
178
+ request = env["raiha.request"]
179
+ [200, { "content-type" => "text/plain" }, ["#{env["REQUEST_METHOD"]} #{env["PATH_INFO"]} over #{env["SERVER_PROTOCOL"]}, ",
180
+ "early data: #{request.early_data?}\n"]]
181
+ end
182
+
183
+ server.run(&Raiha::Runtime::Rack.new(app))
184
+ ```
185
+
186
+ What the adapter does:
187
+
188
+ - `rack.input` reads the request body as it arrives. It supports `read`, `read(length)`, `gets`, `each` and `close`.
189
+ - A body that responds to `each` is written chunk by chunk. A body that responds to `call` (a streaming body) is called with a stream that reads the request (`read`) and writes the response (`write`, `<<`, `flush`). The response ends at `close_write` or `close`, even if the body goes on.
190
+ - A header value that is an Array is sent as one field line per element. Headers whose names start with `rack.` are not sent.
191
+ - The response to `HEAD` is sent without its body.
192
+ - `SERVER_PROTOCOL` is `"HTTP/3"`. `HTTP_HOST`, `SERVER_NAME` and `SERVER_PORT` come from `:authority`, or from the `host` field when there is none. A missing port is 443 for https and 80 for http.
193
+ - Repeated header fields are joined with `", "`, and `cookie` fields with `"; "`.
194
+ - A header field whose name has an underscore is left out, so that `x_forwarded_for` cannot pass for `x-forwarded-for`.
195
+ - A request whose scheme is not `http` or `https` is answered with 400.
196
+ - For an Extended CONNECT, `rack.protocol` is `[protocol]`.
197
+ - `env["raiha.request"]` is the `Runtime::HTTP3::Request`, for the trailers, `early_data?`, `priority=` and the rest.
198
+
199
+ A streaming body, echoing the request:
200
+
201
+ ```ruby
202
+ echo = lambda do |env|
203
+ [200, { "content-type" => "application/octet-stream" }, proc do |stream|
204
+ while (chunk = stream.read(16_384))
205
+ stream.write(chunk)
206
+ end
207
+ stream.close
208
+ end]
209
+ end
210
+ ```
211
+
212
+ ### Several Ractors with Workers
213
+
214
+ `Raiha::Runtime::Workers` runs a server in each of several Ractors, all on one port. It binds a socket per worker with `SO_REUSEPORT`, and runs your block in each worker's Ractor with its `Worker`. The block makes a server with `worker:` and `config: worker.config`, and runs it under a Fiber scheduler of its own.
215
+
216
+ ```ruby
217
+ identity = Ractor.make_shareable(Raiha::TLS::Keyring::Identity.new(
218
+ cert_der: OpenSSL::X509::Certificate.load(File.read("fullchain.pem")).map(&:to_der),
219
+ key_der: OpenSSL::PKey.read(File.read("privkey.pem")).private_to_der
220
+ ))
221
+
222
+ workers = Raiha::Runtime::Workers.new(count: 4, config: Raiha::QUIC::Config.new, host: "::", port: 4433, args: [tls, identity]) do |worker, tls, identity|
223
+ keyring = Raiha::TLS::Keyring.server(config: tls, identities: [identity])
224
+ Sync do
225
+ Raiha::Runtime::HTTP3::Server.new(config: worker.config, tls_config: tls, keyring:, worker:).run do |request|
226
+ request.respond(200, [["content-type", "text/plain"]], "worker #{worker.id} answered #{request.path}\n")
227
+ end
228
+ end
229
+ end
230
+ trap("INT") { workers.stop }
231
+ workers.run
232
+ ```
233
+
234
+ - The block runs in another Ractor and cannot use local variables from outside it. Pass what it needs in `args:`; each is given to the block after the worker. Arguments that are not shareable are copied.
235
+ - A `Keyring` cannot be sent to another Ractor, so pass the identities and build the keyring inside the block.
236
+ - `count` is 1 to 256. `host` defaults to `"::"` and `port` to `443`.
237
+ - The `config` is shared by all workers. If it has no `retry_token_key` or `stateless_reset_key`, one is generated for all of them, so that each worker accepts the tokens and recognizes the connection IDs that another issued. Its `connection_id_length` must be at least 4 (the default is 8), since the connection IDs carry the worker's ID.
238
+ - The workers share one record of 0-RTT, so a ClientHello's 0-RTT is taken once across all of them.
239
+ - A datagram that arrives at one worker for another worker's connection, as after a client migrates, is handed on to that worker.
240
+
241
+ Methods:
242
+
243
+ - `run` blocks until every worker is over. When one worker's block ends, the others are told to stop. If a worker raised, `run` raises the first error.
244
+ - `stop(timeout: 30)` stops every worker as `Server#stop` does. It may be called from a signal handler.
245
+ - `reconfigure(tls_config:, identities:)` makes every worker take new connections with another TLS config, building its keyring from `identities`.
246
+ - `stats(timeout: 1.0)` returns a `Worker::Stats` per worker (`id`, `sent`, `received` and `dropped` counts of datagrams handed between workers), or `nil` for a worker that does not answer in time.
247
+ - `local_address` is `[address, port]` once `run` has bound the sockets.
248
+
249
+ `SO_REUSEPORT` spreads datagrams across the sockets on Linux. On other systems, such as OpenBSD, the kernel may give them all to one socket. The worker that has it then takes every new connection, so the load is not spread. See [platforms.md](platforms.md).
250
+
251
+ ## HTTP/3 client
252
+
253
+ ### A minimal request
254
+
255
+ ```ruby
256
+ require "raiha"
257
+ require "async"
258
+
259
+ registry = Raiha::TLS::Extension::Registry::BUILTIN.with(Raiha::QUIC::TransportParameters::Extension)
260
+ tls = Raiha::TLS::Config.client(trust_anchors: [File.read("ca.der")], profile: Raiha::TLS::Profile::QUIC, alpn: [Raiha::Runtime::HTTP3::Client::ALPN], registry:)
261
+ keyring = Raiha::TLS::Keyring.client(config: tls)
262
+
263
+ Sync do
264
+ response = Raiha::Runtime::Client.connect("localhost", 4433, config: Raiha::QUIC::Config.new, tls_config: tls, keyring:) do |session|
265
+ Raiha::Runtime::HTTP3::Client.new(session).get("/", headers: [["accept", "text/plain"]])
266
+ end
267
+ puts response.status, response.headers.inspect, response.body
268
+ end
269
+ ```
270
+
271
+ - The TLS `Config` uses the QUIC profile, offers `"h3"` (`Runtime::HTTP3::Client::ALPN`) by ALPN, and carries the extension registry with QUIC's transport parameters.
272
+ - `trust_anchors` is an Array of DER-encoded CA certificates that the server's certificate is verified against. See [Trust anchors](configuration.md#trust-anchors) for the system's store.
273
+ - `Client.connect` gives the block a `Session` once the handshake completes, and returns the block's value. When the block is over, the connection is closed with `H3_NO_ERROR`.
274
+ - `HTTP3::Client.new(session)` attaches HTTP/3 to the session. Make one per connection.
275
+
276
+ ### Connecting
277
+
278
+ `Runtime::Client.connect(host, port, **options) { |session| ... }` resolves `host` and tries each of its addresses in turn, with a socket of its own for each, until one completes its handshake. There is no discovery of HTTP/3 through Alt-Svc or HTTPS records, and no fallback to TCP: the host and port are taken to speak QUIC.
279
+
280
+ | Keyword | Default | Meaning |
281
+ | --- | --- | --- |
282
+ | `config:` | required | The `QUIC::Config` of the connection. See [configuration.md](configuration.md). |
283
+ | `tls_config:` | required | A client `TLS::Config` with `"h3"` in `alpn`. |
284
+ | `keyring:` | required | `TLS::Keyring.client` for that config. |
285
+ | `server_name:` | `host` | The name sent by SNI and verified against the certificate. It is also the default `:authority` of requests. |
286
+ | `connect_timeout:` | `5.0` | Seconds to wait for each address's handshake. |
287
+ | `qlog_dir:` | `nil` | A directory to write a qlog of each connection tried to. See [qlog.md](qlog.md). |
288
+ | `session:` | `nil` | A ticket to resume. See [Resumption and 0-RTT](#resumption-and-0-rtt). |
289
+ | `token:` | `nil` | An address validation token from an earlier connection, a `Raiha::QUIC::Token`. |
290
+ | `early_data:` | `false` | Send requests in 0-RTT when the ticket allows it. |
291
+
292
+ When no address completes a handshake, `connect` raises `Runtime::ConnectError`. Its `errors` has `[address, error]` for each address tried: the `Raiha::QUIC::ClosedError` of a connection that closed or ran out of time, or the error of a name that did not resolve.
293
+
294
+ ```ruby
295
+ begin
296
+ Raiha::Runtime::Client.connect("localhost", 4433, config: Raiha::QUIC::Config.new, tls_config: tls, keyring:, connect_timeout: 1) do |session|
297
+ Raiha::Runtime::HTTP3::Client.new(session).get("/")
298
+ end
299
+ rescue Raiha::Runtime::ConnectError => error
300
+ error.errors.each { |address, failure| warn "#{address.inspect}: #{failure.message}" }
301
+ end
302
+ ```
303
+
304
+ Once the block has started, its connection is not retried at another address. If the connection closes while the block is using it, the waiting call raises `Raiha::QUIC::ClosedError`.
305
+
306
+ `HTTP3::Client.new(session, authority: nil, settings: Raiha::HTTP3::Settings.new)` takes the `:authority` of its requests (the session's `server_name` by default) and its own HTTP/3 SETTINGS. Requests always go with `:scheme` `https`.
307
+
308
+ ### Requests
309
+
310
+ `client.get(path, headers: [])` sends a GET and reads the whole response.
311
+
312
+ `client.request(method, path, headers: [], body: nil, urgency: nil, incremental: nil)` sends any request:
313
+
314
+ - `headers` is an Array of `[name, value]` pairs, without pseudo-header fields. Names must be lowercase; a malformed field, such as `["Accept", "*/*"]`, raises `ArgumentError`.
315
+ - `body` is a String, or anything that reads as an IO does (`read(length)`), such as a File. It is read 64 KiB at a time and sent as the server's flow control allows. If the server stops the request with `H3_NO_ERROR` because it does not want the rest of the body, sending stops and the response is read all the same.
316
+ - `urgency` (0 to 7) and `incremental` are sent as the `priority` header field (RFC 9218). An urgency outside 0 to 7 raises `ArgumentError`.
317
+
318
+ Without a block, `request` and `get` return a `Runtime::HTTP3::Response`, with `status` (an Integer), `headers` (without pseudo-header fields), `body` (a binary String) and `trailers` (`[]` when there are none). Interim (1xx) responses are skipped.
319
+
320
+ ```ruby
321
+ Raiha::Runtime::Client.connect("localhost", 4433, config: Raiha::QUIC::Config.new, tls_config: tls, keyring:) do |session|
322
+ client = Raiha::Runtime::HTTP3::Client.new(session)
323
+ client.request("POST", "/form", headers: [["content-type", "application/x-www-form-urlencoded"]], body: "name=raiha")
324
+ File.open("upload.bin", "rb") { |file| client.request("PUT", "/files/upload.bin", body: file) }
325
+ client.request("GET", "/style.css", urgency: 1, incremental: false)
326
+ end
327
+ ```
328
+
329
+ #### Several requests at once
330
+
331
+ Requests made from different fibers share the connection and run side by side:
332
+
333
+ ```ruby
334
+ bodies = %w[/a /b /c].map { |path| Async { client.get(path).body } }.map(&:wait)
335
+ ```
336
+
337
+ ### Streaming a response
338
+
339
+ Give `request` a block, and it is called with a `Runtime::HTTP3::ResponseStream` once the response's header section has arrived. The block's value is returned.
340
+
341
+ - `status` and `headers` are those of the response.
342
+ - `body.read_chunk` returns the next chunk, waiting for it, and `nil` at the end. `body.each { |chunk| ... }` yields each chunk, and `body.read` returns all that is left.
343
+ - `trailers` is the trailer fields, once the body has been read to its end.
344
+ - `cancel` stops the request and its response with `H3_REQUEST_CANCELLED`.
345
+
346
+ ```ruby
347
+ client.request("GET", "/big") do |response|
348
+ size = 0
349
+ response.body.each { |chunk| size += chunk.bytesize }
350
+ [response.status, size, response.trailers]
351
+ end
352
+ ```
353
+
354
+ The client keeps at most 256 KiB of the body unread. Past that, it stops reading the stream, and QUIC flow control holds the server back until the application reads more. A response the block leaves unread when it returns is cancelled.
355
+
356
+ ### Errors
357
+
358
+ | Error | When |
359
+ | --- | --- |
360
+ | `Runtime::ConnectError` | `Client.connect` could not connect to any address. |
361
+ | `Runtime::HTTP3::StreamReset` | The server reset the response, or stopped the request with an error. `stream_id` and `error_code` (the HTTP/3 error code) tell which and why. The connection and other requests go on. |
362
+ | `Raiha::QUIC::ClosedError` | The connection closed. `error` has the code, whether it is an application error, and the reason. |
363
+ | `Raiha::QUIC::Error::ZeroRttRejected` | A request sent in 0-RTT was rejected by the server. See below. |
364
+ | `Runtime::Error::Usage` | A call the runtime does not allow, such as `connect` without a Fiber scheduler. |
365
+
366
+ ```ruby
367
+ begin
368
+ client.get("/reset")
369
+ rescue Raiha::Runtime::HTTP3::StreamReset => error
370
+ warn "stream #{error.stream_id} reset with 0x#{error.error_code.to_s(16)}"
371
+ end
372
+ ```
373
+
374
+ ### Resumption and 0-RTT
375
+
376
+ A connection that resumes an earlier one skips the server's certificate, and may send requests in 0-RTT, before the handshake completes.
377
+
378
+ - `client.tickets` gives the session tickets the server sent, each a `Raiha::HTTP3::Session` that carries the server's SETTINGS too. There are none until the server's SETTINGS have arrived. The newest is last.
379
+ - `session.tokens` gives the address validation tokens the server sent in NEW_TOKEN frames, newest last, each a `Raiha::QUIC::Token` (`to_h` and `Raiha::QUIC::Token.from_h` turn one into plain values and back). A connection that presents one need not have its address validated again.
380
+ - Pass a ticket as `session:` and a token as `token:` to `Client.connect`. Each is for one connection only: using one again links the connections for anyone watching, so drop it once used.
381
+ - With `early_data: true` and a ticket that allows 0-RTT, the block is given the session at once, and the requests it makes go in 0-RTT. While 0-RTT goes, HTTP/3 keeps to the SETTINGS stored in the ticket.
382
+
383
+ ```ruby
384
+ ticket = token = nil
385
+ Raiha::Runtime::Client.connect("localhost", 4433, config: Raiha::QUIC::Config.new, tls_config: tls, keyring:) do |session|
386
+ client = Raiha::Runtime::HTTP3::Client.new(session)
387
+ client.get("/")
388
+ ticket = client.tickets.last
389
+ token = session.tokens.last
390
+ end
391
+
392
+ Raiha::Runtime::Client.connect("localhost", 4433, config: Raiha::QUIC::Config.new, tls_config: tls, keyring:, session: ticket, token:, early_data: true) do |session|
393
+ client = Raiha::Runtime::HTTP3::Client.new(session)
394
+ response = begin
395
+ client.get("/")
396
+ rescue Raiha::QUIC::Error::ZeroRttRejected
397
+ client.get("/")
398
+ end
399
+ end
400
+ ```
401
+
402
+ 0-RTT can be replayed by an attacker, so send in it only requests that are safe to repeat. Call `session.wait_handshake` before any other request to wait until the handshake has completed.
403
+
404
+ When the server rejects 0-RTT, each request that went in it raises `Raiha::QUIC::Error::ZeroRttRejected`, and HTTP/3 starts over on the connection. Whether to send the request again is up to the application; requests made after the rejection go normally. `session.connection.zero_rtt_state` tells how 0-RTT went (`:accepted` or `:rejected`), and `session.handshake.resumed` whether the connection resumed.
405
+
406
+ A connection given to the block is not tried at another address, because what it sent in 0-RTT must not be sent again without the application deciding to.
407
+
408
+ ## QUIC
409
+
410
+ `Runtime::Server` and `Runtime::Client.connect` run QUIC connections without HTTP/3: the application gets a `Session` and reads and writes its streams. The HTTP/3 server and client above are built on them, so the options of this section apply to those as well.
411
+
412
+ ### A minimal echo
413
+
414
+ ```ruby
415
+ require "raiha/runtime"
416
+ require "async"
417
+ require "./examples/_certificate" # a throwaway CA and a certificate for "localhost"
418
+
419
+ Warning[:experimental] = false # async reads with IO::Buffer, which Ruby 4.0 calls experimental
420
+
421
+ registry = Raiha::TLS::Extension::Registry::BUILTIN.with(Raiha::QUIC::TransportParameters::Extension)
422
+ alpn = ["echo"]
423
+
424
+ server_tls = Raiha::TLS::Config.server(profile: Raiha::TLS::Profile::QUIC, alpn:, registry:)
425
+ server = Raiha::Runtime::Server.new(
426
+ config: Raiha::QUIC::Config.new,
427
+ tls_config: server_tls,
428
+ keyring: Raiha::TLS::Keyring.server(config: server_tls, identities: [ExampleCertificate.identity]),
429
+ host: "127.0.0.1", port: 0
430
+ )
431
+
432
+ client_tls = Raiha::TLS::Config.client(trust_anchors: [ExampleCertificate.ca_der], profile: Raiha::TLS::Profile::QUIC, alpn:, registry:)
433
+
434
+ Async do
435
+ serving = Async do
436
+ server.run do |session|
437
+ session.each_stream do |stream|
438
+ stream << stream.read
439
+ stream.close_write
440
+ end
441
+ end
442
+ end
443
+ sleep 0.01 until server.local_address
444
+
445
+ reply = Raiha::Runtime::Client.connect("127.0.0.1", server.local_address[1], server_name: "localhost",
446
+ config: Raiha::QUIC::Config.new, tls_config: client_tls, keyring: Raiha::TLS::Keyring.client(config: client_tls)) do |session|
447
+ stream = session.open_stream
448
+ stream << "hello"
449
+ stream.close_write
450
+ stream.read
451
+ end
452
+ puts reply # => hello
453
+
454
+ server.stop(timeout: 1)
455
+ serving.wait
456
+ end
457
+ ```
458
+
459
+ Run it from the root of the repository with `bundle exec ruby -Ilib echo.rb`. [examples/high_level_loopback.rb](../examples/high_level_loopback.rb) is the same echo, run as one of the examples.
460
+
461
+ ### Server
462
+
463
+ ```ruby
464
+ server = Raiha::Runtime::Server.new(config:, tls_config:, keyring:, host: "::", port: 443)
465
+ server.run { |session| ... }
466
+ ```
467
+
468
+ | Argument | Default | Meaning |
469
+ | --- | --- | --- |
470
+ | `config` | required | The `QUIC::Config` of every connection. |
471
+ | `tls_config` | required | A server `TLS::Config` with the QUIC profile. |
472
+ | `keyring` | required | The `TLS::Keyring.server` of `tls_config`, holding the certificates. |
473
+ | `host` | `"::"` | The address to bind. On Linux, `"::"` takes IPv4 too. |
474
+ | `port` | `443` | The UDP port. `0` lets the OS choose one. |
475
+ | `max_connections` | `1024` | The most connections at a time. Clients beyond it are refused with `CONNECTION_REFUSED`. |
476
+ | `max_unvalidated` | `max_connections / 2` | How many connections may have unvalidated addresses before new clients are sent a Retry. `0` sends every new client one. |
477
+ | `qlog_dir` | `nil` | A directory for a qlog of each connection. See [qlog.md](qlog.md). |
478
+ | `anti_replay` | a new `TLS::AntiReplay::Memory` | Where the 0-RTT the server took is recorded, so that each ClientHello's 0-RTT is taken at most once. |
479
+ | `app_early_data_context` | `""` | What your 0-RTT depends on. A ticket issued under another context has its 0-RTT rejected. |
480
+ | `worker`, `stop_error_code` | `nil`, `0` | Set by `Runtime::Workers`. A `worker` given along with `host` or `port` raises `ArgumentError`. |
481
+
482
+ `run` binds the socket and serves until the server stops. It gives the block the `Session` of each connection once its handshake completes, in a fiber of its own. When the block returns, the server lets what the streams sent be acknowledged, until three PTOs go with no more of it acknowledged or 30 seconds in all, then closes the connection with application error 0. When the block raises, the connection closes with `INTERNAL_ERROR` and the exception goes on to the scheduler. Other connections are not touched either way. `run` raises whatever failed inside the runtime.
483
+
484
+ `local_address` is `[address, port]` once `run` has bound the socket, and `nil` before. With `port: 0`, wait for it as the example does.
485
+
486
+ `stop(timeout: 30, error_code: 0)` asks the server to stop. It takes no lock and does not block, so a signal handler may call it, and only the first call counts. The server takes no new connection and tells every `Session` it is `stopping?`. The sessions get `timeout` seconds to end their connections. Those left open are then closed with `error_code`, and `run` returns. A connection whose block has not started yet is closed at once.
487
+
488
+ `reconfigure(tls_config:, keyring:)` makes connections from then on use another TLS config and keyring, such as a renewed certificate. Connections already taken keep theirs, and the QUIC `Config` cannot be changed.
489
+
490
+ #### Address validation and Retry
491
+
492
+ The server counts the connections whose client address has not been validated yet. Those are the handshakes admitted and not finished, plus the connections whose handshake has not validated the address. Once there are `max_unvalidated` of them, a client that shows no token is sent a Retry first. Initials from spoofed addresses therefore cannot use up all of `max_connections`. A token from an earlier connection (`Session#tokens`, given back to `Client.connect(token:)`) skips the Retry.
493
+
494
+ #### Preferred addresses
495
+
496
+ With `QUIC::Config.new(preferred_address: {ipv4: [host, port], ipv6: [host, port]})`, the server offers its clients an address to move to once the handshake is confirmed. `run` binds a socket to each preferred address that the first socket does not already cover, and raises the bind error if one fails, so no client is offered an address nobody listens at. The client moves on its own; there is no call for it.
497
+
498
+ #### Workers
499
+
500
+ `Raiha::Runtime::Workers` runs several servers, each in a Ractor of its own, on one port. See [Several Ractors with Workers](#several-ractors-with-workers).
501
+
502
+ ### Client
503
+
504
+ ```ruby
505
+ value = Raiha::Runtime::Client.connect(host, port, config:, tls_config:, keyring:) { |session| ... }
506
+ ```
507
+
508
+ | Argument | Default | Meaning |
509
+ | --- | --- | --- |
510
+ | `host`, `port` | required | Where to connect. The host is resolved with `Addrinfo.getaddrinfo`. |
511
+ | `config` | required | The `QUIC::Config` of the connection. |
512
+ | `tls_config`, `keyring` | required | A client `TLS::Config` with the QUIC profile, and its `TLS::Keyring.client`. |
513
+ | `server_name` | `host` | The name sent in SNI and checked against the certificate. |
514
+ | `connect_timeout` | `5.0` | Seconds each address has to complete its handshake. |
515
+ | `qlog_dir` | `nil` | A directory for a qlog of each connection tried. |
516
+ | `session`, `token`, `early_data` | `nil`, `nil`, `false` | Resumption and 0-RTT; see below. |
517
+
518
+ `connect` tries each address of the host in turn, each from a socket of its own, until one completes its handshake within `connect_timeout`. It then calls the block with the `Session` and returns the block's value. There is no HTTP/3 discovery (Alt-Svc or HTTPS records) and no fallback to TCP: the host and port are taken to speak QUIC.
519
+
520
+ When the block returns, what the streams sent is let be acknowledged, until three PTOs go with no more of it acknowledged or 30 seconds in all, so a final write is not cut short. The connection then closes with application error 0, or with the close code of the protocol attached to the session (`H3_NO_ERROR` for HTTP/3). The closing period is not waited out: the CONNECTION_CLOSE is sent and the socket closes.
521
+
522
+ When no address works, `connect` raises `Raiha::Runtime::ConnectError`. Its `errors` is a list of `[address, error]` pairs: a `QUIC::ClosedError` for a connection that closed or timed out, a `SystemCallError` for a socket that could not be made, or a `SocketError` for a name that did not resolve.
523
+
524
+ ```text
525
+ could not connect to 127.0.0.1:9 (["127.0.0.1", 9]: closed with transport error 0x0: no handshake in 1 seconds)
526
+ ```
527
+
528
+ Each socket is bound to `"::"`, which on Linux sends to IPv4 too, so the connection can move to a preferred address of either family. Where `"::"` takes no IPv4, as on OpenBSD, or cannot be bound at all, the client binds `"0.0.0.0"` for an IPv4 server. See [platforms.md](platforms.md).
529
+
530
+ #### Resuming a connection
531
+
532
+ A client's `Session#tickets` holds the session tickets the server sent (the newest 8). `Session#tokens` holds the NEW_TOKEN tokens (also the newest 8). Pass one ticket as `session:` and one token as `token:` to a later `connect` to resume and to skip address validation. Use each only once and then drop it, since reusing one links the two connections for anyone watching.
533
+
534
+ With `early_data: true` and a ticket that allows 0-RTT, the block is called before the handshake completes, and what it writes goes in 0-RTT. An attacker can replay 0-RTT, so write only what is safe to repeat before calling `session.wait_handshake`. A connection given to the block is not retried at another address. If the server rejects the 0-RTT, the streams opened in it raise `QUIC::Error::ZeroRttRejected`, and sending that data again is up to you. `session.connection.zero_rtt_state` is `:disabled`, `:pending`, `:accepted` or `:rejected`.
535
+
536
+ ```ruby
537
+ reply = Raiha::Runtime::Client.connect("127.0.0.1", port, server_name: "localhost", config: Raiha::QUIC::Config.new,
538
+ tls_config: client_tls, keyring: client_keyring, session: ticket, token:, early_data: true) do |session|
539
+ stream = session.open_stream
540
+ (stream << "safe to repeat").close_write
541
+ session.wait_handshake
542
+ stream.read
543
+ end
544
+ ```
545
+
546
+ The server's side of this, ticket keys and 0-RTT, is set in its `TLS::Config`; see [configuration.md](configuration.md#tickets-and-0-rtt).
547
+
548
+ ### Session
549
+
550
+ | Method | What it does |
551
+ | --- | --- |
552
+ | `open_stream(direction: :bidi)` | Opens a stream (`:bidi` or `:uni`), waiting until the peer's stream limit allows it. Returns a `Stream`. |
553
+ | `accept_stream` | Waits for the next stream the peer opens. Returns `nil` once the connection has closed, or once the server is stopping and no stream has come. |
554
+ | `each_stream { \|stream\| }` | Calls the block for each stream the peer opens, each in a fiber of its own, until `accept_stream` returns `nil`. |
555
+ | `wait_handshake` | Waits until the handshake has completed. |
556
+ | `wait_ready` | Waits until the application may send: once the handshake has completed, or right away while 0-RTT is pending. |
557
+ | `wait_acknowledged(seconds)` | Waits up to `seconds` until everything the streams sent has been acknowledged. Returns whether it has. |
558
+ | `close(error_code: 0, reason: "")` | Closes the connection with an application error code. |
559
+ | `close_when_acknowledged(error_code: 0, timeout: 30)` | Closes once what was sent is acknowledged, or once three PTOs go with no more of it acknowledged, or after `timeout` seconds in all. |
560
+ | `closed?` | Whether the connection has closed. |
561
+ | `stopping?`, `stop_deadline` | At a server, whether it is stopping, and the clock time at which it will close what is left. |
562
+ | `handshake` | The `TLS::Event::HandshakeComplete` of the handshake once it is done, with what was negotiated. |
563
+ | `tickets`, `tokens` | At a client, the session tickets and NEW_TOKEN tokens the server sent. |
564
+ | `server_name`, `resumed` | At a client, the server's name and the ticket given to `connect`. |
565
+ | `connection` | The underlying `QUIC::Connection`, for what the session does not wrap. |
566
+
567
+ Once the connection has closed, a call that waits raises `Raiha::QUIC::ClosedError`, whose message gives the close reason. There are two exceptions: `accept_stream` returns `nil` instead, and a read still returns the data that arrived before the close. If the runtime itself stops, a waiting call raises whatever failed in it.
568
+
569
+ #### Streams
570
+
571
+ A `Stream` is read and written like an IO.
572
+
573
+ - `read(length)` returns up to `length` bytes as soon as there are any, and `nil` at the end of the stream.
574
+ - `read` with no length returns everything up to the end, and `""` if the stream has already ended.
575
+ - `write(data)` writes all of `data`, waiting while the peer's flow control holds it back, and returns its length. `<<` does the same and returns the stream.
576
+ - `close_write` ends the sending part (FIN).
577
+ - `id` is the stream ID.
578
+
579
+ A unidirectional stream can only be written by the side that opened it and only read by the other.
580
+
581
+ When the peer resets a stream you are reading, `read` raises `Raiha::Runtime::StreamReset`. When the peer sends STOP_SENDING for a stream you are writing, `write` raises it. `error_code` and `stream_id` tell which. `Stream` has no reset of its own; reset a stream through the core connection and wake the runtime:
582
+
583
+ ```ruby
584
+ session.connection.stream_reset(stream.id, error_code: 7) # RESET_STREAM
585
+ session.connection.stream_stop_sending(stream.id, error_code: 7) # STOP_SENDING
586
+ session.changed
587
+ ```
588
+
589
+ #### Not in the runtime
590
+
591
+ The runtime's `Session` has no API for QUIC DATAGRAM frames. Even with `max_datagram_frame_size` set in the `Config`, the session drops the DATAGRAM frames it receives; drive the connection yourself, as [QUIC](quic.md) shows, to use them. Connection migration needs no API: a server follows a client that moves, and a client moves to the server's preferred address on its own.