h3x 0.2.0

High-performance zero-copy DHTTP/3 implementation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
use std::{
    collections::hash_map::DefaultHasher,
    error::Error,
    hash::{Hash, Hasher},
    pin::pin,
    sync::{Arc, LazyLock},
};

use dashmap::DashMap;
use futures::{StreamExt, never::Never};
use http::uri::Authority;
use snafu::{OptionExt, ResultExt, Snafu};
use tokio::sync::Mutex as AsyncMutex;
use tokio_util::task::AbortOnDropHandle;
use tracing::Instrument;

use crate::{
    connection::{Connection, ConnectionBuilder},
    quic,
    util::watch::Watch,
};

#[derive(Debug)]
pub struct ReuseableConnection<C: quic::Connection> {
    connection: Watch<Arc<Connection<C>>>,
    task: AsyncMutex<Option<AbortOnDropHandle<()>>>,
}

type ConnectionIdentifier = (Authority, u64);
type ReuseableConnections<C> = DashMap<ConnectionIdentifier, Arc<ReuseableConnection<C>>>;

impl<C: quic::Connection> ReuseableConnection<C> {
    pub fn pending() -> Self {
        Self {
            connection: Watch::new(),
            task: AsyncMutex::new(None),
        }
    }

    pub fn peek(&self) -> Option<Arc<Connection<C>>> {
        self.connection.peek()
    }

    pub fn reuse(&self) -> Option<Arc<Connection<C>>> {
        let connection = self.peek()?;
        // proactively check if the QUIC connection is still alive
        if connection.check().is_err() {
            return None;
        }
        if connection.peek_peer_goaway().is_some() {
            return None;
        }
        Some(connection)
    }

    pub async fn insert(&self, connection: Arc<Connection<C>>, task: AbortOnDropHandle<()>) {
        self.insert_with(async || (connection, task)).await
    }

    pub async fn insert_with(
        &self,
        f: impl AsyncFnOnce() -> (Arc<Connection<C>>, AbortOnDropHandle<()>),
    ) {
        self.try_insert_with::<Never>(async || Ok(f().await))
            .await
            .ok();
    }

    pub async fn try_insert_with<E>(
        &self,
        f: impl AsyncFnOnce() -> Result<(Arc<Connection<C>>, AbortOnDropHandle<()>), E>,
    ) -> Result<(), E> {
        let mut task_guard = self.task.lock().await;
        let (connection, task) = f().await?;
        self.connection.set(connection);
        *task_guard = Some(task);
        Ok(())
    }
}

#[derive(Debug)]
pub struct Pool<C: quic::Connection> {
    connections: Arc<ReuseableConnections<C>>,
}

impl<C: quic::Connection> Clone for Pool<C> {
    fn clone(&self) -> Self {
        Self {
            connections: self.connections.clone(),
        }
    }
}

impl<C: quic::Connection> Pool<C> {
    pub fn empty() -> Self {
        Self {
            connections: Default::default(),
        }
    }

    pub fn global() -> &'static Self {
        use std::any::{Any, TypeId};

        static POOLS: LazyLock<DashMap<TypeId, &'static (dyn Any + Send + Sync)>> =
            LazyLock::new(DashMap::new);
        POOLS
            .entry(TypeId::of::<C>())
            .or_insert_with(|| Box::leak(Box::new(Pool::<C>::empty())))
            .downcast_ref::<Pool<C>>()
            .expect("type id collision")
    }
}

impl<C: quic::Connection> Default for Pool<C> {
    fn default() -> Self {
        Self::empty()
    }
}

#[derive(Debug, Snafu)]
#[snafu(module)]
pub enum ConnectError<E: Error + 'static> {
    #[snafu(display("failed to initialize QUIC connection"))]
    Connector { source: E },
    #[snafu(transparent)]
    H3 { source: quic::ConnectionError },
    #[snafu(display("peer name mismatch: expected {expected}, actual {}", match actual {
        Some(name) => name,
        None => "<anonymous>", 
    }))]
    IncorrectIdentity {
        expected: String,
        actual: Option<String>,
    },
}

#[derive(Debug, Snafu)]
#[snafu(module)]
pub enum InsertError {
    #[snafu(transparent)]
    Quic { source: quic::ConnectionError },
    #[snafu(display("peer does not provide identity"))]
    MissingIdentity,
    #[snafu(display("peer provided invalid identity (cannot be parsed as Authority)"))]
    InvalidIdentity,
}

impl<C: quic::Connection> Pool<C> {
    fn spawn_try_release(self, identify: ConnectionIdentifier) {
        tokio::spawn(
            async move {
                (self.connections.as_ref())
                    .remove_if(&identify, |_, connection| connection.reuse().is_none());
            }
            .in_current_span(),
        );
    }

    #[tracing::instrument(level = "debug", skip(self, connector), err)]
    pub async fn reuse_or_connect_with<Client>(
        &self,
        connector: &Client,
        builder: Arc<ConnectionBuilder<C>>,
        server: Authority,
    ) -> Result<Arc<Connection<C>>, ConnectError<Client::Error>>
    where
        Client: quic::Connect<Connection = C>,
    {
        let builder_hash = {
            let mut hasher = DefaultHasher::new();
            builder.hash(&mut hasher);
            Hasher::finish(&hasher)
        };
        let reuseable_connection = self
            .connections
            .entry((server.clone(), builder_hash))
            .or_insert_with(|| Arc::new(ReuseableConnection::pending()))
            .clone();
        // break borrow of dashmap::Entry to avoid deadlock

        let result = {
            let mut connections = pin!(reuseable_connection.connection.watch());

            loop {
                tracing::trace!("(re)trying to reuse connection");
                if let Some(connection) = reuseable_connection.reuse() {
                    tracing::trace!("found reusable connection, gogogo");
                    break Ok(connection);
                }

                let try_connect = async || {
                    let quic_conn = connector
                        .connect(&server)
                        .await
                        .context(connect_error::ConnectorSnafu)?;
                    let connection = builder.build(quic_conn).await?;

                    tracing::trace!("h3 connection established, verifying peer identity");
                    let remote_agent = connection.remote_agent().await?;
                    let actual_peer_name = remote_agent.as_ref().map(|agent| agent.name());
                    if actual_peer_name.as_ref() != Some(&server.host()) {
                        return connect_error::IncorrectIdentitySnafu {
                            expected: server.host().to_string(),
                            actual: actual_peer_name.map(ToOwned::to_owned),
                        }
                        .fail();
                    }

                    let connection = Arc::new(connection);
                    // its ok to replace the connection, reference of replaced connection still in task until closed
                    let task = AbortOnDropHandle::new(tokio::spawn({
                        let connection = connection.clone();
                        let pool = self.clone();
                        let server = server.clone();
                        async move {
                            connection.closed().await;
                            pool.spawn_try_release((server, builder_hash));
                        }
                        .in_current_span()
                    }));
                    Ok((connection, task))
                };

                tokio::select! {
                    biased;
                    _new_conn = connections.next() => {
                        tracing::trace!("entry updated, try to reuse connection");
                    }
                    result = reuseable_connection.try_insert_with(try_connect) => {
                        result?;
                        tracing::trace!("new connection inserted");
                    }
                }
            }
        };

        match &result {
            Ok(..) => tracing::trace!("connection ready to use"),
            Err(..) => self.clone().spawn_try_release((server, builder_hash)),
        }

        result
    }

    pub async fn try_insert(
        &self,
        connection: Arc<Connection<C>>,
        builder_hash: u64,
    ) -> Result<(), InsertError> {
        let remote_agent = connection
            .remote_agent()
            .await?
            .context(insert_error::MissingIdentitySnafu)?;

        let client = remote_agent
            .name()
            .parse()
            .ok()
            .context(insert_error::InvalidIdentitySnafu)?;

        let identity = (client, builder_hash);
        let reuseable_connection = self
            .connections
            .entry(identity.clone())
            .or_insert_with(|| Arc::new(ReuseableConnection::pending()))
            .clone();

        let pool = self.clone();
        reuseable_connection
            .insert(
                connection.clone(),
                AbortOnDropHandle::new(tokio::spawn(
                    async move {
                        connection.closed().await;
                        pool.spawn_try_release(identity);
                    }
                    .in_current_span(),
                )),
            )
            .await;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;
    #[cfg(feature = "dquic")]
    use std::{
        collections::hash_map::DefaultHasher,
        hash::{Hash, Hasher},
    };

    use tokio_util::task::AbortOnDropHandle;

    use super::ReuseableConnection;
    #[cfg(feature = "dquic")]
    use crate::{
        connection::ConnectionBuilder,
        dhttp::settings::{MaxFieldSectionSize, Settings},
    };
    use crate::{
        connection::{Connection, ConnectionState},
        dhttp::{goaway::Goaway, protocol::DHttpProtocol},
        quic,
        varint::VarInt,
    };

    #[cfg(feature = "dquic")]
    fn hash_of<T: Hash>(val: &T) -> u64 {
        let mut hasher = DefaultHasher::new();
        val.hash(&mut hasher);
        hasher.finish()
    }

    #[cfg(feature = "dquic")]
    type C = dquic::prelude::Connection;

    #[cfg(feature = "dquic")]
    #[test]
    fn pool_key_different_builders_different_entries() {
        let s1 = Arc::new(Settings::default());
        let mut s2_inner = Settings::default();
        s2_inner.set(MaxFieldSectionSize::setting(VarInt::from_u32(9999)));
        let s2 = Arc::new(s2_inner);

        let builder_a = ConnectionBuilder::<C>::new(s1);
        let builder_b = ConnectionBuilder::<C>::new(s2);

        let key_a = hash_of(&builder_a);
        let key_b = hash_of(&builder_b);
        assert_ne!(
            key_a, key_b,
            "different protocol stacks must produce different pool keys"
        );
    }

    #[cfg(feature = "dquic")]
    #[test]
    fn pool_key_same_builder_same_entry() {
        let s = Arc::new(Settings::default());
        let builder_a = ConnectionBuilder::<C>::new(s.clone());
        let builder_b = ConnectionBuilder::<C>::new(s);

        let key_a = hash_of(&builder_a);
        let key_b = hash_of(&builder_b);
        assert_eq!(
            key_a, key_b,
            "identical protocol stacks must produce the same pool key"
        );
    }

    fn test_connection_error(reason: &str) -> quic::ConnectionError {
        quic::ConnectionError::Transport {
            source: quic::TransportError {
                kind: VarInt::from_u32(0x01),
                frame_type: VarInt::from_u32(0x00),
                reason: reason.to_owned().into(),
            },
        }
    }

    fn abort_handle() -> AbortOnDropHandle<()> {
        AbortOnDropHandle::new(tokio::spawn(async {}))
    }

    async fn reusable_connection(
        connection: Connection<crate::connection::tests::MockConnection>,
    ) -> Arc<ReuseableConnection<crate::connection::tests::MockConnection>> {
        let reusable = Arc::new(ReuseableConnection::pending());
        reusable.insert(Arc::new(connection), abort_handle()).await;
        reusable
    }

    #[tokio::test]
    async fn reuse_returns_none_when_connection_is_unhealthy() {
        let quic = crate::connection::tests::MockConnection::new();
        quic.set_terminal_error(test_connection_error("broken"));

        let state = ConnectionState::new_for_test(
            Arc::new(quic),
            Arc::new(crate::protocol::Protocols::new()),
        );
        let reusable = reusable_connection(Connection::from_state_for_test(state)).await;

        assert!(reusable.reuse().is_none());
    }

    #[tokio::test]
    async fn pool_reuse_returns_none_after_peer_goaway_observed() {
        let quic = crate::connection::tests::MockConnection::new();

        let protocols = {
            let mut protocols = crate::protocol::Protocols::new();
            protocols.insert(DHttpProtocol::new_for_test(Arc::new(quic.clone())));
            Arc::new(protocols)
        };
        let state = ConnectionState::new_for_test(Arc::new(quic), protocols);
        let dhttp = state.dhttp();
        dhttp.peer_goaway.set(Goaway::new(VarInt::from_u32(123)));

        let reusable = reusable_connection(Connection::from_state_for_test(state)).await;
        assert!(reusable.reuse().is_none());
    }
}