use super::proxy;
use crate::stream::{Incoming, Stream};
use futures::AsyncReadExt;
use std::net::SocketAddr;
use std::time::Duration;
#[derive(Debug)]
pub struct IngressConn {
pub name: String,
pub client: Option<SocketAddr>,
pub ingress: Option<SocketAddr>,
pub http: bool,
pub header: Vec<u8>,
pub stream: Stream,
}
pub struct IngressIncoming {
pub(crate) inc: Incoming,
}
impl IngressIncoming {
pub async fn next(&mut self) -> Option<IngressConn> {
loop {
let s = self.inc.next().await?;
if let Some(c) = read_header(s).await {
return Some(c);
}
}
}
pub fn accept(&mut self) -> Option<IngressConn> {
futures::executor::block_on(self.next())
}
pub fn accept_timeout(&mut self, d: Duration) -> Option<IngressConn> {
let end = std::time::Instant::now() + d;
loop {
let s = self.inc.accept_timeout(end.saturating_duration_since(std::time::Instant::now()))?;
if let Some(c) = futures::executor::block_on(read_header(s)) {
return Some(c);
}
}
}
}
async fn read_header(mut s: Stream) -> Option<IngressConn> {
let mut head = vec![0u8; 16];
s.read_exact(&mut head).await.ok()?;
let len = u16::from_be_bytes([head[14], head[15]]) as usize;
head.resize(16 + len, 0);
s.read_exact(&mut head[16..]).await.ok()?;
let (h, _) = proxy::decode(&head).ok()??;
let name = h.authority?;
Some(IngressConn { name, client: h.source, ingress: h.dest, http: h.http, header: head, stream: s })
}