Skip to main content

sim_lib_server/
citizen.rs

1use sim_citizen_derive::Citizen;
2use sim_kernel::{Expr, Result, Symbol};
3
4/// Citizen descriptor for a `server/Address`, wrapping a validated address [`Expr`].
5#[derive(Clone, Debug, PartialEq, Citizen)]
6#[citizen(symbol = "server/Address", version = 1)]
7pub struct ServerAddressDescriptor {
8    #[citizen(with = "address_expr")]
9    address: Expr,
10}
11
12/// Citizen descriptor for a `server/Frame`, capturing the wire metadata of one transport frame.
13#[derive(Clone, Debug, PartialEq, Citizen)]
14#[citizen(symbol = "server/Frame", version = 1)]
15pub struct ServerFrameDescriptor {
16    /// Frame format version.
17    pub version: u64,
18    /// Codec symbol identifying how the payload is encoded.
19    pub codec: Symbol,
20    /// Frame kind symbol (for example `request` or `reply`).
21    pub kind: Symbol,
22    /// Message id, present when the frame participates in correlation.
23    pub msg_id: Option<u64>,
24    /// Id of the message this frame correlates with, when it is a reply.
25    pub correlate: Option<u64>,
26    /// Raw encoded payload bytes.
27    pub payload: Vec<u8>,
28}
29
30impl ServerAddressDescriptor {
31    /// Builds a descriptor from `address`, validating that it is a well-formed server address.
32    pub fn from_expr(address: Expr) -> Result<Self> {
33        address_expr::decode(&address)?;
34        Ok(Self { address })
35    }
36
37    /// Returns the wrapped address expression.
38    pub fn as_expr(&self) -> &Expr {
39        &self.address
40    }
41}
42
43impl Default for ServerAddressDescriptor {
44    fn default() -> Self {
45        Self::from_expr(Expr::Symbol(Symbol::new("local")))
46            .expect("default server address descriptor should be valid")
47    }
48}
49
50impl Default for ServerFrameDescriptor {
51    fn default() -> Self {
52        Self {
53            version: 1,
54            codec: Symbol::qualified("codec", "binary"),
55            kind: Symbol::new("request"),
56            msg_id: Some(1),
57            correlate: None,
58            payload: b"citizen-frame".to_vec(),
59        }
60    }
61}
62
63/// Returns the class symbol `server/Address` for the address descriptor citizen.
64pub fn server_address_class_symbol() -> Symbol {
65    Symbol::qualified("server", "Address")
66}
67
68/// Returns the class symbol `server/Frame` for the frame descriptor citizen.
69pub fn server_frame_class_symbol() -> Symbol {
70    Symbol::qualified("server", "Frame")
71}
72
73pub(crate) mod address_expr {
74    use sim_kernel::{Expr, Result};
75
76    use crate::ServerAddress;
77
78    pub fn encode(expr: &Expr) -> Expr {
79        expr.clone()
80    }
81
82    pub fn decode(expr: &Expr) -> Result<Expr> {
83        ServerAddress::from_expr(expr)?;
84        Ok(expr.clone())
85    }
86}