summaryrefslogtreecommitdiff
path: root/support/texlab/crates/jsonrpc/src/server.rs
blob: ce34dc8b604c32b43aa1358f042da89134cbd2be (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
use super::types::*;
use async_trait::async_trait;
use futures::prelude::*;
use serde::{de::DeserializeOwned, Serialize};
use serde_json::json;

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

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

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

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

    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 async fn handle_notification<'a, H, F, I>(notification: Notification, handler: H)
where
    H: Fn(I) -> F + Send + Sync + 'a,
    F: Future<Output = ()> + Send,
    I: DeserializeOwned + Send,
{
    let error = Error::deserialize_error().message;
    let params = serde_json::from_value(notification.params).expect(&error);
    handler(params).await;
}

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

    const METHOD_NAME: &str = "foo";

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

    async 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!(()),
        }
    }

    #[tokio::test]
    async fn request_valid() {
        let value = 42;
        let request = setup_request(value);

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

        assert_eq!(response, expected);
    }

    #[tokio::test]
    async fn request_invalid_params() {
        let request = setup_request((0, 0));

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

        assert_eq!(response, expected);
    }

    #[tokio::test]
    #[should_panic(expected = "success")]
    async fn notification_valid() {
        let notification = setup_notification();
        handle_notification(notification, panic).await;
    }

    #[tokio::test]
    #[should_panic]
    async fn notification_invalid_params() {
        let notification = Notification {
            params: json!(0),
            ..setup_notification()
        };
        handle_notification(notification, panic).await;
    }
}