Debian Codegraph @

include/dap/session.h

raw
1 // Copyright 2019 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #ifndef dap_session_h
16 #define dap_session_h
17
18 #include "future.h"
19 #include "io.h"
20 #include "traits.h"
21 #include "typeinfo.h"
22 #include "typeof.h"
23
24 #include <functional>
25
26 namespace dap {
27
28 // Forward declarations
29 struct Request;
30 struct Response;
31 struct Event;
32
33 ////////////////////////////////////////////////////////////////////////////////
34 // Error
35 ////////////////////////////////////////////////////////////////////////////////
36
37 // Error represents an error message in response to a DAP request.
38 struct Error {
39 Error() = default;
40 Error(const std::string& error);
41 Error(const char* msg, ...);
42
43 // operator bool() returns true if there is an error.
44 inline operator bool() const { return message.size() > 0; }
45
46 std::string message; // empty represents success.
47 };
48
49 ////////////////////////////////////////////////////////////////////////////////
50 // ResponseOrError<T>
51 ////////////////////////////////////////////////////////////////////////////////
52
53 // ResponseOrError holds either the response to a DAP request or an error
54 // message.
55 template <typename T>
56 struct ResponseOrError {
57 using Request = T;
58
59 inline ResponseOrError() = default;
60 inline ResponseOrError(const T& response);
61 inline ResponseOrError(T&& response);
62 inline ResponseOrError(const Error& error);
63 inline ResponseOrError(Error&& error);
64 inline ResponseOrError(const ResponseOrError& other);
65 inline ResponseOrError(ResponseOrError&& other);
66
67 inline ResponseOrError& operator=(const ResponseOrError& other);
68 inline ResponseOrError& operator=(ResponseOrError&& other);
69
70 T response;
71 Error error; // empty represents success.
72 };
73
74 template <typename T>
75 ResponseOrError<T>::ResponseOrError(const T& resp) : response(resp) {}
76 template <typename T>
77 ResponseOrError<T>::ResponseOrError(T&& resp) : response(std::move(resp)) {}
78 template <typename T>
79 ResponseOrError<T>::ResponseOrError(const Error& err) : error(err) {}
80 template <typename T>
81 ResponseOrError<T>::ResponseOrError(Error&& err) : error(std::move(err)) {}
82 template <typename T>
83 ResponseOrError<T>::ResponseOrError(const ResponseOrError& other)
84 : response(other.response), error(other.error) {}
85 template <typename T>
86 ResponseOrError<T>::ResponseOrError(ResponseOrError&& other)
87 : response(std::move(other.response)), error(std::move(other.error)) {}
88 template <typename T>
89 ResponseOrError<T>& ResponseOrError<T>::operator=(
90 const ResponseOrError& other) {
91 response = other.response;
92 error = other.error;
93 return *this;
94 }
95 template <typename T>
96 ResponseOrError<T>& ResponseOrError<T>::operator=(ResponseOrError&& other) {
97 response = std::move(other.response);
98 error = std::move(other.error);
99 return *this;
100 }
101
102 ////////////////////////////////////////////////////////////////////////////////
103 // Session
104 ////////////////////////////////////////////////////////////////////////////////
105
106 // Session implements a DAP client or server endpoint.
107 // The general usage is as follows:
108 // (1) Create a session with Session::create().
109 // (2) Register request and event handlers with registerHandler().
110 // (3) Optionally register a protocol error handler with onError().
111 // (3) Bind the session to the remote endpoint with bind().
112 // (4) Send requests or events with send().
113 class Session {
114 template <typename F, int N>
115 using ParamType = traits::ParameterType<F, N>;
116
117 template <typename T>
118 using IsRequest = traits::EnableIfIsType<dap::Request, T>;
119
120 template <typename T>
121 using IsEvent = traits::EnableIfIsType<dap::Event, T>;
122
123 template <typename F>
124 using IsRequestHandlerWithoutCallback = traits::EnableIf<
125 traits::CompatibleWith<F, std::function<void(dap::Request)>>::value>;
126
127 template <typename F, typename CallbackType>
128 using IsRequestHandlerWithCallback = traits::EnableIf<traits::CompatibleWith<
129 F,
130 std::function<void(dap::Request, std::function<void(CallbackType)>)>>::
131 value>;
132
133 public:
134 virtual ~Session();
135
136 // ErrorHandler is the type of callback function used for reporting protocol
137 // errors.
138 using ErrorHandler = std::function<void(const char*)>;
139
140 // ClosedHandler is the type of callback function used to signal that a
141 // connected endpoint has closed.
142 using ClosedHandler = std::function<void()>;
143
144 // create() constructs and returns a new Session.
145 static std::unique_ptr<Session> create();
146
147 // onError() registers a error handler that will be called whenever a protocol
148 // error is encountered.
149 // Only one error handler can be bound at any given time, and later calls
150 // will replace the existing error handler.
151 virtual void onError(const ErrorHandler&) = 0;
152
153 // registerHandler() registers a request handler for a specific request type.
154 // The function F must have one of the following signatures:
155 // ResponseOrError<ResponseType>(const RequestType&)
156 // ResponseType(const RequestType&)
157 // Error(const RequestType&)
158 template <typename F, typename RequestType = ParamType<F, 0>>
159 inline IsRequestHandlerWithoutCallback<F> registerHandler(F&& handler);
160
161 // registerHandler() registers a request handler for a specific request type.
162 // The handler has a response callback function for the second argument of the
163 // handler function. This callback may be called after the handler has
164 // returned.
165 // The function F must have the following signature:
166 // void(const RequestType& request,
167 // std::function<void(ResponseType)> response)
168 template <typename F,
169 typename RequestType = ParamType<F, 0>,
170 typename ResponseType = typename RequestType::Response>
171 inline IsRequestHandlerWithCallback<F, ResponseType> registerHandler(
172 F&& handler);
173
174 // registerHandler() registers a request handler for a specific request type.
175 // The handler has a response callback function for the second argument of the
176 // handler function. This callback may be called after the handler has
177 // returned.
178 // The function F must have the following signature:
179 // void(const RequestType& request,
180 // std::function<void(ResponseOrError<ResponseType>)> response)
181 template <typename F,
182 typename RequestType = ParamType<F, 0>,
183 typename ResponseType = typename RequestType::Response>
184 inline IsRequestHandlerWithCallback<F, ResponseOrError<ResponseType>>
185 registerHandler(F&& handler);
186
187 // registerHandler() registers a event handler for a specific event type.
188 // The function F must have the following signature:
189 // void(const EventType&)
190 template <typename F, typename EventType = ParamType<F, 0>>
191 inline IsEvent<EventType> registerHandler(F&& handler);
192
193 // registerSentHandler() registers the function F to be called when a response
194 // of the specific type has been sent.
195 // The function F must have the following signature:
196 // void(const ResponseOrError<ResponseType>&)
197 template <typename F,
198 typename ResponseType = typename ParamType<F, 0>::Request>
199 inline void registerSentHandler(F&& handler);
200
201 // send() sends the request to the connected endpoint and returns a
202 // future that is assigned the request response or error.
203 template <typename T, typename = IsRequest<T>>
204 future<ResponseOrError<typename T::Response>> send(const T& request);
205
206 // send() sends the event to the connected endpoint.
207 template <typename T, typename = IsEvent<T>>
208 void send(const T& event);
209
210 // bind() connects this Session to an endpoint using connect(), and then
211 // starts processing incoming messages with startProcessingMessages().
212 // onClose is the optional callback which will be called when the session
213 // endpoint has been closed.
214 inline void bind(const std::shared_ptr<Reader>& reader,
215 const std::shared_ptr<Writer>& writer,
216 const ClosedHandler& onClose);
217 inline void bind(const std::shared_ptr<ReaderWriter>& readerWriter,
218 const ClosedHandler& onClose);
219
220 //////////////////////////////////////////////////////////////////////////////
221 // Note:
222 // Methods and members below this point are for advanced usage, and are more
223 // likely to change signature than the methods above.
224 // The methods above this point should be sufficient for most use cases.
225 //////////////////////////////////////////////////////////////////////////////
226
227 // connect() connects this Session to an endpoint.
228 // connect() can only be called once. Repeated calls will raise an error, but
229 // otherwise will do nothing.
230 // Note: This method is used for explicit control over message handling.
231 // Most users will use bind() instead of calling this method directly.
232 virtual void connect(const std::shared_ptr<Reader>&,
233 const std::shared_ptr<Writer>&) = 0;
234 inline void connect(const std::shared_ptr<ReaderWriter>&);
235
236 // startProcessingMessages() starts a new thread to receive and dispatch
237 // incoming messages.
238 // onClose is the optional callback which will be called when the session
239 // endpoint has been closed.
240 // Note: This method is used for explicit control over message handling.
241 // Most users will use bind() instead of calling this method directly.
242 virtual void startProcessingMessages(const ClosedHandler& onClose = {}) = 0;
243
244 // getPayload() blocks until the next incoming message is received, returning
245 // the payload or an empty function if the connection was lost. The returned
246 // payload is function that can be called on any thread to dispatch the
247 // message to the Session handler.
248 // Note: This method is used for explicit control over message handling.
249 // Most users will use bind() instead of calling this method directly.
250 virtual std::function<void()> getPayload() = 0;
251
252 // The callback function type called when a request handler is invoked, and
253 // the request returns a successful result.
254 // 'responseTypeInfo' is the type information of the response data structure.
255 // 'responseData' is a pointer to response payload data.
256 using RequestHandlerSuccessCallback =
257 std::function<void(const TypeInfo* responseTypeInfo,
258 const void* responseData)>;
259
260 // The callback function type used to notify when a DAP request fails.
261 // 'responseTypeInfo' is the type information of the response data structure.
262 // 'message' is the error message
263 using RequestHandlerErrorCallback =
264 std::function<void(const TypeInfo* responseTypeInfo,
265 const Error& message)>;
266
267 // The callback function type used to invoke a request handler.
268 // 'request' is a pointer to the request data structure
269 // 'onSuccess' is the function to call if the request completed succesfully.
270 // 'onError' is the function to call if the request failed.
271 // For each call of the request handler, 'onSuccess' or 'onError' must be
272 // called exactly once.
273 using GenericRequestHandler =
274 std::function<void(const void* request,
275 const RequestHandlerSuccessCallback& onSuccess,
276 const RequestHandlerErrorCallback& onError)>;
277
278 // The callback function type used to handle a response to a request.
279 // 'response' is a pointer to the response data structure. May be nullptr.
280 // 'error' is a pointer to the reponse error message. May be nullptr.
281 // One of 'data' or 'error' will be nullptr.
282 using GenericResponseHandler =
283 std::function<void(const void* response, const Error* error)>;
284
285 // The callback function type used to handle an event.
286 // 'event' is a pointer to the event data structure.
287 using GenericEventHandler = std::function<void(const void* event)>;
288
289 // The callback function type used to notify when a response has been sent
290 // from this session endpoint.
291 // 'response' is a pointer to the response data structure.
292 // 'error' is a pointer to the reponse error message. May be nullptr.
293 using GenericResponseSentHandler =
294 std::function<void(const void* response, const Error* error)>;
295
296 // registerHandler() registers 'handler' as the request handler callback for
297 // requests of the type 'typeinfo'.
298 virtual void registerHandler(const TypeInfo* typeinfo,
299 const GenericRequestHandler& handler) = 0;
300
301 // registerHandler() registers 'handler' as the event handler callback for
302 // events of the type 'typeinfo'.
303 virtual void registerHandler(const TypeInfo* typeinfo,
304 const GenericEventHandler& handler) = 0;
305
306 // registerHandler() registers 'handler' as the response-sent handler function
307 // which is called whenever a response of the type 'typeinfo' is sent from
308 // this session endpoint.
309 virtual void registerHandler(const TypeInfo* typeinfo,
310 const GenericResponseSentHandler& handler) = 0;
311
312 // send() sends a request to the remote endpoint.
313 // 'requestTypeInfo' is the type info of the request data structure.
314 // 'requestTypeInfo' is the type info of the response data structure.
315 // 'request' is a pointer to the request data structure.
316 // 'responseHandler' is the handler function for the response.
317 virtual bool send(const dap::TypeInfo* requestTypeInfo,
318 const dap::TypeInfo* responseTypeInfo,
319 const void* request,
320 const GenericResponseHandler& responseHandler) = 0;
321
322 // send() sends an event to the remote endpoint.
323 // 'eventTypeInfo' is the type info for the event data structure.
324 // 'event' is a pointer to the event data structure.
325 virtual bool send(const TypeInfo* eventTypeInfo, const void* event) = 0;
326 };
327
328 template <typename F, typename RequestType>
329 Session::IsRequestHandlerWithoutCallback<F> Session::registerHandler(
330 F&& handler) {
331 using ResponseType = typename RequestType::Response;
332 const TypeInfo* typeinfo = TypeOf<RequestType>::type();
333 registerHandler(typeinfo,
334 [handler](const void* args,
335 const RequestHandlerSuccessCallback& onSuccess,
336 const RequestHandlerErrorCallback& onError) {
337 ResponseOrError<ResponseType> res =
338 handler(*reinterpret_cast<const RequestType*>(args));
339 if (res.error) {
340 onError(TypeOf<ResponseType>::type(), res.error);
341 } else {
342 onSuccess(TypeOf<ResponseType>::type(), &res.response);
343 }
344 });
345 }
346
347 template <typename F, typename RequestType, typename ResponseType>
348 Session::IsRequestHandlerWithCallback<F, ResponseType> Session::registerHandler(
349 F&& handler) {
350 using CallbackType = ParamType<F, 1>;
351 registerHandler(
352 TypeOf<RequestType>::type(),
353 [handler](const void* args,
354 const RequestHandlerSuccessCallback& onSuccess,
355 const RequestHandlerErrorCallback&) {
356 CallbackType responseCallback = [onSuccess](const ResponseType& res) {
357 onSuccess(TypeOf<ResponseType>::type(), &res);
358 };
359 handler(*reinterpret_cast<const RequestType*>(args), responseCallback);
360 });
361 }
362
363 template <typename F, typename RequestType, typename ResponseType>
364 Session::IsRequestHandlerWithCallback<F, ResponseOrError<ResponseType>>
365 Session::registerHandler(F&& handler) {
366 using CallbackType = ParamType<F, 1>;
367 registerHandler(
368 TypeOf<RequestType>::type(),
369 [handler](const void* args,
370 const RequestHandlerSuccessCallback& onSuccess,
371 const RequestHandlerErrorCallback& onError) {
372 CallbackType responseCallback =
373 [onError, onSuccess](const ResponseOrError<ResponseType>& res) {
374 if (res.error) {
375 onError(TypeOf<ResponseType>::type(), res.error);
376 } else {
377 onSuccess(TypeOf<ResponseType>::type(), &res.response);
378 }
379 };
380 handler(*reinterpret_cast<const RequestType*>(args), responseCallback);
381 });
382 }
383
384 template <typename F, typename T>
385 Session::IsEvent<T> Session::registerHandler(F&& handler) {
386 auto cb = [handler](const void* args) {
387 handler(*reinterpret_cast<const T*>(args));
388 };
389 const TypeInfo* typeinfo = TypeOf<T>::type();
390 registerHandler(typeinfo, cb);
391 }
392
393 template <typename F, typename T>
394 void Session::registerSentHandler(F&& handler) {
395 auto cb = [handler](const void* response, const Error* error) {
396 if (error != nullptr) {
397 handler(ResponseOrError<T>(*error));
398 } else {
399 handler(ResponseOrError<T>(*reinterpret_cast<const T*>(response)));
400 }
401 };
402 const TypeInfo* typeinfo = TypeOf<T>::type();
403 registerHandler(typeinfo, cb);
404 }
405
406 template <typename T, typename>
407 future<ResponseOrError<typename T::Response>> Session::send(const T& request) {
408 using Response = typename T::Response;
409 promise<ResponseOrError<Response>> promise;
410 auto sent = send(TypeOf<T>::type(), TypeOf<Response>::type(), &request,
411 [=](const void* result, const Error* error) {
412 if (error != nullptr) {
413 promise.set_value(ResponseOrError<Response>(*error));
414 } else {
415 promise.set_value(ResponseOrError<Response>(
416 *reinterpret_cast<const Response*>(result)));
417 }
418 });
419 if (!sent) {
420 promise.set_value(Error("Failed to send request"));
421 }
422 return promise.get_future();
423 }
424
425 template <typename T, typename>
426 void Session::send(const T& event) {
427 const TypeInfo* typeinfo = TypeOf<T>::type();
428 send(typeinfo, &event);
429 }
430
431 void Session::connect(const std::shared_ptr<ReaderWriter>& rw) {
432 connect(rw, rw);
433 }
434
435 void Session::bind(const std::shared_ptr<dap::Reader>& r,
436 const std::shared_ptr<dap::Writer>& w,
437 const ClosedHandler& onClose = {}) {
438 connect(r, w);
439 startProcessingMessages(onClose);
440 }
441
442 void Session::bind(const std::shared_ptr<ReaderWriter>& rw,
443 const ClosedHandler& onClose = {}) {
444 bind(rw, rw, onClose);
445 }
446
447 } // namespace dap
448
449 #endif // dap_session_h