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

ambee/giterated

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

Remove unneeded logs

Amber - ⁨2⁩ years ago

parent: tbd commit: ⁨cfba404

⁨giterated-daemon/src/connection/wrapper.rs⁩ - ⁨9768⁩ 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::{error::OperationError, 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 // Map result to Vec<u8> on both
91 let result = match result {
92 Ok(result) => Ok(serde_json::to_vec(&result).unwrap()),
93 Err(err) => Err(match err {
94 OperationError::Operation(err) => {
95 OperationError::Operation(serde_json::to_vec(&err).unwrap())
96 }
97 OperationError::Internal(err) => OperationError::Internal(err),
98 OperationError::Unhandled => OperationError::Unhandled,
99 }),
100 };
101
102 let mut socket = connection_state.socket.lock().await;
103 let _ = socket
104 .send(Message::Binary(bincode::serialize(&result).unwrap()))
105 .await;
106
107 drop(socket);
108 }
109 _ => {
110 return;
111 }
112 }
113 }
114
115 // loop {
116 // let mut socket = connection_state.socket.lock().await;
117 // let message = socket.next().await;
118 // drop(socket);
119
120 // match message {
121 // Some(Ok(message)) => {
122 // let payload = match message {
123 // Message::Binary(payload) => payload,
124 // Message::Ping(_) => {
125 // let mut socket = connection_state.socket.lock().await;
126 // let _ = socket.send(Message::Pong(vec![])).await;
127 // drop(socket);
128 // continue;
129 // }
130 // Message::Close(_) => return,
131 // _ => continue,
132 // };
133
134 // let message = NetworkMessage(payload.clone());
135
136 // if !handshaked {
137 // if handshake_handle(&message, &connection_state).await.is_ok() {
138 // if connection_state.handshaked.load(Ordering::SeqCst) {
139 // handshaked = true;
140 // }
141 // }
142 // } else {
143 // let raw = serde_json::from_slice::<AuthenticatedPayload>(&payload).unwrap();
144
145 // if let Some(target_instance) = &raw.target_instance {
146 // if connection_state.instance != *target_instance {
147 // // Forward request
148 // info!("Forwarding message to {}", target_instance.url);
149 // let mut instance_connections = instance_connections.lock().await;
150 // let pool = instance_connections.get_or_open(&target_instance).unwrap();
151 // let pool_clone = pool.clone();
152 // drop(pool);
153
154 // let result = wrap_forwarded(&pool_clone, raw).await;
155
156 // let mut socket = connection_state.socket.lock().await;
157 // let _ = socket.send(result).await;
158
159 // continue;
160 // }
161 // }
162
163 // let message_type = &raw.message_type;
164
165 // match authentication_handle(message_type, &message, &connection_state).await {
166 // Err(e) => {
167 // let _ = connection_state
168 // .send_raw(ConnectionError(e.to_string()))
169 // .await;
170 // }
171 // Ok(true) => continue,
172 // Ok(false) => {}
173 // }
174
175 // match repository_handle(message_type, &message, &connection_state).await {
176 // Err(e) => {
177 // let _ = connection_state
178 // .send_raw(ConnectionError(e.to_string()))
179 // .await;
180 // }
181 // Ok(true) => continue,
182 // Ok(false) => {}
183 // }
184
185 // match user_handle(message_type, &message, &connection_state).await {
186 // Err(e) => {
187 // let _ = connection_state
188 // .send_raw(ConnectionError(e.to_string()))
189 // .await;
190 // }
191 // Ok(true) => continue,
192 // Ok(false) => {}
193 // }
194
195 // match authentication_handle(message_type, &message, &connection_state).await {
196 // Err(e) => {
197 // let _ = connection_state
198 // .send_raw(ConnectionError(e.to_string()))
199 // .await;
200 // }
201 // Ok(true) => continue,
202 // Ok(false) => {}
203 // }
204
205 // error!(
206 // "Message completely unhandled: {}",
207 // std::str::from_utf8(&payload).unwrap()
208 // );
209 // }
210 // }
211 // Some(Err(e)) => {
212 // error!("Closing connection for {:?} for {}", e, addr);
213 // return;
214 // }
215 // _ => {
216 // continue;
217 // }
218 // }
219 // }
220 }
221
222 #[derive(Clone)]
223 pub struct ConnectionState {
224 socket: Arc<Mutex<WebSocketStream<TcpStream>>>,
225 pub connections: Arc<Mutex<Connections>>,
226 pub repository_backend: Arc<Mutex<dyn RepositoryBackend + Send>>,
227 pub user_backend: Arc<Mutex<dyn UserBackend + Send>>,
228 pub auth_granter: Arc<Mutex<AuthenticationTokenGranter>>,
229 pub settings_backend: Arc<Mutex<dyn MetadataBackend + Send>>,
230 pub addr: SocketAddr,
231 pub instance: Instance,
232 pub handshaked: Arc<AtomicBool>,
233 pub key_cache: Arc<Mutex<PublicKeyCache>>,
234 pub instance_connections: Arc<Mutex<InstanceConnections>>,
235 pub config: Table,
236 }
237
238 impl ConnectionState {
239 pub async fn send<T: Serialize>(&self, message: T) -> Result<(), Error> {
240 let payload = serde_json::to_string(&message)?;
241 self.socket
242 .lock()
243 .await
244 .send(Message::Binary(payload.into_bytes()))
245 .await?;
246
247 Ok(())
248 }
249
250 pub async fn send_raw<T: Serialize>(&self, message: T) -> Result<(), Error> {
251 let payload = serde_json::to_string(&message)?;
252 self.socket
253 .lock()
254 .await
255 .send(Message::Binary(payload.into_bytes()))
256 .await?;
257
258 Ok(())
259 }
260
261 pub async fn public_key(&self, instance: &Instance) -> Result<String, Error> {
262 let mut keys = self.key_cache.lock().await;
263 keys.get(instance).await
264 }
265 }
266