use std::fmt::Debug; use deadpool::managed::Pool; use futures_util::{SinkExt, StreamExt}; use giterated_models::{ error::OperationError, model::{authenticated::Authenticated, MessageTarget}, operation::{ GiteratedMessage, GiteratedObject, GiteratedOperation, Object, ObjectBackend, ObjectRequest, ObjectRequestError, ObjectResponse, }, }; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use tokio_tungstenite::tungstenite::Message; use crate::{pool::GiteratedConnectionPool, DaemonConnectionPool, Socket}; #[async_trait::async_trait] impl ObjectBackend for DaemonConnectionPool { async fn object_operation + Debug>( &self, object: O, operation: D, ) -> Result> { let message = GiteratedMessage { object, operation: operation.operation_name().to_string(), payload: operation, }; let mut connection = self .0 .get() .await .map_err(|e| OperationError::Internal(e.to_string()))?; let authenticated = Authenticated::new(message); send_expect(&mut connection, authenticated).await } async fn get_object( &self, object_str: &str, ) -> Result, OperationError> { let operation = ObjectRequest(object_str.to_string()); let message = GiteratedMessage { object: self.0.manager().target_instance.clone(), operation: operation.operation_name().to_string(), payload: operation, }; let mut connection = self .0 .get() .await .map_err(|e| OperationError::Internal(e.to_string()))?; let authenticated = Authenticated::new(message); let object_raw: ObjectResponse = send_expect(&mut connection, authenticated).await?; Ok(unsafe { Object::new_unchecked( serde_json::from_slice(&object_raw.0) .map_err(|e| OperationError::Internal(e.to_string()))?, self.clone(), ) }) } } async fn send_expect< O: GiteratedObject, D: GiteratedOperation, B: DeserializeOwned, R: DeserializeOwned, >( socket: &mut Socket, message: Authenticated, ) -> Result> { let payload = serde_json::to_vec(&message.into_payload()).unwrap(); socket .send(Message::Binary(payload)) .await .map_err(|e| OperationError::Internal(e.to_string()))?; while let Some(message) = socket.next().await { let payload = match message.map_err(|e| OperationError::Internal(e.to_string()))? { Message::Binary(payload) => payload, _ => { continue; } }; let as_target = serde_json::from_slice::(&payload) .map_err(|e| OperationError::Internal(e.to_string()))?; } panic!() }