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
use crate::connection::{Connection, ConnectionError}; use crate::engine::Engine; use tokio::net::TcpListener; pub struct BindOptions { addr: String, port: u16, } impl BindOptions { pub fn new() -> Self { Self { addr: "127.0.0.1".to_owned(), port: 5432, } } pub fn with_port(mut self, port: u16) -> Self { self.port = port; self } pub fn with_addr(mut self, addr: impl Into<String>) -> Self { self.addr = addr.into(); self } pub fn use_all_interfaces(self) -> Self { self.with_addr("0.0.0.0") } } pub async fn run_with_listener<E: Engine>(listener: TcpListener) -> Result<(), ConnectionError> { loop { let (stream, _) = listener.accept().await?; tokio::spawn(async move { let mut conn = Connection::new(stream, E::new().await); conn.run().await.unwrap(); }); } } pub async fn run<E: Engine>(bind: BindOptions) -> Result<(), ConnectionError> { let listener = TcpListener::bind((bind.addr, bind.port)).await?; run_with_listener::<E>(listener).await } pub async fn run_background<E: Engine>(bind: BindOptions) -> Result<u16, ConnectionError> { let listener = TcpListener::bind((bind.addr, bind.port)).await?; let port = listener.local_addr()?.port(); tokio::spawn(async move { run_with_listener::<E>(listener).await }); Ok(port) }