use std::{error::Error, net::SocketAddr, sync::Arc}; use connection::{connection_worker, Connections, RawConnection, UnestablishedConnection}; use giterated_daemon::{ backend::{git::GitBackend, RepositoryBackend}, connection, listener, }; use listener::Listeners; use tokio::{ io::{AsyncRead, AsyncWrite}, net::{TcpListener, TcpStream}, sync::Mutex, }; use tokio_tungstenite::{accept_async, WebSocketStream}; #[macro_use] extern crate tracing; #[tokio::main] async fn main() -> Result<(), Box> { tracing_subscriber::fmt::init(); let mut listener = TcpListener::bind("127.0.0.1:8080").await?; let mut connections: Arc> = Arc::default(); let mut listeners: Arc> = Arc::default(); let mut backend: Arc> = Arc::new(Mutex::new(GitBackend::new())); loop { let stream = accept_stream(&mut listener).await; let (stream, address) = match stream { Ok(stream) => stream, Err(err) => { error!("Failed to accept connection. {:?}", err); continue; } }; info!("Accepted connection from {}", address); let connection = accept_websocket_connection(stream).await; let connection = match connection { Ok(connection) => connection, Err(err) => { error!( "Failed to initiate Websocket connection from {}. {:?}", address, err ); continue; } }; info!("Websocket connection established with {}", address); let connection = RawConnection { task: tokio::spawn(connection_worker( connection, listeners.clone(), connections.clone(), backend.clone(), address, )), }; connections.lock().await.connections.push(connection); } } async fn accept_stream( listener: &mut TcpListener, ) -> Result<(TcpStream, SocketAddr), Box> { let stream = listener.accept().await?; Ok(stream) } async fn accept_websocket_connection( stream: S, ) -> Result, Box> { let connection = accept_async(stream).await?; Ok(connection) }