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

ambee/giterated

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

Utilize for GitBackend and trim end slashes in folder

Emilia - ⁨1⁩ year ago

parent: tbd commit: ⁨4b440ef

⁨giterated-daemon/src/main.rs⁩ - ⁨5443⁩ 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::new(
63 &db_pool,
64 &String::from(
65 config["giterated"]["backend"]["git"]["root"]
66 .as_str()
67 .unwrap(),
68 ),
69 Instance::from_str(config["giterated"]["instance"].as_str().unwrap()).unwrap(),
70 stack_cell.clone(),
71 )));
72
73 let token_granter = Arc::new(Mutex::new(AuthenticationTokenGranter {
74 config: config.clone(),
75 instance: Instance::from_str(config["giterated"]["instance"].as_str().unwrap()).unwrap(),
76 }));
77
78 let user_backend: Arc<Mutex<dyn UserBackend + Send>> = Arc::new(Mutex::new(UserAuth::new(
79 db_pool.clone(),
80 &Instance::from_str(config["giterated"]["instance"].as_str().unwrap()).unwrap(),
81 token_granter.clone(),
82 settings.clone(),
83 )));
84
85 info!("Connected");
86
87 let database_backend = DatabaseBackend::new(
88 Instance::from_str(config["giterated"]["instance"].as_str().unwrap()).unwrap(),
89 user_backend.clone(),
90 repository_backend.clone(),
91 db_pool.clone(),
92 stack_cell.clone(),
93 );
94
95 let mut runtime = GiteratedStackBuilder::default();
96
97 let database_backend = database_backend.into_substack();
98 runtime.merge_builder(database_backend);
99
100 let cache_backend = CacheSubstack::default();
101 runtime.merge_builder(cache_backend.into_substack());
102
103 let networked_stack = NetworkedSubstack {
104 home_uri: Some(
105 Instance::from_str(config["giterated"]["instance"].as_str().unwrap())
106 .unwrap()
107 .0,
108 ),
109 };
110 runtime.merge_builder(networked_stack.into_server_substack());
111
112 let runtime = runtime.finish();
113
114 stack_cell
115 .set(runtime.clone())
116 .expect("failed to store global daemon stack");
117
118 let pool = LocalPoolHandle::new(5);
119
120 loop {
121 let stream = accept_stream(&mut listener).await;
122 info!("Connected");
123
124 let (stream, address) = match stream {
125 Ok(stream) => stream,
126 Err(err) => {
127 error!("Failed to accept connection. {:?}", err);
128 continue;
129 }
130 };
131
132 info!("Accepted connection from {}", address);
133
134 let connection = accept_websocket_connection(stream).await;
135
136 let connection = match connection {
137 Ok(connection) => connection,
138 Err(err) => {
139 error!(
140 "Failed to initiate Websocket connection from {}. {:?}",
141 address, err
142 );
143 continue;
144 }
145 };
146
147 info!("Websocket connection established with {}", address);
148
149 let our_instance =
150 Instance::from_str(config["giterated"]["instance"].as_str().unwrap()).unwrap();
151 let runtime = runtime.clone();
152
153 pool.spawn_pinned(move || client_wrapper(our_instance, connection, runtime));
154 }
155 }
156
157 async fn accept_stream(listener: &mut TcpListener) -> Result<(TcpStream, SocketAddr), Error> {
158 let stream = listener.accept().await?;
159
160 Ok(stream)
161 }
162
163 async fn accept_websocket_connection<S: AsyncRead + AsyncWrite + Unpin>(
164 stream: S,
165 ) -> Result<WebSocketStream<S>, Error> {
166 let connection = accept_async(stream).await?;
167
168 Ok(connection)
169 }
170