rwebtransport 0.1.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 (122) hide show
  1. package/Cargo.lock +666 -0
  2. package/Cargo.toml +31 -0
  3. package/LICENSE +202 -0
  4. package/NOTICE +41 -0
  5. package/README.md +550 -0
  6. package/crates/echo-server/Cargo.toml +20 -0
  7. package/crates/echo-server/src/main.rs +666 -0
  8. package/crates/native/Cargo.toml +23 -0
  9. package/crates/native/src/config.rs +129 -0
  10. package/crates/native/src/driver.rs +463 -0
  11. package/crates/native/src/lib.rs +821 -0
  12. package/crates/native/src/server.rs +718 -0
  13. package/crates/native/src/session.rs +1191 -0
  14. package/crates/native/src/tls.rs +96 -0
  15. package/crates/wtcore/Cargo.toml +15 -0
  16. package/crates/wtcore/src/h3.rs +226 -0
  17. package/crates/wtcore/src/lib.rs +9 -0
  18. package/dist/datagrams.d.ts +16 -0
  19. package/dist/errors.d.ts +10 -0
  20. package/dist/index.d.ts +7 -0
  21. package/dist/index.js +1512 -0
  22. package/dist/index.js.map +1 -0
  23. package/dist/index.mjs +1473 -0
  24. package/dist/index.mjs.map +1 -0
  25. package/dist/loader.d.ts +2 -0
  26. package/dist/native.d.ts +226 -0
  27. package/dist/server.d.ts +44 -0
  28. package/dist/streams.d.ts +14 -0
  29. package/dist/types.d.ts +24 -0
  30. package/dist/webtransport.d.ts +20 -0
  31. package/package.json +79 -0
  32. package/prebuilds/win32-x64/rwebtransport.node +0 -0
  33. package/scripts/bench.mjs +180 -0
  34. package/scripts/build.js +67 -0
  35. package/scripts/postinstall.js +67 -0
  36. package/scripts/setup-unix.sh +129 -0
  37. package/scripts/setup-windows.ps1 +229 -0
  38. package/vendor/quiche/AGENTS.md +75 -0
  39. package/vendor/quiche/COPYING +23 -0
  40. package/vendor/quiche/Cargo.lock +1212 -0
  41. package/vendor/quiche/Cargo.toml +215 -0
  42. package/vendor/quiche/README.md +466 -0
  43. package/vendor/quiche/examples/Makefile +46 -0
  44. package/vendor/quiche/examples/README.md +20 -0
  45. package/vendor/quiche/examples/cert-big.crt +90 -0
  46. package/vendor/quiche/examples/cert.crt +18 -0
  47. package/vendor/quiche/examples/cert.key +28 -0
  48. package/vendor/quiche/examples/client.c +343 -0
  49. package/vendor/quiche/examples/client.rs +281 -0
  50. package/vendor/quiche/examples/gen-certs.sh +15 -0
  51. package/vendor/quiche/examples/http3-client.c +473 -0
  52. package/vendor/quiche/examples/http3-client.rs +349 -0
  53. package/vendor/quiche/examples/http3-server.c +614 -0
  54. package/vendor/quiche/examples/http3-server.rs +680 -0
  55. package/vendor/quiche/examples/qpack-decode.rs +87 -0
  56. package/vendor/quiche/examples/qpack-encode.rs +88 -0
  57. package/vendor/quiche/examples/rootca.crt +21 -0
  58. package/vendor/quiche/examples/server.c +529 -0
  59. package/vendor/quiche/examples/server.rs +529 -0
  60. package/vendor/quiche/include/quiche.h +1282 -0
  61. package/vendor/quiche/quiche.svg +1 -0
  62. package/vendor/quiche/src/buffers.rs +105 -0
  63. package/vendor/quiche/src/build.rs +66 -0
  64. package/vendor/quiche/src/cid.rs +1079 -0
  65. package/vendor/quiche/src/crypto/boringssl.rs +373 -0
  66. package/vendor/quiche/src/crypto/mod.rs +671 -0
  67. package/vendor/quiche/src/dgram.rs +118 -0
  68. package/vendor/quiche/src/error.rs +263 -0
  69. package/vendor/quiche/src/ffi.rs +2290 -0
  70. package/vendor/quiche/src/flowcontrol.rs +246 -0
  71. package/vendor/quiche/src/frame.rs +2172 -0
  72. package/vendor/quiche/src/h3/AGENTS.md +54 -0
  73. package/vendor/quiche/src/h3/ffi.rs +442 -0
  74. package/vendor/quiche/src/h3/frame.rs +1404 -0
  75. package/vendor/quiche/src/h3/mod.rs +8223 -0
  76. package/vendor/quiche/src/h3/qpack/decoder.rs +288 -0
  77. package/vendor/quiche/src/h3/qpack/encoder.rs +235 -0
  78. package/vendor/quiche/src/h3/qpack/mod.rs +202 -0
  79. package/vendor/quiche/src/h3/qpack/static_table.rs +323 -0
  80. package/vendor/quiche/src/h3/stream.rs +1595 -0
  81. package/vendor/quiche/src/lib.rs +9556 -0
  82. package/vendor/quiche/src/minmax.rs +446 -0
  83. package/vendor/quiche/src/packet.rs +2334 -0
  84. package/vendor/quiche/src/path.rs +1374 -0
  85. package/vendor/quiche/src/pmtud.rs +652 -0
  86. package/vendor/quiche/src/rand.rs +64 -0
  87. package/vendor/quiche/src/range_buf.rs +186 -0
  88. package/vendor/quiche/src/ranges.rs +755 -0
  89. package/vendor/quiche/src/recovery/AGENTS.md +80 -0
  90. package/vendor/quiche/src/recovery/bandwidth.rs +565 -0
  91. package/vendor/quiche/src/recovery/bytes_in_flight.rs +179 -0
  92. package/vendor/quiche/src/recovery/congestion/cubic.rs +1038 -0
  93. package/vendor/quiche/src/recovery/congestion/delivery_rate.rs +514 -0
  94. package/vendor/quiche/src/recovery/congestion/hystart.rs +241 -0
  95. package/vendor/quiche/src/recovery/congestion/mod.rs +361 -0
  96. package/vendor/quiche/src/recovery/congestion/prr.rs +238 -0
  97. package/vendor/quiche/src/recovery/congestion/recovery.rs +1170 -0
  98. package/vendor/quiche/src/recovery/congestion/reno.rs +291 -0
  99. package/vendor/quiche/src/recovery/congestion/test_sender.rs +201 -0
  100. package/vendor/quiche/src/recovery/gcongestion/bbr/bandwidth_sampler.rs +1947 -0
  101. package/vendor/quiche/src/recovery/gcongestion/bbr/windowed_filter.rs +158 -0
  102. package/vendor/quiche/src/recovery/gcongestion/bbr.rs +37 -0
  103. package/vendor/quiche/src/recovery/gcongestion/bbr2/drain.rs +120 -0
  104. package/vendor/quiche/src/recovery/gcongestion/bbr2/mode.rs +318 -0
  105. package/vendor/quiche/src/recovery/gcongestion/bbr2/network_model.rs +784 -0
  106. package/vendor/quiche/src/recovery/gcongestion/bbr2/probe_bw.rs +729 -0
  107. package/vendor/quiche/src/recovery/gcongestion/bbr2/probe_rtt.rs +175 -0
  108. package/vendor/quiche/src/recovery/gcongestion/bbr2/startup.rs +190 -0
  109. package/vendor/quiche/src/recovery/gcongestion/bbr2.rs +855 -0
  110. package/vendor/quiche/src/recovery/gcongestion/mod.rs +275 -0
  111. package/vendor/quiche/src/recovery/gcongestion/pacer.rs +294 -0
  112. package/vendor/quiche/src/recovery/gcongestion/recovery.rs +1384 -0
  113. package/vendor/quiche/src/recovery/mod.rs +3086 -0
  114. package/vendor/quiche/src/recovery/rtt.rs +152 -0
  115. package/vendor/quiche/src/stream/mod.rs +2210 -0
  116. package/vendor/quiche/src/stream/recv_buf.rs +1236 -0
  117. package/vendor/quiche/src/stream/send_buf.rs +849 -0
  118. package/vendor/quiche/src/test_utils.rs +681 -0
  119. package/vendor/quiche/src/tests.rs +12922 -0
  120. package/vendor/quiche/src/tls/boringssl.rs +375 -0
  121. package/vendor/quiche/src/tls/mod.rs +1245 -0
  122. package/vendor/quiche/src/transport_params.rs +628 -0
@@ -0,0 +1,129 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ //! QUIC client configuration built on the vendored Cloudflare quiche.
3
+
4
+ use crate::tls::{build_client_tls, CertVerification};
5
+
6
+ /// HTTP/3 ALPN token.
7
+ pub const H3_ALPN: &[u8] = b"h3";
8
+
9
+ /// Tunable client parameters. Defaults are chosen to comfortably run a
10
+ /// WebTransport session (control + QPACK streams plus application streams and
11
+ /// datagrams) against a public-internet server.
12
+ #[derive(Clone, Debug)]
13
+ pub struct ClientConfigParams {
14
+ pub verify: CertVerification,
15
+ pub max_idle_timeout_ms: u64,
16
+ pub max_udp_payload_size: usize,
17
+ pub initial_max_data: u64,
18
+ pub initial_max_stream_data: u64,
19
+ pub initial_max_streams_bidi: u64,
20
+ pub initial_max_streams_uni: u64,
21
+ pub dgram_recv_queue: usize,
22
+ pub dgram_send_queue: usize,
23
+ }
24
+
25
+ impl Default for ClientConfigParams {
26
+ fn default() -> Self {
27
+ Self {
28
+ verify: CertVerification::PkiDefault,
29
+ max_idle_timeout_ms: 30_000,
30
+ max_udp_payload_size: 1350,
31
+ initial_max_data: 10 * 1024 * 1024,
32
+ initial_max_stream_data: 1024 * 1024,
33
+ initial_max_streams_bidi: 256,
34
+ initial_max_streams_uni: 256,
35
+ // Bounded so a hostile server flooding datagrams cannot balloon
36
+ // memory: quiche drops incoming datagrams once this queue is full.
37
+ dgram_recv_queue: 1024,
38
+ dgram_send_queue: 1024,
39
+ }
40
+ }
41
+ }
42
+
43
+ /// Build a ready-to-use quiche client [`quiche::Config`].
44
+ pub fn build_config(p: &ClientConfigParams) -> Result<quiche::Config, String> {
45
+ let builder = build_client_tls(&p.verify)?;
46
+ let mut config = quiche::Config::with_boring_ssl_ctx_builder(quiche::PROTOCOL_VERSION, builder)
47
+ .map_err(|e| format!("quiche config: {e:?}"))?;
48
+
49
+ config
50
+ .set_application_protos(&[H3_ALPN])
51
+ .map_err(|e| format!("set_application_protos: {e:?}"))?;
52
+
53
+ match p.verify {
54
+ CertVerification::PkiDefault => {
55
+ // Turn on BoringSSL's built-in chain + hostname verification and give
56
+ // it a trust anchor set. Hostname verification is wired by quiche's
57
+ // `set_host_name` (X509_VERIFY_PARAM_set1_host).
58
+ config.verify_peer(true);
59
+ #[cfg(unix)]
60
+ {
61
+ // Best-effort system roots. If neither path exists the handshake
62
+ // will fail closed, which is the correct default.
63
+ let _ = config.load_verify_locations_from_directory("/etc/ssl/certs");
64
+ }
65
+ }
66
+ CertVerification::Hashes(_) | CertVerification::Insecure => {
67
+ // Verification is fully handled on the SSL context (custom callback /
68
+ // NONE). Do NOT call verify_peer here — it would install quiche's own
69
+ // None-callback over ours.
70
+ }
71
+ }
72
+
73
+ config.set_max_idle_timeout(p.max_idle_timeout_ms);
74
+ config.set_max_recv_udp_payload_size(p.max_udp_payload_size);
75
+ config.set_max_send_udp_payload_size(p.max_udp_payload_size);
76
+ config.set_initial_max_data(p.initial_max_data);
77
+ config.set_initial_max_stream_data_bidi_local(p.initial_max_stream_data);
78
+ config.set_initial_max_stream_data_bidi_remote(p.initial_max_stream_data);
79
+ config.set_initial_max_stream_data_uni(p.initial_max_stream_data);
80
+ config.set_initial_max_streams_bidi(p.initial_max_streams_bidi);
81
+ config.set_initial_max_streams_uni(p.initial_max_streams_uni);
82
+ config.set_disable_active_migration(true);
83
+ config.enable_dgram(true, p.dgram_recv_queue, p.dgram_send_queue);
84
+
85
+ Ok(config)
86
+ }
87
+
88
+ /// Build a QUIC **server** config from PEM certificate + private-key file paths.
89
+ /// Uses the same conservative transport limits as the client and the same
90
+ /// bounded datagram queues.
91
+ pub fn build_server_config(cert_path: &str, key_path: &str) -> Result<quiche::Config, String> {
92
+ use boring::ssl::{SslContextBuilder, SslMethod, SslVersion};
93
+
94
+ let mut builder =
95
+ SslContextBuilder::new(SslMethod::tls()).map_err(|e| format!("SslContextBuilder: {e}"))?;
96
+ builder
97
+ .set_min_proto_version(Some(SslVersion::TLS1_3))
98
+ .map_err(|e| format!("set_min_proto_version: {e}"))?;
99
+ builder
100
+ .set_max_proto_version(Some(SslVersion::TLS1_3))
101
+ .map_err(|e| format!("set_max_proto_version: {e}"))?;
102
+
103
+ let mut config = quiche::Config::with_boring_ssl_ctx_builder(quiche::PROTOCOL_VERSION, builder)
104
+ .map_err(|e| format!("quiche config: {e:?}"))?;
105
+ config
106
+ .load_cert_chain_from_pem_file(cert_path)
107
+ .map_err(|e| format!("failed to load certificate {cert_path}: {e:?}"))?;
108
+ config
109
+ .load_priv_key_from_pem_file(key_path)
110
+ .map_err(|e| format!("failed to load private key {key_path}: {e:?}"))?;
111
+ config
112
+ .set_application_protos(&[H3_ALPN])
113
+ .map_err(|e| format!("set_application_protos: {e:?}"))?;
114
+
115
+ let p = ClientConfigParams::default();
116
+ config.set_max_idle_timeout(p.max_idle_timeout_ms);
117
+ config.set_max_recv_udp_payload_size(p.max_udp_payload_size);
118
+ config.set_max_send_udp_payload_size(p.max_udp_payload_size);
119
+ config.set_initial_max_data(p.initial_max_data);
120
+ config.set_initial_max_stream_data_bidi_local(p.initial_max_stream_data);
121
+ config.set_initial_max_stream_data_bidi_remote(p.initial_max_stream_data);
122
+ config.set_initial_max_stream_data_uni(p.initial_max_stream_data);
123
+ config.set_initial_max_streams_bidi(p.initial_max_streams_bidi);
124
+ config.set_initial_max_streams_uni(p.initial_max_streams_uni);
125
+ config.set_disable_active_migration(true);
126
+ config.enable_dgram(true, p.dgram_recv_queue, p.dgram_send_queue);
127
+
128
+ Ok(config)
129
+ }
@@ -0,0 +1,463 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ //! The per-session driver thread: a mio event loop that owns the UDP socket and
3
+ //! the quiche connection, feeds packets to [`crate::session::WtSession`], and
4
+ //! ferries commands in and events out.
5
+
6
+ use std::net::{SocketAddr, ToSocketAddrs};
7
+ use std::sync::atomic::{AtomicBool, AtomicI64, AtomicUsize, Ordering};
8
+ use std::sync::mpsc::Receiver;
9
+ use std::sync::Arc;
10
+ use std::time::Instant;
11
+
12
+ use mio::net::UdpSocket;
13
+ use mio::{Events, Poll, Token};
14
+
15
+ use crate::config::{build_config, ClientConfigParams};
16
+ use crate::session::{Ev, WtSession};
17
+
18
+ pub const SOCKET_TOKEN: Token = Token(0);
19
+ pub const WAKE_TOKEN: Token = Token(1);
20
+
21
+ /// Max number of event batches that may be in flight to the JS event loop before
22
+ /// the driver stops pulling high-volume data (datagrams + WebTransport stream
23
+ /// bytes) out of quiche. This bounds the neon Channel / libuv queue so a hostile
24
+ /// server flooding datagrams or stream data cannot grow it without limit (OOM).
25
+ /// When exceeded, unread stream data stays in quiche (flow-controlling the peer)
26
+ /// and excess datagrams are dropped by quiche's bounded recv queue.
27
+ const MAX_INFLIGHT_BATCHES: i64 = 128;
28
+
29
+ /// State shared between the driver thread and the JS-facing handle so that
30
+ /// synchronous property reads (e.g. `datagrams.maxDatagramSize`) don't require a
31
+ /// round trip through the command channel.
32
+ #[derive(Default)]
33
+ pub struct DriverShared {
34
+ pub max_datagram_size: AtomicUsize,
35
+ pub ready: AtomicBool,
36
+ pub closed: AtomicBool,
37
+ /// Event batches emitted but not yet processed by the JS thread. Incremented
38
+ /// by the sink before `Channel::send`, decremented inside the JS callback.
39
+ pub inflight: AtomicI64,
40
+ }
41
+
42
+ /// Commands sent from JS (via the neon layer) into the driver thread.
43
+ pub enum Command {
44
+ OpenStream {
45
+ request_id: u64,
46
+ bidi: bool,
47
+ },
48
+ Write {
49
+ id: u64,
50
+ data: Vec<u8>,
51
+ request_id: u64,
52
+ },
53
+ Fin {
54
+ id: u64,
55
+ },
56
+ ResetStream {
57
+ id: u64,
58
+ code: u64,
59
+ },
60
+ StopSending {
61
+ id: u64,
62
+ code: u64,
63
+ },
64
+ SetPaused {
65
+ id: u64,
66
+ paused: bool,
67
+ },
68
+ SendDatagram {
69
+ data: Vec<u8>,
70
+ request_id: u64,
71
+ },
72
+ Close {
73
+ code: u32,
74
+ reason: Vec<u8>,
75
+ },
76
+ /// Tear the driver down (the JS handle was closed/GC'd).
77
+ Shutdown,
78
+ }
79
+
80
+ /// Sink for events produced by the driver. Implemented by the neon layer using a
81
+ /// `neon::event::Channel`.
82
+ pub trait EventSink: Send {
83
+ fn emit(&self, events: Vec<Ev>);
84
+ }
85
+
86
+ /// Everything the driver thread needs to establish a session. DNS resolution,
87
+ /// socket bind, TLS/QUIC config, and the quiche handshake all happen on the
88
+ /// driver thread (never on the JS event loop).
89
+ pub struct SessionSetup {
90
+ pub host: String,
91
+ pub port: u16,
92
+ /// SNI / verification host (None for IP literals).
93
+ pub sni: Option<String>,
94
+ pub authority: String,
95
+ pub path: String,
96
+ pub origin: Option<String>,
97
+ pub extra_headers: Vec<(String, String)>,
98
+ pub config: ClientConfigParams,
99
+ }
100
+
101
+ /// Entry point for the driver thread. Wraps setup + the event loop in
102
+ /// `catch_unwind` so that a panic anywhere (DNS, bind, quiche, the loop) can
103
+ /// NEVER crash the Node process and can NEVER silently hang the session: on
104
+ /// panic (or a setup failure) we emit an `error` event followed by `closed`, so
105
+ /// the JS `ready`/`closed` promises reject.
106
+ pub fn run(
107
+ setup: SessionSetup,
108
+ poll: Poll,
109
+ rx: Receiver<Command>,
110
+ sink: Box<dyn EventSink>,
111
+ shared: Arc<DriverShared>,
112
+ ) {
113
+ let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
114
+ setup_and_run(setup, poll, rx, sink.as_ref(), &shared);
115
+ }));
116
+ if let Err(payload) = result {
117
+ let msg = payload
118
+ .downcast_ref::<&str>()
119
+ .map(|s| (*s).to_string())
120
+ .or_else(|| payload.downcast_ref::<String>().cloned())
121
+ .unwrap_or_else(|| "unknown panic".to_string());
122
+ shared.closed.store(true, Ordering::Relaxed);
123
+ sink.emit(vec![
124
+ Ev::Error(format!("rwebtransport internal driver error: {msg}")),
125
+ Ev::Closed {
126
+ code: 0,
127
+ reason: b"driver panic".to_vec(),
128
+ remote: false,
129
+ },
130
+ ]);
131
+ }
132
+ }
133
+
134
+ /// Emit a fatal setup error to JS and mark the session closed.
135
+ fn emit_fatal(sink: &dyn EventSink, shared: &Arc<DriverShared>, message: String) {
136
+ shared.closed.store(true, Ordering::Relaxed);
137
+ sink.emit(vec![
138
+ Ev::Error(message),
139
+ Ev::Closed {
140
+ code: 0,
141
+ reason: b"setup failed".to_vec(),
142
+ remote: false,
143
+ },
144
+ ]);
145
+ }
146
+
147
+ fn random_scid() -> [u8; 16] {
148
+ let mut b = [0u8; 16];
149
+ if getrandom::getrandom(&mut b).is_err() {
150
+ let seed: u128 = std::time::SystemTime::now()
151
+ .duration_since(std::time::UNIX_EPOCH)
152
+ .map(|d| d.as_nanos())
153
+ .unwrap_or(0);
154
+ b.copy_from_slice(&seed.to_le_bytes());
155
+ }
156
+ b
157
+ }
158
+
159
+ /// Resolve DNS, bind the UDP socket, build the QUIC config, perform the handshake
160
+ /// handshake, then run the event loop. Any setup failure is surfaced to JS.
161
+ fn setup_and_run(
162
+ setup: SessionSetup,
163
+ poll: Poll,
164
+ rx: Receiver<Command>,
165
+ sink: &dyn EventSink,
166
+ shared: &Arc<DriverShared>,
167
+ ) {
168
+ // DNS resolution — potentially blocking, so it runs here (driver thread),
169
+ // never on the JS event loop.
170
+ let peer = match (setup.host.as_str(), setup.port)
171
+ .to_socket_addrs()
172
+ .ok()
173
+ .and_then(|mut it| it.next())
174
+ {
175
+ Some(p) => p,
176
+ None => {
177
+ emit_fatal(
178
+ sink,
179
+ shared,
180
+ format!("failed to resolve {}:{}", setup.host, setup.port),
181
+ );
182
+ return;
183
+ }
184
+ };
185
+
186
+ let bind: SocketAddr = if peer.is_ipv4() {
187
+ "0.0.0.0:0".parse().unwrap()
188
+ } else {
189
+ "[::]:0".parse().unwrap()
190
+ };
191
+ let socket = match UdpSocket::bind(bind) {
192
+ Ok(s) => s,
193
+ Err(e) => {
194
+ emit_fatal(sink, shared, format!("failed to bind UDP socket: {e}"));
195
+ return;
196
+ }
197
+ };
198
+ let local_addr = match socket.local_addr() {
199
+ Ok(a) => a,
200
+ Err(e) => {
201
+ emit_fatal(sink, shared, format!("failed to read local addr: {e}"));
202
+ return;
203
+ }
204
+ };
205
+
206
+ let mut config = match build_config(&setup.config) {
207
+ Ok(c) => c,
208
+ Err(e) => {
209
+ emit_fatal(sink, shared, e);
210
+ return;
211
+ }
212
+ };
213
+
214
+ let scid = random_scid();
215
+ let scid = quiche::ConnectionId::from_ref(&scid);
216
+ let conn = match quiche::connect(setup.sni.as_deref(), &scid, local_addr, peer, &mut config) {
217
+ Ok(c) => c,
218
+ Err(e) => {
219
+ emit_fatal(sink, shared, format!("quiche connect: {e:?}"));
220
+ return;
221
+ }
222
+ };
223
+
224
+ let session = WtSession::new_client(
225
+ setup.authority,
226
+ setup.path,
227
+ setup.origin,
228
+ setup.extra_headers,
229
+ );
230
+
231
+ run_inner(poll, socket, local_addr, conn, session, rx, sink, shared);
232
+ }
233
+
234
+ /// The actual event loop. Runs until the connection closes or a fatal error
235
+ /// occurs. Never call this directly from the spawned thread — go through
236
+ /// [`run`], which contains the panic boundary.
237
+ #[allow(clippy::too_many_arguments)]
238
+ fn run_inner(
239
+ mut poll: Poll,
240
+ mut socket: UdpSocket,
241
+ local_addr: std::net::SocketAddr,
242
+ mut conn: quiche::Connection,
243
+ mut session: WtSession,
244
+ rx: Receiver<Command>,
245
+ sink: &dyn EventSink,
246
+ shared: &Arc<DriverShared>,
247
+ ) {
248
+ if let Err(e) = poll
249
+ .registry()
250
+ .register(&mut socket, SOCKET_TOKEN, mio::Interest::READABLE)
251
+ {
252
+ sink.emit(vec![Ev::Error(format!("failed to register socket: {e}"))]);
253
+ return;
254
+ }
255
+
256
+ let mut events = Events::with_capacity(1024);
257
+ let mut recv_buf = vec![0u8; 65_535];
258
+ let mut send_buf = vec![0u8; 1350];
259
+
260
+ let debug = std::env::var("RWT_DEBUG").is_ok();
261
+ // Read once per driver thread (each session spawns a fresh thread), so tests
262
+ // can arm/disarm it per-connection via the environment.
263
+ let test_panic = std::env::var("RWT_TEST_PANIC").is_ok();
264
+ let mut established_logged = false;
265
+ if debug {
266
+ eprintln!("[rwt-driver] start local={local_addr}");
267
+ }
268
+
269
+ // Prime the handshake (send the client Initial).
270
+ flush_send(&mut conn, &socket, &mut send_buf, debug);
271
+
272
+ loop {
273
+ let timeout = conn.timeout();
274
+ if let Err(e) = poll.poll(&mut events, timeout) {
275
+ if e.kind() == std::io::ErrorKind::Interrupted {
276
+ continue;
277
+ }
278
+ sink.emit(vec![Ev::Error(format!("poll error: {e}"))]);
279
+ return;
280
+ }
281
+
282
+ let mut evs: Vec<Ev> = Vec::new();
283
+ let mut shutdown = false;
284
+
285
+ // 1. Read all datagrams the socket has.
286
+ let mut got_packet = false;
287
+ loop {
288
+ match socket.recv_from(&mut recv_buf) {
289
+ Ok((len, from)) => {
290
+ got_packet = true;
291
+ if debug {
292
+ eprintln!("[rwt-driver] recv {len} bytes from {from}");
293
+ }
294
+ let info = quiche::RecvInfo {
295
+ from,
296
+ to: local_addr,
297
+ };
298
+ match conn.recv(&mut recv_buf[..len], info) {
299
+ Ok(_) => {}
300
+ Err(quiche::Error::Done) => {}
301
+ Err(e) => {
302
+ if debug {
303
+ eprintln!("[rwt-driver] recv err {e:?}");
304
+ }
305
+ evs.push(Ev::Error(format!("quic recv: {e:?}")));
306
+ }
307
+ }
308
+ }
309
+ Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => break,
310
+ Err(e) => {
311
+ evs.push(Ev::Error(format!("socket recv: {e}")));
312
+ break;
313
+ }
314
+ }
315
+ }
316
+
317
+ // 2. Fire the timeout if nothing else woke us.
318
+ if !got_packet && events.is_empty() {
319
+ conn.on_timeout();
320
+ }
321
+
322
+ // 3. Drain commands.
323
+ while let Ok(cmd) = rx.try_recv() {
324
+ match cmd {
325
+ Command::OpenStream { request_id, bidi } => {
326
+ session.open_stream(bidi, request_id, &mut evs)
327
+ }
328
+ Command::Write {
329
+ id,
330
+ data,
331
+ request_id,
332
+ } => session.stream_write(id, data, request_id, &mut evs),
333
+ Command::Fin { id } => session.stream_fin(id),
334
+ Command::ResetStream { id, code } => session.stream_reset(&mut conn, id, code),
335
+ Command::StopSending { id, code } => {
336
+ session.stream_stop_sending(&mut conn, id, code)
337
+ }
338
+ Command::SetPaused { id, paused } => session.set_paused(id, paused),
339
+ Command::SendDatagram { data, request_id } => {
340
+ session.send_datagram(&mut conn, &data, request_id, &mut evs)
341
+ }
342
+ Command::Close { code, reason } => session.close(code, reason),
343
+ Command::Shutdown => {
344
+ shutdown = true;
345
+ break;
346
+ }
347
+ }
348
+ }
349
+
350
+ if shutdown {
351
+ let _ = conn.close(true, 0, b"");
352
+ flush_send(&mut conn, &socket, &mut send_buf, debug);
353
+ return;
354
+ }
355
+
356
+ // 4. Drive the session forward.
357
+ if conn.is_established() {
358
+ // Test-only hook: prove that a panic on the driver thread is
359
+ // contained (rejects ready/closed, never crashes Node). Gated behind
360
+ // an env var so it is inert in production.
361
+ if test_panic {
362
+ panic!("RWT_TEST_PANIC: intentional driver-thread panic for containment testing");
363
+ }
364
+ if debug && !established_logged {
365
+ established_logged = true;
366
+ eprintln!(
367
+ "[rwt-driver] QUIC established, alpn={:?}",
368
+ conn.application_proto()
369
+ );
370
+ }
371
+ session.on_established(&mut evs);
372
+ }
373
+
374
+ // Backpressure: if the JS thread is behind on processing events, stop
375
+ // pulling high-volume data out of quiche this iteration. Unread stream
376
+ // bytes stay flow-controlled in quiche and excess datagrams are dropped
377
+ // by quiche's bounded recv queue, so the event queue cannot grow without
378
+ // bound (hostile-flood OOM protection). Control-plane processing (the
379
+ // CONNECT response, SETTINGS, session close) always runs.
380
+ let backpressured = shared.inflight.load(Ordering::Relaxed) >= MAX_INFLIGHT_BATCHES;
381
+
382
+ if !backpressured {
383
+ session.on_datagrams(&mut conn, &mut evs);
384
+ }
385
+
386
+ let readable: Vec<u64> = conn.readable().collect();
387
+ for id in readable {
388
+ session.on_readable(&mut conn, id, backpressured, &mut evs);
389
+ }
390
+
391
+ session.flush(&mut conn, &mut evs);
392
+
393
+ // 5. Send everything queued.
394
+ flush_send(&mut conn, &socket, &mut send_buf, debug);
395
+
396
+ // Publish synchronously-readable state.
397
+ shared
398
+ .max_datagram_size
399
+ .store(session.max_datagram_size(&conn), Ordering::Relaxed);
400
+ shared.ready.store(session.is_ready(), Ordering::Relaxed);
401
+
402
+ // 6. Terminal state?
403
+ if conn.is_closed() {
404
+ if !session.is_closed() {
405
+ let (code, reason, remote) = closure_info(&conn);
406
+ session.mark_closed(&mut evs, code, reason, remote);
407
+ }
408
+ shared.closed.store(true, Ordering::Relaxed);
409
+ if !evs.is_empty() {
410
+ sink.emit(evs);
411
+ }
412
+ return;
413
+ }
414
+
415
+ if !evs.is_empty() {
416
+ sink.emit(evs);
417
+ }
418
+ }
419
+ }
420
+
421
+ /// Drain quiche's send queue to the socket.
422
+ fn flush_send(conn: &mut quiche::Connection, socket: &UdpSocket, out: &mut [u8], debug: bool) {
423
+ loop {
424
+ match conn.send(out) {
425
+ Ok((write, info)) => {
426
+ // Ignore pacing (`info.at`); send immediately.
427
+ let _ = info.at;
428
+ if debug {
429
+ eprintln!("[rwt-driver] send {write} bytes to {}", info.to);
430
+ }
431
+ if let Err(e) = socket.send_to(&out[..write], info.to) {
432
+ if debug {
433
+ eprintln!("[rwt-driver] send_to err {e}");
434
+ }
435
+ if e.kind() == std::io::ErrorKind::WouldBlock {
436
+ // Socket buffer full; try again on the next wake.
437
+ return;
438
+ }
439
+ }
440
+ }
441
+ Err(quiche::Error::Done) => return,
442
+ Err(e) => {
443
+ if debug {
444
+ eprintln!("[rwt-driver] send err {e:?}");
445
+ }
446
+ return;
447
+ }
448
+ }
449
+ }
450
+ }
451
+
452
+ /// Extract a close code/reason from a terminated connection.
453
+ fn closure_info(conn: &quiche::Connection) -> (u32, Vec<u8>, bool) {
454
+ if let Some(err) = conn.peer_error() {
455
+ return (err.error_code as u32, err.reason.clone(), true);
456
+ }
457
+ if let Some(err) = conn.local_error() {
458
+ return (err.error_code as u32, err.reason.clone(), false);
459
+ }
460
+ // Idle timeout / no explicit error.
461
+ let _ = Instant::now();
462
+ (0, Vec::new(), true)
463
+ }