Replace gRPC Backend #10
2
Cargo.lock
generated
2
Cargo.lock
generated
@@ -2258,10 +2258,10 @@ name = "simple_command"
|
|||||||
version = "0.0.0"
|
version = "0.0.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
|
"api",
|
||||||
"chrono",
|
"chrono",
|
||||||
"log",
|
"log",
|
||||||
"num-traits",
|
"num-traits",
|
||||||
"server",
|
|
||||||
"tokio",
|
"tokio",
|
||||||
"tokio-util",
|
"tokio-util",
|
||||||
"tonic",
|
"tonic",
|
||||||
|
|||||||
@@ -1,20 +1,23 @@
|
|||||||
pub mod error;
|
pub mod error;
|
||||||
|
|
||||||
use crate::client::error::{MessageError, RequestError};
|
use crate::client::error::{MessageError, RequestError};
|
||||||
|
use crate::messages::callback::GenericCallbackError;
|
||||||
|
use crate::messages::payload::RequestMessagePayload;
|
||||||
use crate::messages::payload::ResponseMessagePayload;
|
use crate::messages::payload::ResponseMessagePayload;
|
||||||
use crate::messages::{ClientMessage, RequestMessage, RequestResponse, ResponseMessage};
|
use crate::messages::{
|
||||||
|
ClientMessage, RegisterCallback, RequestMessage, RequestResponse, ResponseMessage,
|
||||||
|
};
|
||||||
use error::ConnectError;
|
use error::ConnectError;
|
||||||
use futures_util::stream::StreamExt;
|
use futures_util::stream::StreamExt;
|
||||||
use futures_util::SinkExt;
|
use futures_util::SinkExt;
|
||||||
use log::{debug, error};
|
use log::{debug, error, warn};
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::sync::mpsc::sync_channel;
|
use std::sync::mpsc::sync_channel;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::thread;
|
use std::thread;
|
||||||
use tokio::net::TcpStream;
|
use tokio::net::TcpStream;
|
||||||
use tokio::select;
|
|
||||||
use tokio::sync::mpsc::{Receiver, Sender};
|
|
||||||
use tokio::sync::{mpsc, oneshot, RwLock, RwLockWriteGuard};
|
use tokio::sync::{mpsc, oneshot, RwLock, RwLockWriteGuard};
|
||||||
|
use tokio::{select, spawn};
|
||||||
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
|
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
|
||||||
use tokio_tungstenite::tungstenite::handshake::client::Request;
|
use tokio_tungstenite::tungstenite::handshake::client::Request;
|
||||||
use tokio_tungstenite::tungstenite::Message;
|
use tokio_tungstenite::tungstenite::Message;
|
||||||
@@ -22,9 +25,13 @@ use tokio_tungstenite::{connect_async, MaybeTlsStream, WebSocketStream};
|
|||||||
use tokio_util::sync::CancellationToken;
|
use tokio_util::sync::CancellationToken;
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
type RegisteredCallback = mpsc::Sender<(ResponseMessage, oneshot::Sender<RequestMessagePayload>)>;
|
||||||
|
type ClientChannel = Arc<RwLock<mpsc::Sender<OutgoingMessage>>>;
|
||||||
|
|
||||||
enum Callback {
|
enum Callback {
|
||||||
None,
|
None,
|
||||||
Once(oneshot::Sender<ResponseMessage>),
|
Once(oneshot::Sender<ResponseMessage>),
|
||||||
|
Registered(RegisteredCallback),
|
||||||
}
|
}
|
||||||
|
|
||||||
struct OutgoingMessage {
|
struct OutgoingMessage {
|
||||||
@@ -34,7 +41,7 @@ struct OutgoingMessage {
|
|||||||
|
|
||||||
pub struct Client {
|
pub struct Client {
|
||||||
cancel: CancellationToken,
|
cancel: CancellationToken,
|
||||||
channel: Arc<RwLock<Sender<OutgoingMessage>>>,
|
channel: ClientChannel,
|
||||||
}
|
}
|
||||||
|
|
||||||
struct ClientContext {
|
struct ClientContext {
|
||||||
@@ -128,10 +135,101 @@ impl Client {
|
|||||||
|
|
||||||
Ok(response)
|
Ok(response)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn register_callback_channel<M: RegisterCallback>(
|
||||||
|
&self,
|
||||||
|
msg: M,
|
||||||
|
) -> Result<mpsc::Receiver<(M::Callback, oneshot::Sender<M::Response>)>, MessageError>
|
||||||
|
where
|
||||||
|
<M as RegisterCallback>::Callback: Send + 'static,
|
||||||
|
<M as RegisterCallback>::Response: Send + 'static,
|
||||||
|
<<M as RegisterCallback>::Callback as TryFrom<ResponseMessagePayload>>::Error: Send,
|
||||||
|
{
|
||||||
|
let sender = self.channel.read().await;
|
||||||
|
let data = sender.reserve().await?;
|
||||||
|
|
||||||
|
let (inner_tx, mut inner_rx) = mpsc::channel(16);
|
||||||
|
let (outer_tx, outer_rx) = mpsc::channel(1);
|
||||||
|
|
||||||
|
data.send(OutgoingMessage {
|
||||||
|
msg: RequestMessage {
|
||||||
|
uuid: Uuid::new_v4(),
|
||||||
|
response: None,
|
||||||
|
payload: msg.into(),
|
||||||
|
},
|
||||||
|
callback: Callback::Registered(inner_tx),
|
||||||
|
});
|
||||||
|
|
||||||
|
spawn(async move {
|
||||||
|
// If the handler was unregistered we can stop
|
||||||
|
while let Some((msg, responder)) = inner_rx.recv().await {
|
||||||
|
let response: RequestMessagePayload = match M::Callback::try_from(msg.payload) {
|
||||||
|
Err(_) => GenericCallbackError::MismatchedType.into(),
|
||||||
|
Ok(o) => {
|
||||||
|
let (response_tx, response_rx) = oneshot::channel::<M::Response>();
|
||||||
|
match outer_tx.send((o, response_tx)).await {
|
||||||
|
Err(_) => GenericCallbackError::CallbackClosed.into(),
|
||||||
|
Ok(()) => response_rx
|
||||||
|
.await
|
||||||
|
.map(M::Response::into)
|
||||||
|
.unwrap_or_else(|_| GenericCallbackError::CallbackClosed.into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if responder.send(response).is_err() {
|
||||||
|
// If the callback was unregistered we can stop
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
Ok(outer_rx)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn register_callback_fn<M: RegisterCallback, F>(
|
||||||
|
&self,
|
||||||
|
msg: M,
|
||||||
|
mut f: F,
|
||||||
|
) -> Result<(), MessageError>
|
||||||
|
where
|
||||||
|
F: FnMut(M::Callback) -> M::Response + Send + 'static,
|
||||||
|
{
|
||||||
|
let sender = self.channel.read().await;
|
||||||
|
let data = sender.reserve().await?;
|
||||||
|
|
||||||
|
let (inner_tx, mut inner_rx) = mpsc::channel(16);
|
||||||
|
|
||||||
|
data.send(OutgoingMessage {
|
||||||
|
msg: RequestMessage {
|
||||||
|
uuid: Uuid::new_v4(),
|
||||||
|
response: None,
|
||||||
|
payload: msg.into(),
|
||||||
|
},
|
||||||
|
callback: Callback::Registered(inner_tx),
|
||||||
|
});
|
||||||
|
|
||||||
|
spawn(async move {
|
||||||
|
// If the handler was unregistered we can stop
|
||||||
|
while let Some((msg, responder)) = inner_rx.recv().await {
|
||||||
|
let response: RequestMessagePayload = match M::Callback::try_from(msg.payload) {
|
||||||
|
Err(_) => GenericCallbackError::MismatchedType.into(),
|
||||||
|
Ok(o) => f(o).into(),
|
||||||
|
};
|
||||||
|
|
||||||
|
if responder.send(response).is_err() {
|
||||||
|
// If the callback was unregistered we can stop
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ClientContext {
|
impl ClientContext {
|
||||||
fn start(mut self, channel: Arc<RwLock<Sender<OutgoingMessage>>>) -> Result<(), ConnectError> {
|
fn start(mut self, channel: ClientChannel) -> Result<(), ConnectError> {
|
||||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||||
.enable_all()
|
.enable_all()
|
||||||
.build()?;
|
.build()?;
|
||||||
@@ -162,9 +260,9 @@ impl ClientContext {
|
|||||||
|
|
||||||
async fn run_connection<'a>(
|
async fn run_connection<'a>(
|
||||||
&mut self,
|
&mut self,
|
||||||
mut write_lock: RwLockWriteGuard<'a, Sender<OutgoingMessage>>,
|
mut write_lock: RwLockWriteGuard<'a, mpsc::Sender<OutgoingMessage>>,
|
||||||
channel: &'a Arc<RwLock<Sender<OutgoingMessage>>>,
|
channel: &'a ClientChannel,
|
||||||
) -> RwLockWriteGuard<'a, Sender<OutgoingMessage>> {
|
) -> RwLockWriteGuard<'a, mpsc::Sender<OutgoingMessage>> {
|
||||||
let mut ws = match connect_async(self.request.clone()).await {
|
let mut ws = match connect_async(self.request.clone()).await {
|
||||||
Ok((ws, _)) => ws,
|
Ok((ws, _)) => ws,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
@@ -177,7 +275,7 @@ impl ClientContext {
|
|||||||
*write_lock = tx;
|
*write_lock = tx;
|
||||||
drop(write_lock);
|
drop(write_lock);
|
||||||
|
|
||||||
let close_connection = self.handle_connection(&mut ws, rx).await;
|
let close_connection = self.handle_connection(&mut ws, rx, channel).await;
|
||||||
|
|
||||||
let write_lock = channel.write().await;
|
let write_lock = channel.write().await;
|
||||||
if close_connection {
|
if close_connection {
|
||||||
@@ -191,7 +289,8 @@ impl ClientContext {
|
|||||||
async fn handle_connection(
|
async fn handle_connection(
|
||||||
&mut self,
|
&mut self,
|
||||||
ws: &mut WebSocketStream<MaybeTlsStream<TcpStream>>,
|
ws: &mut WebSocketStream<MaybeTlsStream<TcpStream>>,
|
||||||
mut rx: Receiver<OutgoingMessage>,
|
mut rx: mpsc::Receiver<OutgoingMessage>,
|
||||||
|
channel: &ClientChannel,
|
||||||
) -> bool {
|
) -> bool {
|
||||||
let mut callbacks = HashMap::<Uuid, Callback>::new();
|
let mut callbacks = HashMap::<Uuid, Callback>::new();
|
||||||
loop {
|
loop {
|
||||||
@@ -209,7 +308,7 @@ impl ClientContext {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
self.handle_incoming(msg, &mut callbacks).await;
|
self.handle_incoming(msg, &mut callbacks, channel).await;
|
||||||
}
|
}
|
||||||
Message::Binary(_) => unimplemented!("Binary Data Not Implemented"),
|
Message::Binary(_) => unimplemented!("Binary Data Not Implemented"),
|
||||||
Message::Ping(data) => {
|
Message::Ping(data) => {
|
||||||
@@ -235,7 +334,10 @@ impl ClientContext {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
Some(msg) = rx.recv() => {
|
Some(msg) = rx.recv() => {
|
||||||
|
// Insert a callback if it isn't a None callback
|
||||||
|
if !matches!(msg.callback, Callback::None) {
|
||||||
callbacks.insert(msg.msg.uuid, msg.callback);
|
callbacks.insert(msg.msg.uuid, msg.callback);
|
||||||
|
}
|
||||||
let msg = match serde_json::to_string(&msg.msg) {
|
let msg = match serde_json::to_string(&msg.msg) {
|
||||||
Ok(m) => m,
|
Ok(m) => m,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
@@ -258,22 +360,77 @@ impl ClientContext {
|
|||||||
&mut self,
|
&mut self,
|
||||||
msg: ResponseMessage,
|
msg: ResponseMessage,
|
||||||
callbacks: &mut HashMap<Uuid, Callback>,
|
callbacks: &mut HashMap<Uuid, Callback>,
|
||||||
|
channel: &ClientChannel,
|
||||||
) {
|
) {
|
||||||
if let Some(response_uuid) = msg.response {
|
if let Some(response_uuid) = msg.response {
|
||||||
match callbacks.get(&response_uuid) {
|
match callbacks.get(&response_uuid) {
|
||||||
|
Some(Callback::None) => {
|
||||||
|
callbacks.remove(&response_uuid);
|
||||||
|
unreachable!("We skip registering callbacks of None type");
|
||||||
|
}
|
||||||
Some(Callback::Once(_)) => {
|
Some(Callback::Once(_)) => {
|
||||||
let Some(Callback::Once(callback)) = callbacks.remove(&response_uuid) else {
|
let Some(Callback::Once(callback)) = callbacks.remove(&response_uuid) else {
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
let _ = callback.send(msg);
|
let _ = callback.send(msg);
|
||||||
}
|
}
|
||||||
Some(Callback::None) => {
|
Some(Callback::Registered(callback)) => {
|
||||||
callbacks.remove(&response_uuid);
|
let callback = callback.clone();
|
||||||
|
spawn(Self::handle_registered_callback(
|
||||||
|
callback,
|
||||||
|
msg,
|
||||||
|
channel.clone(),
|
||||||
|
));
|
||||||
}
|
}
|
||||||
None => {}
|
None => {
|
||||||
|
warn!("No Callback Registered for {response_uuid}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn handle_registered_callback(
|
||||||
|
callback: RegisteredCallback,
|
||||||
|
msg: ResponseMessage,
|
||||||
|
channel: ClientChannel,
|
||||||
|
) {
|
||||||
|
let (tx, rx) = oneshot::channel();
|
||||||
|
|
||||||
|
let uuid = msg.uuid;
|
||||||
|
|
||||||
|
let response = match callback.send((msg, tx)).await {
|
||||||
|
Err(_) => GenericCallbackError::CallbackClosed.into(),
|
||||||
|
Ok(()) => rx
|
||||||
|
.await
|
||||||
|
.unwrap_or_else(|_| GenericCallbackError::CallbackClosed.into()),
|
||||||
|
};
|
||||||
|
|
||||||
|
if let Err(e) = Self::send_response(channel, response, uuid).await {
|
||||||
|
error!("Failed to send response {e}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn send_response(
|
||||||
|
channel: ClientChannel,
|
||||||
|
payload: RequestMessagePayload,
|
||||||
|
response_uuid: Uuid,
|
||||||
|
) -> Result<(), MessageError> {
|
||||||
|
// If this failed that means we're in the middle of reconnecting, so our callbacks
|
||||||
|
// are all being cleaned up as-is. No response needed.
|
||||||
|
let sender = channel.try_read()?;
|
||||||
|
let data = sender.reserve().await?;
|
||||||
|
|
||||||
|
data.send(OutgoingMessage {
|
||||||
|
msg: RequestMessage {
|
||||||
|
uuid: Uuid::new_v4(),
|
||||||
|
response: Some(response_uuid),
|
||||||
|
payload,
|
||||||
|
},
|
||||||
|
callback: Callback::None,
|
||||||
|
});
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Drop for Client {
|
impl Drop for Client {
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
|
use derive_more::TryInto;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Copy, Serialize, Deserialize, TryInto)]
|
||||||
pub enum DataValue {
|
pub enum DataValue {
|
||||||
Float32(f32),
|
Float32(f32),
|
||||||
Float64(f64),
|
Float64(f64),
|
||||||
|
|||||||
7
api/src/messages/callback.rs
Normal file
7
api/src/messages/callback.rs
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub enum GenericCallbackError {
|
||||||
|
CallbackClosed,
|
||||||
|
MismatchedType,
|
||||||
|
}
|
||||||
35
api/src/messages/command.rs
Normal file
35
api/src/messages/command.rs
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
use crate::data_type::DataType;
|
||||||
|
use crate::data_value::DataValue;
|
||||||
|
use crate::messages::RegisterCallback;
|
||||||
|
use chrono::{DateTime, Utc};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct CommandParameterDefinition {
|
||||||
|
pub name: String,
|
||||||
|
pub data_type: DataType,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct CommandDefinition {
|
||||||
|
pub name: String,
|
||||||
|
pub parameters: Vec<CommandParameterDefinition>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RegisterCallback for CommandDefinition {
|
||||||
|
type Callback = Command;
|
||||||
|
type Response = CommandResponse;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct Command {
|
||||||
|
pub timestamp: DateTime<Utc>,
|
||||||
|
pub parameters: HashMap<String, DataValue>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct CommandResponse {
|
||||||
|
pub success: bool,
|
||||||
|
pub response: String,
|
||||||
|
}
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
|
pub mod callback;
|
||||||
|
pub mod command;
|
||||||
pub mod payload;
|
pub mod payload;
|
||||||
pub mod telemetry_definition;
|
pub mod telemetry_definition;
|
||||||
pub mod telemetry_entry;
|
pub mod telemetry_entry;
|
||||||
@@ -28,7 +30,7 @@ pub trait RequestResponse: Into<RequestMessagePayload> {
|
|||||||
type Response: TryFrom<ResponseMessagePayload>;
|
type Response: TryFrom<ResponseMessagePayload>;
|
||||||
}
|
}
|
||||||
|
|
||||||
// pub trait RegisterCallback {
|
pub trait RegisterCallback: Into<RequestMessagePayload> {
|
||||||
// type Callback : TryFrom<ResponseMessagePayload>;
|
type Callback: TryFrom<ResponseMessagePayload>;
|
||||||
// type Response : Into<RequestMessagePayload>;
|
type Response: Into<RequestMessagePayload>;
|
||||||
// }
|
}
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
use crate::messages::callback::GenericCallbackError;
|
||||||
|
use crate::messages::command::{Command, CommandDefinition, CommandResponse};
|
||||||
use crate::messages::telemetry_definition::{
|
use crate::messages::telemetry_definition::{
|
||||||
TelemetryDefinitionRequest, TelemetryDefinitionResponse,
|
TelemetryDefinitionRequest, TelemetryDefinitionResponse,
|
||||||
};
|
};
|
||||||
@@ -9,9 +11,13 @@ use serde::{Deserialize, Serialize};
|
|||||||
pub enum RequestMessagePayload {
|
pub enum RequestMessagePayload {
|
||||||
TelemetryDefinitionRequest(TelemetryDefinitionRequest),
|
TelemetryDefinitionRequest(TelemetryDefinitionRequest),
|
||||||
TelemetryEntry(TelemetryEntry),
|
TelemetryEntry(TelemetryEntry),
|
||||||
|
GenericCallbackError(GenericCallbackError),
|
||||||
|
CommandDefinition(CommandDefinition),
|
||||||
|
CommandResponse(CommandResponse),
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize, From, TryInto)]
|
#[derive(Debug, Clone, Serialize, Deserialize, From, TryInto)]
|
||||||
pub enum ResponseMessagePayload {
|
pub enum ResponseMessagePayload {
|
||||||
TelemetryDefinitionResponse(TelemetryDefinitionResponse),
|
TelemetryDefinitionResponse(TelemetryDefinitionResponse),
|
||||||
|
Command(Command),
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ name = "simple_command"
|
|||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
server = { path = "../../server" }
|
api = { path = "../../api" }
|
||||||
tonic = "0.12.3"
|
tonic = "0.12.3"
|
||||||
tokio = { version = "1.43.0", features = ["rt-multi-thread", "signal"] }
|
tokio = { version = "1.43.0", features = ["rt-multi-thread", "signal"] }
|
||||||
chrono = "0.4.39"
|
chrono = "0.4.39"
|
||||||
|
|||||||
@@ -1,78 +1,36 @@
|
|||||||
use chrono::DateTime;
|
use anyhow::anyhow;
|
||||||
use server::core::client_side_command::Inner;
|
use api::client::Client;
|
||||||
use server::core::command_service_client::CommandServiceClient;
|
use api::data_type::DataType;
|
||||||
use server::core::telemetry_value::Value;
|
use api::messages::command::{
|
||||||
use server::core::{
|
Command, CommandDefinition, CommandParameterDefinition, CommandResponse,
|
||||||
ClientSideCommand, Command, CommandDefinitionRequest, CommandParameterDefinition,
|
|
||||||
CommandResponse, TelemetryDataType,
|
|
||||||
};
|
};
|
||||||
use std::error::Error;
|
use std::error::Error;
|
||||||
use tokio::select;
|
use std::sync::Arc;
|
||||||
use tokio::sync::mpsc;
|
|
||||||
use tokio::task::JoinHandle;
|
|
||||||
use tokio_util::sync::CancellationToken;
|
use tokio_util::sync::CancellationToken;
|
||||||
use tonic::codegen::tokio_stream::wrappers::ReceiverStream;
|
|
||||||
use tonic::codegen::tokio_stream::StreamExt;
|
|
||||||
use tonic::transport::Channel;
|
|
||||||
|
|
||||||
struct CommandHandler {
|
fn handle_command(command: Command) -> anyhow::Result<String> {
|
||||||
handle: JoinHandle<()>,
|
let timestamp = command.timestamp;
|
||||||
}
|
let a: f32 = (*command
|
||||||
|
.parameters
|
||||||
|
.get("a")
|
||||||
|
.ok_or(anyhow!("Parameter 'a' Missing"))?)
|
||||||
|
.try_into()?;
|
||||||
|
let b: f64 = (*command
|
||||||
|
.parameters
|
||||||
|
.get("b")
|
||||||
|
.ok_or(anyhow!("Parameter 'b' Missing"))?)
|
||||||
|
.try_into()?;
|
||||||
|
let c: bool = (*command
|
||||||
|
.parameters
|
||||||
|
.get("c")
|
||||||
|
.ok_or(anyhow!("Parameter 'c' Missing"))?)
|
||||||
|
.try_into()?;
|
||||||
|
|
||||||
impl CommandHandler {
|
println!("Command Received:\n timestamp: {timestamp}\n a: {a}\n b: {b}\n c: {c}");
|
||||||
pub async fn new<F: Fn(Command) -> CommandResponse + Send + 'static>(
|
|
||||||
cancellation_token: CancellationToken,
|
|
||||||
client: &mut CommandServiceClient<Channel>,
|
|
||||||
command_definition_request: CommandDefinitionRequest,
|
|
||||||
handler: F,
|
|
||||||
) -> anyhow::Result<Self> {
|
|
||||||
let (tx, rx) = mpsc::channel(4);
|
|
||||||
|
|
||||||
// The buffer size of 4 means this is safe to send immediately
|
Ok(format!(
|
||||||
tx.send(ClientSideCommand {
|
"Successfully Received Command! timestamp: {timestamp} a: {a} b: {b} c: {c}"
|
||||||
inner: Some(Inner::Request(command_definition_request)),
|
))
|
||||||
})
|
|
||||||
.await?;
|
|
||||||
let response = client.new_command(ReceiverStream::new(rx)).await?;
|
|
||||||
let mut cmd_stream = response.into_inner();
|
|
||||||
|
|
||||||
let handle = tokio::spawn(async move {
|
|
||||||
loop {
|
|
||||||
select! {
|
|
||||||
_ = cancellation_token.cancelled() => break,
|
|
||||||
Some(msg) = cmd_stream.next() => {
|
|
||||||
match msg {
|
|
||||||
Ok(cmd) => {
|
|
||||||
let uuid = cmd.uuid.clone();
|
|
||||||
let mut response = handler(cmd);
|
|
||||||
response.uuid = uuid;
|
|
||||||
match tx.send(ClientSideCommand {
|
|
||||||
inner: Some(Inner::Response(response))
|
|
||||||
}).await {
|
|
||||||
Ok(()) => {},
|
|
||||||
Err(e) => {
|
|
||||||
println!("SendError: {e}");
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
println!("Error: {e}");
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
else => break,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
Ok(Self { handle })
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn join(self) -> anyhow::Result<()> {
|
|
||||||
Ok(self.handle.await?)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
@@ -86,56 +44,41 @@ async fn main() -> Result<(), Box<dyn Error>> {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut client = CommandServiceClient::connect("http://[::1]:50051").await?;
|
let client = Arc::new(Client::connect("ws://[::1]:8080/backend")?);
|
||||||
|
|
||||||
let cmd_handler = CommandHandler::new(
|
client
|
||||||
cancellation_token,
|
.register_callback_fn(
|
||||||
&mut client,
|
CommandDefinition {
|
||||||
CommandDefinitionRequest {
|
|
||||||
name: "simple_command/a".to_string(),
|
name: "simple_command/a".to_string(),
|
||||||
parameters: vec![
|
parameters: vec![
|
||||||
CommandParameterDefinition {
|
CommandParameterDefinition {
|
||||||
name: "a".to_string(),
|
name: "a".to_string(),
|
||||||
data_type: TelemetryDataType::Float32.into(),
|
data_type: DataType::Float32,
|
||||||
},
|
},
|
||||||
CommandParameterDefinition {
|
CommandParameterDefinition {
|
||||||
name: "b".to_string(),
|
name: "b".to_string(),
|
||||||
data_type: TelemetryDataType::Float64.into(),
|
data_type: DataType::Float64,
|
||||||
},
|
},
|
||||||
CommandParameterDefinition {
|
CommandParameterDefinition {
|
||||||
name: "c".to_string(),
|
name: "c".to_string(),
|
||||||
data_type: TelemetryDataType::Boolean.into(),
|
data_type: DataType::Boolean,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
|command| {
|
|command| match handle_command(command) {
|
||||||
let timestamp = command.timestamp.expect("Missing Timestamp");
|
Ok(response) => CommandResponse {
|
||||||
let timestamp = DateTime::from_timestamp(timestamp.secs, timestamp.nanos as u32)
|
|
||||||
.expect("Could not construct date time");
|
|
||||||
let Value::Float32(a) = command.parameters["a"].value.expect("Missing Value a") else {
|
|
||||||
panic!("Wrong Type a");
|
|
||||||
};
|
|
||||||
let Value::Float64(b) = command.parameters["b"].value.expect("Missing Value b") else {
|
|
||||||
panic!("Wrong Type b");
|
|
||||||
};
|
|
||||||
let Value::Boolean(c) = command.parameters["c"].value.expect("Missing Value c") else {
|
|
||||||
panic!("Wrong Type c");
|
|
||||||
};
|
|
||||||
|
|
||||||
println!("Command Received:\n timestamp: {timestamp}\n a: {a}\n b: {b}\n c: {c}");
|
|
||||||
|
|
||||||
CommandResponse {
|
|
||||||
uuid: command.uuid.clone(),
|
|
||||||
success: true,
|
success: true,
|
||||||
response: format!(
|
response,
|
||||||
"Successfully Received Command! timestamp: {timestamp} a: {a} b: {b} c: {c}"
|
},
|
||||||
),
|
Err(error) => CommandResponse {
|
||||||
}
|
success: false,
|
||||||
|
response: error.to_string(),
|
||||||
|
},
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
cmd_handler.join().await?;
|
cancellation_token.cancelled().await;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
println!("cargo:rerun-if-changed=migrations");
|
println!("cargo:rerun-if-changed=migrations");
|
||||||
tonic_build::compile_protos("proto/core.proto")?;
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,60 +0,0 @@
|
|||||||
|
|
||||||
syntax = "proto3";
|
|
||||||
package core;
|
|
||||||
|
|
||||||
enum TelemetryDataType {
|
|
||||||
Float32 = 0;
|
|
||||||
Float64 = 1;
|
|
||||||
Boolean = 2;
|
|
||||||
}
|
|
||||||
|
|
||||||
message TelemetryValue {
|
|
||||||
oneof value {
|
|
||||||
float float_32 = 1;
|
|
||||||
double float_64 = 2;
|
|
||||||
bool boolean = 3;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
message UUID {
|
|
||||||
string value = 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
// UTC since UNIX
|
|
||||||
message Timestamp {
|
|
||||||
sfixed64 secs = 1;
|
|
||||||
sfixed32 nanos = 2;
|
|
||||||
}
|
|
||||||
|
|
||||||
message CommandParameterDefinition {
|
|
||||||
string name = 1;
|
|
||||||
TelemetryDataType data_type = 2;
|
|
||||||
}
|
|
||||||
|
|
||||||
message CommandDefinitionRequest {
|
|
||||||
string name = 1;
|
|
||||||
repeated CommandParameterDefinition parameters = 2;
|
|
||||||
}
|
|
||||||
|
|
||||||
message Command {
|
|
||||||
UUID uuid = 1;
|
|
||||||
Timestamp timestamp = 2;
|
|
||||||
map<string, TelemetryValue> parameters = 3;
|
|
||||||
}
|
|
||||||
|
|
||||||
message CommandResponse {
|
|
||||||
UUID uuid = 1;
|
|
||||||
bool success = 2;
|
|
||||||
string response = 3;
|
|
||||||
}
|
|
||||||
|
|
||||||
message ClientSideCommand {
|
|
||||||
oneof inner {
|
|
||||||
CommandDefinitionRequest request = 1;
|
|
||||||
CommandResponse response = 2;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
service CommandService {
|
|
||||||
rpc NewCommand (stream ClientSideCommand) returns (stream Command);
|
|
||||||
}
|
|
||||||
20
server/src/command/command_handle.rs
Normal file
20
server/src/command/command_handle.rs
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
pub struct CommandHandle {
|
||||||
|
name: String,
|
||||||
|
uuid: Uuid,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CommandHandle {
|
||||||
|
pub fn new(name: String, uuid: Uuid) -> Self {
|
||||||
|
Self { name, uuid }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn name(&self) -> &str {
|
||||||
|
&self.name
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn uuid(&self) -> &Uuid {
|
||||||
|
&self.uuid
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,22 +1,5 @@
|
|||||||
use crate::command::service::RegisteredCommand;
|
use crate::command::service::RegisteredCommand;
|
||||||
use crate::core::TelemetryDataType;
|
use api::messages::command::{CommandDefinition, CommandParameterDefinition};
|
||||||
use crate::telemetry::data_type::tlm_data_type_deserializer;
|
|
||||||
use crate::telemetry::data_type::tlm_data_type_serializer;
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
|
||||||
pub struct CommandParameterDefinition {
|
|
||||||
pub name: String,
|
|
||||||
#[serde(serialize_with = "tlm_data_type_serializer")]
|
|
||||||
#[serde(deserialize_with = "tlm_data_type_deserializer")]
|
|
||||||
pub data_type: TelemetryDataType,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
|
||||||
pub struct CommandDefinition {
|
|
||||||
pub name: String,
|
|
||||||
pub parameters: Vec<CommandParameterDefinition>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<RegisteredCommand> for CommandDefinition {
|
impl From<RegisteredCommand> for CommandDefinition {
|
||||||
fn from(value: RegisteredCommand) -> Self {
|
fn from(value: RegisteredCommand) -> Self {
|
||||||
@@ -27,7 +10,7 @@ impl From<RegisteredCommand> for CommandDefinition {
|
|||||||
.parameters
|
.parameters
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|param| CommandParameterDefinition {
|
.map(|param| CommandParameterDefinition {
|
||||||
data_type: param.data_type(),
|
data_type: param.data_type,
|
||||||
name: param.name,
|
name: param.name,
|
||||||
})
|
})
|
||||||
.collect(),
|
.collect(),
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
use crate::core::TelemetryDataType;
|
|
||||||
use actix_web::http::StatusCode;
|
use actix_web::http::StatusCode;
|
||||||
use actix_web::ResponseError;
|
use actix_web::ResponseError;
|
||||||
|
use api::data_type::DataType;
|
||||||
use thiserror::Error;
|
use thiserror::Error;
|
||||||
|
|
||||||
#[derive(Error, Debug)]
|
#[derive(Error, Debug)]
|
||||||
@@ -14,7 +14,7 @@ pub enum Error {
|
|||||||
#[error("Incorrect Parameter Type for {name}. {expected_type:?} expected.")]
|
#[error("Incorrect Parameter Type for {name}. {expected_type:?} expected.")]
|
||||||
WrongParameterType {
|
WrongParameterType {
|
||||||
name: String,
|
name: String,
|
||||||
expected_type: TelemetryDataType,
|
expected_type: DataType,
|
||||||
},
|
},
|
||||||
#[error("No Command Receiver")]
|
#[error("No Command Receiver")]
|
||||||
NoCommandReceiver,
|
NoCommandReceiver,
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
pub mod command_handle;
|
||||||
mod definition;
|
mod definition;
|
||||||
pub mod error;
|
pub mod error;
|
||||||
pub mod service;
|
pub mod service;
|
||||||
|
|||||||
@@ -1,36 +1,40 @@
|
|||||||
use crate::command::definition::CommandDefinition;
|
use crate::command::command_handle::CommandHandle;
|
||||||
use crate::command::error::Error as CmdError;
|
use crate::command::error::Error as CmdError;
|
||||||
use crate::command::error::Error::{
|
use crate::command::error::Error::{
|
||||||
CommandFailure, CommandNotFound, FailedToReceiveResponse, FailedToSend,
|
CommandFailure, CommandNotFound, FailedToReceiveResponse, FailedToSend,
|
||||||
IncorrectParameterCount, MisingParameter, NoCommandReceiver, WrongParameterType,
|
IncorrectParameterCount, MisingParameter, NoCommandReceiver, WrongParameterType,
|
||||||
};
|
};
|
||||||
use crate::core::telemetry_value::Value;
|
use anyhow::bail;
|
||||||
use crate::core::{
|
use api::data_type::DataType;
|
||||||
Command, CommandDefinitionRequest, CommandResponse, TelemetryDataType, TelemetryValue,
|
use api::data_value::DataValue;
|
||||||
Timestamp, Uuid,
|
use api::messages::command::{Command, CommandDefinition, CommandResponse};
|
||||||
};
|
use api::messages::ResponseMessage;
|
||||||
use chrono::{DateTime, Utc};
|
use chrono::Utc;
|
||||||
use log::error;
|
use log::error;
|
||||||
use papaya::HashMap;
|
use papaya::HashMap;
|
||||||
use std::collections::HashMap as StdHashMap;
|
use std::collections::HashMap as StdHashMap;
|
||||||
use tokio::sync::mpsc;
|
|
||||||
use tokio::sync::oneshot;
|
use tokio::sync::oneshot;
|
||||||
|
use tokio::sync::{mpsc, RwLock};
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub(super) struct RegisteredCommand {
|
pub(super) struct RegisteredCommand {
|
||||||
pub(super) name: String,
|
pub(super) name: String,
|
||||||
pub(super) definition: CommandDefinitionRequest,
|
pub(super) definition: CommandDefinition,
|
||||||
tx: mpsc::Sender<Option<(Command, oneshot::Sender<CommandResponse>)>>,
|
response_uuid: Uuid,
|
||||||
|
tx: mpsc::Sender<ResponseMessage>,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct CommandManagementService {
|
pub struct CommandManagementService {
|
||||||
registered_commands: HashMap<String, RegisteredCommand>,
|
registered_commands: HashMap<String, RegisteredCommand>,
|
||||||
|
outstanding_responses: RwLock<StdHashMap<Uuid, oneshot::Sender<CommandResponse>>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl CommandManagementService {
|
impl CommandManagementService {
|
||||||
pub fn new() -> Self {
|
pub fn new() -> Self {
|
||||||
Self {
|
Self {
|
||||||
registered_commands: HashMap::new(),
|
registered_commands: HashMap::new(),
|
||||||
|
outstanding_responses: RwLock::new(StdHashMap::new()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -52,26 +56,26 @@ impl CommandManagementService {
|
|||||||
.map(|registration| registration.clone().into())
|
.map(|registration| registration.clone().into())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn register_command(
|
pub fn register_command(
|
||||||
&self,
|
&self,
|
||||||
command: CommandDefinitionRequest,
|
uuid: Uuid,
|
||||||
) -> anyhow::Result<mpsc::Receiver<Option<(Command, oneshot::Sender<CommandResponse>)>>> {
|
command: CommandDefinition,
|
||||||
let (tx, rx) = mpsc::channel(1);
|
tx: mpsc::Sender<ResponseMessage>,
|
||||||
|
) -> anyhow::Result<CommandHandle> {
|
||||||
let registered_commands = self.registered_commands.pin_owned();
|
let registered_commands = self.registered_commands.pin();
|
||||||
if let Some(previous) = registered_commands.insert(
|
// We don't care about the previously registered command
|
||||||
command.name.clone(),
|
let name = command.name.clone();
|
||||||
|
let _ = registered_commands.insert(
|
||||||
|
name.clone(),
|
||||||
RegisteredCommand {
|
RegisteredCommand {
|
||||||
name: command.name.clone(),
|
response_uuid: uuid,
|
||||||
|
name: name.clone(),
|
||||||
definition: command,
|
definition: command,
|
||||||
tx,
|
tx,
|
||||||
},
|
},
|
||||||
) {
|
);
|
||||||
// If the receiver was already closed, we don't care (ignore error)
|
|
||||||
let _ = previous.tx.send(None).await;
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(rx)
|
Ok(CommandHandle::new(name, uuid))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn send_command(
|
pub async fn send_command(
|
||||||
@@ -80,8 +84,6 @@ impl CommandManagementService {
|
|||||||
parameters: serde_json::Map<String, serde_json::Value>,
|
parameters: serde_json::Map<String, serde_json::Value>,
|
||||||
) -> Result<String, CmdError> {
|
) -> Result<String, CmdError> {
|
||||||
let timestamp = Utc::now();
|
let timestamp = Utc::now();
|
||||||
let offset_from_unix_epoch =
|
|
||||||
timestamp - DateTime::from_timestamp(0, 0).expect("Could not get Unix epoch");
|
|
||||||
|
|
||||||
let name = name.into();
|
let name = name.into();
|
||||||
let registered_commands = self.registered_commands.pin();
|
let registered_commands = self.registered_commands.pin();
|
||||||
@@ -100,27 +102,21 @@ impl CommandManagementService {
|
|||||||
let Some(param_value) = parameters.get(¶meter.name) else {
|
let Some(param_value) = parameters.get(¶meter.name) else {
|
||||||
return Err(MisingParameter(parameter.name.clone()));
|
return Err(MisingParameter(parameter.name.clone()));
|
||||||
};
|
};
|
||||||
let Some(param_value) = (match parameter.data_type() {
|
let Some(param_value) = (match parameter.data_type {
|
||||||
TelemetryDataType::Float32 => {
|
DataType::Float32 => param_value.as_f64().map(|v| DataValue::Float32(v as f32)),
|
||||||
param_value.as_f64().map(|v| Value::Float32(v as f32))
|
DataType::Float64 => param_value.as_f64().map(DataValue::Float64),
|
||||||
}
|
DataType::Boolean => param_value.as_bool().map(DataValue::Boolean),
|
||||||
TelemetryDataType::Float64 => param_value.as_f64().map(Value::Float64),
|
|
||||||
TelemetryDataType::Boolean => param_value.as_bool().map(Value::Boolean),
|
|
||||||
}) else {
|
}) else {
|
||||||
return Err(WrongParameterType {
|
return Err(WrongParameterType {
|
||||||
name: parameter.name.clone(),
|
name: parameter.name.clone(),
|
||||||
expected_type: parameter.data_type(),
|
expected_type: parameter.data_type,
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
result_parameters.insert(
|
result_parameters.insert(parameter.name.clone(), param_value);
|
||||||
parameter.name.clone(),
|
|
||||||
TelemetryValue {
|
|
||||||
value: Some(param_value),
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Clone & Drop lets us use a standard pin instead of an owned pin
|
// Clone & Drop lets us use a standard pin instead of an owned pin
|
||||||
|
let response_uuid = registration.response_uuid;
|
||||||
let tx = registration.tx.clone();
|
let tx = registration.tx.clone();
|
||||||
drop(registered_commands);
|
drop(registered_commands);
|
||||||
|
|
||||||
@@ -128,23 +124,27 @@ impl CommandManagementService {
|
|||||||
return Err(NoCommandReceiver);
|
return Err(NoCommandReceiver);
|
||||||
}
|
}
|
||||||
|
|
||||||
let uuid = Uuid::random();
|
let uuid = Uuid::new_v4();
|
||||||
let (response_tx, response_rx) = oneshot::channel();
|
let (response_tx, response_rx) = oneshot::channel();
|
||||||
|
|
||||||
|
{
|
||||||
|
let mut outstanding_responses = self.outstanding_responses.write().await;
|
||||||
|
outstanding_responses.insert(uuid, response_tx);
|
||||||
|
}
|
||||||
|
|
||||||
if let Err(e) = tx
|
if let Err(e) = tx
|
||||||
.send(Some((
|
.send(ResponseMessage {
|
||||||
Command {
|
uuid,
|
||||||
uuid: Some(uuid),
|
response: Some(response_uuid),
|
||||||
timestamp: Some(Timestamp {
|
payload: Command {
|
||||||
secs: offset_from_unix_epoch.num_seconds(),
|
timestamp,
|
||||||
nanos: offset_from_unix_epoch.subsec_nanos(),
|
|
||||||
}),
|
|
||||||
parameters: result_parameters,
|
parameters: result_parameters,
|
||||||
},
|
}
|
||||||
response_tx,
|
.into(),
|
||||||
)))
|
})
|
||||||
.await
|
.await
|
||||||
{
|
{
|
||||||
error!("Failed to Send Command: {e}");
|
error!("Failed to Send Command {e}");
|
||||||
return Err(FailedToSend);
|
return Err(FailedToSend);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -162,4 +162,33 @@ impl CommandManagementService {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn handle_command_response(
|
||||||
|
&self,
|
||||||
|
uuid: Uuid,
|
||||||
|
response: CommandResponse,
|
||||||
|
) -> anyhow::Result<()> {
|
||||||
|
let responder = {
|
||||||
|
let mut outstanding_responses = self.outstanding_responses.write().await;
|
||||||
|
outstanding_responses.remove(&uuid)
|
||||||
|
};
|
||||||
|
match responder {
|
||||||
|
None => bail!("Unexpected Command Response for Command {uuid}"),
|
||||||
|
Some(response_tx) => {
|
||||||
|
if let Err(e) = response_tx.send(response) {
|
||||||
|
bail!("Failed to send Command Response {e:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn unregister(&self, command_handle: CommandHandle) {
|
||||||
|
let registered_commands = self.registered_commands.pin();
|
||||||
|
// We don't care if this succeeded
|
||||||
|
let _ = registered_commands.remove_if(command_handle.name(), |_, registration| {
|
||||||
|
registration.response_uuid == *command_handle.uuid()
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,33 +0,0 @@
|
|||||||
mod cmd;
|
|
||||||
|
|
||||||
use crate::command::service::CommandManagementService;
|
|
||||||
use crate::core::command_service_server::CommandServiceServer;
|
|
||||||
use crate::grpc::cmd::CoreCommandService;
|
|
||||||
use log::{error, info};
|
|
||||||
use std::sync::Arc;
|
|
||||||
use tokio::task::JoinHandle;
|
|
||||||
use tokio_util::sync::CancellationToken;
|
|
||||||
use tonic::transport::Server;
|
|
||||||
|
|
||||||
pub fn setup(
|
|
||||||
token: CancellationToken,
|
|
||||||
command_service: Arc<CommandManagementService>,
|
|
||||||
) -> anyhow::Result<JoinHandle<()>> {
|
|
||||||
let addr = "[::1]:50051".parse()?;
|
|
||||||
Ok(tokio::spawn(async move {
|
|
||||||
let cmd_service = CoreCommandService {
|
|
||||||
command_service,
|
|
||||||
cancellation_token: token.clone(),
|
|
||||||
};
|
|
||||||
|
|
||||||
info!("Starting gRPC Server");
|
|
||||||
let result = Server::builder()
|
|
||||||
.add_service(CommandServiceServer::new(cmd_service))
|
|
||||||
.serve_with_shutdown(addr, token.cancelled_owned())
|
|
||||||
.await;
|
|
||||||
|
|
||||||
if let Err(err) = result {
|
|
||||||
error!("gRPC Server Encountered An Error: {err}");
|
|
||||||
}
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
@@ -4,6 +4,7 @@ use crate::panels::PanelService;
|
|||||||
use actix_web::{delete, get, post, put, web, Responder};
|
use actix_web::{delete, get, post, put, web, Responder};
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
struct CreateParam {
|
struct CreateParam {
|
||||||
@@ -13,7 +14,7 @@ struct CreateParam {
|
|||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
struct IdParam {
|
struct IdParam {
|
||||||
id: String,
|
id: Uuid,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[post("/panel")]
|
#[post("/panel")]
|
||||||
@@ -22,7 +23,7 @@ pub(super) async fn new(
|
|||||||
data: web::Json<CreateParam>,
|
data: web::Json<CreateParam>,
|
||||||
) -> Result<impl Responder, HttpServerResultError> {
|
) -> Result<impl Responder, HttpServerResultError> {
|
||||||
let uuid = panels.create(&data.name, &data.data).await?;
|
let uuid = panels.create(&data.name, &data.data).await?;
|
||||||
Ok(web::Json(uuid.value))
|
Ok(web::Json(uuid))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[get("/panel")]
|
#[get("/panel")]
|
||||||
@@ -38,12 +39,10 @@ pub(super) async fn get_one(
|
|||||||
panels: web::Data<Arc<PanelService>>,
|
panels: web::Data<Arc<PanelService>>,
|
||||||
path: web::Path<IdParam>,
|
path: web::Path<IdParam>,
|
||||||
) -> Result<impl Responder, HttpServerResultError> {
|
) -> Result<impl Responder, HttpServerResultError> {
|
||||||
let result = panels.read(path.id.clone().into()).await?;
|
let result = panels.read(path.id).await?;
|
||||||
match result {
|
match result {
|
||||||
Some(result) => Ok(web::Json(result)),
|
Some(result) => Ok(web::Json(result)),
|
||||||
None => Err(HttpServerResultError::PanelUuidNotFound {
|
None => Err(HttpServerResultError::PanelUuidNotFound { uuid: path.id }),
|
||||||
uuid: path.id.clone(),
|
|
||||||
}),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -53,7 +52,7 @@ pub(super) async fn set(
|
|||||||
path: web::Path<IdParam>,
|
path: web::Path<IdParam>,
|
||||||
data: web::Json<PanelUpdate>,
|
data: web::Json<PanelUpdate>,
|
||||||
) -> Result<impl Responder, HttpServerResultError> {
|
) -> Result<impl Responder, HttpServerResultError> {
|
||||||
panels.update(path.id.clone().into(), data.0).await?;
|
panels.update(path.id, data.0).await?;
|
||||||
Ok(web::Json(()))
|
Ok(web::Json(()))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -62,6 +61,6 @@ pub(super) async fn delete(
|
|||||||
panels: web::Data<Arc<PanelService>>,
|
panels: web::Data<Arc<PanelService>>,
|
||||||
path: web::Path<IdParam>,
|
path: web::Path<IdParam>,
|
||||||
) -> Result<impl Responder, HttpServerResultError> {
|
) -> Result<impl Responder, HttpServerResultError> {
|
||||||
panels.delete(path.id.clone().into()).await?;
|
panels.delete(path.id).await?;
|
||||||
Ok(web::Json(()))
|
Ok(web::Json(()))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
use crate::command::command_handle::CommandHandle;
|
||||||
|
use crate::command::service::CommandManagementService;
|
||||||
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;
|
||||||
@@ -10,18 +12,26 @@ use uuid::Uuid;
|
|||||||
pub(super) struct BackendConnection {
|
pub(super) struct BackendConnection {
|
||||||
session: Session,
|
session: Session,
|
||||||
tlm_management: Arc<TelemetryManagementService>,
|
tlm_management: Arc<TelemetryManagementService>,
|
||||||
|
cmd_management: Arc<CommandManagementService>,
|
||||||
tx: Sender<ResponseMessage>,
|
tx: Sender<ResponseMessage>,
|
||||||
|
commands: Vec<CommandHandle>,
|
||||||
pub rx: Receiver<ResponseMessage>,
|
pub rx: Receiver<ResponseMessage>,
|
||||||
pub should_close: bool,
|
pub should_close: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl BackendConnection {
|
impl BackendConnection {
|
||||||
pub fn new(session: Session, tlm_management: Arc<TelemetryManagementService>) -> Self {
|
pub fn new(
|
||||||
|
session: Session,
|
||||||
|
tlm_management: Arc<TelemetryManagementService>,
|
||||||
|
cmd_management: Arc<CommandManagementService>,
|
||||||
|
) -> Self {
|
||||||
let (tx, rx) = tokio::sync::mpsc::channel::<ResponseMessage>(128);
|
let (tx, rx) = tokio::sync::mpsc::channel::<ResponseMessage>(128);
|
||||||
Self {
|
Self {
|
||||||
session,
|
session,
|
||||||
tlm_management,
|
tlm_management,
|
||||||
|
cmd_management,
|
||||||
tx,
|
tx,
|
||||||
|
commands: vec![],
|
||||||
rx,
|
rx,
|
||||||
should_close: false,
|
should_close: false,
|
||||||
}
|
}
|
||||||
@@ -41,6 +51,21 @@ impl BackendConnection {
|
|||||||
RequestMessagePayload::TelemetryEntry(tlm_entry) => {
|
RequestMessagePayload::TelemetryEntry(tlm_entry) => {
|
||||||
self.tlm_management.add_tlm_item(tlm_entry)?;
|
self.tlm_management.add_tlm_item(tlm_entry)?;
|
||||||
}
|
}
|
||||||
|
RequestMessagePayload::GenericCallbackError(_) => todo!(),
|
||||||
|
RequestMessagePayload::CommandDefinition(def) => {
|
||||||
|
let cmd = self
|
||||||
|
.cmd_management
|
||||||
|
.register_command(msg.uuid, def, self.tx.clone())?;
|
||||||
|
self.commands.push(cmd);
|
||||||
|
}
|
||||||
|
RequestMessagePayload::CommandResponse(response) => match msg.response {
|
||||||
|
None => bail!("Command Response Payload Must Respond to a Command"),
|
||||||
|
Some(uuid) => {
|
||||||
|
self.cmd_management
|
||||||
|
.handle_command_response(uuid, response)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
},
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -78,6 +103,15 @@ impl BackendConnection {
|
|||||||
|
|
||||||
pub async fn cleanup(mut self) {
|
pub async fn cleanup(mut self) {
|
||||||
self.rx.close();
|
self.rx.close();
|
||||||
let _ = self.session.close(None).await;
|
// Clone here to prevent conflict with the Drop trait
|
||||||
|
let _ = self.session.clone().close(None).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for BackendConnection {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
for command in self.commands.drain(..) {
|
||||||
|
self.cmd_management.unregister(command);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
mod connection;
|
mod connection;
|
||||||
|
|
||||||
|
use crate::command::service::CommandManagementService;
|
||||||
use crate::http::backend::connection::BackendConnection;
|
use crate::http::backend::connection::BackendConnection;
|
||||||
use crate::telemetry::management_service::TelemetryManagementService;
|
use crate::telemetry::management_service::TelemetryManagementService;
|
||||||
use actix_web::{rt, web, HttpRequest, HttpResponse};
|
use actix_web::{rt, web, HttpRequest, HttpResponse};
|
||||||
@@ -14,6 +15,7 @@ async fn backend_connect(
|
|||||||
stream: web::Payload,
|
stream: web::Payload,
|
||||||
cancel_token: web::Data<CancellationToken>,
|
cancel_token: web::Data<CancellationToken>,
|
||||||
telemetry_management_service: web::Data<Arc<TelemetryManagementService>>,
|
telemetry_management_service: web::Data<Arc<TelemetryManagementService>>,
|
||||||
|
command_management_service: web::Data<Arc<CommandManagementService>>,
|
||||||
) -> Result<HttpResponse, actix_web::Error> {
|
) -> Result<HttpResponse, actix_web::Error> {
|
||||||
trace!("backend_connect");
|
trace!("backend_connect");
|
||||||
let (res, session, stream) = actix_ws::handle(&req, stream)?;
|
let (res, session, stream) = actix_ws::handle(&req, stream)?;
|
||||||
@@ -25,9 +27,10 @@ async fn backend_connect(
|
|||||||
|
|
||||||
let cancel_token = cancel_token.get_ref().clone();
|
let cancel_token = cancel_token.get_ref().clone();
|
||||||
let tlm_management = telemetry_management_service.get_ref().clone();
|
let tlm_management = telemetry_management_service.get_ref().clone();
|
||||||
|
let cmd_management = command_management_service.get_ref().clone();
|
||||||
|
|
||||||
rt::spawn(async move {
|
rt::spawn(async move {
|
||||||
let mut connection = BackendConnection::new(session, tlm_management);
|
let mut connection = BackendConnection::new(session, tlm_management, cmd_management);
|
||||||
while !connection.should_close {
|
while !connection.should_close {
|
||||||
let result = select! {
|
let result = select! {
|
||||||
_ = cancel_token.cancelled() => {
|
_ = cancel_token.cancelled() => {
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ pub enum HttpServerResultError {
|
|||||||
#[error("Internal Error")]
|
#[error("Internal Error")]
|
||||||
InternalError(#[from] anyhow::Error),
|
InternalError(#[from] anyhow::Error),
|
||||||
#[error("Panel Uuid Not Found: {uuid}")]
|
#[error("Panel Uuid Not Found: {uuid}")]
|
||||||
PanelUuidNotFound { uuid: String },
|
PanelUuidNotFound { uuid: Uuid },
|
||||||
#[error(transparent)]
|
#[error(transparent)]
|
||||||
Command(#[from] crate::command::error::Error),
|
Command(#[from] crate::command::error::Error),
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +1,8 @@
|
|||||||
mod command;
|
mod command;
|
||||||
mod grpc;
|
|
||||||
mod http;
|
mod http;
|
||||||
mod panels;
|
mod panels;
|
||||||
mod serialization;
|
mod serialization;
|
||||||
mod telemetry;
|
mod telemetry;
|
||||||
mod uuid;
|
|
||||||
|
|
||||||
pub mod core {
|
|
||||||
tonic::include_proto!("core");
|
|
||||||
}
|
|
||||||
|
|
||||||
use crate::command::service::CommandManagementService;
|
use crate::command::service::CommandManagementService;
|
||||||
use crate::panels::PanelService;
|
use crate::panels::PanelService;
|
||||||
@@ -53,14 +47,11 @@ pub async fn setup() -> anyhow::Result<()> {
|
|||||||
|
|
||||||
let cmd = Arc::new(CommandManagementService::new());
|
let cmd = Arc::new(CommandManagementService::new());
|
||||||
|
|
||||||
let grpc_server = grpc::setup(cancellation_token.clone(), cmd.clone())?;
|
|
||||||
|
|
||||||
let panel_service = PanelService::new(sqlite.clone());
|
let panel_service = PanelService::new(sqlite.clone());
|
||||||
|
|
||||||
let result = http::setup(cancellation_token.clone(), tlm.clone(), panel_service, cmd).await;
|
let result = http::setup(cancellation_token.clone(), tlm.clone(), panel_service, cmd).await;
|
||||||
cancellation_token.cancel();
|
cancellation_token.cancel();
|
||||||
result?; // result is dropped
|
result?; // result is dropped
|
||||||
grpc_server.await?; //grpc server is dropped
|
|
||||||
drop(cancellation_token); // All cancellation tokens are now dropped
|
drop(cancellation_token); // All cancellation tokens are now dropped
|
||||||
|
|
||||||
sqlite.close().await;
|
sqlite.close().await;
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
pub mod panel;
|
pub mod panel;
|
||||||
|
|
||||||
use crate::core::Uuid;
|
|
||||||
use crate::panels::panel::{PanelRequired, PanelUpdate};
|
use crate::panels::panel::{PanelRequired, PanelUpdate};
|
||||||
use panel::Panel;
|
use panel::Panel;
|
||||||
use sqlx::SqlitePool;
|
use sqlx::SqlitePool;
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
pub struct PanelService {
|
pub struct PanelService {
|
||||||
pool: SqlitePool,
|
pool: SqlitePool,
|
||||||
@@ -15,7 +15,8 @@ impl PanelService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub async fn create(&self, name: &str, data: &str) -> anyhow::Result<Uuid> {
|
pub async fn create(&self, name: &str, data: &str) -> anyhow::Result<Uuid> {
|
||||||
let id = Uuid::random();
|
let id = Uuid::new_v4();
|
||||||
|
let id_string = id.to_string();
|
||||||
|
|
||||||
let mut transaction = self.pool.begin().await?;
|
let mut transaction = self.pool.begin().await?;
|
||||||
|
|
||||||
@@ -24,7 +25,7 @@ impl PanelService {
|
|||||||
INSERT INTO PANELS (id, name, data, deleted)
|
INSERT INTO PANELS (id, name, data, deleted)
|
||||||
VALUES ($1, $2, $3, FALSE);
|
VALUES ($1, $2, $3, FALSE);
|
||||||
"#,
|
"#,
|
||||||
id.value,
|
id_string,
|
||||||
name,
|
name,
|
||||||
data
|
data
|
||||||
)
|
)
|
||||||
@@ -65,7 +66,7 @@ impl PanelService {
|
|||||||
WHERE id = $1 AND deleted = FALSE
|
WHERE id = $1 AND deleted = FALSE
|
||||||
"#,
|
"#,
|
||||||
)
|
)
|
||||||
.bind(id.value)
|
.bind(id.to_string())
|
||||||
.fetch_optional(&mut *transaction)
|
.fetch_optional(&mut *transaction)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
@@ -75,6 +76,7 @@ impl PanelService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub async fn update(&self, id: Uuid, data: PanelUpdate) -> anyhow::Result<()> {
|
pub async fn update(&self, id: Uuid, data: PanelUpdate) -> anyhow::Result<()> {
|
||||||
|
let id = id.to_string();
|
||||||
let mut transaction = self.pool.begin().await?;
|
let mut transaction = self.pool.begin().await?;
|
||||||
|
|
||||||
if let Some(name) = data.name {
|
if let Some(name) = data.name {
|
||||||
@@ -84,7 +86,7 @@ impl PanelService {
|
|||||||
SET name = $2
|
SET name = $2
|
||||||
WHERE id = $1;
|
WHERE id = $1;
|
||||||
"#,
|
"#,
|
||||||
id.value,
|
id,
|
||||||
name
|
name
|
||||||
)
|
)
|
||||||
.execute(&mut *transaction)
|
.execute(&mut *transaction)
|
||||||
@@ -97,7 +99,7 @@ impl PanelService {
|
|||||||
SET data = $2
|
SET data = $2
|
||||||
WHERE id = $1;
|
WHERE id = $1;
|
||||||
"#,
|
"#,
|
||||||
id.value,
|
id,
|
||||||
data
|
data
|
||||||
)
|
)
|
||||||
.execute(&mut *transaction)
|
.execute(&mut *transaction)
|
||||||
@@ -110,6 +112,7 @@ impl PanelService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub async fn delete(&self, id: Uuid) -> anyhow::Result<()> {
|
pub async fn delete(&self, id: Uuid) -> anyhow::Result<()> {
|
||||||
|
let id = id.to_string();
|
||||||
let mut transaction = self.pool.begin().await?;
|
let mut transaction = self.pool.begin().await?;
|
||||||
|
|
||||||
let _ = sqlx::query!(
|
let _ = sqlx::query!(
|
||||||
@@ -118,7 +121,7 @@ impl PanelService {
|
|||||||
SET deleted = TRUE
|
SET deleted = TRUE
|
||||||
WHERE id = $1;
|
WHERE id = $1;
|
||||||
"#,
|
"#,
|
||||||
id.value,
|
id,
|
||||||
)
|
)
|
||||||
.execute(&mut *transaction)
|
.execute(&mut *transaction)
|
||||||
.await?;
|
.await?;
|
||||||
|
|||||||
@@ -1,38 +0,0 @@
|
|||||||
use crate::core::TelemetryDataType;
|
|
||||||
use serde::de::Visitor;
|
|
||||||
use serde::{Deserializer, Serializer};
|
|
||||||
use std::fmt::Formatter;
|
|
||||||
|
|
||||||
pub fn tlm_data_type_serializer<S>(
|
|
||||||
tlm_data_type: &TelemetryDataType,
|
|
||||||
serializer: S,
|
|
||||||
) -> Result<S::Ok, S::Error>
|
|
||||||
where
|
|
||||||
S: Serializer,
|
|
||||||
{
|
|
||||||
serializer.serialize_str(tlm_data_type.as_str_name())
|
|
||||||
}
|
|
||||||
|
|
||||||
struct TlmDataTypeVisitor;
|
|
||||||
|
|
||||||
impl Visitor<'_> for TlmDataTypeVisitor {
|
|
||||||
type Value = TelemetryDataType;
|
|
||||||
|
|
||||||
fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
|
|
||||||
formatter.write_str("A &str")
|
|
||||||
}
|
|
||||||
|
|
||||||
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
|
|
||||||
where
|
|
||||||
E: serde::de::Error,
|
|
||||||
{
|
|
||||||
TelemetryDataType::from_str_name(v).ok_or(E::custom("Invalid TelemetryDataType"))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn tlm_data_type_deserializer<'de, D>(deserializer: D) -> Result<TelemetryDataType, D::Error>
|
|
||||||
where
|
|
||||||
D: Deserializer<'de>,
|
|
||||||
{
|
|
||||||
deserializer.deserialize_str(TlmDataTypeVisitor)
|
|
||||||
}
|
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
pub mod data;
|
pub mod data;
|
||||||
pub mod data_item;
|
pub mod data_item;
|
||||||
pub mod data_type;
|
|
||||||
pub mod definition;
|
pub mod definition;
|
||||||
pub mod history;
|
pub mod history;
|
||||||
pub mod management_service;
|
pub mod management_service;
|
||||||
|
|||||||
@@ -1,18 +0,0 @@
|
|||||||
use crate::core::Uuid;
|
|
||||||
use rand::RngCore;
|
|
||||||
|
|
||||||
impl Uuid {
|
|
||||||
pub fn random() -> Self {
|
|
||||||
let mut uuid = [0u8; 16];
|
|
||||||
rand::rng().fill_bytes(&mut uuid);
|
|
||||||
Self {
|
|
||||||
value: hex::encode(uuid),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<String> for Uuid {
|
|
||||||
fn from(value: String) -> Self {
|
|
||||||
Self { value }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user