domain/net/client/multi_stream.rs
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 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652
//! A DNS over multiple octet streams transport
// To do:
// - too many connection errors
use crate::base::Message;
use crate::net::client::protocol::AsyncConnect;
use crate::net::client::request::{
ComposeRequest, Error, GetResponse, RequestMessageMulti, SendRequest,
};
use crate::net::client::stream;
use bytes::Bytes;
use futures_util::stream::FuturesUnordered;
use futures_util::StreamExt;
use rand::random;
use std::boxed::Box;
use std::fmt::Debug;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;
use std::vec::Vec;
use tokio::io;
use tokio::io::{AsyncRead, AsyncWrite};
use tokio::sync::{mpsc, oneshot};
use tokio::time::{sleep_until, Instant};
//------------ Constants -----------------------------------------------------
/// Capacity of the channel that transports [`ChanReq`].
const DEF_CHAN_CAP: usize = 8;
/// Error messafe when the connection is closed.
const ERR_CONN_CLOSED: &str = "connection closed";
//------------ Config ---------------------------------------------------------
/// Configuration for an multi-stream transport.
#[derive(Clone, Debug, Default)]
pub struct Config {
/// Configuration of the underlying stream transport.
stream: stream::Config,
}
impl Config {
/// Returns the underlying stream config.
pub fn stream(&self) -> &stream::Config {
&self.stream
}
/// Returns a mutable reference to the underlying stream config.
pub fn stream_mut(&mut self) -> &mut stream::Config {
&mut self.stream
}
}
impl From<stream::Config> for Config {
fn from(stream: stream::Config) -> Self {
Self { stream }
}
}
//------------ Connection -----------------------------------------------------
/// A connection to a multi-stream transport.
#[derive(Debug)]
pub struct Connection<Req> {
/// The sender half of the connection request channel.
sender: mpsc::Sender<ChanReq<Req>>,
}
impl<Req> Connection<Req> {
/// Creates a new multi-stream transport with default configuration.
pub fn new<Remote>(remote: Remote) -> (Self, Transport<Remote, Req>) {
Self::with_config(remote, Default::default())
}
/// Creates a new multi-stream transport.
pub fn with_config<Remote>(
remote: Remote,
config: Config,
) -> (Self, Transport<Remote, Req>) {
let (sender, transport) = Transport::new(remote, config);
(Self { sender }, transport)
}
}
impl<Req: ComposeRequest + Clone + 'static> Connection<Req> {
/// Sends a request and receives a response.
pub async fn request(
&self,
request: Req,
) -> Result<Message<Bytes>, Error> {
Request::new(self.clone(), request).get_response().await
}
/// Starts a request.
///
/// This is the future that is returned by the `SendRequest` impl.
async fn _send_request(
&self,
request: &Req,
) -> Result<Box<dyn GetResponse + Send>, Error>
where
Req: 'static,
{
let gr = Request::new(self.clone(), request.clone());
Ok(Box::new(gr))
}
/// Request a new connection.
async fn new_conn(
&self,
opt_id: Option<u64>,
) -> Result<oneshot::Receiver<ChanResp<Req>>, Error> {
let (sender, receiver) = oneshot::channel();
let req = ChanReq {
cmd: ReqCmd::NewConn(opt_id, sender),
};
self.sender
.send(req)
.await
.map_err(|_| Error::ConnectionClosed)?;
Ok(receiver)
}
/// Request a shutdown.
pub async fn shutdown(&self) -> Result<(), &'static str> {
let req = ChanReq {
cmd: ReqCmd::Shutdown,
};
match self.sender.send(req).await {
Err(_) =>
// Send error. The receiver is gone, this means that the
// connection is closed.
{
Err(ERR_CONN_CLOSED)
}
Ok(_) => Ok(()),
}
}
}
//--- Clone
impl<Req> Clone for Connection<Req> {
fn clone(&self) -> Self {
Self {
sender: self.sender.clone(),
}
}
}
//--- SendRequest
impl<Req> SendRequest<Req> for Connection<Req>
where
Req: ComposeRequest + Clone + 'static,
{
fn send_request(
&self,
request: Req,
) -> Box<dyn GetResponse + Send + Sync> {
Box::new(Request::new(self.clone(), request))
}
}
//------------ Request --------------------------------------------------------
/// The connection side of an active request.
#[derive(Debug)]
struct Request<Req> {
/// The request message.
///
/// It is kept so we can compare a response with it.
request_msg: Req,
/// Current state of the query.
state: QueryState<Req>,
/// The underlying transport.
conn: Connection<Req>,
/// The id of the most recent connection, if any.
conn_id: Option<u64>,
/// Number of retries with delay.
delayed_retry_count: u64,
}
/// The states of the query state machine.
#[derive(Debug)]
enum QueryState<Req> {
/// Request a new connection.
RequestConn,
/// Receive a new connection from the receiver.
ReceiveConn(oneshot::Receiver<ChanResp<Req>>),
/// Start a query using the given stream transport.
StartQuery(Arc<stream::Connection<Req, RequestMessageMulti<Vec<u8>>>>),
/// Get the result of the query.
GetResult(stream::Request),
/// Wait until trying again.
///
/// The instant represents when the error occurred, the duration how
/// long to wait.
Delay(Instant, Duration),
/// A response has been received and the query is done.
Done,
}
/// The response to a connection request.
type ChanResp<Req> = Result<ChanRespOk<Req>, Arc<std::io::Error>>;
/// The successful response to a connection request.
#[derive(Debug)]
struct ChanRespOk<Req> {
/// The id of this connection.
id: u64,
/// The new stream transport to use for sending a request.
conn: Arc<stream::Connection<Req, RequestMessageMulti<Vec<u8>>>>,
}
impl<Req> Request<Req> {
/// Creates a new query.
fn new(conn: Connection<Req>, request_msg: Req) -> Self {
Self {
conn,
request_msg,
state: QueryState::RequestConn,
conn_id: None,
delayed_retry_count: 0,
}
}
}
impl<Req: ComposeRequest + Clone + 'static> Request<Req> {
/// Get the result of a DNS request.
///
/// This function is cancellation safe. If its future is dropped before
/// it is resolved, you can call it again to get a new future.
pub async fn get_response(&mut self) -> Result<Message<Bytes>, Error> {
loop {
match self.state {
QueryState::RequestConn => {
let rx = match self.conn.new_conn(self.conn_id).await {
Ok(rx) => rx,
Err(err) => {
self.state = QueryState::Done;
return Err(err);
}
};
self.state = QueryState::ReceiveConn(rx);
}
QueryState::ReceiveConn(ref mut receiver) => {
let res = match receiver.await {
Ok(res) => res,
Err(_) => {
// Assume receive error
self.state = QueryState::Done;
return Err(Error::StreamReceiveError);
}
};
// Another Result. This time from executing the request
match res {
Err(_) => {
self.delayed_retry_count += 1;
let retry_time =
retry_time(self.delayed_retry_count);
self.state =
QueryState::Delay(Instant::now(), retry_time);
continue;
}
Ok(ok_res) => {
let id = ok_res.id;
let conn = ok_res.conn;
self.conn_id = Some(id);
self.state = QueryState::StartQuery(conn);
continue;
}
}
}
QueryState::StartQuery(ref mut conn) => {
self.state = QueryState::GetResult(
conn.get_request(self.request_msg.clone()),
);
continue;
}
QueryState::GetResult(ref mut query) => {
let res = query.get_response().await;
match res {
Ok(reply) => {
return Ok(reply);
}
// XXX This replicates the previous behavior. But
// maybe we should have a whole category of
// fatal errors where retrying doesn’t make any
// sense?
Err(Error::WrongReplyForQuery) => {
return Err(Error::WrongReplyForQuery)
}
Err(Error::ConnectionClosed) => {
// The stream may immedately return that the
// connection was already closed. Do not delay
// the first time.
self.delayed_retry_count += 1;
if self.delayed_retry_count == 1 {
self.state = QueryState::RequestConn;
} else {
let retry_time =
retry_time(self.delayed_retry_count);
self.state = QueryState::Delay(
Instant::now(),
retry_time,
);
}
}
Err(_) => {
self.delayed_retry_count += 1;
let retry_time =
retry_time(self.delayed_retry_count);
self.state =
QueryState::Delay(Instant::now(), retry_time);
}
}
}
QueryState::Delay(instant, duration) => {
sleep_until(instant + duration).await;
self.state = QueryState::RequestConn;
}
QueryState::Done => {
panic!("Already done");
}
}
}
}
}
impl<Req: ComposeRequest + Clone + 'static> GetResponse for Request<Req> {
fn get_response(
&mut self,
) -> Pin<
Box<
dyn Future<Output = Result<Message<Bytes>, Error>>
+ Send
+ Sync
+ '_,
>,
> {
Box::pin(Self::get_response(self))
}
}
//------------ Transport ------------------------------------------------
/// The actual implementation of [Connection].
#[derive(Debug)]
pub struct Transport<Remote, Req> {
/// User configuration values.
config: Config,
/// The remote destination.
stream: Remote,
/// Underlying stream connection.
conn_state: SingleConnState3<Req>,
/// Current connection id.
conn_id: u64,
/// Receiver part of the channel.
receiver: mpsc::Receiver<ChanReq<Req>>,
}
#[derive(Debug)]
/// A request to [Connection::run] either for a new stream or to
/// shutdown.
struct ChanReq<Req> {
/// A requests consists of a command.
cmd: ReqCmd<Req>,
}
#[derive(Debug)]
/// Commands that can be requested.
enum ReqCmd<Req> {
/// Request for a (new) connection.
///
/// The id of the previous connection (if any) is passed as well as a
/// channel to send the reply.
NewConn(Option<u64>, ReplySender<Req>),
/// Shutdown command.
Shutdown,
}
/// This is the type of sender in [ReqCmd].
type ReplySender<Req> = oneshot::Sender<ChanResp<Req>>;
/// State of the current underlying stream transport.
#[derive(Debug)]
enum SingleConnState3<Req> {
/// No current stream transport.
None,
/// Current stream transport.
Some(Arc<stream::Connection<Req, RequestMessageMulti<Vec<u8>>>>),
/// State that deals with an error getting a new octet stream from
/// a connection stream.
Err(ErrorState),
}
/// State associated with a failed attempt to create a new stream
/// transport.
#[derive(Clone, Debug)]
struct ErrorState {
/// The error we got from the most recent attempt.
error: Arc<std::io::Error>,
/// How many times we tried so far.
retries: u64,
/// When we got an error.
timer: Instant,
/// Time to wait before trying to create a new connection.
timeout: Duration,
}
impl<Remote, Req> Transport<Remote, Req> {
/// Creates a new transport.
fn new(
stream: Remote,
config: Config,
) -> (mpsc::Sender<ChanReq<Req>>, Self) {
let (sender, receiver) = mpsc::channel(DEF_CHAN_CAP);
(
sender,
Self {
config,
stream,
conn_state: SingleConnState3::None,
conn_id: 0,
receiver,
},
)
}
}
impl<Remote, Req: ComposeRequest> Transport<Remote, Req>
where
Remote: AsyncConnect,
Remote::Connection: AsyncRead + AsyncWrite,
Req: ComposeRequest,
{
/// Run the transport machinery.
pub async fn run(mut self) {
let mut curr_cmd: Option<ReqCmd<Req>> = None;
let mut do_stream = false;
let mut runners = FuturesUnordered::new();
let mut stream_fut: Pin<
Box<
dyn Future<
Output = Result<Remote::Connection, std::io::Error>,
> + Send,
>,
> = Box::pin(stream_nop());
let mut opt_chan = None;
loop {
if let Some(req) = curr_cmd {
assert!(!do_stream);
curr_cmd = None;
match req {
ReqCmd::NewConn(opt_id, chan) => {
if let SingleConnState3::Err(error_state) =
&self.conn_state
{
if error_state.timer.elapsed()
< error_state.timeout
{
let resp =
ChanResp::Err(error_state.error.clone());
// Ignore errors. We don't care if the receiver
// is gone
_ = chan.send(resp);
continue;
}
// Try to set up a new connection
}
// Check if the command has an id greather than the
// current id.
if let Some(id) = opt_id {
if id >= self.conn_id {
// We need a new connection. Remove the
// current one. This is the best place to
// increment conn_id.
self.conn_id += 1;
self.conn_state = SingleConnState3::None;
}
}
// If we still have a connection then we can reply
// immediately.
if let SingleConnState3::Some(conn) = &self.conn_state
{
let resp = ChanResp::Ok(ChanRespOk {
id: self.conn_id,
conn: conn.clone(),
});
// Ignore errors. We don't care if the receiver
// is gone
_ = chan.send(resp);
} else {
opt_chan = Some(chan);
stream_fut = Box::pin(self.stream.connect());
do_stream = true;
}
}
ReqCmd::Shutdown => break,
}
}
if do_stream {
let runners_empty = runners.is_empty();
loop {
tokio::select! {
res_conn = stream_fut.as_mut() => {
do_stream = false;
stream_fut = Box::pin(stream_nop());
let stream = match res_conn {
Ok(stream) => stream,
Err(error) => {
let error = Arc::new(error);
match self.conn_state {
SingleConnState3::None =>
self.conn_state =
SingleConnState3::Err(ErrorState {
error: error.clone(),
retries: 0,
timer: Instant::now(),
timeout: retry_time(0),
}),
SingleConnState3::Some(_) =>
panic!("Illegal Some state"),
SingleConnState3::Err(error_state) => {
self.conn_state =
SingleConnState3::Err(ErrorState {
error:
error_state.error.clone(),
retries: error_state.retries+1,
timer: Instant::now(),
timeout: retry_time(
error_state.retries+1),
});
}
}
let resp = ChanResp::Err(error);
let loc_opt_chan = opt_chan.take();
// Ignore errors. We don't care if the receiver
// is gone
_ = loc_opt_chan.expect("weird, no channel?")
.send(resp);
break;
}
};
let (conn, tran) = stream::Connection::with_config(
stream, self.config.stream.clone()
);
let conn = Arc::new(conn);
runners.push(Box::pin(tran.run()));
let resp = ChanResp::Ok(ChanRespOk {
id: self.conn_id,
conn: conn.clone(),
});
self.conn_state = SingleConnState3::Some(conn);
let loc_opt_chan = opt_chan.take();
// Ignore errors. We don't care if the receiver
// is gone
_ = loc_opt_chan.expect("weird, no channel?")
.send(resp);
break;
}
_ = runners.next(), if !runners_empty => {
}
}
}
continue;
}
assert!(curr_cmd.is_none());
let recv_fut = self.receiver.recv();
let runners_empty = runners.is_empty();
tokio::select! {
msg = recv_fut => {
if msg.is_none() {
// All references to the connection object have been
// dropped. Shutdown.
break;
}
curr_cmd = Some(msg.expect("None is checked before").cmd);
}
_ = runners.next(), if !runners_empty => {
}
}
}
// Avoid new queries
drop(self.receiver);
// Wait for existing stream runners to terminate
while !runners.is_empty() {
runners.next().await;
}
}
}
//------------ Utility --------------------------------------------------------
/// Compute the retry timeout based on the number of retries so far.
///
/// The computation is a random value (in microseconds) between zero and
/// two to the power of the number of retries.
fn retry_time(retries: u64) -> Duration {
let to_secs = if retries > 6 { 60 } else { 1 << retries };
let to_usecs = to_secs * 1000000;
let rnd: f64 = random();
let to_usecs = to_usecs as f64 * rnd;
Duration::from_micros(to_usecs as u64)
}
/// Helper function to create an empty future that is compatible with the
/// future returned by a connection stream.
async fn stream_nop<IO>() -> Result<IO, std::io::Error> {
Err(io::Error::new(io::ErrorKind::Other, "nop"))
}