libp2p_quic/provider.rs
1// Copyright 2022 Protocol Labs.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a
4// copy of this software and associated documentation files (the "Software"),
5// to deal in the Software without restriction, including without limitation
6// the rights to use, copy, modify, merge, publish, distribute, sublicense,
7// and/or sell copies of the Software, and to permit persons to whom the
8// Software is furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in
11// all copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
19// DEALINGS IN THE SOFTWARE.
20
21use std::{
22 io,
23 net::{SocketAddr, UdpSocket},
24 task::{Context, Poll},
25 time::Duration,
26};
27
28use futures::future::BoxFuture;
29use if_watch::IfEvent;
30
31#[cfg(feature = "tokio")]
32pub mod tokio;
33
34pub enum Runtime {
35 #[cfg(feature = "tokio")]
36 Tokio,
37 Dummy,
38}
39
40/// Provider for a corresponding quinn runtime and spawning tasks.
41pub trait Provider: Unpin + Send + Sized + 'static {
42 type IfWatcher: Unpin + Send;
43
44 /// Run the corresponding runtime
45 fn runtime() -> Runtime;
46
47 /// Create a new [`if_watch`] watcher that reports [`IfEvent`]s for network interface changes.
48 fn new_if_watcher() -> io::Result<Self::IfWatcher>;
49
50 /// Poll for an address change event.
51 fn poll_if_event(
52 watcher: &mut Self::IfWatcher,
53 cx: &mut Context<'_>,
54 ) -> Poll<io::Result<IfEvent>>;
55
56 /// Sleep for specified amount of time.
57 fn sleep(duration: Duration) -> BoxFuture<'static, ()>;
58
59 /// Sends data on the socket to the given address. On success,
60 /// returns the number of bytes written.
61 fn send_to<'a>(
62 udp_socket: &'a UdpSocket,
63 buf: &'a [u8],
64 target: SocketAddr,
65 ) -> BoxFuture<'a, io::Result<usize>>;
66}