summaryrefslogtreecommitdiff
path: root/support/texlab/crates/jsonrpc/src/client.rs
blob: 2cf18af1ffbf3a41165d28bc62a558655591a3d6 (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
use crate::types::*;
use chashmap::CHashMap;
use futures::channel::*;
use futures::prelude::*;
use futures_boxed::boxed;
use serde::Serialize;
use serde_json::json;
use std::sync::atomic::{AtomicU64, Ordering};

pub type Result<T> = std::result::Result<T, Error>;

pub trait ResponseHandler {
    #[boxed]
    async fn handle(&self, response: Response);
}

pub struct Client {
    output: mpsc::Sender<String>,
    request_id: AtomicU64,
    senders_by_id: CHashMap<Id, oneshot::Sender<Result<serde_json::Value>>>,
}

impl Client {
    pub fn new(output: mpsc::Sender<String>) -> Self {
        Client {
            output,
            request_id: AtomicU64::new(0),
            senders_by_id: CHashMap::new(),
        }
    }

    pub async fn send_request<T: Serialize>(
        &self,
        method: String,
        params: T,
    ) -> Result<serde_json::Value> {
        let id = self.request_id.fetch_add(1, Ordering::SeqCst);
        let request = Request::new(method, json!(params), Id::Number(id));

        let (result_tx, result_rx) = oneshot::channel();
        self.senders_by_id.insert(request.id.clone(), result_tx);
        self.send(Message::Request(request)).await;

        result_rx.await.unwrap()
    }

    pub async fn send_notification<T: Serialize>(&self, method: String, params: T) {
        let notification = Notification::new(method, json!(params));
        self.send(Message::Notification(notification)).await;
    }

    async fn send(&self, message: Message) {
        let mut output = self.output.clone();
        let json = serde_json::to_string(&message).unwrap();
        output.send(json).await.unwrap();
    }
}

impl ResponseHandler for Client {
    #[boxed]
    async fn handle(&self, response: Response) {
        let id = response.id.expect("Expected response with id");
        let result = match response.error {
            Some(why) => Err(why),
            None => Ok(response.result.unwrap_or(serde_json::Value::Null)),
        };

        let result_tx = self
            .senders_by_id
            .remove(&id)
            .expect("Unexpected response received");
        result_tx.send(result).unwrap();
    }
}