move cmd off of grpc
This commit is contained in:
@@ -1,5 +1,4 @@
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
println!("cargo:rerun-if-changed=migrations");
|
||||
tonic_build::compile_protos("proto/core.proto")?;
|
||||
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::core::TelemetryDataType;
|
||||
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>,
|
||||
}
|
||||
use api::messages::command::{CommandDefinition, CommandParameterDefinition};
|
||||
|
||||
impl From<RegisteredCommand> for CommandDefinition {
|
||||
fn from(value: RegisteredCommand) -> Self {
|
||||
@@ -27,7 +10,7 @@ impl From<RegisteredCommand> for CommandDefinition {
|
||||
.parameters
|
||||
.into_iter()
|
||||
.map(|param| CommandParameterDefinition {
|
||||
data_type: param.data_type(),
|
||||
data_type: param.data_type,
|
||||
name: param.name,
|
||||
})
|
||||
.collect(),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::core::TelemetryDataType;
|
||||
use actix_web::http::StatusCode;
|
||||
use actix_web::ResponseError;
|
||||
use api::data_type::DataType;
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
@@ -14,7 +14,7 @@ pub enum Error {
|
||||
#[error("Incorrect Parameter Type for {name}. {expected_type:?} expected.")]
|
||||
WrongParameterType {
|
||||
name: String,
|
||||
expected_type: TelemetryDataType,
|
||||
expected_type: DataType,
|
||||
},
|
||||
#[error("No Command Receiver")]
|
||||
NoCommandReceiver,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
pub mod command_handle;
|
||||
mod definition;
|
||||
pub mod error;
|
||||
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::{
|
||||
CommandFailure, CommandNotFound, FailedToReceiveResponse, FailedToSend,
|
||||
IncorrectParameterCount, MisingParameter, NoCommandReceiver, WrongParameterType,
|
||||
};
|
||||
use crate::core::telemetry_value::Value;
|
||||
use crate::core::{
|
||||
Command, CommandDefinitionRequest, CommandResponse, TelemetryDataType, TelemetryValue,
|
||||
Timestamp, Uuid,
|
||||
};
|
||||
use chrono::{DateTime, Utc};
|
||||
use anyhow::bail;
|
||||
use api::data_type::DataType;
|
||||
use api::data_value::DataValue;
|
||||
use api::messages::command::{Command, CommandDefinition, CommandResponse};
|
||||
use api::messages::ResponseMessage;
|
||||
use chrono::Utc;
|
||||
use log::error;
|
||||
use papaya::HashMap;
|
||||
use std::collections::HashMap as StdHashMap;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::sync::oneshot;
|
||||
use tokio::sync::{mpsc, RwLock};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(super) struct RegisteredCommand {
|
||||
pub(super) name: String,
|
||||
pub(super) definition: CommandDefinitionRequest,
|
||||
tx: mpsc::Sender<Option<(Command, oneshot::Sender<CommandResponse>)>>,
|
||||
pub(super) definition: CommandDefinition,
|
||||
response_uuid: Uuid,
|
||||
tx: mpsc::Sender<ResponseMessage>,
|
||||
}
|
||||
|
||||
pub struct CommandManagementService {
|
||||
registered_commands: HashMap<String, RegisteredCommand>,
|
||||
outstanding_responses: RwLock<StdHashMap<Uuid, oneshot::Sender<CommandResponse>>>,
|
||||
}
|
||||
|
||||
impl CommandManagementService {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
registered_commands: HashMap::new(),
|
||||
outstanding_responses: RwLock::new(StdHashMap::new()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,26 +56,26 @@ impl CommandManagementService {
|
||||
.map(|registration| registration.clone().into())
|
||||
}
|
||||
|
||||
pub async fn register_command(
|
||||
pub fn register_command(
|
||||
&self,
|
||||
command: CommandDefinitionRequest,
|
||||
) -> anyhow::Result<mpsc::Receiver<Option<(Command, oneshot::Sender<CommandResponse>)>>> {
|
||||
let (tx, rx) = mpsc::channel(1);
|
||||
|
||||
let registered_commands = self.registered_commands.pin_owned();
|
||||
if let Some(previous) = registered_commands.insert(
|
||||
command.name.clone(),
|
||||
uuid: Uuid,
|
||||
command: CommandDefinition,
|
||||
tx: mpsc::Sender<ResponseMessage>,
|
||||
) -> anyhow::Result<CommandHandle> {
|
||||
let registered_commands = self.registered_commands.pin();
|
||||
// We don't care about the previously registered command
|
||||
let name = command.name.clone();
|
||||
let _ = registered_commands.insert(
|
||||
name.clone(),
|
||||
RegisteredCommand {
|
||||
name: command.name.clone(),
|
||||
response_uuid: uuid,
|
||||
name: name.clone(),
|
||||
definition: command,
|
||||
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(
|
||||
@@ -80,8 +84,6 @@ impl CommandManagementService {
|
||||
parameters: serde_json::Map<String, serde_json::Value>,
|
||||
) -> Result<String, CmdError> {
|
||||
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 registered_commands = self.registered_commands.pin();
|
||||
@@ -100,27 +102,21 @@ impl CommandManagementService {
|
||||
let Some(param_value) = parameters.get(¶meter.name) else {
|
||||
return Err(MisingParameter(parameter.name.clone()));
|
||||
};
|
||||
let Some(param_value) = (match parameter.data_type() {
|
||||
TelemetryDataType::Float32 => {
|
||||
param_value.as_f64().map(|v| Value::Float32(v as f32))
|
||||
}
|
||||
TelemetryDataType::Float64 => param_value.as_f64().map(Value::Float64),
|
||||
TelemetryDataType::Boolean => param_value.as_bool().map(Value::Boolean),
|
||||
let Some(param_value) = (match parameter.data_type {
|
||||
DataType::Float32 => param_value.as_f64().map(|v| DataValue::Float32(v as f32)),
|
||||
DataType::Float64 => param_value.as_f64().map(DataValue::Float64),
|
||||
DataType::Boolean => param_value.as_bool().map(DataValue::Boolean),
|
||||
}) else {
|
||||
return Err(WrongParameterType {
|
||||
name: parameter.name.clone(),
|
||||
expected_type: parameter.data_type(),
|
||||
expected_type: parameter.data_type,
|
||||
});
|
||||
};
|
||||
result_parameters.insert(
|
||||
parameter.name.clone(),
|
||||
TelemetryValue {
|
||||
value: Some(param_value),
|
||||
},
|
||||
);
|
||||
result_parameters.insert(parameter.name.clone(), param_value);
|
||||
}
|
||||
|
||||
// Clone & Drop lets us use a standard pin instead of an owned pin
|
||||
let response_uuid = registration.response_uuid;
|
||||
let tx = registration.tx.clone();
|
||||
drop(registered_commands);
|
||||
|
||||
@@ -128,23 +124,27 @@ impl CommandManagementService {
|
||||
return Err(NoCommandReceiver);
|
||||
}
|
||||
|
||||
let uuid = Uuid::random();
|
||||
let uuid = Uuid::new_v4();
|
||||
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
|
||||
.send(Some((
|
||||
Command {
|
||||
uuid: Some(uuid),
|
||||
timestamp: Some(Timestamp {
|
||||
secs: offset_from_unix_epoch.num_seconds(),
|
||||
nanos: offset_from_unix_epoch.subsec_nanos(),
|
||||
}),
|
||||
.send(ResponseMessage {
|
||||
uuid,
|
||||
response: Some(response_uuid),
|
||||
payload: Command {
|
||||
timestamp,
|
||||
parameters: result_parameters,
|
||||
},
|
||||
response_tx,
|
||||
)))
|
||||
}
|
||||
.into(),
|
||||
})
|
||||
.await
|
||||
{
|
||||
error!("Failed to Send Command: {e}");
|
||||
error!("Failed to Send Command {e}");
|
||||
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 serde::Deserialize;
|
||||
use std::sync::Arc;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct CreateParam {
|
||||
@@ -13,7 +14,7 @@ struct CreateParam {
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct IdParam {
|
||||
id: String,
|
||||
id: Uuid,
|
||||
}
|
||||
|
||||
#[post("/panel")]
|
||||
@@ -22,7 +23,7 @@ pub(super) async fn new(
|
||||
data: web::Json<CreateParam>,
|
||||
) -> Result<impl Responder, HttpServerResultError> {
|
||||
let uuid = panels.create(&data.name, &data.data).await?;
|
||||
Ok(web::Json(uuid.value))
|
||||
Ok(web::Json(uuid))
|
||||
}
|
||||
|
||||
#[get("/panel")]
|
||||
@@ -38,12 +39,10 @@ pub(super) async fn get_one(
|
||||
panels: web::Data<Arc<PanelService>>,
|
||||
path: web::Path<IdParam>,
|
||||
) -> Result<impl Responder, HttpServerResultError> {
|
||||
let result = panels.read(path.id.clone().into()).await?;
|
||||
let result = panels.read(path.id).await?;
|
||||
match result {
|
||||
Some(result) => Ok(web::Json(result)),
|
||||
None => Err(HttpServerResultError::PanelUuidNotFound {
|
||||
uuid: path.id.clone(),
|
||||
}),
|
||||
None => Err(HttpServerResultError::PanelUuidNotFound { uuid: path.id }),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,7 +52,7 @@ pub(super) async fn set(
|
||||
path: web::Path<IdParam>,
|
||||
data: web::Json<PanelUpdate>,
|
||||
) -> Result<impl Responder, HttpServerResultError> {
|
||||
panels.update(path.id.clone().into(), data.0).await?;
|
||||
panels.update(path.id, data.0).await?;
|
||||
Ok(web::Json(()))
|
||||
}
|
||||
|
||||
@@ -62,6 +61,6 @@ pub(super) async fn delete(
|
||||
panels: web::Data<Arc<PanelService>>,
|
||||
path: web::Path<IdParam>,
|
||||
) -> Result<impl Responder, HttpServerResultError> {
|
||||
panels.delete(path.id.clone().into()).await?;
|
||||
panels.delete(path.id).await?;
|
||||
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 actix_ws::{AggregatedMessage, ProtocolError, Session};
|
||||
use anyhow::bail;
|
||||
@@ -10,18 +12,26 @@ use uuid::Uuid;
|
||||
pub(super) struct BackendConnection {
|
||||
session: Session,
|
||||
tlm_management: Arc<TelemetryManagementService>,
|
||||
cmd_management: Arc<CommandManagementService>,
|
||||
tx: Sender<ResponseMessage>,
|
||||
commands: Vec<CommandHandle>,
|
||||
pub rx: Receiver<ResponseMessage>,
|
||||
pub should_close: bool,
|
||||
}
|
||||
|
||||
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);
|
||||
Self {
|
||||
session,
|
||||
tlm_management,
|
||||
cmd_management,
|
||||
tx,
|
||||
commands: vec![],
|
||||
rx,
|
||||
should_close: false,
|
||||
}
|
||||
@@ -41,6 +51,21 @@ impl BackendConnection {
|
||||
RequestMessagePayload::TelemetryEntry(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(())
|
||||
}
|
||||
@@ -78,6 +103,15 @@ impl BackendConnection {
|
||||
|
||||
pub async fn cleanup(mut self) {
|
||||
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;
|
||||
|
||||
use crate::command::service::CommandManagementService;
|
||||
use crate::http::backend::connection::BackendConnection;
|
||||
use crate::telemetry::management_service::TelemetryManagementService;
|
||||
use actix_web::{rt, web, HttpRequest, HttpResponse};
|
||||
@@ -14,6 +15,7 @@ async fn backend_connect(
|
||||
stream: web::Payload,
|
||||
cancel_token: web::Data<CancellationToken>,
|
||||
telemetry_management_service: web::Data<Arc<TelemetryManagementService>>,
|
||||
command_management_service: web::Data<Arc<CommandManagementService>>,
|
||||
) -> Result<HttpResponse, actix_web::Error> {
|
||||
trace!("backend_connect");
|
||||
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 tlm_management = telemetry_management_service.get_ref().clone();
|
||||
let cmd_management = command_management_service.get_ref().clone();
|
||||
|
||||
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 {
|
||||
let result = select! {
|
||||
_ = cancel_token.cancelled() => {
|
||||
|
||||
@@ -20,7 +20,7 @@ pub enum HttpServerResultError {
|
||||
#[error("Internal Error")]
|
||||
InternalError(#[from] anyhow::Error),
|
||||
#[error("Panel Uuid Not Found: {uuid}")]
|
||||
PanelUuidNotFound { uuid: String },
|
||||
PanelUuidNotFound { uuid: Uuid },
|
||||
#[error(transparent)]
|
||||
Command(#[from] crate::command::error::Error),
|
||||
}
|
||||
|
||||
@@ -1,14 +1,8 @@
|
||||
mod command;
|
||||
mod grpc;
|
||||
mod http;
|
||||
mod panels;
|
||||
mod serialization;
|
||||
mod telemetry;
|
||||
mod uuid;
|
||||
|
||||
pub mod core {
|
||||
tonic::include_proto!("core");
|
||||
}
|
||||
|
||||
use crate::command::service::CommandManagementService;
|
||||
use crate::panels::PanelService;
|
||||
@@ -53,14 +47,11 @@ pub async fn setup() -> anyhow::Result<()> {
|
||||
|
||||
let cmd = Arc::new(CommandManagementService::new());
|
||||
|
||||
let grpc_server = grpc::setup(cancellation_token.clone(), cmd.clone())?;
|
||||
|
||||
let panel_service = PanelService::new(sqlite.clone());
|
||||
|
||||
let result = http::setup(cancellation_token.clone(), tlm.clone(), panel_service, cmd).await;
|
||||
cancellation_token.cancel();
|
||||
result?; // result is dropped
|
||||
grpc_server.await?; //grpc server is dropped
|
||||
drop(cancellation_token); // All cancellation tokens are now dropped
|
||||
|
||||
sqlite.close().await;
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
pub mod panel;
|
||||
|
||||
use crate::core::Uuid;
|
||||
use crate::panels::panel::{PanelRequired, PanelUpdate};
|
||||
use panel::Panel;
|
||||
use sqlx::SqlitePool;
|
||||
use uuid::Uuid;
|
||||
|
||||
pub struct PanelService {
|
||||
pool: SqlitePool,
|
||||
@@ -15,7 +15,8 @@ impl PanelService {
|
||||
}
|
||||
|
||||
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?;
|
||||
|
||||
@@ -24,7 +25,7 @@ impl PanelService {
|
||||
INSERT INTO PANELS (id, name, data, deleted)
|
||||
VALUES ($1, $2, $3, FALSE);
|
||||
"#,
|
||||
id.value,
|
||||
id_string,
|
||||
name,
|
||||
data
|
||||
)
|
||||
@@ -65,7 +66,7 @@ impl PanelService {
|
||||
WHERE id = $1 AND deleted = FALSE
|
||||
"#,
|
||||
)
|
||||
.bind(id.value)
|
||||
.bind(id.to_string())
|
||||
.fetch_optional(&mut *transaction)
|
||||
.await?;
|
||||
|
||||
@@ -75,6 +76,7 @@ impl PanelService {
|
||||
}
|
||||
|
||||
pub async fn update(&self, id: Uuid, data: PanelUpdate) -> anyhow::Result<()> {
|
||||
let id = id.to_string();
|
||||
let mut transaction = self.pool.begin().await?;
|
||||
|
||||
if let Some(name) = data.name {
|
||||
@@ -84,7 +86,7 @@ impl PanelService {
|
||||
SET name = $2
|
||||
WHERE id = $1;
|
||||
"#,
|
||||
id.value,
|
||||
id,
|
||||
name
|
||||
)
|
||||
.execute(&mut *transaction)
|
||||
@@ -97,7 +99,7 @@ impl PanelService {
|
||||
SET data = $2
|
||||
WHERE id = $1;
|
||||
"#,
|
||||
id.value,
|
||||
id,
|
||||
data
|
||||
)
|
||||
.execute(&mut *transaction)
|
||||
@@ -110,6 +112,7 @@ impl PanelService {
|
||||
}
|
||||
|
||||
pub async fn delete(&self, id: Uuid) -> anyhow::Result<()> {
|
||||
let id = id.to_string();
|
||||
let mut transaction = self.pool.begin().await?;
|
||||
|
||||
let _ = sqlx::query!(
|
||||
@@ -118,7 +121,7 @@ impl PanelService {
|
||||
SET deleted = TRUE
|
||||
WHERE id = $1;
|
||||
"#,
|
||||
id.value,
|
||||
id,
|
||||
)
|
||||
.execute(&mut *transaction)
|
||||
.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_item;
|
||||
pub mod data_type;
|
||||
pub mod definition;
|
||||
pub mod history;
|
||||
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