use crate::listeners::tls::Acceptor;
use crate::protocols::tls::{AutoFlushableStream, TlsStream};
use crate::protocols::IO;
use pingora_error::ErrorType::TLSHandshakeFailure;
use pingora_error::{Error, Result};
use std::time::Instant;
pub async fn handshake<S: IO>(acceptor: &Acceptor, stream: S) -> Result<TlsStream<S>> {
let auto_flushable_stream = AutoFlushableStream::new(stream, true);
let handshake_start = Instant::now();
let mut s2n_stream = acceptor
.acceptor
.accept(auto_flushable_stream)
.await
.map_err(|e| {
let context = format!("TLS accept() failed: {e}");
Error::explain(TLSHandshakeFailure, context)
})?;
let handshake_duration = handshake_start.elapsed();
s2n_stream.get_mut().set_auto_flush(false);
Ok(TlsStream::from_s2n_stream(s2n_stream, handshake_duration))
}