summaryrefslogtreecommitdiff
path: root/graphics/asymptote/LspCpp/include/LibLsp/JsonRpc/RemoteEndPoint.h
blob: 4045098f1bfbf3807ec6966d582feed30f375fd3 (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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
#pragma once
#include "LibLsp/lsp/lsp_diagnostic.h"
#include "LibLsp/JsonRpc/Cancellation.h"
#include "LibLsp/JsonRpc/lsResponseMessage.h"
#include "LibLsp/JsonRpc/RequestInMessage.h"
#include "LibLsp/JsonRpc/NotificationInMessage.h"
#include "traits.h"
#include <future>
#include <string>
#include "threaded_queue.h"
#include <unordered_map>
#include "MessageIssue.h"
#include "LibLsp/JsonRpc/MessageJsonHandler.h"
#include "Endpoint.h"
#include "future.h"


class MessageJsonHandler;
class  Endpoint;
struct LspMessage;
class RemoteEndPoint;
namespace lsp {
        class ostream;
        class istream;

        ////////////////////////////////////////////////////////////////////////////////
        // ResponseOrError<T>
        ////////////////////////////////////////////////////////////////////////////////

        // ResponseOrError holds either the response to a  request or an error
        // message.
        template <typename T>
        struct ResponseOrError {
                 using Request = T;
                 ResponseOrError();
                 ResponseOrError(const T& response);
                 ResponseOrError(T&& response);
                 ResponseOrError(const Rsp_Error& error);
                 ResponseOrError(Rsp_Error&& error);
                 ResponseOrError(const ResponseOrError& other);
                 ResponseOrError(ResponseOrError&& other) noexcept;

                 ResponseOrError& operator=(const ResponseOrError& other);
                 ResponseOrError& operator=(ResponseOrError&& other) noexcept;
                bool  IsError() const { return  is_error; }
                std::string ToJson()
                {
                        if (is_error) return  error.ToJson();
                        return  response.ToJson();
                }
                T response;
                Rsp_Error error;  // empty represents success.
                bool is_error;
        };

        template <typename T>
        ResponseOrError<T>::ResponseOrError(): is_error(false)
        {
        }

        template <typename T>
        ResponseOrError<T>::ResponseOrError(const T& resp) : response(resp), is_error(false) {}
        template <typename T>
        ResponseOrError<T>::ResponseOrError(T&& resp) : response(std::move(resp)), is_error(false) {}
        template <typename T>
        ResponseOrError<T>::ResponseOrError(const Rsp_Error& err) : error(err), is_error(true) {}
        template <typename T>
        ResponseOrError<T>::ResponseOrError(Rsp_Error&& err) : error(std::move(err)), is_error(true) {}
        template <typename T>
        ResponseOrError<T>::ResponseOrError(const ResponseOrError& other)
                : response(other.response), error(other.error), is_error(other.is_error) {}
        template <typename T>
        ResponseOrError<T>::ResponseOrError(ResponseOrError&& other) noexcept
                : response(std::move(other.response)), error(std::move(other.error)), is_error(other.is_error) {}
        template <typename T>
        ResponseOrError<T>& ResponseOrError<T>::operator=(
                const ResponseOrError& other) {
                response = other.response;
                error = other.error;
                is_error = other.is_error;
                return *this;
        }
        template <typename T>
        ResponseOrError<T>& ResponseOrError<T>::operator=(ResponseOrError&& other) noexcept
        {
                response = std::move(other.response);
                error = std::move(other.error);
                is_error = other.is_error;
                return *this;
        }

}


class RemoteEndPoint :MessageIssueHandler
{

        template <typename F, int N>
        using ParamType = lsp::traits::ParameterType<F, N>;

        template <typename T>
        using IsRequest = lsp::traits::EnableIfIsType<RequestInMessage, T>;

        template <typename T>
        using IsResponse = lsp::traits::EnableIfIsType<ResponseInMessage, T>;

        template <typename T>
        using IsNotify = lsp::traits::EnableIfIsType<NotificationInMessage, T>;


        template <typename F, typename ReturnType>
        using IsRequestHandler = lsp::traits::EnableIf<lsp::traits::CompatibleWith<
                F,
                std::function<ReturnType(const RequestInMessage&)>>::
                value>;

        template <typename F, typename ReturnType>
        using IsRequestHandlerWithMonitor = lsp::traits::EnableIf<lsp::traits::CompatibleWith<
                F,
                std::function<ReturnType(const RequestInMessage&,const CancelMonitor&)>>::
                value>;

public:


        RemoteEndPoint(const std::shared_ptr <MessageJsonHandler>& json_handler,
                const std::shared_ptr < Endpoint >& localEndPoint,
                lsp::Log& _log, uint8_t max_workers = 2);

        ~RemoteEndPoint() override;
        template <typename F, typename RequestType = ParamType<F, 0>, typename ResponseType = typename RequestType::Response>
        IsRequestHandler< F, lsp::ResponseOrError<ResponseType> >  registerHandler(F&& handler)
        {
                processRequestJsonHandler(handler);
                local_endpoint->registerRequestHandler(RequestType::kMethodInfo, [=](std::unique_ptr<LspMessage> msg) {
                        auto  req = reinterpret_cast<const RequestType*>(msg.get());
                        lsp::ResponseOrError<ResponseType> res(handler(*req));
                        if (res.is_error) {
                                res.error.id = req->id;
                                send(res.error);
                        }
                        else
                        {
                                res.response.id = req->id;
                                send(res.response);
                        }
                        return  true;
                });
        }
        template <typename F, typename RequestType = ParamType<F, 0>, typename ResponseType = typename RequestType::Response>
        IsRequestHandlerWithMonitor< F, lsp::ResponseOrError<ResponseType> >  registerHandler(F&& handler)  {
                processRequestJsonHandler(handler);
                local_endpoint->registerRequestHandler(RequestType::kMethodInfo, [=](std::unique_ptr<LspMessage> msg) {
                        auto  req = static_cast<const RequestType*>(msg.get());
                        lsp::ResponseOrError<ResponseType> res(handler(*req , getCancelMonitor(req->id)));
                        if (res.is_error) {
                                res.error.id = req->id;
                                send(res.error);
                        }
                        else
                        {
                                res.response.id = req->id;
                                send(res.response);
                        }
                        return  true;
                });
        }
        using RequestErrorCallback = std::function<void(const Rsp_Error&)>;

        template <typename T, typename F, typename ResponseType = ParamType<F, 0> >
        void send(T& request, F&& handler, RequestErrorCallback onError)
        {
                processRequestJsonHandler(handler);
                auto cb = [=](std::unique_ptr<LspMessage> msg) {
                        if (!msg)
                                return true;
                        const auto result = msg.get();

                        if (static_cast<ResponseInMessage*>(result)->IsErrorType()) {
                                const auto rsp_error = static_cast<const Rsp_Error*>(result);
                                onError(*rsp_error);
                        }
                        else {
                                handler(*static_cast<ResponseType*>(result));
                        }

                        return  true;
                };
                internalSendRequest(request, cb);
        }


        template <typename F, typename NotifyType = ParamType<F, 0> >
        IsNotify<NotifyType>  registerHandler(F&& handler) {
                {
                        std::lock_guard<std::mutex> lock(m_sendMutex);
                        if (!jsonHandler->GetNotificationJsonHandler(NotifyType::kMethodInfo))
                        {
                                jsonHandler->SetNotificationJsonHandler(NotifyType::kMethodInfo,
                                        [](Reader& visitor)
                                        {
                                                return NotifyType::ReflectReader(visitor);
                                        });
                        }
                }
                local_endpoint->registerNotifyHandler(NotifyType::kMethodInfo, [=](std::unique_ptr<LspMessage> msg) {
                        handler(*static_cast<NotifyType*>(msg.get()));
                        return  true;
                        });
        }

        template <typename T, typename = IsRequest<T>>
        lsp::future< lsp::ResponseOrError<typename T::Response> > send(T& request) {

                processResponseJsonHandler(request);
                using Response = typename T::Response;
                auto promise = std::make_shared< lsp::promise<lsp::ResponseOrError<Response>>>();
                auto cb = [=](std::unique_ptr<LspMessage> msg) {
                        if (!msg)
                                return true;
                        auto result = msg.get();

                        if (reinterpret_cast<ResponseInMessage*>(result)->IsErrorType())
                        {
                                Rsp_Error* rsp_error = static_cast<Rsp_Error*>(result);
                                Rsp_Error temp;
                                std::swap(temp, *rsp_error);
                                promise->set_value(std::move(lsp::ResponseOrError<Response>(std::move(temp))));
                        }
                        else
                        {
                                Response temp;
                                std::swap(temp, *static_cast<Response*>(result));
                                promise->set_value(std::move(lsp::ResponseOrError<Response>(std::move(temp))));
                        }
                        return  true;
                };
                internalSendRequest(request, cb);
                return promise->get_future();
        }

        template <typename T, typename = IsRequest<T>>
        std::unique_ptr<lsp::ResponseOrError<typename T::Response>> waitResponse(T& request, const unsigned time_out = 0)
        {
                auto future_rsp = send(request);
                if (time_out == 0)
                {
                        future_rsp.wait();
                }
                else
                {
                        auto state = future_rsp.wait_for(std::chrono::milliseconds(time_out));
                        if (lsp::future_status::timeout == state)
                        {
                                return {};
                        }
                }

                using Response = typename T::Response;
                return std::make_unique<lsp::ResponseOrError<Response>>(std::move(future_rsp.get()));
        }

        void send(NotificationInMessage& msg)
        {
                sendMsg(msg);
        }

        void send(ResponseInMessage& msg)
        {
                sendMsg(msg);
        }

        void sendNotification(NotificationInMessage& msg)
        {
                send(msg);
        }
        void sendResponse(ResponseInMessage& msg)
        {
                send(msg);
        }
    template <typename T>
    T createRequest() {
        auto req = T();
        req.id.set(getNextRequestId());
        return req;
    }

    int getNextRequestId();

    bool cancelRequest(const lsRequestId&);

        void startProcessingMessages(std::shared_ptr<lsp::istream> r,
                std::shared_ptr<lsp::ostream> w);

        bool isWorking() const;
        void stop();

        std::unique_ptr<LspMessage> internalWaitResponse(RequestInMessage&, unsigned time_out = 0);

        bool internalSendRequest(RequestInMessage &info, GenericResponseHandler handler);

        void handle(std::vector<MessageIssue>&&) override;
        void handle(MessageIssue&&) override;
private:
        CancelMonitor getCancelMonitor(const lsRequestId&);
        void sendMsg(LspMessage& msg);
        void mainLoop(std::unique_ptr<LspMessage>);
        bool dispatch(const std::string&);
        template <typename F, typename RequestType = ParamType<F, 0>>
        IsRequest<RequestType>  processRequestJsonHandler(const F& handler) {
                std::lock_guard<std::mutex> lock(m_sendMutex);
                if (!jsonHandler->GetRequestJsonHandler(RequestType::kMethodInfo))
                {
                        jsonHandler->SetRequestJsonHandler(RequestType::kMethodInfo,
                                [](Reader& visitor)
                                {
                                        return RequestType::ReflectReader(visitor);
                                });
                }
        }
        template <typename T, typename = IsRequest<T>>
        void processResponseJsonHandler(T& request)
        {
                using Response = typename T::Response;
                std::lock_guard<std::mutex> lock(m_sendMutex);
                if (!jsonHandler->GetResponseJsonHandler(T::kMethodInfo))
                {
                        jsonHandler->SetResponseJsonHandler(T::kMethodInfo, [](Reader& visitor)
                                {
                                        if (visitor.HasMember("error"))
                                                return  Rsp_Error::ReflectReader(visitor);
                                        return Response::ReflectReader(visitor);
                                });
                }
        }

        struct Data;

        Data* d_ptr;

        std::shared_ptr < MessageJsonHandler> jsonHandler;
        std::mutex m_sendMutex;

        std::shared_ptr < Endpoint > local_endpoint;
public:
        std::shared_ptr < std::thread > message_producer_thread_;
};