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

ambee/giterated

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

Major post-refactor cleanup

Amber - ⁨2⁩ years ago

parent: tbd commit: ⁨f90d7fb

⁨src/main.rs⁩ - ⁨4177⁩ bytes
Raw
1 use anyhow::Error;
2 use connection::{Connections, RawConnection};
3 use giterated_daemon::{
4 authentication::AuthenticationTokenGranter,
5 backend::{git::GitBackend, user::UserAuth, RepositoryBackend, UserBackend},
6 connection::{self, wrapper::connection_wrapper},
7 model::instance::Instance,
8 };
9 use sqlx::{postgres::PgConnectOptions, ConnectOptions, PgPool};
10 use std::{net::SocketAddr, str::FromStr, sync::Arc};
11 use tokio::{
12 fs::File,
13 io::{AsyncRead, AsyncReadExt, AsyncWrite},
14 net::{TcpListener, TcpStream},
15 sync::Mutex,
16 };
17 use tokio_tungstenite::{accept_async, WebSocketStream};
18 use toml::Table;
19
20 #[macro_use]
21 extern crate tracing;
22
23 #[tokio::main]
24 async fn main() -> Result<(), Error> {
25 tracing_subscriber::fmt::init();
26 let mut listener = TcpListener::bind("0.0.0.0:7270").await?;
27 let connections: Arc<Mutex<Connections>> = Arc::default();
28 let config: Table = {
29 let mut file = File::open("Giterated.toml").await?;
30 let mut text = String::new();
31 file.read_to_string(&mut text).await?;
32 text.parse()?
33 };
34 let db_conn_options = PgConnectOptions::new()
35 .host(config["postgres"]["host"].as_str().unwrap())
36 .port(config["postgres"]["port"].as_integer().unwrap() as u16)
37 .database(config["postgres"]["database"].as_str().unwrap())
38 .username(config["postgres"]["user"].as_str().unwrap())
39 .password(config["postgres"]["password"].as_str().unwrap())
40 .log_statements(log::LevelFilter::Off);
41 let db_pool = PgPool::connect_with(db_conn_options).await?;
42
43 debug!("Running database migrations...");
44 sqlx::migrate!().run(&db_pool).await?;
45 info!("Connected");
46
47 let repository_backend: Arc<Mutex<dyn RepositoryBackend + Send>> =
48 Arc::new(Mutex::new(GitBackend {
49 pg_pool: db_pool.clone(),
50 repository_folder: String::from(
51 config["giterated"]["backend"]["git"]["root"]
52 .as_str()
53 .unwrap(),
54 ),
55 instance: Instance::from_str("giterated.dev").unwrap(),
56 }));
57
58 let token_granter = Arc::new(Mutex::new(AuthenticationTokenGranter {
59 config: config.clone(),
60 instance: Instance::from_str("giterated.dev").unwrap(),
61 }));
62
63 let user_backend: Arc<Mutex<dyn UserBackend + Send>> = Arc::new(Mutex::new(UserAuth::new(
64 db_pool.clone(),
65 &Instance::from_str("giterated.dev").unwrap(),
66 token_granter.clone(),
67 )));
68
69 info!("Connected");
70
71 loop {
72 let stream = accept_stream(&mut listener).await;
73 info!("Connected");
74
75 let (stream, address) = match stream {
76 Ok(stream) => stream,
77 Err(err) => {
78 error!("Failed to accept connection. {:?}", err);
79 continue;
80 }
81 };
82
83 info!("Accepted connection from {}", address);
84
85 let connection = accept_websocket_connection(stream).await;
86
87 let connection = match connection {
88 Ok(connection) => connection,
89 Err(err) => {
90 error!(
91 "Failed to initiate Websocket connection from {}. {:?}",
92 address, err
93 );
94 continue;
95 }
96 };
97
98 info!("Websocket connection established with {}", address);
99
100 let connection = RawConnection {
101 task: tokio::spawn(connection_wrapper(
102 connection,
103 connections.clone(),
104 repository_backend.clone(),
105 user_backend.clone(),
106 token_granter.clone(),
107 address,
108 Instance::from_str("giterated.dev").unwrap(),
109 )),
110 };
111
112 connections.lock().await.connections.push(connection);
113 }
114 }
115
116 async fn accept_stream(listener: &mut TcpListener) -> Result<(TcpStream, SocketAddr), Error> {
117 let stream = listener.accept().await?;
118
119 Ok(stream)
120 }
121
122 async fn accept_websocket_connection<S: AsyncRead + AsyncWrite + Unpin>(
123 stream: S,
124 ) -> Result<WebSocketStream<S>, Error> {
125 let connection = accept_async(stream).await?;
126
127 Ok(connection)
128 }
129