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

ambee/giterated

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

Fixes

Amber - ⁨2⁩ years ago

parent: tbd commit: ⁨b87f0a3

⁨giterated-daemon/src/connection/wrapper.rs⁩ - ⁨9473⁩ bytes
Raw
1 use std::{
2 net::SocketAddr,
3 sync::{atomic::AtomicBool, Arc},
4 };
5
6 use anyhow::Error;
7 use futures_util::{SinkExt, StreamExt};
8
9 use giterated_models::instance::Instance;
10
11 use giterated_models::object_backend::ObjectBackend;
12
13 use giterated_models::{
14 authenticated::AuthenticatedPayload, message::GiteratedMessage, object::AnyObject,
15 operation::AnyOperation,
16 };
17 use serde::Serialize;
18
19 use tokio::{net::TcpStream, sync::Mutex};
20 use tokio_tungstenite::{tungstenite::Message, WebSocketStream};
21 use toml::Table;
22
23 use crate::{
24 authentication::AuthenticationTokenGranter,
25 backend::{MetadataBackend, RepositoryBackend, UserBackend},
26 database_backend::DatabaseBackend,
27 federation::connections::InstanceConnections,
28 keys::PublicKeyCache,
29 };
30
31 use super::Connections;
32
33 pub async fn connection_wrapper(
34 socket: WebSocketStream<TcpStream>,
35 connections: Arc<Mutex<Connections>>,
36 repository_backend: Arc<Mutex<dyn RepositoryBackend + Send>>,
37 user_backend: Arc<Mutex<dyn UserBackend + Send>>,
38 auth_granter: Arc<Mutex<AuthenticationTokenGranter>>,
39 settings_backend: Arc<Mutex<dyn MetadataBackend + Send>>,
40 addr: SocketAddr,
41 instance: impl ToOwned<Owned = Instance>,
42 instance_connections: Arc<Mutex<InstanceConnections>>,
43 config: Table,
44 backend: DatabaseBackend,
45 ) {
46 let connection_state = ConnectionState {
47 socket: Arc::new(Mutex::new(socket)),
48 connections,
49 repository_backend,
50 user_backend,
51 auth_granter,
52 settings_backend,
53 addr,
54 instance: instance.to_owned(),
55 handshaked: Arc::new(AtomicBool::new(false)),
56 key_cache: Arc::default(),
57 instance_connections: instance_connections.clone(),
58 config,
59 };
60
61 let _handshaked = false;
62
63 loop {
64 let mut socket = connection_state.socket.lock().await;
65 let message = socket.next().await;
66 drop(socket);
67
68 match message {
69 Some(Ok(message)) => {
70 let payload = match message {
71 Message::Binary(payload) => payload,
72 Message::Ping(_) => {
73 let mut socket = connection_state.socket.lock().await;
74 let _ = socket.send(Message::Pong(vec![])).await;
75 drop(socket);
76 continue;
77 }
78 Message::Close(_) => return,
79 _ => continue,
80 };
81
82 let message: AuthenticatedPayload = bincode::deserialize(&payload).unwrap();
83
84 let message: GiteratedMessage<AnyObject, AnyOperation> = message.into_message();
85
86 let result = backend
87 .object_operation(message.object, &message.operation, message.payload)
88 .await;
89
90 let mut socket = connection_state.socket.lock().await;
91 let _ = socket
92 .send(Message::Binary(bincode::serialize(&result).unwrap()))
93 .await;
94
95 info!("Done!");
96 drop(socket);
97 }
98 _ => {
99 return;
100 }
101 }
102 }
103
104 // loop {
105 // let mut socket = connection_state.socket.lock().await;
106 // let message = socket.next().await;
107 // drop(socket);
108
109 // match message {
110 // Some(Ok(message)) => {
111 // let payload = match message {
112 // Message::Binary(payload) => payload,
113 // Message::Ping(_) => {
114 // let mut socket = connection_state.socket.lock().await;
115 // let _ = socket.send(Message::Pong(vec![])).await;
116 // drop(socket);
117 // continue;
118 // }
119 // Message::Close(_) => return,
120 // _ => continue,
121 // };
122 // info!("one payload");
123
124 // let message = NetworkMessage(payload.clone());
125
126 // if !handshaked {
127 // info!("im foo baring");
128 // if handshake_handle(&message, &connection_state).await.is_ok() {
129 // if connection_state.handshaked.load(Ordering::SeqCst) {
130 // handshaked = true;
131 // }
132 // }
133 // } else {
134 // let raw = serde_json::from_slice::<AuthenticatedPayload>(&payload).unwrap();
135
136 // if let Some(target_instance) = &raw.target_instance {
137 // if connection_state.instance != *target_instance {
138 // // Forward request
139 // info!("Forwarding message to {}", target_instance.url);
140 // let mut instance_connections = instance_connections.lock().await;
141 // let pool = instance_connections.get_or_open(&target_instance).unwrap();
142 // let pool_clone = pool.clone();
143 // drop(pool);
144
145 // let result = wrap_forwarded(&pool_clone, raw).await;
146
147 // let mut socket = connection_state.socket.lock().await;
148 // let _ = socket.send(result).await;
149
150 // continue;
151 // }
152 // }
153
154 // let message_type = &raw.message_type;
155
156 // info!("Handling message with type: {}", message_type);
157
158 // match authentication_handle(message_type, &message, &connection_state).await {
159 // Err(e) => {
160 // let _ = connection_state
161 // .send_raw(ConnectionError(e.to_string()))
162 // .await;
163 // }
164 // Ok(true) => continue,
165 // Ok(false) => {}
166 // }
167
168 // match repository_handle(message_type, &message, &connection_state).await {
169 // Err(e) => {
170 // let _ = connection_state
171 // .send_raw(ConnectionError(e.to_string()))
172 // .await;
173 // }
174 // Ok(true) => continue,
175 // Ok(false) => {}
176 // }
177
178 // match user_handle(message_type, &message, &connection_state).await {
179 // Err(e) => {
180 // let _ = connection_state
181 // .send_raw(ConnectionError(e.to_string()))
182 // .await;
183 // }
184 // Ok(true) => continue,
185 // Ok(false) => {}
186 // }
187
188 // match authentication_handle(message_type, &message, &connection_state).await {
189 // Err(e) => {
190 // let _ = connection_state
191 // .send_raw(ConnectionError(e.to_string()))
192 // .await;
193 // }
194 // Ok(true) => continue,
195 // Ok(false) => {}
196 // }
197
198 // error!(
199 // "Message completely unhandled: {}",
200 // std::str::from_utf8(&payload).unwrap()
201 // );
202 // }
203 // }
204 // Some(Err(e)) => {
205 // error!("Closing connection for {:?} for {}", e, addr);
206 // return;
207 // }
208 // _ => {
209 // info!("Unhandled");
210 // continue;
211 // }
212 // }
213 // }
214 }
215
216 #[derive(Clone)]
217 pub struct ConnectionState {
218 socket: Arc<Mutex<WebSocketStream<TcpStream>>>,
219 pub connections: Arc<Mutex<Connections>>,
220 pub repository_backend: Arc<Mutex<dyn RepositoryBackend + Send>>,
221 pub user_backend: Arc<Mutex<dyn UserBackend + Send>>,
222 pub auth_granter: Arc<Mutex<AuthenticationTokenGranter>>,
223 pub settings_backend: Arc<Mutex<dyn MetadataBackend + Send>>,
224 pub addr: SocketAddr,
225 pub instance: Instance,
226 pub handshaked: Arc<AtomicBool>,
227 pub key_cache: Arc<Mutex<PublicKeyCache>>,
228 pub instance_connections: Arc<Mutex<InstanceConnections>>,
229 pub config: Table,
230 }
231
232 impl ConnectionState {
233 pub async fn send<T: Serialize>(&self, message: T) -> Result<(), Error> {
234 let payload = serde_json::to_string(&message)?;
235 info!("Sending payload: {}", &payload);
236 self.socket
237 .lock()
238 .await
239 .send(Message::Binary(payload.into_bytes()))
240 .await?;
241
242 Ok(())
243 }
244
245 pub async fn send_raw<T: Serialize>(&self, message: T) -> Result<(), Error> {
246 let payload = serde_json::to_string(&message)?;
247 info!("Sending payload: {}", &payload);
248 self.socket
249 .lock()
250 .await
251 .send(Message::Binary(payload.into_bytes()))
252 .await?;
253
254 Ok(())
255 }
256
257 pub async fn public_key(&self, instance: &Instance) -> Result<String, Error> {
258 let mut keys = self.key_cache.lock().await;
259 keys.get(instance).await
260 }
261 }
262