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

ambee/giterated

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

Connection

Amber - ⁨2⁩ years ago

parent: tbd commit: ⁨415ff8d

⁨src/main.rs⁩ - ⁨2093⁩ bytes
Raw
1 use std::{error::Error, net::SocketAddr, sync::Arc};
2
3 use connection::{connection_worker, Connections, RawConnection, UnestablishedConnection};
4 use listener::Listeners;
5 use tokio::{
6 io::{AsyncRead, AsyncWrite},
7 net::{TcpListener, TcpStream},
8 sync::Mutex,
9 };
10 use tokio_tungstenite::{accept_async, WebSocketStream};
11
12 pub mod command;
13 pub mod connection;
14 pub mod handshake;
15 pub mod listener;
16 pub mod model;
17
18 #[macro_use]
19 extern crate tracing;
20
21 #[tokio::main]
22 async fn main() -> Result<(), Box<dyn Error>> {
23 let mut listener = TcpListener::bind("127.0.0.1:8080").await?;
24 let mut connections: Arc<Mutex<Connections>> = Arc::default();
25 let mut listeners: Arc<Mutex<Listeners>> = Arc::default();
26
27 loop {
28 let stream = accept_stream(&mut listener).await;
29
30 let (stream, address) = match stream {
31 Ok(stream) => stream,
32 Err(err) => {
33 error!("Failed to accept connection. {:?}", err);
34 continue;
35 }
36 };
37
38 let connection = accept_websocket_connection(stream).await;
39
40 let connection = match connection {
41 Ok(connection) => connection,
42 Err(err) => {
43 error!(
44 "Failed to initiate Websocket connection from {}. {:?}",
45 address, err
46 );
47 continue;
48 }
49 };
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