Replace gRPC Backend #10
5
Cargo.lock
generated
5
Cargo.lock
generated
@@ -257,9 +257,14 @@ version = "0.1.0"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"chrono",
|
"chrono",
|
||||||
"derive_more",
|
"derive_more",
|
||||||
|
"futures-util",
|
||||||
"log",
|
"log",
|
||||||
"serde",
|
"serde",
|
||||||
|
"serde_json",
|
||||||
"thiserror",
|
"thiserror",
|
||||||
|
"tokio",
|
||||||
|
"tokio-tungstenite",
|
||||||
|
"tokio-util",
|
||||||
"uuid",
|
"uuid",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|||||||
@@ -12,3 +12,8 @@ serde = { version = "1.0.228", features = ["derive"] }
|
|||||||
derive_more = { version = "2.1.0", features = ["from", "try_into"] }
|
derive_more = { version = "2.1.0", features = ["from", "try_into"] }
|
||||||
uuid = { version = "1.19.0", features = ["v4", "serde"] }
|
uuid = { version = "1.19.0", features = ["v4", "serde"] }
|
||||||
chrono = { version = "0.4.39", features = ["serde"] }
|
chrono = { version = "0.4.39", features = ["serde"] }
|
||||||
|
tokio = { version = "1.43.0", features = ["rt", "macros"] }
|
||||||
|
tokio-tungstenite = { version = "0.28.0", features = ["rustls-tls-native-roots"] }
|
||||||
|
tokio-util = "0.7.17"
|
||||||
|
futures-util = "0.3.31"
|
||||||
|
serde_json = "1.0.145"
|
||||||
|
|||||||
31
api/src/client/error.rs
Normal file
31
api/src/client/error.rs
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
use thiserror::Error;
|
||||||
|
|
||||||
|
#[derive(Error, Debug)]
|
||||||
|
pub enum ConnectError {
|
||||||
|
#[error(transparent)]
|
||||||
|
TungsteniteError(#[from] tokio_tungstenite::tungstenite::Error),
|
||||||
|
#[error(transparent)]
|
||||||
|
IoError(#[from] std::io::Error),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Error, Debug)]
|
||||||
|
pub enum MessageError {
|
||||||
|
#[error(transparent)]
|
||||||
|
TokioSendError(#[from] tokio::sync::mpsc::error::SendError<()>),
|
||||||
|
#[error(transparent)]
|
||||||
|
TokioTrySendError(#[from] tokio::sync::mpsc::error::TrySendError<()>),
|
||||||
|
#[error(transparent)]
|
||||||
|
TokioLockError(#[from] tokio::sync::TryLockError),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Error, Debug)]
|
||||||
|
pub enum RequestError<E> {
|
||||||
|
#[error(transparent)]
|
||||||
|
TokioSendError(#[from] tokio::sync::mpsc::error::SendError<()>),
|
||||||
|
#[error(transparent)]
|
||||||
|
TokioLockError(#[from] tokio::sync::TryLockError),
|
||||||
|
#[error(transparent)]
|
||||||
|
RecvError(#[from] tokio::sync::oneshot::error::RecvError),
|
||||||
|
#[error(transparent)]
|
||||||
|
Inner(E),
|
||||||
|
}
|
||||||
283
api/src/client/mod.rs
Normal file
283
api/src/client/mod.rs
Normal file
@@ -0,0 +1,283 @@
|
|||||||
|
pub mod error;
|
||||||
|
|
||||||
|
use crate::client::error::{MessageError, RequestError};
|
||||||
|
use crate::messages::payload::ResponseMessagePayload;
|
||||||
|
use crate::messages::{ClientMessage, RequestMessage, RequestResponse, ResponseMessage};
|
||||||
|
use error::ConnectError;
|
||||||
|
use futures_util::stream::StreamExt;
|
||||||
|
use futures_util::SinkExt;
|
||||||
|
use log::{debug, error};
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::sync::mpsc::sync_channel;
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::thread;
|
||||||
|
use tokio::net::TcpStream;
|
||||||
|
use tokio::select;
|
||||||
|
use tokio::sync::mpsc::{Receiver, Sender};
|
||||||
|
use tokio::sync::{mpsc, oneshot, RwLock, RwLockWriteGuard};
|
||||||
|
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
|
||||||
|
use tokio_tungstenite::tungstenite::handshake::client::Request;
|
||||||
|
use tokio_tungstenite::tungstenite::Message;
|
||||||
|
use tokio_tungstenite::{connect_async, MaybeTlsStream, WebSocketStream};
|
||||||
|
use tokio_util::sync::CancellationToken;
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
enum Callback {
|
||||||
|
None,
|
||||||
|
Once(oneshot::Sender<ResponseMessage>),
|
||||||
|
}
|
||||||
|
|
||||||
|
struct OutgoingMessage {
|
||||||
|
msg: RequestMessage,
|
||||||
|
callback: Callback,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Client {
|
||||||
|
cancel: CancellationToken,
|
||||||
|
channel: Arc<RwLock<Sender<OutgoingMessage>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct ClientContext {
|
||||||
|
cancel: CancellationToken,
|
||||||
|
request: Request,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Client {
|
||||||
|
pub fn connect<R>(request: R) -> Result<Self, ConnectError>
|
||||||
|
where
|
||||||
|
R: IntoClientRequest,
|
||||||
|
{
|
||||||
|
let (tx, _rx) = mpsc::channel(1);
|
||||||
|
let cancel = CancellationToken::new();
|
||||||
|
let channel = Arc::new(RwLock::new(tx));
|
||||||
|
let context = ClientContext {
|
||||||
|
cancel: cancel.clone(),
|
||||||
|
request: request.into_client_request()?,
|
||||||
|
};
|
||||||
|
|
||||||
|
context.start(channel.clone())?;
|
||||||
|
|
||||||
|
Ok(Self { cancel, channel })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn send_message<M: ClientMessage>(&self, msg: M) -> Result<(), MessageError> {
|
||||||
|
let sender = self.channel.read().await;
|
||||||
|
let data = sender.reserve().await?;
|
||||||
|
data.send(OutgoingMessage {
|
||||||
|
msg: RequestMessage {
|
||||||
|
uuid: Uuid::new_v4(),
|
||||||
|
response: None,
|
||||||
|
payload: msg.into(),
|
||||||
|
},
|
||||||
|
callback: Callback::None,
|
||||||
|
});
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn send_message_if_connected<M: ClientMessage>(
|
||||||
|
&self,
|
||||||
|
msg: M,
|
||||||
|
) -> Result<(), MessageError> {
|
||||||
|
let sender = self.channel.try_read()?;
|
||||||
|
let data = sender.reserve().await?;
|
||||||
|
data.send(OutgoingMessage {
|
||||||
|
msg: RequestMessage {
|
||||||
|
uuid: Uuid::new_v4(),
|
||||||
|
response: None,
|
||||||
|
payload: msg.into(),
|
||||||
|
},
|
||||||
|
callback: Callback::None,
|
||||||
|
});
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn try_send_message<M: ClientMessage>(&self, msg: M) -> Result<(), MessageError> {
|
||||||
|
let sender = self.channel.try_read()?;
|
||||||
|
let data = sender.try_reserve()?;
|
||||||
|
data.send(OutgoingMessage {
|
||||||
|
msg: RequestMessage {
|
||||||
|
uuid: Uuid::new_v4(),
|
||||||
|
response: None,
|
||||||
|
payload: msg.into(),
|
||||||
|
},
|
||||||
|
callback: Callback::None,
|
||||||
|
});
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn send_request<M: RequestResponse>(
|
||||||
|
&self,
|
||||||
|
msg: M,
|
||||||
|
) -> Result<M::Response, RequestError<<M::Response as TryFrom<ResponseMessagePayload>>::Error>>
|
||||||
|
{
|
||||||
|
let sender = self.channel.read().await;
|
||||||
|
let data = sender.reserve().await?;
|
||||||
|
|
||||||
|
let (tx, rx) = oneshot::channel();
|
||||||
|
data.send(OutgoingMessage {
|
||||||
|
msg: RequestMessage {
|
||||||
|
uuid: Uuid::new_v4(),
|
||||||
|
response: None,
|
||||||
|
payload: msg.into(),
|
||||||
|
},
|
||||||
|
callback: Callback::Once(tx),
|
||||||
|
});
|
||||||
|
|
||||||
|
let response = rx.await?;
|
||||||
|
let response = M::Response::try_from(response.payload).map_err(RequestError::Inner)?;
|
||||||
|
|
||||||
|
Ok(response)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ClientContext {
|
||||||
|
fn start(mut self, channel: Arc<RwLock<Sender<OutgoingMessage>>>) -> Result<(), ConnectError> {
|
||||||
|
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||||
|
.enable_all()
|
||||||
|
.build()?;
|
||||||
|
|
||||||
|
let (tx, rx) = sync_channel::<()>(1);
|
||||||
|
|
||||||
|
let _detached = thread::Builder::new()
|
||||||
|
.name("tlm-client".to_string())
|
||||||
|
.spawn(move || {
|
||||||
|
runtime.block_on(async {
|
||||||
|
let mut write_lock = channel.write().await;
|
||||||
|
|
||||||
|
// This cannot fail
|
||||||
|
let _ = tx.send(());
|
||||||
|
|
||||||
|
while !self.cancel.is_cancelled() {
|
||||||
|
write_lock = self.run_connection(write_lock, &channel).await;
|
||||||
|
}
|
||||||
|
drop(write_lock);
|
||||||
|
});
|
||||||
|
})?;
|
||||||
|
|
||||||
|
// This cannot fail
|
||||||
|
let _ = rx.recv();
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn run_connection<'a>(
|
||||||
|
&mut self,
|
||||||
|
mut write_lock: RwLockWriteGuard<'a, Sender<OutgoingMessage>>,
|
||||||
|
channel: &'a Arc<RwLock<Sender<OutgoingMessage>>>,
|
||||||
|
) -> RwLockWriteGuard<'a, Sender<OutgoingMessage>> {
|
||||||
|
let mut ws = match connect_async(self.request.clone()).await {
|
||||||
|
Ok((ws, _)) => ws,
|
||||||
|
Err(e) => {
|
||||||
|
error!("Connect Error: {e}");
|
||||||
|
return write_lock;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let (tx, rx) = mpsc::channel(128);
|
||||||
|
*write_lock = tx;
|
||||||
|
drop(write_lock);
|
||||||
|
|
||||||
|
let close_connection = self.handle_connection(&mut ws, rx).await;
|
||||||
|
|
||||||
|
let write_lock = channel.write().await;
|
||||||
|
if close_connection {
|
||||||
|
if let Err(e) = ws.close(None).await {
|
||||||
|
println!("Close Error {e}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
write_lock
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn handle_connection(
|
||||||
|
&mut self,
|
||||||
|
ws: &mut WebSocketStream<MaybeTlsStream<TcpStream>>,
|
||||||
|
mut rx: Receiver<OutgoingMessage>,
|
||||||
|
) -> bool {
|
||||||
|
let mut callbacks = HashMap::<Uuid, Callback>::new();
|
||||||
|
loop {
|
||||||
|
select! {
|
||||||
|
_ = self.cancel.cancelled() => { break; },
|
||||||
|
Some(msg) = ws.next() => {
|
||||||
|
match msg {
|
||||||
|
Ok(msg) => {
|
||||||
|
match msg {
|
||||||
|
Message::Text(msg) => {
|
||||||
|
let msg: ResponseMessage = match serde_json::from_str(&msg) {
|
||||||
|
Ok(m) => m,
|
||||||
|
Err(e) => {
|
||||||
|
error!("Failed to deserialize {e}");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
self.handle_incoming(msg, &mut callbacks).await;
|
||||||
|
}
|
||||||
|
Message::Binary(_) => unimplemented!("Binary Data Not Implemented"),
|
||||||
|
Message::Ping(data) => {
|
||||||
|
if let Err(e) = ws.send(Message::Pong(data)).await {
|
||||||
|
error!("Failed to send Pong {e}");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Message::Pong(_) => {
|
||||||
|
// Intentionally Left Empty
|
||||||
|
}
|
||||||
|
Message::Close(_) => {
|
||||||
|
debug!("Websocket Closed");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
Message::Frame(_) => unreachable!("Not Possible"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
error!("Receive Error {e}");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Some(msg) = rx.recv() => {
|
||||||
|
callbacks.insert(msg.msg.uuid, msg.callback);
|
||||||
|
let msg = match serde_json::to_string(&msg.msg) {
|
||||||
|
Ok(m) => m,
|
||||||
|
Err(e) => {
|
||||||
|
error!("Encode Error {e}");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if let Err(e) = ws.send(Message::Text(msg.into())).await {
|
||||||
|
error!("Send Error {e}");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else => { break; },
|
||||||
|
}
|
||||||
|
}
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn handle_incoming(
|
||||||
|
&mut self,
|
||||||
|
msg: ResponseMessage,
|
||||||
|
callbacks: &mut HashMap<Uuid, Callback>,
|
||||||
|
) {
|
||||||
|
if let Some(response_uuid) = msg.response {
|
||||||
|
match callbacks.get(&response_uuid) {
|
||||||
|
Some(Callback::Once(_)) => {
|
||||||
|
let Some(Callback::Once(callback)) = callbacks.remove(&response_uuid) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let _ = callback.send(msg);
|
||||||
|
}
|
||||||
|
Some(Callback::None) => {
|
||||||
|
callbacks.remove(&response_uuid);
|
||||||
|
}
|
||||||
|
None => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for Client {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
self.cancel.cancel();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
|
pub mod client;
|
||||||
pub mod data_type;
|
pub mod data_type;
|
||||||
pub mod data_value;
|
pub mod data_value;
|
||||||
pub mod request;
|
pub mod messages;
|
||||||
pub mod response;
|
|
||||||
|
|||||||
34
api/src/messages/mod.rs
Normal file
34
api/src/messages/mod.rs
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
pub mod payload;
|
||||||
|
pub mod telemetry_definition;
|
||||||
|
pub mod telemetry_entry;
|
||||||
|
|
||||||
|
use payload::{RequestMessagePayload, ResponseMessagePayload};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct RequestMessage {
|
||||||
|
pub uuid: Uuid,
|
||||||
|
pub response: Option<Uuid>,
|
||||||
|
#[serde(flatten)]
|
||||||
|
pub payload: RequestMessagePayload,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct ResponseMessage {
|
||||||
|
pub uuid: Uuid,
|
||||||
|
pub response: Option<Uuid>,
|
||||||
|
#[serde(flatten)]
|
||||||
|
pub payload: ResponseMessagePayload,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait ClientMessage: Into<RequestMessagePayload> {}
|
||||||
|
|
||||||
|
pub trait RequestResponse: Into<RequestMessagePayload> {
|
||||||
|
type Response: TryFrom<ResponseMessagePayload>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// pub trait RegisterCallback {
|
||||||
|
// type Callback : TryFrom<ResponseMessagePayload>;
|
||||||
|
// type Response : Into<RequestMessagePayload>;
|
||||||
|
// }
|
||||||
17
api/src/messages/payload.rs
Normal file
17
api/src/messages/payload.rs
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
use crate::messages::telemetry_definition::{
|
||||||
|
TelemetryDefinitionRequest, TelemetryDefinitionResponse,
|
||||||
|
};
|
||||||
|
use crate::messages::telemetry_entry::TelemetryEntry;
|
||||||
|
use derive_more::{From, TryInto};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize, From)]
|
||||||
|
pub enum RequestMessagePayload {
|
||||||
|
TelemetryDefinitionRequest(TelemetryDefinitionRequest),
|
||||||
|
TelemetryEntry(TelemetryEntry),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize, From, TryInto)]
|
||||||
|
pub enum ResponseMessagePayload {
|
||||||
|
TelemetryDefinitionResponse(TelemetryDefinitionResponse),
|
||||||
|
}
|
||||||
19
api/src/messages/telemetry_definition.rs
Normal file
19
api/src/messages/telemetry_definition.rs
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
use crate::data_type::DataType;
|
||||||
|
use crate::messages::RequestResponse;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct TelemetryDefinitionRequest {
|
||||||
|
pub name: String,
|
||||||
|
pub data_type: DataType,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct TelemetryDefinitionResponse {
|
||||||
|
pub uuid: Uuid,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RequestResponse for TelemetryDefinitionRequest {
|
||||||
|
type Response = TelemetryDefinitionResponse;
|
||||||
|
}
|
||||||
14
api/src/messages/telemetry_entry.rs
Normal file
14
api/src/messages/telemetry_entry.rs
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
use crate::data_value::DataValue;
|
||||||
|
use crate::messages::ClientMessage;
|
||||||
|
use chrono::{DateTime, Utc};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct TelemetryEntry {
|
||||||
|
pub uuid: Uuid,
|
||||||
|
pub value: DataValue,
|
||||||
|
pub timestamp: DateTime<Utc>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ClientMessage for TelemetryEntry {}
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
use crate::data_type::DataType;
|
|
||||||
use crate::data_value::DataValue;
|
|
||||||
use chrono::{DateTime, Utc};
|
|
||||||
use derive_more::From;
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
use uuid::Uuid;
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
|
||||||
pub struct TelemetryDefinitionRequest {
|
|
||||||
pub name: String,
|
|
||||||
pub data_type: DataType,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
|
||||||
pub struct TelemetryEntry {
|
|
||||||
pub uuid: Uuid,
|
|
||||||
pub value: DataValue,
|
|
||||||
pub timestamp: DateTime<Utc>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize, From)]
|
|
||||||
pub enum RequestMessagePayload {
|
|
||||||
TelemetryDefinitionRequest(TelemetryDefinitionRequest),
|
|
||||||
TelemetryEntry(TelemetryEntry),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
|
||||||
pub struct RequestMessage {
|
|
||||||
pub uuid: Uuid,
|
|
||||||
#[serde(flatten)]
|
|
||||||
pub payload: RequestMessagePayload,
|
|
||||||
}
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
use derive_more::{From, TryInto};
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
use uuid::Uuid;
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
|
||||||
pub struct TelemetryDefinitionResponse {
|
|
||||||
pub uuid: Uuid,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize, From, TryInto)]
|
|
||||||
pub enum ResponseMessagePayload {
|
|
||||||
TelemetryDefinitionResponse(TelemetryDefinitionResponse),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
|
||||||
pub struct ResponseMessage {
|
|
||||||
pub uuid: Uuid,
|
|
||||||
#[serde(flatten)]
|
|
||||||
pub payload: ResponseMessagePayload,
|
|
||||||
}
|
|
||||||
@@ -1,273 +1,71 @@
|
|||||||
use anyhow::anyhow;
|
use api::client::error::MessageError;
|
||||||
|
use api::client::Client;
|
||||||
use api::data_type::DataType;
|
use api::data_type::DataType;
|
||||||
use api::data_value::DataValue;
|
use api::data_value::DataValue;
|
||||||
use api::request::{
|
use api::messages::telemetry_definition::TelemetryDefinitionRequest;
|
||||||
RequestMessage, RequestMessagePayload, TelemetryDefinitionRequest, TelemetryEntry,
|
use api::messages::telemetry_entry::TelemetryEntry;
|
||||||
};
|
|
||||||
use api::response::{ResponseMessage, ResponseMessagePayload, TelemetryDefinitionResponse};
|
|
||||||
use chrono::{DateTime, TimeDelta, Utc};
|
use chrono::{DateTime, TimeDelta, Utc};
|
||||||
use futures_util::future::join_all;
|
use futures_util::future::join_all;
|
||||||
use futures_util::{SinkExt, StreamExt};
|
|
||||||
use num_traits::FloatConst;
|
use num_traits::FloatConst;
|
||||||
use std::collections::HashMap;
|
|
||||||
use std::sync::atomic::{AtomicBool, Ordering};
|
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
use tokio::net::TcpStream;
|
use tokio::time::{sleep_until, Instant};
|
||||||
use tokio::sync::mpsc;
|
|
||||||
use tokio::sync::mpsc::channel;
|
|
||||||
use tokio::time::{sleep, sleep_until, Instant};
|
|
||||||
use tokio::{pin, select};
|
|
||||||
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
|
|
||||||
use tokio_tungstenite::tungstenite::Message;
|
|
||||||
use tokio_tungstenite::{connect_async, MaybeTlsStream, WebSocketStream};
|
|
||||||
use tokio_util::sync::CancellationToken;
|
use tokio_util::sync::CancellationToken;
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
struct Telemetry {
|
struct Telemetry {
|
||||||
is_connected: Arc<AtomicBool>,
|
client: Arc<Client>,
|
||||||
tx: mpsc::Sender<RequestMessage>,
|
|
||||||
callback_new: mpsc::Sender<(Uuid, mpsc::Sender<ResponseMessagePayload>)>,
|
|
||||||
callback_delete: mpsc::Sender<Uuid>,
|
|
||||||
cancel: CancellationToken,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
struct TelemetryItemHandle<'a> {
|
struct TelemetryItemHandle {
|
||||||
uuid: Uuid,
|
uuid: Uuid,
|
||||||
tlm: &'a Telemetry,
|
client: Arc<Client>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Telemetry {
|
impl Telemetry {
|
||||||
async fn connect<R>(request: R) -> anyhow::Result<WebSocketStream<MaybeTlsStream<TcpStream>>>
|
pub fn new(client: Arc<Client>) -> Self {
|
||||||
where
|
Self { client }
|
||||||
R: IntoClientRequest + Unpin,
|
|
||||||
{
|
|
||||||
let (client, _) = match connect_async(request).await {
|
|
||||||
Ok(o) => o,
|
|
||||||
Err(e) => {
|
|
||||||
sleep(Duration::from_secs(1)).await;
|
|
||||||
return Err(e.into());
|
|
||||||
}
|
|
||||||
};
|
|
||||||
Ok(client)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn new<R>(request: R) -> anyhow::Result<Self>
|
|
||||||
where
|
|
||||||
R: IntoClientRequest + Unpin + Clone + Send + 'static,
|
|
||||||
{
|
|
||||||
let cancel = CancellationToken::new();
|
|
||||||
let cancel_stored = cancel.clone();
|
|
||||||
let (tx_tx, mut tx_rx) = channel(128);
|
|
||||||
let (callback_new_tx, mut callback_new_rx) = channel(16);
|
|
||||||
let (callback_delete_tx, mut callback_delete_rx) = channel(16);
|
|
||||||
|
|
||||||
let is_connected = Arc::new(AtomicBool::new(false));
|
|
||||||
let connected = is_connected.clone();
|
|
||||||
|
|
||||||
tokio::spawn(async move {
|
|
||||||
while !cancel.is_cancelled() {
|
|
||||||
let client = Self::connect(request.clone());
|
|
||||||
pin!(client);
|
|
||||||
let mut client = match loop {
|
|
||||||
break select! {
|
|
||||||
c = &mut client => {
|
|
||||||
c
|
|
||||||
},
|
|
||||||
Some(_) = tx_rx.recv() => {continue;},
|
|
||||||
Some(_) = callback_new_rx.recv() => {continue;},
|
|
||||||
Some(_) = callback_delete_rx.recv() => {continue;},
|
|
||||||
};
|
|
||||||
} {
|
|
||||||
Ok(c) => c,
|
|
||||||
Err(e) => {
|
|
||||||
println!("Connect Error: {e}");
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut close_connection = true;
|
|
||||||
let mut callbacks = HashMap::<Uuid, mpsc::Sender<ResponseMessagePayload>>::new();
|
|
||||||
connected.store(true, Ordering::SeqCst);
|
|
||||||
|
|
||||||
loop {
|
|
||||||
select! {
|
|
||||||
biased;
|
|
||||||
_ = cancel.cancelled() => { break; },
|
|
||||||
Some(msg) = callback_new_rx.recv() => {
|
|
||||||
let (uuid, callback) = msg;
|
|
||||||
callbacks.insert(uuid, callback);
|
|
||||||
},
|
|
||||||
Some(msg) = callback_delete_rx.recv() => {
|
|
||||||
callbacks.remove(&msg);
|
|
||||||
},
|
|
||||||
Some(msg) = client.next() => {
|
|
||||||
match msg {
|
|
||||||
Ok(msg) => {
|
|
||||||
match msg {
|
|
||||||
Message::Text(msg) => {
|
|
||||||
let msg: ResponseMessage = match serde_json::from_str(&msg) {
|
|
||||||
Ok(m) => m,
|
|
||||||
Err(e) => {
|
|
||||||
println!("Failed to deserialize {e}");
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
if let Some(cb) = callbacks.get_mut(&msg.uuid) {
|
|
||||||
if let Err(e) = cb.send(msg.payload).await {
|
|
||||||
println!("Failed to call callback {e}");
|
|
||||||
callbacks.remove(&msg.uuid);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
unimplemented!("Unexpected Message: {msg:?}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Message::Binary(_) => unimplemented!("Binary Unsupported"),
|
|
||||||
Message::Ping(data) => {
|
|
||||||
if let Err(e) = client.send(Message::Pong(data)).await {
|
|
||||||
println!("Failed to send Pong {e}");
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Message::Pong(_) => {
|
|
||||||
// Intentionally Left Empty
|
|
||||||
}
|
|
||||||
Message::Close(_) => {
|
|
||||||
println!("Websocket Closed");
|
|
||||||
close_connection = false;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
Message::Frame(_) => unreachable!("Not Possible"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
println!("Receive Error {e}");
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
Some(msg) = tx_rx.recv() => {
|
|
||||||
let msg = match serde_json::to_string(&msg) {
|
|
||||||
Ok(m) => m,
|
|
||||||
Err(e) => {
|
|
||||||
println!("Encode Error {e}");
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
if let Err(e) = client.send(Message::Text(msg.into())).await {
|
|
||||||
println!("Send Error {e}");
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
else => { break; },
|
|
||||||
}
|
|
||||||
}
|
|
||||||
connected.store(false, Ordering::SeqCst);
|
|
||||||
if close_connection {
|
|
||||||
if let Err(e) = client.close(None).await {
|
|
||||||
println!("Close Error {e}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Callbacks gets dropped here - closing all listeners automatically
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
Ok(Self {
|
|
||||||
tx: tx_tx,
|
|
||||||
callback_new: callback_new_tx,
|
|
||||||
callback_delete: callback_delete_tx,
|
|
||||||
cancel: cancel_stored,
|
|
||||||
is_connected,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn wait_connected(&self) {
|
|
||||||
while !self.is_connected.load(Ordering::Relaxed) {
|
|
||||||
sleep(Duration::from_millis(10)).await;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Send a message and don't expect a response
|
|
||||||
pub async fn send_message<P: Into<RequestMessagePayload>>(
|
|
||||||
&self,
|
|
||||||
payload: P,
|
|
||||||
) -> anyhow::Result<()> {
|
|
||||||
self.tx
|
|
||||||
.send(RequestMessage {
|
|
||||||
uuid: Uuid::new_v4(),
|
|
||||||
payload: payload.into(),
|
|
||||||
})
|
|
||||||
.await?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn send_request<
|
|
||||||
P: Into<RequestMessagePayload>,
|
|
||||||
R: TryFrom<ResponseMessagePayload, Error = impl std::error::Error + Send + Sync + 'static>,
|
|
||||||
>(
|
|
||||||
&self,
|
|
||||||
payload: P,
|
|
||||||
) -> anyhow::Result<R> {
|
|
||||||
let uuid = Uuid::new_v4();
|
|
||||||
let (tx, mut rx) = channel(1);
|
|
||||||
|
|
||||||
self.wait_connected().await;
|
|
||||||
self.callback_new.send((uuid, tx)).await?;
|
|
||||||
self.tx
|
|
||||||
.send(RequestMessage {
|
|
||||||
uuid,
|
|
||||||
payload: payload.into(),
|
|
||||||
})
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
let response = rx.recv().await.ok_or(anyhow!("No Response Received"))?;
|
|
||||||
|
|
||||||
let response = R::try_from(response)?;
|
|
||||||
|
|
||||||
self.callback_delete.send(uuid).await?;
|
|
||||||
|
|
||||||
Ok(response)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn register(
|
pub async fn register(
|
||||||
&self,
|
&self,
|
||||||
name: String,
|
name: String,
|
||||||
data_type: DataType,
|
data_type: DataType,
|
||||||
) -> anyhow::Result<TelemetryItemHandle<'_>> {
|
) -> anyhow::Result<TelemetryItemHandle> {
|
||||||
let response: TelemetryDefinitionResponse = self
|
let response = self
|
||||||
|
.client
|
||||||
.send_request(TelemetryDefinitionRequest { name, data_type })
|
.send_request(TelemetryDefinitionRequest { name, data_type })
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
Ok(TelemetryItemHandle {
|
Ok(TelemetryItemHandle {
|
||||||
uuid: response.uuid,
|
uuid: response.uuid,
|
||||||
tlm: self,
|
client: self.client.clone(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Drop for Telemetry {
|
impl TelemetryItemHandle {
|
||||||
fn drop(&mut self) {
|
|
||||||
self.cancel.cancel();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a> TelemetryItemHandle<'a> {
|
|
||||||
pub async fn publish(&self, value: DataValue, timestamp: DateTime<Utc>) -> anyhow::Result<()> {
|
pub async fn publish(&self, value: DataValue, timestamp: DateTime<Utc>) -> anyhow::Result<()> {
|
||||||
self.tlm
|
self.client
|
||||||
.send_message(TelemetryEntry {
|
.send_message_if_connected(TelemetryEntry {
|
||||||
uuid: self.uuid,
|
uuid: self.uuid,
|
||||||
value,
|
value,
|
||||||
timestamp,
|
timestamp,
|
||||||
})
|
})
|
||||||
.await?;
|
.await
|
||||||
|
.or_else(|e| match e {
|
||||||
|
MessageError::TokioLockError(_) => Ok(()),
|
||||||
|
e => Err(e),
|
||||||
|
})?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
async fn main() -> anyhow::Result<()> {
|
async fn main() -> anyhow::Result<()> {
|
||||||
let tlm = Telemetry::new("ws://[::1]:8080/backend").await?;
|
let client = Arc::new(Client::connect("ws://[::1]:8080/backend")?);
|
||||||
|
let tlm = Telemetry::new(client);
|
||||||
|
|
||||||
{
|
{
|
||||||
let time_offset = tlm
|
let time_offset = tlm
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
use crate::telemetry::management_service::TelemetryManagementService;
|
use crate::telemetry::management_service::TelemetryManagementService;
|
||||||
use actix_ws::{AggregatedMessage, ProtocolError, Session};
|
use actix_ws::{AggregatedMessage, ProtocolError, Session};
|
||||||
use anyhow::bail;
|
use anyhow::bail;
|
||||||
use api::request::{RequestMessage, RequestMessagePayload};
|
use api::messages::payload::RequestMessagePayload;
|
||||||
use api::response::ResponseMessage;
|
use api::messages::{RequestMessage, ResponseMessage};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use tokio::sync::mpsc::{Receiver, Sender};
|
use tokio::sync::mpsc::{Receiver, Sender};
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
pub(super) struct BackendConnection {
|
pub(super) struct BackendConnection {
|
||||||
session: Session,
|
session: Session,
|
||||||
@@ -31,7 +32,8 @@ impl BackendConnection {
|
|||||||
RequestMessagePayload::TelemetryDefinitionRequest(tlm_def) => {
|
RequestMessagePayload::TelemetryDefinitionRequest(tlm_def) => {
|
||||||
self.tx
|
self.tx
|
||||||
.send(ResponseMessage {
|
.send(ResponseMessage {
|
||||||
uuid: msg.uuid,
|
uuid: Uuid::new_v4(),
|
||||||
|
response: Some(msg.uuid),
|
||||||
payload: self.tlm_management.register(tlm_def)?.into(),
|
payload: self.tlm_management.register(tlm_def)?.into(),
|
||||||
})
|
})
|
||||||
.await?;
|
.await?;
|
||||||
|
|||||||
@@ -5,8 +5,10 @@ use crate::telemetry::history::{TelemetryHistory, TelemetryHistoryService};
|
|||||||
use anyhow::bail;
|
use anyhow::bail;
|
||||||
use api::data_type::DataType;
|
use api::data_type::DataType;
|
||||||
use api::data_value::DataValue;
|
use api::data_value::DataValue;
|
||||||
use api::request::{TelemetryDefinitionRequest, TelemetryEntry};
|
use api::messages::telemetry_definition::{
|
||||||
use api::response::TelemetryDefinitionResponse;
|
TelemetryDefinitionRequest, TelemetryDefinitionResponse,
|
||||||
|
};
|
||||||
|
use api::messages::telemetry_entry::TelemetryEntry;
|
||||||
use chrono::SecondsFormat;
|
use chrono::SecondsFormat;
|
||||||
use log::{error, info, warn};
|
use log::{error, info, warn};
|
||||||
use papaya::{HashMap, HashMapRef, LocalGuard};
|
use papaya::{HashMap, HashMapRef, LocalGuard};
|
||||||
|
|||||||
Reference in New Issue
Block a user