JavaScript is disabled, refresh for a better experience. ambee/giterated

ambee/giterated

Git repository hosting, collaboration, and discovery for the Fediverse.

Changes

Amber - ⁨2⁩ years ago

parent: tbd commit: ⁨5ede041

⁨src/main.rs⁩ - ⁨2049⁩ bytes
Raw
1 use std::{error::Error, net::SocketAddr, sync::Arc};
2
3 use connection::{connection_worker, Connections, RawConnection, UnestablishedConnection};
4 use giterated_daemon::{connection, listener};
5 use listener::Listeners;
6 use tokio::{
7 io::{AsyncRead, AsyncWrite},
8 net::{TcpListener, TcpStream},
9 sync::Mutex,
10 };
11 use tokio_tungstenite::{accept_async, WebSocketStream};
12
13 #[macro_use]
14 extern crate tracing;
15
16 #[tokio::main]
17 async fn main() -> Result<(), Box<dyn Error>> {
18 let mut listener = TcpListener::bind("127.0.0.1:8080").await?;
19 let mut connections: Arc<Mutex<Connections>> = Arc::default();
20 let mut listeners: Arc<Mutex<Listeners>> = Arc::default();
21
22 loop {
23 let stream = accept_stream(&mut listener).await;
24
25 let (stream, address) = match stream {
26 Ok(stream) => stream,
27 Err(err) => {
28 error!("Failed to accept connection. {:?}", err);
29 continue;
30 }
31 };
32
33 let connection = accept_websocket_connection(stream).await;
34
35 let connection = match connection {
36 Ok(connection) => connection,
37 Err(err) => {
38 error!(
39 "Failed to initiate Websocket connection from {}. {:?}",
40 address, err
41 );
42 continue;
43 }
44 };
45
46 let connection = RawConnection {
47 task: tokio::spawn(connection_worker(
48 connection,
49 listeners.clone(),
50 connections.clone(),
51 address,
52 )),
53 };
54
55 connections.lock().await.connections.push(connection);
56 }
57 }
58
59 async fn accept_stream(
60 listener: &mut TcpListener,
61 ) -> Result<(TcpStream, SocketAddr), Box<dyn Error>> {
62 let stream = listener.accept().await?;
63
64 Ok(stream)
65 }
66
67 async fn accept_websocket_connection<S: AsyncRead + AsyncWrite + Unpin>(
68 stream: S,
69 ) -> Result<WebSocketStream<S>, Box<dyn Error>> {
70 let connection = accept_async(stream).await?;
71
72 Ok(connection)
73 }
74