uses a proc-macro to automate command definitions

This commit is contained in:
2025-12-31 00:23:30 -05:00
parent 6fdbb868b7
commit 0e28b0416a
26 changed files with 757 additions and 177 deletions

211
Cargo.lock generated
View File

@@ -65,7 +65,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e01ed3140b2f8d422c68afa1ed2e85d996ea619c988ac834d255db32138655cb" checksum = "e01ed3140b2f8d422c68afa1ed2e85d996ea619c988ac834d255db32138655cb"
dependencies = [ dependencies = [
"quote", "quote",
"syn", "syn 2.0.112",
] ]
[[package]] [[package]]
@@ -183,7 +183,7 @@ dependencies = [
"actix-router", "actix-router",
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn", "syn 2.0.112",
] ]
[[package]] [[package]]
@@ -305,6 +305,8 @@ checksum = "a23eb6b1614318a8071c9b2521f36b424b2c83db5eb3a0fead4a6c0809af6e61"
name = "api" name = "api"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"api-core",
"api-proc-macro",
"chrono", "chrono",
"derive_more", "derive_more",
"futures-util", "futures-util",
@@ -318,6 +320,28 @@ dependencies = [
"uuid", "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]] [[package]]
name = "atoi" name = "atoi"
version = "2.0.0" version = "2.0.0"
@@ -602,7 +626,7 @@ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"rustc_version", "rustc_version",
"syn", "syn 2.0.112",
"unicode-xid", "unicode-xid",
] ]
@@ -626,7 +650,7 @@ checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn", "syn 2.0.112",
] ]
[[package]] [[package]]
@@ -807,7 +831,7 @@ checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn", "syn 2.0.112",
] ]
[[package]] [[package]]
@@ -872,6 +896,12 @@ dependencies = [
"windows-targets 0.52.6", "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]] [[package]]
name = "h2" name = "h2"
version = "0.3.27" version = "0.3.27"
@@ -902,13 +932,19 @@ dependencies = [
"foldhash", "foldhash",
] ]
[[package]]
name = "hashbrown"
version = "0.16.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
[[package]] [[package]]
name = "hashlink" name = "hashlink"
version = "0.10.0" version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7382cf6263419f2d8df38c55d7da83da5c18aef87fc7a7fc1fb1e344edfe14c1" checksum = "7382cf6263419f2d8df38c55d7da83da5c18aef87fc7a7fc1fb1e344edfe14c1"
dependencies = [ dependencies = [
"hashbrown", "hashbrown 0.15.0",
] ]
[[package]] [[package]]
@@ -1123,12 +1159,12 @@ checksum = "aae21c3177a27788957044151cc2800043d127acaa460a47ebb9b84dfa2c6aa0"
[[package]] [[package]]
name = "indexmap" name = "indexmap"
version = "2.6.0" version = "2.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "707907fe3c25f5424cce2cb7e1cbcafee6bdbe735ca90ef77c29e84591e5b9da" checksum = "0ad4bb2b565bca0645f4d68c5c9af97fba094e9791da685bf83cb5f3ce74acf2"
dependencies = [ dependencies = [
"equivalent", "equivalent",
"hashbrown", "hashbrown 0.16.1",
] ]
[[package]] [[package]]
@@ -1164,7 +1200,7 @@ checksum = "b787bebb543f8969132630c51fd0afab173a86c6abae56ff3b9e5e3e3f9f6e58"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn", "syn 2.0.112",
] ]
[[package]] [[package]]
@@ -1526,6 +1562,30 @@ dependencies = [
"zerocopy 0.7.35", "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]] [[package]]
name = "proc-macro2" name = "proc-macro2"
version = "1.0.104" version = "1.0.104"
@@ -1831,7 +1891,7 @@ checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn", "syn 2.0.112",
] ]
[[package]] [[package]]
@@ -1847,6 +1907,15 @@ dependencies = [
"zmij", "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]] [[package]]
name = "serde_urlencoded" name = "serde_urlencoded"
version = "0.7.1" version = "0.7.1"
@@ -2043,7 +2112,7 @@ dependencies = [
"futures-intrusive", "futures-intrusive",
"futures-io", "futures-io",
"futures-util", "futures-util",
"hashbrown", "hashbrown 0.15.0",
"hashlink", "hashlink",
"indexmap", "indexmap",
"log", "log",
@@ -2073,7 +2142,7 @@ dependencies = [
"quote", "quote",
"sqlx-core", "sqlx-core",
"sqlx-macros-core", "sqlx-macros-core",
"syn", "syn 2.0.112",
] ]
[[package]] [[package]]
@@ -2096,7 +2165,7 @@ dependencies = [
"sqlx-mysql", "sqlx-mysql",
"sqlx-postgres", "sqlx-postgres",
"sqlx-sqlite", "sqlx-sqlite",
"syn", "syn 2.0.112",
"tokio", "tokio",
"url", "url",
] ]
@@ -2227,6 +2296,16 @@ version = "2.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" 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]] [[package]]
name = "syn" name = "syn"
version = "2.0.112" version = "2.0.112"
@@ -2246,7 +2325,22 @@ checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "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]] [[package]]
@@ -2266,7 +2360,7 @@ checksum = "3ff15c8ecd7de3849db632e14d18d2571fa09dfc5ed93479bc4485c7a517c913"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn", "syn 2.0.112",
] ]
[[package]] [[package]]
@@ -2350,7 +2444,7 @@ checksum = "af407857209536a95c8e56f8231ef2c2e2aff839b22e07a1ffcbc617e9db9fa5"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn", "syn 2.0.112",
] ]
[[package]] [[package]]
@@ -2403,6 +2497,45 @@ dependencies = [
"tokio", "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]] [[package]]
name = "tracing" name = "tracing"
version = "0.1.40" version = "0.1.40"
@@ -2423,7 +2556,7 @@ checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn", "syn 2.0.112",
] ]
[[package]] [[package]]
@@ -2435,6 +2568,21 @@ dependencies = [
"once_cell", "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]] [[package]]
name = "tungstenite" name = "tungstenite"
version = "0.28.0" version = "0.28.0"
@@ -2612,7 +2760,7 @@ dependencies = [
"bumpalo", "bumpalo",
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn", "syn 2.0.112",
"wasm-bindgen-shared", "wasm-bindgen-shared",
] ]
@@ -2635,6 +2783,15 @@ dependencies = [
"wasite", "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]] [[package]]
name = "windows-core" name = "windows-core"
version = "0.52.0" version = "0.52.0"
@@ -2872,6 +3029,12 @@ version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650"
[[package]]
name = "winnow"
version = "0.7.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a5364e9d77fcdeeaa6062ced926ee3381faa2ee02d3eb83a5c27a8825540829"
[[package]] [[package]]
name = "wit-bindgen-rt" name = "wit-bindgen-rt"
version = "0.33.0" version = "0.33.0"
@@ -2906,7 +3069,7 @@ checksum = "b659052874eb698efe5b9e8cf382204678a0086ebf46982b79d6ca3182927e5d"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn", "syn 2.0.112",
"synstructure", "synstructure",
] ]
@@ -2937,7 +3100,7 @@ checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn", "syn 2.0.112",
] ]
[[package]] [[package]]
@@ -2948,7 +3111,7 @@ checksum = "76331675d372f91bf8d17e13afbd5fe639200b73d01f0fc748bb059f9cca2db7"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn", "syn 2.0.112",
] ]
[[package]] [[package]]
@@ -2968,7 +3131,7 @@ checksum = "d71e5d6e06ab090c67b5e44993ec16b72dcbaabc526db883a360057678b48502"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn", "syn 2.0.112",
"synstructure", "synstructure",
] ]
@@ -3008,7 +3171,7 @@ checksum = "eadce39539ca5cb3985590102671f2567e659fca9666581ad3411d59207951f3"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn", "syn 2.0.112",
] ]
[[package]] [[package]]

View File

@@ -1,5 +1,5 @@
[workspace] [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" resolver = "2"
[workspace.dependencies] [workspace.dependencies]
@@ -14,13 +14,17 @@ futures-util = "0.3.31"
log = "0.4.29" log = "0.4.29"
num-traits = "0.2.19" num-traits = "0.2.19"
papaya = "0.2.3" papaya = "0.2.3"
proc-macro-error = "1.0.4"
quote = "1.0.42"
serde = { version = "1.0.228" } serde = { version = "1.0.228" }
serde_json = "1.0.148" serde_json = "1.0.148"
sqlx = "0.8.6" sqlx = "0.8.6"
syn = "2.0.112"
thiserror = "2.0.17" thiserror = "2.0.17"
tokio = { version = "1.48.0" } tokio = { version = "1.48.0" }
tokio-tungstenite = { version = "0.28.0" } tokio-tungstenite = { version = "0.28.0" }
tokio-util = "0.7.17" tokio-util = "0.7.17"
trybuild = "1.0.114"
uuid = { version = "1.19.0", features = ["v4"] } uuid = { version = "1.19.0", features = ["v4"] }
[profile.dev.package.sqlx-macros] [profile.dev.package.sqlx-macros]

12
api-core/Cargo.toml Normal file
View File

@@ -0,0 +1,12 @@
[package]
name = "api-core"
edition = "2021"
version = "0.1.0"
authors = ["Sergey <me@sergeysav.com>"]
[dependencies]
chrono = { workspace = true, features = ["serde"] }
derive_more = { workspace = true, features = ["try_into"] }
serde = { workspace = true, features = ["derive"] }
thiserror = { workspace = true }

47
api-core/src/command.rs Normal file
View File

@@ -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<CommandParameterDefinition>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CommandHeader {
pub timestamp: DateTime<Utc>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Command {
#[serde(flatten)]
pub header: CommandHeader,
pub parameters: HashMap<String, DataValue>,
}
#[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<Self, IntoCommandDefinitionError>;
}

24
api-core/src/data_type.rs Normal file
View File

@@ -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);

View File

@@ -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),
}

3
api-core/src/lib.rs Normal file
View File

@@ -0,0 +1,3 @@
pub mod command;
pub mod data_type;
pub mod data_value;

19
api-proc-macro/Cargo.toml Normal file
View File

@@ -0,0 +1,19 @@
[package]
name = "api-proc-macro"
edition = "2021"
version = "0.1.0"
authors = ["Sergey <me@sergeysav.com>"]
[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" }

View File

@@ -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<Self, api::messages::command::IntoCommandDefinitionError> {
#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<api::data_value::DataValue>
));
}
}
generics
}

11
api-proc-macro/src/lib.rs Normal file
View File

@@ -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)
}

View File

@@ -0,0 +1,10 @@
use api_proc_macro::IntoCommandDefinition;
#[derive(IntoCommandDefinition)]
enum TestEnum {
Variant
}
fn main() {
}

View File

@@ -0,0 +1,5 @@
error: IntoCommandDefinition not supported for enum
--> tests/into_command_definition/enum_fails.rs:4:1
|
4 | enum TestEnum {
| ^^^^

View File

@@ -0,0 +1,12 @@
use api_proc_macro::IntoCommandDefinition;
#[derive(IntoCommandDefinition)]
#[repr(C)]
union TestUnion {
f1: u32,
f2: f32,
}
fn main() {
}

View File

@@ -0,0 +1,5 @@
error: IntoCommandDefinition not supported for union
--> tests/into_command_definition/union_fails.rs:5:1
|
5 | union TestUnion {
| ^^^^^

View File

@@ -0,0 +1,8 @@
use api_proc_macro::IntoCommandDefinition;
#[derive(IntoCommandDefinition)]
struct TestUnnamedStruct(f32, f64, bool);
fn main() {
}

View File

@@ -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);
| ^^^^^^^^^^^^^^^^

View File

@@ -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<T> {
#[allow(unused)]
a: T,
}
let command_definition = TestStruct::<f32>::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::<f32>::parse(Command {
header: CommandHeader {
timestamp: Default::default(),
},
parameters,
})
.unwrap();
assert_eq!(result.a, 1.0f32);
let command_definition = TestStruct::<f64>::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::<f64>::parse(Command {
header: CommandHeader {
timestamp: Default::default(),
},
parameters,
})
.unwrap();
assert_eq!(result.a, 2.0f64);
let command_definition = TestStruct::<bool>::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::<bool>::parse(Command {
header: CommandHeader {
timestamp: Default::default(),
},
parameters,
})
.unwrap();
assert_eq!(result.a, true);
}

View File

@@ -6,14 +6,16 @@ version = "0.1.0"
authors = ["Sergey <me@sergeysav.com>"] authors = ["Sergey <me@sergeysav.com>"]
[dependencies] [dependencies]
log = { workspace = true } api-core = { path = "../api-core" }
thiserror = { workspace = true } api-proc-macro = { path = "../api-proc-macro" }
serde = { workspace = true, features = ["derive"] }
derive_more = { workspace = true, features = ["from", "try_into"] }
uuid = { workspace = true, features = ["serde"] }
chrono = { workspace = true, features = ["serde"] } 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 = { workspace = true, features = ["rt", "macros", "time"] }
tokio-tungstenite = { workspace = true, features = ["rustls-tls-native-roots"] } tokio-tungstenite = { workspace = true, features = ["rustls-tls-native-roots"] }
tokio-util = { workspace = true } tokio-util = { workspace = true }
futures-util = { workspace = true } uuid = { workspace = true, features = ["serde"] }
serde_json = { workspace = true }

73
api/src/client/command.rs Normal file
View File

@@ -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<C: IntoCommandDefinition, F, E: Display>(
client: Arc<Client>,
command_name: String,
mut callback: F,
) -> CommandHandle
where
F: FnMut(CommandHeader, C) -> Result<String, E> + 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();
}
}

View File

@@ -1,3 +1,4 @@
pub mod command;
mod context; mod context;
pub mod error; pub mod error;
pub mod telemetry; pub mod telemetry;

View File

@@ -1,8 +1 @@
use serde::{Deserialize, Serialize}; pub use api_core::data_type::*;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum DataType {
Float32,
Float64,
Boolean,
}

View File

@@ -1,9 +1 @@
use derive_more::TryInto; pub use api_core::data_value::*;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, Serialize, Deserialize, TryInto)]
pub enum DataValue {
Float32(f32),
Float64(f64),
Boolean(bool),
}

View File

@@ -2,3 +2,7 @@ pub mod client;
pub mod data_type; pub mod data_type;
pub mod data_value; pub mod data_value;
pub mod messages; pub mod messages;
pub mod macros {
pub use api_proc_macro::IntoCommandDefinition;
}

View File

@@ -1,33 +1,13 @@
use crate::data_type::DataType;
use crate::data_value::DataValue;
use crate::messages::RegisterCallback; use crate::messages::RegisterCallback;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::collections::HashMap;
#[derive(Debug, Clone, Serialize, Deserialize)] pub use api_core::command::*;
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 { impl RegisterCallback for CommandDefinition {
type Callback = Command; type Callback = Command;
type Response = CommandResponse; 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)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CommandResponse { pub struct CommandResponse {
pub success: bool, pub success: bool,

View File

@@ -1,92 +1,12 @@
use anyhow::anyhow; use api::client::command::Commanding;
use api::client::Client; use api::client::Client;
use api::data_type::DataType; use api::macros::IntoCommandDefinition;
use api::messages::command::{ use api::messages::command::CommandHeader;
Command, CommandDefinition, CommandParameterDefinition, CommandResponse,
};
use log::info; use log::info;
use std::error::Error; use std::error::Error;
use std::sync::Arc; use std::sync::Arc;
use tokio_util::sync::CancellationToken; use tokio_util::sync::CancellationToken;
fn handle_command(command: Command) -> anyhow::Result<String> {
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<Client>,
command_definition: CommandDefinition,
mut callback: impl FnMut(Command) -> anyhow::Result<String> + Send + 'static,
) -> anyhow::Result<Self> {
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] #[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> { async fn main() -> Result<(), Box<dyn Error>> {
env_logger::init(); env_logger::init();
@@ -102,28 +22,8 @@ async fn main() -> Result<(), Box<dyn Error>> {
let client = Arc::new(Client::connect("ws://[::1]:8080/backend")?); let client = Arc::new(Client::connect("ws://[::1]:8080/backend")?);
let handle = CommandHandle::register( let handle =
client, Commanding::register_handler(client, "simple_command/a".to_string(), handle_command);
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?;
cancellation_token.cancelled().await; cancellation_token.cancelled().await;
@@ -131,3 +31,21 @@ async fn main() -> Result<(), Box<dyn Error>> {
Ok(()) Ok(())
} }
#[derive(IntoCommandDefinition)]
struct SimpleCommandA {
a: f32,
b: f64,
c: bool,
}
fn handle_command(header: CommandHeader, command: SimpleCommandA) -> anyhow::Result<String> {
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}"
))
}

View File

@@ -7,7 +7,7 @@ use crate::command::error::Error::{
use anyhow::bail; use anyhow::bail;
use api::data_type::DataType; use api::data_type::DataType;
use api::data_value::DataValue; use api::data_value::DataValue;
use api::messages::command::{Command, CommandDefinition, CommandResponse}; use api::messages::command::{Command, CommandDefinition, CommandHeader, CommandResponse};
use api::messages::ResponseMessage; use api::messages::ResponseMessage;
use chrono::Utc; use chrono::Utc;
use log::error; use log::error;
@@ -137,7 +137,7 @@ impl CommandManagementService {
uuid, uuid,
response: Some(response_uuid), response: Some(response_uuid),
payload: Command { payload: Command {
timestamp, header: CommandHeader { timestamp },
parameters: result_parameters, parameters: result_parameters,
} }
.into(), .into(),