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

ambee/giterated

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

The long awaited, exhalted huge networking stack change.

Amber - ⁨2⁩ years ago

parent: tbd commit: ⁨21b6a72

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