aboutsummaryrefslogtreecommitdiff
path: root/jsonrpc/examples/pubsub_server.rs
blob: d1623c15670d98773e1055e305ef84c47773debc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
use std::{sync::Arc, time::Duration};

use log::error;
use serde::{Deserialize, Serialize};
use serde_json::Value;

use karyon_core::async_util::sleep;
use karyon_jsonrpc::{
    message::SubscriptionID, rpc_impl, rpc_pubsub_impl, Channel, RPCError, Server,
};

struct Calc {}

#[derive(Deserialize, Serialize)]
struct Req {
    x: u32,
    y: u32,
}

#[derive(Deserialize, Serialize)]
struct Pong {}

#[rpc_impl]
impl Calc {
    async fn ping(&self, _params: Value) -> Result<Value, RPCError> {
        Ok(serde_json::json!(Pong {}))
    }
}

#[rpc_pubsub_impl]
impl Calc {
    async fn log_subscribe(
        &self,
        chan: Arc<Channel>,
        method: String,
        _params: Value,
    ) -> Result<Value, RPCError> {
        let sub = chan.new_subscription(&method).await;
        let sub_id = sub.id.clone();
        smol::spawn(async move {
            loop {
                sleep(Duration::from_millis(500)).await;
                if let Err(err) = sub.notify(serde_json::json!("Hello")).await {
                    error!("Send notification {err}");
                    break;
                }
            }
        })
        .detach();

        Ok(serde_json::json!(sub_id))
    }

    async fn log_unsubscribe(
        &self,
        chan: Arc<Channel>,
        _method: String,
        params: Value,
    ) -> Result<Value, RPCError> {
        let sub_id: SubscriptionID = serde_json::from_value(params)?;
        chan.remove_subscription(&sub_id).await;
        Ok(serde_json::json!(true))
    }
}

fn main() {
    env_logger::init();
    smol::block_on(async {
        let calc = Arc::new(Calc {});

        // Creates a new server
        let server = Server::builder("tcp://127.0.0.1:6000")
            .expect("Create a new server builder")
            .service(calc.clone())
            .pubsub_service(calc)
            .build()
            .await
            .expect("Build a new server");

        // Start the server
        server.start();

        sleep(Duration::MAX).await;
    });
}