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

ambee/giterated

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

Unified stack refactor clean up

Clean up obsolete code and some warnings

Amber - ⁨2⁩ years ago

parent: tbd commit: ⁨356f714

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