summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--crates/system_action/action_macros/src/lib.rs53
-rw-r--r--crates/system_action/src/action.rs56
-rw-r--r--crates/system_action/src/action_pool.rs20
-rw-r--r--crates/utils/cfg_file/cfg_file_derive/src/lib.rs29
-rw-r--r--crates/utils/cfg_file/src/config.rs70
-rw-r--r--crates/utils/sha1_hash/src/lib.rs3
6 files changed, 223 insertions, 8 deletions
diff --git a/crates/system_action/action_macros/src/lib.rs b/crates/system_action/action_macros/src/lib.rs
index 4c03b63..e6616b4 100644
--- a/crates/system_action/action_macros/src/lib.rs
+++ b/crates/system_action/action_macros/src/lib.rs
@@ -2,13 +2,56 @@ use proc_macro::TokenStream;
use quote::quote;
use syn::{ItemFn, parse_macro_input};
-/// A procedural macro for generating structs that implement the Action trait
+/// # Macro - Generate Action
///
-/// Usage:
-/// #[action_gen] or #[action_gen(local)]
-/// pub fn my_action(ctx: ActionContext, arg: MyArg) -> Result<MyReturn, TcpTargetError> {
-/// todo!()
+/// When annotating a function with the `#[action_gen]` macro in the following format, it generates boilerplate code for client-server interaction
+///
+/// ```ignore
+/// #[action_gen]
+/// async fn action_name(ctx: ActionContext, argument: YourArgument) -> Result<YourResult, TcpTargetError> {
+/// // Write your client and server logic here
+/// if ctx.is_proc_on_remote() {
+/// // Server logic
+/// }
+/// if ctx.is_proc_on_local() {
+/// // Client logic
+/// }
+/// }
+/// ```
+///
+/// > WARNING:
+/// > For Argument and Result types, the `action_gen` macro only supports types that derive serde's Serialize and Deserialize
+///
+/// ## Generated Code
+///
+/// `action_gen` will generate the following:
+///
+/// 1. Complete implementation of Action<Args, Return>
+/// 2. Process / Register method
+///
+/// ## How to use
+///
+/// You can use your generated method as follows
+///
+/// ```ignore
+/// async fn main() -> Result<(), TcpTargetError> {
+///
+/// // Prepare your argument
+/// let args = YourArgument::default();
+///
+/// // Create a pool and context
+/// let mut pool = ActionPool::new();
+/// let ctx = ActionContext::local();
+///
+/// // Register your action
+/// register_your_action(&mut pool);
+///
+/// // Process your action
+/// proc_your_action(&pool, ctx, args).await?;
+///
+/// Ok(())
/// }
+/// ```
#[proc_macro_attribute]
pub fn action_gen(attr: TokenStream, item: TokenStream) -> TokenStream {
let input_fn = parse_macro_input!(item as ItemFn);
diff --git a/crates/system_action/src/action.rs b/crates/system_action/src/action.rs
index ef1bf11..62425ff 100644
--- a/crates/system_action/src/action.rs
+++ b/crates/system_action/src/action.rs
@@ -5,6 +5,40 @@ use std::sync::Arc;
use tcp_connection::{error::TcpTargetError, instance::ConnectionInstance};
use tokio::{net::TcpStream, sync::Mutex};
+/// # Trait - Action<Args, Return>
+///
+/// A trait used to describe the interaction pattern between client and server
+///
+/// ## Generics
+///
+/// Args: Represents the parameter type required for this action
+///
+/// Return: Represents the return type of this action
+///
+/// The above generics must implement serde's Serialize and DeserializeOwned traits,
+/// and must be sendable between threads
+///
+/// ## Implementation
+///
+/// ```ignore
+/// pub trait Action<Args, Return>
+/// where
+/// Args: Serialize + DeserializeOwned + Send,
+/// Return: Serialize + DeserializeOwned + Send,
+/// {
+/// /// Name, used to inform the server which action to execute
+/// fn action_name() -> &'static str;
+///
+/// /// Whether it's a local Action, used to inform the system if it only runs locally
+/// fn is_remote_action() -> bool;
+///
+/// /// Action processing logic
+/// fn process(
+/// context: ActionContext,
+/// args: Args,
+/// ) -> impl std::future::Future<Output = Result<Return, TcpTargetError>> + Send;
+/// }
+/// ```
pub trait Action<Args, Return>
where
Args: Serialize + DeserializeOwned + Send,
@@ -20,6 +54,28 @@ where
) -> impl std::future::Future<Output = Result<Return, TcpTargetError>> + Send;
}
+/// # Struct - ActionContext
+///
+/// Used to inform the Action about the current execution environment
+///
+/// ## Creation
+///
+/// Create ActionContext using the following methods:
+///
+/// ```ignore
+///
+/// // The instance here is the connection instance passed from external sources for communicating with the server
+/// // For specific usage, please refer to the `/crates/utils/tcp_connection` section
+///
+/// fn init_local_action_ctx(instance: ConnectionInstance) {
+/// // Create context and specify execution on local
+/// let mut ctx = ActionContext::local();
+/// }
+///
+/// fn init_remote_action_ctx(instance: ConnectionInstance) {
+/// // Create context and specify execution on remote
+/// let mut ctx = ActionContext::remote();
+/// }
#[derive(Default)]
pub struct ActionContext {
/// Whether the action is executed locally or remotely
diff --git a/crates/system_action/src/action_pool.rs b/crates/system_action/src/action_pool.rs
index c3ad4a1..019fa6d 100644
--- a/crates/system_action/src/action_pool.rs
+++ b/crates/system_action/src/action_pool.rs
@@ -15,7 +15,25 @@ type ProcEndCallback = fn() -> ProcEndFuture;
type ProcBeginFuture<'a> = Pin<Box<dyn Future<Output = Result<(), TcpTargetError>> + Send + 'a>>;
type ProcEndFuture = Pin<Box<dyn Future<Output = Result<(), TcpTargetError>> + Send>>;
-/// A pool of registered actions that can be processed by name
+/// # Struct - ActionPool
+///
+/// This struct is used to register and record all accessible and executable actions
+///
+/// It also registers `on_proc_begin` and `on_proc_end` callback functions
+/// used for action initialization
+///
+/// ## Creating and registering actions
+/// ```ignore
+/// fn init_action_pool() {
+/// let mut pool = Action::new();
+///
+/// // Register action
+/// pool.register<YourAction, ActionArgument, ActionReturn>();
+///
+/// // If the action is implemented with `#[action_gen]`, you can also do
+/// register_your_action(&mut pool);
+/// }
+/// ```
pub struct ActionPool {
/// HashMap storing action name to action implementation mapping
actions: std::collections::HashMap<&'static str, Box<dyn ActionErased>>,
diff --git a/crates/utils/cfg_file/cfg_file_derive/src/lib.rs b/crates/utils/cfg_file/cfg_file_derive/src/lib.rs
index e50a929..e916311 100644
--- a/crates/utils/cfg_file/cfg_file_derive/src/lib.rs
+++ b/crates/utils/cfg_file/cfg_file_derive/src/lib.rs
@@ -4,7 +4,34 @@ use proc_macro::TokenStream;
use quote::quote;
use syn::parse::ParseStream;
use syn::{Attribute, DeriveInput, Expr, parse_macro_input};
-
+/// # Macro - ConfigFile
+///
+/// ## Usage
+///
+/// Use `#[derive(ConfigFile)]` to derive the ConfigFile trait for a struct
+///
+/// Specify the default storage path via `#[cfg_file(path = "...")]`
+///
+/// ## About the `cfg_file` attribute macro
+///
+/// Use `#[cfg_file(path = "string")]` to specify the configuration file path
+///
+/// Or use `#[cfg_file(path = constant_expression)]` to specify the configuration file path
+///
+/// ## Path Rules
+///
+/// Paths starting with `"./"`: relative to the current working directory
+///
+/// Other paths: treated as absolute paths
+///
+/// When no path is specified: use the struct name + ".json" as the default filename (e.g., `my_struct.json`)
+///
+/// ## Example
+/// ```ignore
+/// #[derive(ConfigFile)]
+/// #[cfg_file(path = "./config.json")]
+/// struct AppConfig;
+/// ```
#[proc_macro_derive(ConfigFile, attributes(cfg_file))]
pub fn derive_config_file(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
diff --git a/crates/utils/cfg_file/src/config.rs b/crates/utils/cfg_file/src/config.rs
index a1eb301..a38da9a 100644
--- a/crates/utils/cfg_file/src/config.rs
+++ b/crates/utils/cfg_file/src/config.rs
@@ -33,12 +33,50 @@ impl ConfigFormat {
}
}
+/// # Trait - ConfigFile
+///
+/// Used to implement more convenient persistent storage functionality for structs
+///
+/// This trait requires the struct to implement Default and serde's Serialize and Deserialize traits
+///
+/// ## Implementation
+///
+/// ```ignore
+/// // Your struct
+/// #[derive(Default, Serialize, Deserialize)]
+/// struct YourData;
+///
+/// impl ConfigFile for YourData {
+/// type DataType = YourData;
+///
+/// // Specify default path
+/// fn default_path() -> Result<PathBuf, Error> {
+/// Ok(current_dir()?.join("data.json"))
+/// }
+/// }
+/// ```
+///
+/// > **Using derive macro**
+/// >
+/// > We provide the derive macro `#[derive(ConfigFile)]`
+/// >
+/// > You can implement this trait more quickly, please check the module cfg_file::cfg_file_derive
+///
#[async_trait]
pub trait ConfigFile: Serialize + for<'a> Deserialize<'a> + Default {
type DataType: Serialize + for<'a> Deserialize<'a> + Default + Send + Sync;
fn default_path() -> Result<PathBuf, Error>;
+ /// # Read from default path
+ ///
+ /// Read data from the path specified by default_path()
+ ///
+ /// ```ignore
+ /// fn main() -> Result<(), std::io::Error> {
+ /// let data = YourData::read().await?;
+ /// }
+ /// ```
async fn read() -> Result<Self::DataType, std::io::Error>
where
Self: Sized + Send + Sync,
@@ -47,6 +85,16 @@ pub trait ConfigFile: Serialize + for<'a> Deserialize<'a> + Default {
Self::read_from(path).await
}
+ /// # Read from the given path
+ ///
+ /// Read data from the path specified by the path parameter
+ ///
+ /// ```ignore
+ /// fn main() -> Result<(), std::io::Error> {
+ /// let data_path = current_dir()?.join("data.json");
+ /// let data = YourData::read_from(data_path).await?;
+ /// }
+ /// ```
async fn read_from(path: impl AsRef<Path> + Send) -> Result<Self::DataType, std::io::Error>
where
Self: Sized + Send + Sync,
@@ -91,6 +139,16 @@ pub trait ConfigFile: Serialize + for<'a> Deserialize<'a> + Default {
Ok(result)
}
+ /// # Write to default path
+ ///
+ /// Write data to the path specified by default_path()
+ ///
+ /// ```ignore
+ /// fn main() -> Result<(), std::io::Error> {
+ /// let data = YourData::default();
+ /// YourData::write(&data).await?;
+ /// }
+ /// ```
async fn write(val: &Self::DataType) -> Result<(), std::io::Error>
where
Self: Sized + Send + Sync,
@@ -98,7 +156,17 @@ pub trait ConfigFile: Serialize + for<'a> Deserialize<'a> + Default {
let path = Self::default_path()?;
Self::write_to(val, path).await
}
-
+ /// # Write to the given path
+ ///
+ /// Write data to the path specified by the path parameter
+ ///
+ /// ```ignore
+ /// fn main() -> Result<(), std::io::Error> {
+ /// let data = YourData::default();
+ /// let data_path = current_dir()?.join("data.json");
+ /// YourData::write_to(&data, data_path).await?;
+ /// }
+ /// ```
async fn write_to(
val: &Self::DataType,
path: impl AsRef<Path> + Send,
diff --git a/crates/utils/sha1_hash/src/lib.rs b/crates/utils/sha1_hash/src/lib.rs
index 9963cbe..c34db1d 100644
--- a/crates/utils/sha1_hash/src/lib.rs
+++ b/crates/utils/sha1_hash/src/lib.rs
@@ -5,6 +5,9 @@ use tokio::fs::File;
use tokio::io::{AsyncReadExt, BufReader};
use tokio::task;
+/// # Struct - Sha1Result
+///
+/// Records SHA1 calculation results, including the file path and hash value
#[derive(Debug, Clone)]
pub struct Sha1Result {
pub file_path: PathBuf,