diff --git a/Cargo.lock b/Cargo.lock index 99b6f8b..c40ed3d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -65,7 +65,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e01ed3140b2f8d422c68afa1ed2e85d996ea619c988ac834d255db32138655cb" dependencies = [ "quote", - "syn", + "syn 2.0.112", ] [[package]] @@ -183,7 +183,7 @@ dependencies = [ "actix-router", "proc-macro2", "quote", - "syn", + "syn 2.0.112", ] [[package]] @@ -305,6 +305,8 @@ checksum = "a23eb6b1614318a8071c9b2521f36b424b2c83db5eb3a0fead4a6c0809af6e61" name = "api" version = "0.1.0" dependencies = [ + "api-core", + "api-proc-macro", "chrono", "derive_more", "futures-util", @@ -318,6 +320,28 @@ dependencies = [ "uuid", ] +[[package]] +name = "api-core" +version = "0.1.0" +dependencies = [ + "chrono", + "derive_more", + "serde", + "thiserror", +] + +[[package]] +name = "api-proc-macro" +version = "0.1.0" +dependencies = [ + "api", + "api-core", + "proc-macro-error", + "quote", + "syn 2.0.112", + "trybuild", +] + [[package]] name = "atoi" version = "2.0.0" @@ -602,7 +626,7 @@ dependencies = [ "proc-macro2", "quote", "rustc_version", - "syn", + "syn 2.0.112", "unicode-xid", ] @@ -626,7 +650,7 @@ checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.112", ] [[package]] @@ -807,7 +831,7 @@ checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.112", ] [[package]] @@ -872,6 +896,12 @@ dependencies = [ "windows-targets 0.52.6", ] +[[package]] +name = "glob" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280" + [[package]] name = "h2" version = "0.3.27" @@ -902,13 +932,19 @@ dependencies = [ "foldhash", ] +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" + [[package]] name = "hashlink" version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7382cf6263419f2d8df38c55d7da83da5c18aef87fc7a7fc1fb1e344edfe14c1" dependencies = [ - "hashbrown", + "hashbrown 0.15.0", ] [[package]] @@ -1123,12 +1159,12 @@ checksum = "aae21c3177a27788957044151cc2800043d127acaa460a47ebb9b84dfa2c6aa0" [[package]] name = "indexmap" -version = "2.6.0" +version = "2.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "707907fe3c25f5424cce2cb7e1cbcafee6bdbe735ca90ef77c29e84591e5b9da" +checksum = "0ad4bb2b565bca0645f4d68c5c9af97fba094e9791da685bf83cb5f3ce74acf2" dependencies = [ "equivalent", - "hashbrown", + "hashbrown 0.16.1", ] [[package]] @@ -1164,7 +1200,7 @@ checksum = "b787bebb543f8969132630c51fd0afab173a86c6abae56ff3b9e5e3e3f9f6e58" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.112", ] [[package]] @@ -1526,6 +1562,30 @@ dependencies = [ "zerocopy 0.7.35", ] +[[package]] +name = "proc-macro-error" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" +dependencies = [ + "proc-macro-error-attr", + "proc-macro2", + "quote", + "syn 1.0.109", + "version_check", +] + +[[package]] +name = "proc-macro-error-attr" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" +dependencies = [ + "proc-macro2", + "quote", + "version_check", +] + [[package]] name = "proc-macro2" version = "1.0.104" @@ -1831,7 +1891,7 @@ checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.112", ] [[package]] @@ -1847,6 +1907,15 @@ dependencies = [ "zmij", ] +[[package]] +name = "serde_spanned" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8bbf91e5a4d6315eee45e704372590b30e260ee83af6639d64557f51b067776" +dependencies = [ + "serde_core", +] + [[package]] name = "serde_urlencoded" version = "0.7.1" @@ -2043,7 +2112,7 @@ dependencies = [ "futures-intrusive", "futures-io", "futures-util", - "hashbrown", + "hashbrown 0.15.0", "hashlink", "indexmap", "log", @@ -2073,7 +2142,7 @@ dependencies = [ "quote", "sqlx-core", "sqlx-macros-core", - "syn", + "syn 2.0.112", ] [[package]] @@ -2096,7 +2165,7 @@ dependencies = [ "sqlx-mysql", "sqlx-postgres", "sqlx-sqlite", - "syn", + "syn 2.0.112", "tokio", "url", ] @@ -2227,6 +2296,16 @@ version = "2.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" +[[package]] +name = "syn" +version = "1.0.109" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" +dependencies = [ + "proc-macro2", + "unicode-ident", +] + [[package]] name = "syn" version = "2.0.112" @@ -2246,7 +2325,22 @@ checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.112", +] + +[[package]] +name = "target-triple" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "591ef38edfb78ca4771ee32cf494cb8771944bee237a9b91fc9c1424ac4b777b" + +[[package]] +name = "termcolor" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" +dependencies = [ + "winapi-util", ] [[package]] @@ -2266,7 +2360,7 @@ checksum = "3ff15c8ecd7de3849db632e14d18d2571fa09dfc5ed93479bc4485c7a517c913" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.112", ] [[package]] @@ -2350,7 +2444,7 @@ checksum = "af407857209536a95c8e56f8231ef2c2e2aff839b22e07a1ffcbc617e9db9fa5" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.112", ] [[package]] @@ -2403,6 +2497,45 @@ dependencies = [ "tokio", ] +[[package]] +name = "toml" +version = "0.9.10+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0825052159284a1a8b4d6c0c86cbc801f2da5afd2b225fa548c72f2e74002f48" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow", +] + +[[package]] +name = "toml_datetime" +version = "0.7.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92e1cfed4a3038bc5a127e35a2d360f145e1f4b971b551a2ba5fd7aedf7e1347" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_parser" +version = "1.0.6+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3198b4b0a8e11f09dd03e133c0280504d0801269e9afa46362ffde1cbeebf44" +dependencies = [ + "winnow", +] + +[[package]] +name = "toml_writer" +version = "1.0.6+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab16f14aed21ee8bfd8ec22513f7287cd4a91aa92e44edfe2c17ddd004e92607" + [[package]] name = "tracing" version = "0.1.40" @@ -2423,7 +2556,7 @@ checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.112", ] [[package]] @@ -2435,6 +2568,21 @@ dependencies = [ "once_cell", ] +[[package]] +name = "trybuild" +version = "1.0.114" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e17e807bff86d2a06b52bca4276746584a78375055b6e45843925ce2802b335" +dependencies = [ + "glob", + "serde", + "serde_derive", + "serde_json", + "target-triple", + "termcolor", + "toml", +] + [[package]] name = "tungstenite" version = "0.28.0" @@ -2612,7 +2760,7 @@ dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn", + "syn 2.0.112", "wasm-bindgen-shared", ] @@ -2635,6 +2783,15 @@ dependencies = [ "wasite", ] +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "windows-core" version = "0.52.0" @@ -2872,6 +3029,12 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" +[[package]] +name = "winnow" +version = "0.7.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a5364e9d77fcdeeaa6062ced926ee3381faa2ee02d3eb83a5c27a8825540829" + [[package]] name = "wit-bindgen-rt" version = "0.33.0" @@ -2906,7 +3069,7 @@ checksum = "b659052874eb698efe5b9e8cf382204678a0086ebf46982b79d6ca3182927e5d" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.112", "synstructure", ] @@ -2937,7 +3100,7 @@ checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.112", ] [[package]] @@ -2948,7 +3111,7 @@ checksum = "76331675d372f91bf8d17e13afbd5fe639200b73d01f0fc748bb059f9cca2db7" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.112", ] [[package]] @@ -2968,7 +3131,7 @@ checksum = "d71e5d6e06ab090c67b5e44993ec16b72dcbaabc526db883a360057678b48502" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.112", "synstructure", ] @@ -3008,7 +3171,7 @@ checksum = "eadce39539ca5cb3985590102671f2567e659fca9666581ad3411d59207951f3" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.112", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 4133001..7516f1c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,5 +1,5 @@ [workspace] -members = ["api", "server", "examples/simple_producer", "examples/simple_command"] +members = ["api", "api-core", "api-proc-macro", "server", "examples/simple_producer", "examples/simple_command"] resolver = "2" [workspace.dependencies] @@ -14,13 +14,17 @@ futures-util = "0.3.31" log = "0.4.29" num-traits = "0.2.19" papaya = "0.2.3" +proc-macro-error = "1.0.4" +quote = "1.0.42" serde = { version = "1.0.228" } serde_json = "1.0.148" sqlx = "0.8.6" +syn = "2.0.112" thiserror = "2.0.17" tokio = { version = "1.48.0" } tokio-tungstenite = { version = "0.28.0" } tokio-util = "0.7.17" +trybuild = "1.0.114" uuid = { version = "1.19.0", features = ["v4"] } [profile.dev.package.sqlx-macros] diff --git a/api-core/Cargo.toml b/api-core/Cargo.toml new file mode 100644 index 0000000..a895fe2 --- /dev/null +++ b/api-core/Cargo.toml @@ -0,0 +1,12 @@ + +[package] +name = "api-core" +edition = "2021" +version = "0.1.0" +authors = ["Sergey "] + +[dependencies] +chrono = { workspace = true, features = ["serde"] } +derive_more = { workspace = true, features = ["try_into"] } +serde = { workspace = true, features = ["derive"] } +thiserror = { workspace = true } diff --git a/api-core/src/command.rs b/api-core/src/command.rs new file mode 100644 index 0000000..b46a1f9 --- /dev/null +++ b/api-core/src/command.rs @@ -0,0 +1,47 @@ +use crate::data_type::DataType; +use crate::data_value::DataValue; +use chrono::{DateTime, Utc}; +use serde::{Deserialize, Serialize}; +use std::collections::HashMap; +use thiserror::Error; + +#[derive(Debug, Clone, PartialEq, Eq, 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, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct CommandHeader { + pub timestamp: DateTime, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Command { + #[serde(flatten)] + pub header: CommandHeader, + pub parameters: HashMap, +} + +#[derive(Debug, Error)] +pub enum IntoCommandDefinitionError { + #[error("Parameter Missing: {0}")] + ParameterMissing(String), + #[error("Mismatched Type for {parameter}. {expected:?} expected")] + MismatchedType { + parameter: String, + expected: DataType, + }, +} + +pub trait IntoCommandDefinition: Sized { + fn create(name: String) -> CommandDefinition; + + fn parse(command: Command) -> Result; +} diff --git a/api-core/src/data_type.rs b/api-core/src/data_type.rs new file mode 100644 index 0000000..3600b09 --- /dev/null +++ b/api-core/src/data_type.rs @@ -0,0 +1,24 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum DataType { + Float32, + Float64, + Boolean, +} + +pub trait ToDataType { + const DATA_TYPE: DataType; +} + +macro_rules! impl_to_data_type { + ( $ty:ty, $value:expr ) => { + impl ToDataType for $ty { + const DATA_TYPE: DataType = $value; + } + }; +} + +impl_to_data_type!(f32, DataType::Float32); +impl_to_data_type!(f64, DataType::Float64); +impl_to_data_type!(bool, DataType::Boolean); diff --git a/api-core/src/data_value.rs b/api-core/src/data_value.rs new file mode 100644 index 0000000..35422a3 --- /dev/null +++ b/api-core/src/data_value.rs @@ -0,0 +1,9 @@ +use derive_more::TryInto; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Copy, Serialize, Deserialize, TryInto)] +pub enum DataValue { + Float32(f32), + Float64(f64), + Boolean(bool), +} diff --git a/api-core/src/lib.rs b/api-core/src/lib.rs new file mode 100644 index 0000000..fdd3dc0 --- /dev/null +++ b/api-core/src/lib.rs @@ -0,0 +1,3 @@ +pub mod command; +pub mod data_type; +pub mod data_value; diff --git a/api-proc-macro/Cargo.toml b/api-proc-macro/Cargo.toml new file mode 100644 index 0000000..c1d1649 --- /dev/null +++ b/api-proc-macro/Cargo.toml @@ -0,0 +1,19 @@ + +[package] +name = "api-proc-macro" +edition = "2021" +version = "0.1.0" +authors = ["Sergey "] + +[lib] +proc-macro = true + +[dependencies] +api-core = { path = "../api-core" } +proc-macro-error = { workspace = true } +quote = { workspace = true } +syn = { workspace = true } + +[dev-dependencies] +trybuild = { workspace = true } +api = { path = "../api" } diff --git a/api-proc-macro/src/into_command_definition.rs b/api-proc-macro/src/into_command_definition.rs new file mode 100644 index 0000000..359ed4c --- /dev/null +++ b/api-proc-macro/src/into_command_definition.rs @@ -0,0 +1,129 @@ +use proc_macro_error::abort; +use quote::{quote, quote_spanned}; +use syn::spanned::Spanned; +use syn::{parse_macro_input, parse_quote, Data, DeriveInput, Fields, GenericParam, Generics}; + +pub fn derive_into_command_definition_impl( + item: proc_macro::TokenStream, +) -> proc_macro::TokenStream { + let DeriveInput { + ident, + data, + generics, + .. + }: DeriveInput = parse_macro_input!(item as DeriveInput); + + let data = match data { + Data::Struct(data) => data, + Data::Enum(data) => abort!( + data.enum_token, + "IntoCommandDefinition not supported for enum" + ), + Data::Union(data) => abort!( + data.union_token, + "IntoCommandDefinition not supported for union" + ), + }; + + let generics = add_trait_bounds(generics); + let (impl_generics, ty_generics, where_clause) = generics.split_for_impl(); + + let num_fields = data.fields.len(); + + let create_param_stream = match &data.fields { + Fields::Named(fields) => { + let field_entries = fields.named.iter().map(|field| { + let name = field.ident.clone().map(|id| id.to_string()); + let field_type = &field.ty; + quote_spanned! { field.span() => + parameters.push(api::messages::command::CommandParameterDefinition { + name: #name.to_string(), + data_type: <#field_type as api::data_type::ToDataType>::DATA_TYPE, + }); + } + }); + quote! { #(#field_entries)* } + } + Fields::Unnamed(fields) => abort!( + fields, + "IntoCommandDefinition not supported for unnamed structs" + ), + Fields::Unit => quote! {}, + }; + let parse_param_stream = match &data.fields { + Fields::Named(fields) => { + let field_entries = fields.named.iter().map(|field| { + let name = &field.ident; + let name_string = field.ident.clone().map(|id| id.to_string()); + let field_type = &field.ty; + quote_spanned! { field.span() => + let #name: #field_type = (*command + .parameters + .get(#name_string) + .ok_or_else(|| api::messages::command::IntoCommandDefinitionError::ParameterMissing(#name_string.to_string()))?) + .try_into() + .map_err(|_| api::messages::command::IntoCommandDefinitionError::MismatchedType { + parameter: #name_string.to_string(), + expected: <#field_type as api::data_type::ToDataType>::DATA_TYPE, + })?; + } + }); + quote! { #(#field_entries)* } + } + Fields::Unnamed(fields) => abort!( + fields, + "IntoCommandDefinition not supported for unnamed structs" + ), + Fields::Unit => quote! {}, + }; + let param_name_stream = match &data.fields { + Fields::Named(fields) => { + let field_entries = fields.named.iter().map(|field| { + let name = &field.ident; + quote_spanned! { field.span() => #name, } + }); + quote! { #(#field_entries)* } + } + Fields::Unnamed(fields) => abort!( + fields, + "IntoCommandDefinition not supported for unnamed structs" + ), + Fields::Unit => quote! {}, + }; + + let result = quote! { + impl #impl_generics api::messages::command::IntoCommandDefinition for #ident #ty_generics #where_clause { + fn create(name: std::string::String) -> api::messages::command::CommandDefinition { + let mut parameters = std::vec::Vec::with_capacity( #num_fields ); + #create_param_stream + api::messages::command::CommandDefinition { + name: name, + parameters: parameters, + } + } + + fn parse(command: api::messages::command::Command) -> core::result::Result { + #parse_param_stream + Ok(Self { + #param_name_stream + }) + } + } + }; + + result.into() +} + +fn add_trait_bounds(mut generics: Generics) -> Generics { + for param in &mut generics.params { + if let GenericParam::Type(ref mut type_param) = *param { + type_param + .bounds + .push(parse_quote!(api::data_type::ToDataType)); + type_param.bounds.push(parse_quote!( + core::convert::TryFrom + )); + } + } + generics +} diff --git a/api-proc-macro/src/lib.rs b/api-proc-macro/src/lib.rs new file mode 100644 index 0000000..2638464 --- /dev/null +++ b/api-proc-macro/src/lib.rs @@ -0,0 +1,11 @@ +extern crate proc_macro; + +use proc_macro_error::proc_macro_error; + +mod into_command_definition; + +#[proc_macro_error] +#[proc_macro_derive(IntoCommandDefinition)] +pub fn derive_into_command_definition(item: proc_macro::TokenStream) -> proc_macro::TokenStream { + into_command_definition::derive_into_command_definition_impl(item) +} diff --git a/api-proc-macro/tests/into_command_definition/enum_fails.rs b/api-proc-macro/tests/into_command_definition/enum_fails.rs new file mode 100644 index 0000000..f04e360 --- /dev/null +++ b/api-proc-macro/tests/into_command_definition/enum_fails.rs @@ -0,0 +1,10 @@ +use api_proc_macro::IntoCommandDefinition; + +#[derive(IntoCommandDefinition)] +enum TestEnum { + Variant +} + +fn main() { + +} diff --git a/api-proc-macro/tests/into_command_definition/enum_fails.stderr b/api-proc-macro/tests/into_command_definition/enum_fails.stderr new file mode 100644 index 0000000..71e487f --- /dev/null +++ b/api-proc-macro/tests/into_command_definition/enum_fails.stderr @@ -0,0 +1,5 @@ +error: IntoCommandDefinition not supported for enum + --> tests/into_command_definition/enum_fails.rs:4:1 + | +4 | enum TestEnum { + | ^^^^ diff --git a/api-proc-macro/tests/into_command_definition/union_fails.rs b/api-proc-macro/tests/into_command_definition/union_fails.rs new file mode 100644 index 0000000..ab785a4 --- /dev/null +++ b/api-proc-macro/tests/into_command_definition/union_fails.rs @@ -0,0 +1,12 @@ +use api_proc_macro::IntoCommandDefinition; + +#[derive(IntoCommandDefinition)] +#[repr(C)] +union TestUnion { + f1: u32, + f2: f32, +} + +fn main() { + +} diff --git a/api-proc-macro/tests/into_command_definition/union_fails.stderr b/api-proc-macro/tests/into_command_definition/union_fails.stderr new file mode 100644 index 0000000..136df2c --- /dev/null +++ b/api-proc-macro/tests/into_command_definition/union_fails.stderr @@ -0,0 +1,5 @@ +error: IntoCommandDefinition not supported for union + --> tests/into_command_definition/union_fails.rs:5:1 + | +5 | union TestUnion { + | ^^^^^ diff --git a/api-proc-macro/tests/into_command_definition/unnamed_struct_fails.rs b/api-proc-macro/tests/into_command_definition/unnamed_struct_fails.rs new file mode 100644 index 0000000..5093ce0 --- /dev/null +++ b/api-proc-macro/tests/into_command_definition/unnamed_struct_fails.rs @@ -0,0 +1,8 @@ +use api_proc_macro::IntoCommandDefinition; + +#[derive(IntoCommandDefinition)] +struct TestUnnamedStruct(f32, f64, bool); + +fn main() { + +} diff --git a/api-proc-macro/tests/into_command_definition/unnamed_struct_fails.stderr b/api-proc-macro/tests/into_command_definition/unnamed_struct_fails.stderr new file mode 100644 index 0000000..6d80049 --- /dev/null +++ b/api-proc-macro/tests/into_command_definition/unnamed_struct_fails.stderr @@ -0,0 +1,5 @@ +error: IntoCommandDefinition not supported for unnamed structs + --> tests/into_command_definition/unnamed_struct_fails.rs:4:25 + | +4 | struct TestUnnamedStruct(f32, f64, bool); + | ^^^^^^^^^^^^^^^^ diff --git a/api-proc-macro/tests/test_derive_macro_into_command_definition.rs b/api-proc-macro/tests/test_derive_macro_into_command_definition.rs new file mode 100644 index 0000000..4be746f --- /dev/null +++ b/api-proc-macro/tests/test_derive_macro_into_command_definition.rs @@ -0,0 +1,151 @@ +use api_core::command::{ + Command, CommandHeader, CommandParameterDefinition, IntoCommandDefinition, +}; +use api_core::data_type::DataType; +use api_core::data_value::DataValue; +use api_proc_macro::IntoCommandDefinition; +use std::collections::HashMap; + +#[test] +fn test_enum_fails() { + let t = trybuild::TestCases::new(); + t.compile_fail("tests/into_command_definition/enum_fails.rs"); +} + +#[test] +fn test_union_fails() { + let t = trybuild::TestCases::new(); + t.compile_fail("tests/into_command_definition/union_fails.rs"); +} + +#[test] +fn test_unnamed_struct_fails() { + let t = trybuild::TestCases::new(); + t.compile_fail("tests/into_command_definition/unnamed_struct_fails.rs"); +} + +#[test] +fn test_basic_command() { + #[derive(IntoCommandDefinition)] + struct TestStruct { + #[allow(unused)] + a: f32, + #[allow(unused)] + b: f64, + #[allow(unused)] + c: bool, + } + + let command_definition = TestStruct::create("Test".to_string()); + + assert_eq!(command_definition.name, "Test"); + assert_eq!(command_definition.parameters.capacity(), 3); + assert_eq!( + command_definition.parameters[0], + CommandParameterDefinition { + name: "a".to_string(), + data_type: DataType::Float32, + } + ); + assert_eq!( + command_definition.parameters[1], + CommandParameterDefinition { + name: "b".to_string(), + data_type: DataType::Float64, + } + ); + assert_eq!( + command_definition.parameters[2], + CommandParameterDefinition { + name: "c".to_string(), + data_type: DataType::Boolean, + } + ); + + let mut parameters = HashMap::new(); + parameters.insert("a".to_string(), DataValue::Float32(1.0)); + parameters.insert("b".to_string(), DataValue::Float64(2.0)); + parameters.insert("c".to_string(), DataValue::Boolean(true)); + let result = TestStruct::parse(Command { + header: CommandHeader { + timestamp: Default::default(), + }, + parameters, + }) + .unwrap(); + assert_eq!(result.a, 1.0f32); + assert_eq!(result.b, 2.0f64); + assert_eq!(result.c, true); +} + +#[test] +fn test_generic_command() { + #[derive(IntoCommandDefinition)] + struct TestStruct { + #[allow(unused)] + a: T, + } + + let command_definition = TestStruct::::create("Test".to_string()); + assert_eq!(command_definition.name, "Test"); + assert_eq!(command_definition.parameters.capacity(), 1); + assert_eq!( + command_definition.parameters[0], + CommandParameterDefinition { + name: "a".to_string(), + data_type: DataType::Float32, + } + ); + let mut parameters = HashMap::new(); + parameters.insert("a".to_string(), DataValue::Float32(1.0)); + let result = TestStruct::::parse(Command { + header: CommandHeader { + timestamp: Default::default(), + }, + parameters, + }) + .unwrap(); + assert_eq!(result.a, 1.0f32); + + let command_definition = TestStruct::::create("Test2".to_string()); + assert_eq!(command_definition.name, "Test2"); + assert_eq!(command_definition.parameters.capacity(), 1); + assert_eq!( + command_definition.parameters[0], + CommandParameterDefinition { + name: "a".to_string(), + data_type: DataType::Float64, + } + ); + let mut parameters = HashMap::new(); + parameters.insert("a".to_string(), DataValue::Float64(2.0)); + let result = TestStruct::::parse(Command { + header: CommandHeader { + timestamp: Default::default(), + }, + parameters, + }) + .unwrap(); + assert_eq!(result.a, 2.0f64); + + let command_definition = TestStruct::::create("Test3".to_string()); + assert_eq!(command_definition.name, "Test3"); + assert_eq!(command_definition.parameters.capacity(), 1); + assert_eq!( + command_definition.parameters[0], + CommandParameterDefinition { + name: "a".to_string(), + data_type: DataType::Boolean, + } + ); + let mut parameters = HashMap::new(); + parameters.insert("a".to_string(), DataValue::Boolean(true)); + let result = TestStruct::::parse(Command { + header: CommandHeader { + timestamp: Default::default(), + }, + parameters, + }) + .unwrap(); + assert_eq!(result.a, true); +} diff --git a/api/Cargo.toml b/api/Cargo.toml index 666a009..1548081 100644 --- a/api/Cargo.toml +++ b/api/Cargo.toml @@ -6,14 +6,16 @@ version = "0.1.0" authors = ["Sergey "] [dependencies] -log = { workspace = true } -thiserror = { workspace = true } -serde = { workspace = true, features = ["derive"] } -derive_more = { workspace = true, features = ["from", "try_into"] } -uuid = { workspace = true, features = ["serde"] } +api-core = { path = "../api-core" } +api-proc-macro = { path = "../api-proc-macro" } chrono = { workspace = true, features = ["serde"] } +derive_more = { workspace = true, features = ["from", "try_into"] } +futures-util = { workspace = true } +log = { workspace = true } +serde = { workspace = true, features = ["derive"] } +serde_json = { workspace = true } +thiserror = { workspace = true } tokio = { workspace = true, features = ["rt", "macros", "time"] } tokio-tungstenite = { workspace = true, features = ["rustls-tls-native-roots"] } tokio-util = { workspace = true } -futures-util = { workspace = true } -serde_json = { workspace = true } +uuid = { workspace = true, features = ["serde"] } diff --git a/api/src/client/command.rs b/api/src/client/command.rs new file mode 100644 index 0000000..5d2cfa0 --- /dev/null +++ b/api/src/client/command.rs @@ -0,0 +1,73 @@ +use crate::client::Client; +use crate::messages::command::CommandResponse; +use api_core::command::{CommandHeader, IntoCommandDefinition}; +use std::fmt::Display; +use std::sync::Arc; +use tokio_util::sync::CancellationToken; + +pub struct Commanding; + +impl Commanding { + pub fn register_handler( + client: Arc, + command_name: String, + mut callback: F, + ) -> CommandHandle + where + F: FnMut(CommandHeader, C) -> Result + Send + 'static, + { + let cancellation_token = CancellationToken::new(); + let result = CommandHandle { + cancellation_token: cancellation_token.clone(), + }; + + let command_definition = C::create(command_name); + + tokio::spawn(async move { + while !cancellation_token.is_cancelled() { + // This would only fail if the sender closed while trying to insert data + // It would wait until space is made + let Ok(mut rx) = client + .register_callback_channel(command_definition.clone()) + .await + else { + continue; + }; + + while let Some((cmd, responder)) = rx.recv().await { + let header = cmd.header.clone(); + let response = match C::parse(cmd) { + Ok(cmd) => match callback(header, cmd) { + Ok(response) => CommandResponse { + success: true, + response, + }, + Err(err) => CommandResponse { + success: false, + response: err.to_string(), + }, + }, + Err(err) => CommandResponse { + success: false, + response: err.to_string(), + }, + }; + // This should only err if we had an error elsewhere + let _ = responder.send(response); + } + } + }); + + result + } +} + +pub struct CommandHandle { + cancellation_token: CancellationToken, +} + +impl Drop for CommandHandle { + fn drop(&mut self) { + self.cancellation_token.cancel(); + } +} diff --git a/api/src/client/mod.rs b/api/src/client/mod.rs index ad5f53d..23de189 100644 --- a/api/src/client/mod.rs +++ b/api/src/client/mod.rs @@ -1,3 +1,4 @@ +pub mod command; mod context; pub mod error; pub mod telemetry; diff --git a/api/src/data_type.rs b/api/src/data_type.rs index a9292f3..eaad563 100644 --- a/api/src/data_type.rs +++ b/api/src/data_type.rs @@ -1,8 +1 @@ -use serde::{Deserialize, Serialize}; - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -pub enum DataType { - Float32, - Float64, - Boolean, -} +pub use api_core::data_type::*; diff --git a/api/src/data_value.rs b/api/src/data_value.rs index 35422a3..b147536 100644 --- a/api/src/data_value.rs +++ b/api/src/data_value.rs @@ -1,9 +1 @@ -use derive_more::TryInto; -use serde::{Deserialize, Serialize}; - -#[derive(Debug, Clone, Copy, Serialize, Deserialize, TryInto)] -pub enum DataValue { - Float32(f32), - Float64(f64), - Boolean(bool), -} +pub use api_core::data_value::*; diff --git a/api/src/lib.rs b/api/src/lib.rs index ca58c52..c851964 100644 --- a/api/src/lib.rs +++ b/api/src/lib.rs @@ -2,3 +2,7 @@ pub mod client; pub mod data_type; pub mod data_value; pub mod messages; + +pub mod macros { + pub use api_proc_macro::IntoCommandDefinition; +} diff --git a/api/src/messages/command.rs b/api/src/messages/command.rs index b8c9a81..75b8a1e 100644 --- a/api/src/messages/command.rs +++ b/api/src/messages/command.rs @@ -1,33 +1,13 @@ -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, -} +pub use api_core::command::*; impl RegisterCallback for CommandDefinition { type Callback = Command; type Response = CommandResponse; } -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct Command { - pub timestamp: DateTime, - pub parameters: HashMap, -} - #[derive(Debug, Clone, Serialize, Deserialize)] pub struct CommandResponse { pub success: bool, diff --git a/examples/simple_command/src/main.rs b/examples/simple_command/src/main.rs index 055c611..e4115dd 100644 --- a/examples/simple_command/src/main.rs +++ b/examples/simple_command/src/main.rs @@ -1,92 +1,12 @@ -use anyhow::anyhow; +use api::client::command::Commanding; use api::client::Client; -use api::data_type::DataType; -use api::messages::command::{ - Command, CommandDefinition, CommandParameterDefinition, CommandResponse, -}; +use api::macros::IntoCommandDefinition; +use api::messages::command::CommandHeader; use log::info; use std::error::Error; use std::sync::Arc; use tokio_util::sync::CancellationToken; -fn handle_command(command: Command) -> anyhow::Result { - 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()?; - - info!("Command Received:\n timestamp: {timestamp}\n a: {a}\n b: {b}\n c: {c}"); - - Ok(format!( - "Successfully Received Command! timestamp: {timestamp} a: {a} b: {b} c: {c}" - )) -} - -struct CommandHandle { - cancellation_token: CancellationToken, -} - -impl CommandHandle { - pub async fn register( - client: Arc, - command_definition: CommandDefinition, - mut callback: impl FnMut(Command) -> anyhow::Result + Send + 'static, - ) -> anyhow::Result { - let cancellation_token = CancellationToken::new(); - let result = Self { - cancellation_token: cancellation_token.clone(), - }; - - tokio::spawn(async move { - while !cancellation_token.is_cancelled() { - // This would only fail if the sender closed while trying to insert data - // It would wait until space is made - let Ok(mut rx) = client - .register_callback_channel(command_definition.clone()) - .await - else { - continue; - }; - - while let Some((cmd, responder)) = rx.recv().await { - let response = match callback(cmd) { - Ok(response) => CommandResponse { - success: true, - response, - }, - Err(err) => CommandResponse { - success: false, - response: err.to_string(), - }, - }; - // This should only err if we had an error elsewhere - let _ = responder.send(response); - } - } - }); - - Ok(result) - } -} - -impl Drop for CommandHandle { - fn drop(&mut self) { - self.cancellation_token.cancel(); - } -} - #[tokio::main] async fn main() -> Result<(), Box> { env_logger::init(); @@ -102,28 +22,8 @@ async fn main() -> Result<(), Box> { let client = Arc::new(Client::connect("ws://[::1]:8080/backend")?); - let handle = CommandHandle::register( - client, - CommandDefinition { - name: "simple_command/a".to_string(), - parameters: vec![ - CommandParameterDefinition { - name: "a".to_string(), - data_type: DataType::Float32, - }, - CommandParameterDefinition { - name: "b".to_string(), - data_type: DataType::Float64, - }, - CommandParameterDefinition { - name: "c".to_string(), - data_type: DataType::Boolean, - }, - ], - }, - handle_command, - ) - .await?; + let handle = + Commanding::register_handler(client, "simple_command/a".to_string(), handle_command); cancellation_token.cancelled().await; @@ -131,3 +31,21 @@ async fn main() -> Result<(), Box> { Ok(()) } + +#[derive(IntoCommandDefinition)] +struct SimpleCommandA { + a: f32, + b: f64, + c: bool, +} + +fn handle_command(header: CommandHeader, command: SimpleCommandA) -> anyhow::Result { + let timestamp = header.timestamp; + let SimpleCommandA { a, b, c } = command; + + info!("Command Received:\n timestamp: {timestamp}\n a: {a}\n b: {b}\n c: {c}"); + + Ok(format!( + "Successfully Received Command! timestamp: {timestamp} a: {a} b: {b} c: {c}" + )) +} diff --git a/server/src/command/service.rs b/server/src/command/service.rs index 8aafb11..15a284e 100644 --- a/server/src/command/service.rs +++ b/server/src/command/service.rs @@ -7,7 +7,7 @@ use crate::command::error::Error::{ use anyhow::bail; use api::data_type::DataType; use api::data_value::DataValue; -use api::messages::command::{Command, CommandDefinition, CommandResponse}; +use api::messages::command::{Command, CommandDefinition, CommandHeader, CommandResponse}; use api::messages::ResponseMessage; use chrono::Utc; use log::error; @@ -137,7 +137,7 @@ impl CommandManagementService { uuid, response: Some(response_uuid), payload: Command { - timestamp, + header: CommandHeader { timestamp }, parameters: result_parameters, } .into(),