summaryrefslogtreecommitdiff
path: root/support/texlab/crates/jsonrpc/src/server.rs
blob: ccc04f286e8347e064385ac84d5e0a59802a1336 (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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
use crate::types::*;
use futures::prelude::*;
use futures_boxed::boxed;
use serde::de::DeserializeOwned;
use serde::Serialize;
use serde_json::json;

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

pub trait RequestHandler {
    #[boxed]
    async fn handle_request(&self, request: Request) -> Response;

    fn handle_notification(&self, notification: Notification);
}

pub trait Middleware {
    #[boxed]
    async fn before_message(&self);

    #[boxed]
    async fn after_message(&self);
}

pub async fn handle_request<'a, H, F, I, O>(request: Request, handler: H) -> Response
where
    H: Fn(I) -> F + Send + Sync + 'a,
    F: Future<Output = Result<O>> + Send,
    I: DeserializeOwned + Send,
    O: Serialize,
{
    let handle = |json| {
        async move {
            let params: I = serde_json::from_value(json).map_err(|_| Error::deserialize_error())?;
            let result = handler(params).await.map_err(Error::internal_error)?;
            Ok(result)
        }
    };

    match handle(request.params).await {
        Ok(result) => Response::result(json!(result), request.id),
        Err(error) => Response::error(error, Some(request.id)),
    }
}

pub fn handle_notification<'a, H, I>(notification: Notification, handler: H)
where
    H: Fn(I) -> () + Send + Sync + 'a,
    I: DeserializeOwned + Send,
{
    let params =
        serde_json::from_value(notification.params).expect(&Error::deserialize_error().message);
    handler(params);
}

#[cfg(test)]
mod tests {
    use super::*;
    use futures::executor::block_on;

    const METHOD_NAME: &str = "foo";

    async fn increment(i: i32) -> Result<i32> {
        Ok(i + 1)
    }

    fn panic(_params: ()) {
        panic!("success");
    }

    fn setup_request<T: Serialize>(value: T) -> Request {
        Request {
            jsonrpc: PROTOCOL_VERSION.to_owned(),
            params: json!(value),
            method: METHOD_NAME.to_owned(),
            id: Id::Number(0),
        }
    }

    fn setup_notification() -> Notification {
        Notification {
            jsonrpc: PROTOCOL_VERSION.to_owned(),
            method: METHOD_NAME.to_owned(),
            params: json!(()),
        }
    }

    #[test]
    fn test_request_valid() {
        let value = 42;
        let request = setup_request(value);

        let response = block_on(handle_request(request.clone(), increment));
        let expected = Response {
            jsonrpc: request.jsonrpc,
            result: Some(json!(block_on(increment(value)).unwrap())),
            error: None,
            id: Some(request.id),
        };

        assert_eq!(response, expected);
    }

    #[test]
    fn test_request_invalid_params() {
        let request = setup_request((0, 0));

        let response = block_on(handle_request(request.clone(), increment));
        let expected = Response {
            jsonrpc: request.jsonrpc.clone(),
            result: None,
            error: Some(Error::deserialize_error()),
            id: Some(request.id),
        };

        assert_eq!(response, expected);
    }

    #[test]
    #[should_panic(expected = "success")]
    fn test_notification_valid() {
        let notification = setup_notification();
        handle_notification(notification, panic);
    }

    #[test]
    #[should_panic]
    fn test_notification_invalid_params() {
        let notification = setup_notification();
        let notification = Notification {
            params: json!(0),
            ..notification
        };

        handle_notification(notification, panic);
    }
}