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

ambee/giterated

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

Functionaltiy

Amber - ⁨2⁩ years ago

parent: tbd commit: ⁨5646846

⁨src/main.rs⁩ - ⁨2211⁩ 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 tracing_subscriber::fmt::init();
19 let mut listener = TcpListener::bind("127.0.0.1:8080").await?;
20 let mut connections: Arc<Mutex<Connections>> = Arc::default();
21 let mut listeners: Arc<Mutex<Listeners>> = Arc::default();
22
23 loop {
24 let stream = accept_stream(&mut listener).await;
25
26 let (stream, address) = match stream {
27 Ok(stream) => stream,
28 Err(err) => {
29 error!("Failed to accept connection. {:?}", err);
30 continue;
31 }
32 };
33
34 info!("Accepted connection from {}", address);
35
36 let connection = accept_websocket_connection(stream).await;
37
38 let connection = match connection {
39 Ok(connection) => connection,
40 Err(err) => {
41 error!(
42 "Failed to initiate Websocket connection from {}. {:?}",
43 address, err
44 );
45 continue;
46 }
47 };
48
49 info!("Websocket connection established with {}", address);
50
51 let connection = RawConnection {
52 task: tokio::spawn(connection_worker(
53 connection,
54 listeners.clone(),
55 connections.clone(),
56 address,
57 )),
58 };
59
60 connections.lock().await.connections.push(connection);
61 }
62 }
63
64 async fn accept_stream(
65 listener: &mut TcpListener,
66 ) -> Result<(TcpStream, SocketAddr), Box<dyn Error>> {
67 let stream = listener.accept().await?;
68
69 Ok(stream)
70 }
71
72 async fn accept_websocket_connection<S: AsyncRead + AsyncWrite + Unpin>(
73 stream: S,
74 ) -> Result<WebSocketStream<S>, Box<dyn Error>> {
75 let connection = accept_async(stream).await?;
76
77 Ok(connection)
78 }
79