madsim-rs / madsim

Magical Deterministic Simulator for distributed systems in Rust.
Apache License 2.0
649 stars 46 forks source link

Add `#[service]` macro #3

Closed wangrunji0408 closed 2 years ago

wangrunji0408 commented 2 years ago

Currently building a server on top of the RPC interface needs a lot boilerplate code:

pub struct Server {...}

impl Server {
    pub fn new() -> Arc<Self> {
        let server = Arc::new(Server {...});
        server.add_rpc_handler();
        server
    }

    // boilerplate!
    fn add_rpc_handler(self: Arc<Self>) {
        let net = NetLocalHandle::current();

        let this = self.clone();
        net.add_rpc_handler(move |req: Ping| {
            let this = this.clone();
            async move { this.ping(req) }
        });
    }

    fn ping(&self, req: Ping) {
        // handle RPC...
    }
}

We hope to provide a procedural macro to make that easy:

#[madsim::service]
impl Server {
    #[ctor]
    pub fn new() -> Arc<Self> {
        Arc::new(Server {...})
    }

    #[rpc]
    fn ping(&self, req: Ping) {
        // handle RPC...
    }
}
wangrunji0408 commented 2 years ago

Done in af010159a5f4daa77de7322689132afa518ba341