Actor Attribute Macro
This crate provides the #[actor] procedural macro for the simple_json_server library. The macro automatically implements the Actor trait for structs by generating a JSON-based dispatch method.
How it works
The #[actor] macro:
- Analyzes public async methods in an
implblock - Generates message structs for each method's parameters
- Implements the Actor trait with a
dispatchmethod that:- Deserializes JSON messages in the format
{"method": "method_name", "params": {...}} - Matches method names and calls the appropriate async method
- Serializes the return value back to JSON
- Deserializes JSON messages in the format
Usage
use ;
Generated Code
For the above example, the macro generates:
- Message structs for each method:
- Actor trait implementation:
Message Format
The macro expects JSON messages in this format:
For methods with no parameters, use an empty params object:
Method Requirements
The macro only processes methods that are:
- Public (
pub) - Async (
async fn)
Private methods and synchronous methods are ignored.
Return Values
All return values are automatically serialized to JSON. This includes:
- Primitive types:
42→"42" - Strings:
"hello"→"\"hello\"" - Complex types:
Result<T, E>→{"Ok": value}or{"Err": error} - Custom types (if they implement
Serialize)
Error Handling
The macro handles various error cases:
- Invalid JSON: Returns error message as JSON string
- Missing method field: Returns error message
- Unknown method: Returns "Unknown method" error
- Parameter deserialization errors: Returns detailed error message
- Result serialization errors: Returns error message
Dependencies
This macro requires:
syn- For parsing Rust syntaxquote- For generating Rust codeproc-macro2- For procedural macro supportserdeandserde_json- For JSON serialization/deserializationtokio- For async runtime support