LLDB mainline
JSONTransport.h
Go to the documentation of this file.
1//===-- JSONTransport.h ---------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Transport layer for encoding and decoding JSON protocol messages.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLDB_HOST_JSONTRANSPORT_H
14#define LLDB_HOST_JSONTRANSPORT_H
15
16#include "lldb/Host/MainLoop.h"
19#include "lldb/Utility/Status.h"
20#include "lldb/lldb-forward.h"
21#include "llvm/ADT/FunctionExtras.h"
22#include "llvm/ADT/StringExtras.h"
23#include "llvm/ADT/StringRef.h"
24#include "llvm/Support/Error.h"
25#include "llvm/Support/ErrorHandling.h"
26#include "llvm/Support/FormatVariadic.h"
27#include "llvm/Support/JSON.h"
28#include "llvm/Support/raw_ostream.h"
29#include <atomic>
30#include <functional>
31#include <mutex>
32#include <optional>
33#include <string>
34#include <system_error>
35#include <type_traits>
36#include <utility>
37#include <variant>
38#include <vector>
39#if __cplusplus >= 202002L
40#include <concepts>
41#endif
42
44
45/// An error to indicate that the transport reached EOF but there were still
46/// unhandled contents in the read buffer.
48 : public llvm::ErrorInfo<TransportUnhandledContentsError> {
49public:
50 static char ID;
51
52 explicit TransportUnhandledContentsError(std::string unhandled_contents);
53
54 void log(llvm::raw_ostream &OS) const override;
55 std::error_code convertToErrorCode() const override;
56
57 const std::string &getUnhandledContents() const {
59 }
60
61private:
63};
64
65/// An error to indicate that the parameters of a Req, Resp or Evt could not be
66/// deserialized.
67class InvalidParams : public llvm::ErrorInfo<InvalidParams> {
68public:
69 static char ID;
70
71 explicit InvalidParams(std::string method, std::string context)
72 : m_method(std::move(method)), m_context(std::move(context)) {}
73
74 void log(llvm::raw_ostream &OS) const override;
75 std::error_code convertToErrorCode() const override;
76
77private:
78 /// The JSONRPC remote method call.
79 std::string m_method;
80
81 /// Additional context from the parsing failure, e.g. "missing value at
82 /// (root)[1].str".
83 std::string m_context;
84};
85
86/// An error to indicate that no handler was registered for a given method.
87class MethodNotFound : public llvm::ErrorInfo<MethodNotFound> {
88public:
89 static char ID;
90
91 static constexpr int kErrorCode = -32601;
92
93 explicit MethodNotFound(std::string method) : m_method(std::move(method)) {}
94
95 void log(llvm::raw_ostream &OS) const override;
96 std::error_code convertToErrorCode() const override;
97
98private:
99 std::string m_method;
100};
101
102#if __cplusplus >= 202002L
103/// A ProtocolDescriptor details the types used in a JSONTransport for handling
104/// transport communication.
105template <typename T>
106concept ProtocolDescriptor = requires {
107 typename T::Id;
108 typename T::Req;
109 typename T::Resp;
110 typename T::Evt;
111};
112#endif
113
114/// A transport is responsible for maintaining the connection to a client
115/// application, and reading/writing structured messages to it.
116///
117/// JSONTransport have limited thread safety requirements:
118/// - Messages will not be sent concurrently.
119/// - Messages MAY be sent while Run() is reading, or its callback is active.
120///
121#if __cplusplus >= 202002L
122template <ProtocolDescriptor Proto>
123#else
124template <typename Proto>
125#endif
127public:
128 using Req = typename Proto::Req;
129 using Resp = typename Proto::Resp;
130 using Evt = typename Proto::Evt;
131 using Message = std::variant<Req, Resp, Evt>;
132
133 virtual ~JSONTransport() = default;
134
135 /// Sends an event, a message that does not require a response.
136 virtual llvm::Error Send(const Evt &) = 0;
137 /// Sends a request, a message that expects a response.
138 virtual llvm::Error Send(const Req &) = 0;
139 /// Sends a response to a specific request.
140 virtual llvm::Error Send(const Resp &) = 0;
141
142 /// Implemented to handle incoming messages. (See `RegisterMessageHandler()`
143 /// below).
145 public:
146 virtual ~MessageHandler() = default;
147 /// Called when an event is received.
148 virtual void Received(const Evt &) = 0;
149 /// Called when a request is received.
150 virtual void Received(const Req &) = 0;
151 /// Called when a response is received.
152 virtual void Received(const Resp &) = 0;
153
154 /// Called when an error occurs while reading from the transport.
155 ///
156 /// NOTE: This does *NOT* indicate that a specific request failed, but that
157 /// there was an error in the underlying transport.
158 virtual void OnError(llvm::Error) = 0;
159
160 /// Called on EOF or client disconnect.
161 virtual void OnClosed() = 0;
162 };
163
164 /// RegisterMessageHandler registers the Transport with the given MainLoop and
165 /// handles any incoming messages using the given MessageHandler.
166 ///
167 /// If an unexpected error occurs, the MainLoop will be terminated and a log
168 /// message will include additional information about the termination reason.
169 virtual llvm::Error RegisterMessageHandler(MessageHandler &handler) = 0;
170
171protected:
172 template <typename... Ts> inline auto Logv(const char *Fmt, Ts &&...Vals) {
173 Log(llvm::formatv(Fmt, std::forward<Ts>(Vals)...).str());
174 }
175 virtual void Log(llvm::StringRef message) = 0;
176};
177
178/// An IOTransport sends and receives messages using an IOObject.
179template <typename Proto> class IOTransport : public JSONTransport<Proto> {
180public:
183
185 : m_loop(loop), m_in(in), m_out(out) {}
186
187 llvm::Error Send(const typename Proto::Evt &evt) override {
188 return Write(evt);
189 }
190
191 llvm::Error Send(const typename Proto::Req &req) override {
192 return Write(req);
193 }
194
195 llvm::Error Send(const typename Proto::Resp &resp) override {
196 return Write(resp);
197 }
198
199 llvm::Error RegisterMessageHandler(MessageHandler &handler) override {
200 Status status;
201 m_read_handle = m_loop.RegisterReadObject(
202 m_in, [this, &handler](MainLoopBase &base) { OnRead(base, handler); },
203 status);
204 return status.takeError();
205 }
206
207 /// Public for testing purposes, otherwise this should be an implementation
208 /// detail.
209 static constexpr size_t kReadBufferSize = 1024;
210
211protected:
212 llvm::Error Write(const llvm::json::Value &message) {
213 this->Logv("<-- {0}", message);
214 std::string output = Encode(message);
215 size_t bytes_written = output.size();
216 return m_out->Write(output.data(), bytes_written).takeError();
217 }
218
219 virtual llvm::Expected<std::vector<std::string>> Parse() = 0;
220 virtual std::string Encode(const llvm::json::Value &message) = 0;
221
222 llvm::SmallString<kReadBufferSize> m_buffer;
223
224private:
225 void OnRead(MainLoopBase &loop, MessageHandler &handler) {
226 char buf[kReadBufferSize];
227 size_t num_bytes = sizeof(buf);
228 if (Status status = m_in->Read(buf, num_bytes); status.Fail()) {
229 handler.OnError(status.takeError());
230 return;
231 }
232
233 if (num_bytes)
234 m_buffer.append(llvm::StringRef(buf, num_bytes));
235
236 // If the buffer has contents, try parsing any pending messages.
237 if (!m_buffer.empty()) {
238 llvm::Expected<std::vector<std::string>> raw_messages = Parse();
239 if (llvm::Error error = raw_messages.takeError()) {
240 handler.OnError(std::move(error));
241 return;
242 }
243
244 for (const std::string &raw_message : *raw_messages) {
245 llvm::Expected<Message> message =
246 llvm::json::parse<Message>(raw_message);
247 if (!message) {
248 handler.OnError(message.takeError());
249 return;
250 }
251
252 std::visit([&handler](auto &&msg) { handler.Received(msg); }, *message);
253 }
254 }
255
256 // Check if we reached EOF.
257 if (num_bytes == 0) {
258 // EOF reached, but there may still be unhandled contents in the buffer.
259 if (!m_buffer.empty())
260 handler.OnError(llvm::make_error<TransportUnhandledContentsError>(
261 std::string(m_buffer.str())));
262 handler.OnClosed();
263 // On EOF, remove the read handle from the MainLoop.
264 m_read_handle.reset();
265 }
266 }
267
272};
273
274/// A transport class for JSON with a HTTP header.
275#if __cplusplus >= 202002L
276template <ProtocolDescriptor Proto>
277#else
278template <typename Proto>
279#endif
281public:
282 using IOTransport<Proto>::IOTransport;
283
284protected:
285 /// Encodes messages based on
286 /// https://microsoft.github.io/debug-adapter-protocol/overview#base-protocol
287 std::string Encode(const llvm::json::Value &message) override {
288 std::string output;
289 std::string raw_message = llvm::formatv("{0}", message).str();
290 llvm::raw_string_ostream OS(output);
292 << std::to_string(raw_message.size()) << kEndOfHeader << raw_message;
293 return output;
294 }
295
296 /// Parses messages based on
297 /// https://microsoft.github.io/debug-adapter-protocol/overview#base-protocol
298 llvm::Expected<std::vector<std::string>> Parse() override {
299 std::vector<std::string> messages;
300 llvm::StringRef buffer = this->m_buffer;
301 while (buffer.contains(kEndOfHeader)) {
302 auto [headers, rest] = buffer.split(kEndOfHeader);
303 size_t content_length = 0;
304 // HTTP Headers are formatted like `<field-name> ':' [<field-value>]`.
305 for (const llvm::StringRef &header :
306 llvm::split(headers, kHeaderSeparator)) {
307 auto [key, value] = header.split(kHeaderFieldSeparator);
308 // 'Content-Length' is the only meaningful key at the moment. Others
309 // are ignored.
310 if (!key.equals_insensitive(kHeaderContentLength))
311 continue;
312
313 value = value.trim();
314 if (!llvm::to_integer(value, content_length, 10)) {
315 // Clear the buffer to avoid re-parsing this malformed message.
316 this->m_buffer.clear();
317 return llvm::createStringError(std::errc::invalid_argument,
318 "invalid content length: %s",
319 value.str().c_str());
320 }
321 }
322
323 // Check if we have enough data.
324 if (content_length > rest.size())
325 break;
326
327 llvm::StringRef body = rest.take_front(content_length);
328 buffer = rest.drop_front(content_length);
329 messages.emplace_back(body.str());
330 this->Logv("--> {0}", body);
331 }
332
333 // Store the remainder of the buffer for the next read callback.
334 this->m_buffer = buffer.str();
335
336 return std::move(messages);
337 }
338
339 static constexpr llvm::StringLiteral kHeaderContentLength = "Content-Length";
340 static constexpr llvm::StringLiteral kHeaderFieldSeparator = ":";
341 static constexpr llvm::StringLiteral kHeaderSeparator = "\r\n";
342 static constexpr llvm::StringLiteral kEndOfHeader = "\r\n\r\n";
343};
344
345/// A transport class for JSON RPC.
346#if __cplusplus >= 202002L
347template <ProtocolDescriptor Proto>
348#else
349template <typename Proto>
350#endif
351class JSONRPCTransport : public IOTransport<Proto> {
352public:
353 using IOTransport<Proto>::IOTransport;
354
355protected:
356 std::string Encode(const llvm::json::Value &message) override {
357 return llvm::formatv("{0}{1}", message, kMessageSeparator).str();
358 }
359
360 llvm::Expected<std::vector<std::string>> Parse() override {
361 std::vector<std::string> messages;
362 llvm::StringRef buf = this->m_buffer;
363 while (buf.contains(kMessageSeparator)) {
364 auto [raw_json, rest] = buf.split(kMessageSeparator);
365 buf = rest;
366 messages.emplace_back(raw_json.str());
367 this->Logv("--> {0}", raw_json);
368 }
369
370 // Store the remainder of the buffer for the next read callback.
371 this->m_buffer = buf.str();
372
373 return messages;
374 }
375
376 static constexpr llvm::StringLiteral kMessageSeparator = "\n";
377};
378
379/// A handler for the response to an outgoing request.
380template <typename T>
381using Reply =
382 std::conditional_t<std::is_void_v<T>,
383 llvm::unique_function<void(llvm::Error)>,
384 llvm::unique_function<void(llvm::Expected<T>)>>;
385
386namespace detail {
387template <typename R, typename P> struct request_t final {
388 using type = llvm::unique_function<void(const P &, Reply<R>)>;
389};
390template <typename R> struct request_t<R, void> final {
391 using type = llvm::unique_function<void(Reply<R>)>;
392};
393template <typename P> struct event_t final {
394 using type = llvm::unique_function<void(const P &)>;
395};
396template <> struct event_t<void> final {
397 using type = llvm::unique_function<void()>;
398};
399} // namespace detail
400
401template <typename R, typename P>
403
404/// A function to send an outgoing event.
405template <typename P> using OutgoingEvent = typename detail::event_t<P>::type;
406
407#if __cplusplus >= 202002L
408/// This represents a protocol description that includes additional helpers
409/// for constructing requests, responses and events to work with `Binder`.
410template <typename T>
411concept BindingBuilder =
412 ProtocolDescriptor<T> &&
413 requires(T::Id id, T::Req req, T::Resp resp, T::Evt evt,
414 llvm::StringRef method, std::optional<llvm::json::Value> params,
415 std::optional<llvm::json::Value> result, llvm::Error err) {
416 /// For initializing the unique sequence identifier;
417 { T::InitialId() } -> std::same_as<typename T::Id>;
418 /// Incrementing the sequence identifier.
419 { id++ } -> std::same_as<typename T::Id>;
420
421 /// Constructing protocol types
422 /// @{
423 /// Construct a new request.
424 { T::Make(id, method, params) } -> std::same_as<typename T::Req>;
425 /// Construct a new error response.
426 { T::Make(req, std::move(err)) } -> std::same_as<typename T::Resp>;
427 /// Construct a new success response.
428 { T::Make(req, result) } -> std::same_as<typename T::Resp>;
429 /// Construct a new event.
430 { T::Make(method, params) } -> std::same_as<typename T::Evt>;
431 /// @}
432
433 /// Keys for associated types.
434 /// @{
435 /// Looking up in flight responses.
436 { T::KeyFor(resp) } -> std::same_as<typename T::Id>;
437 /// Extract method from request.
438 { T::KeyFor(req) } -> std::same_as<std::string>;
439 /// Extract method from event.
440 { T::KeyFor(evt) } -> std::same_as<std::string>;
441 /// @}
442
443 /// Extracting information from associated types.
444 /// @{
445 /// Extract parameters from a request.
446 { T::Extract(req) } -> std::same_as<std::optional<llvm::json::Value>>;
447 /// Extract result from a response.
448 { T::Extract(resp) } -> std::same_as<llvm::Expected<llvm::json::Value>>;
449 /// Extract parameters from an event.
450 { T::Extract(evt) } -> std::same_as<std::optional<llvm::json::Value>>;
451 /// @}
452 };
453#endif
454
455/// Binder collects a table of functions that handle calls.
456///
457/// The wrapper takes care of parsing/serializing responses.
458///
459/// This allows a JSONTransport to handle incoming and outgoing requests and
460/// events.
461///
462/// A bind of an incoming request to a lambda.
463/// \code{cpp}
464/// Binder binder{transport};
465/// binder.bind<int, vector<int>>("adder", [](const vector<int> &params) {
466/// int sum = 0;
467/// for (int v : params)
468/// sum += v;
469/// return sum;
470/// });
471/// \endcode
472///
473/// A bind of an outgoing request.
474/// \code{cpp}
475/// OutgoingRequest<int, vector<int>> call_add =
476/// binder.bind<int, vector<int>>("add");
477/// call_add({1,2,3}, [](Expected<int> result) {
478/// cout << *result << "\n";
479/// });
480/// \endcode
481#if __cplusplus >= 202002L
482template <BindingBuilder Proto>
483#else
484template <typename Proto>
485#endif
487 using Req = typename Proto::Req;
488 using Resp = typename Proto::Resp;
489 using Evt = typename Proto::Evt;
490 using Id = typename Proto::Id;
493
494public:
496
497 Binder(const Binder &) = delete;
498 Binder &operator=(const Binder &) = delete;
499
500 /// Bind a handler on transport disconnect.
501 template <typename Fn, typename... Args>
502 void OnDisconnect(Fn &&fn, Args &&...args);
503
504 /// Bind a handler on error when communicating with the transport.
505 template <typename Fn, typename... Args>
506 void OnError(Fn &&fn, Args &&...args);
507
508 /// Bind a handler for an incoming request.
509 /// e.g. `bind("peek", &ThisModule::peek, this);`.
510 /// Handler should be e.g. `Expected<PeekResult> peek(const PeekParams&);`
511 /// PeekParams must be JSON parsable and PeekResult must be serializable.
512 template <typename Result, typename Params, typename Fn, typename... Args>
513 void Bind(llvm::StringLiteral method, Fn &&fn, Args &&...args);
514
515 /// Bind a handler for an incoming event.
516 /// e.g. `bind("peek", &ThisModule::peek, this);`
517 /// Handler should be e.g. `void peek(const PeekParams&);`
518 /// PeekParams must be JSON parsable.
519 template <typename Params, typename Fn, typename... Args>
520 void Bind(llvm::StringLiteral method, Fn &&fn, Args &&...args);
521
522 /// Bind a function object to be used for outgoing requests.
523 /// e.g. `OutgoingRequest<Params, Result> Edit = bind("edit");`
524 /// Params must be JSON-serializable, Result must be parsable.
525 template <typename Result, typename Params>
526 OutgoingRequest<Result, Params> Bind(llvm::StringLiteral method);
527
528 /// Bind a function object to be used for outgoing events.
529 /// e.g. `OutgoingEvent<LogParams> Log = bind("log");`
530 /// LogParams must be JSON-serializable.
531 template <typename Params>
532 OutgoingEvent<Params> Bind(llvm::StringLiteral method);
533
534 void Received(const Evt &evt) override {
535 std::scoped_lock<std::recursive_mutex> guard(m_mutex);
536 auto it = m_event_handlers.find(Proto::KeyFor(evt));
537 if (it == m_event_handlers.end()) {
538 OnError(llvm::createStringError(
539 llvm::formatv("no handled for event {0}", toJSON(evt))));
540 return;
541 }
542 it->second(evt);
543 }
544
545 void Received(const Req &req) override {
546 ReplyOnce reply(req, &m_transport, this);
547
548 std::scoped_lock<std::recursive_mutex> guard(m_mutex);
549 auto it = m_request_handlers.find(Proto::KeyFor(req));
550 if (it == m_request_handlers.end()) {
551 reply(Proto::Make(req, llvm::createStringError("method not found")));
552 return;
553 }
554
555 it->second(req, std::move(reply));
556 }
557
558 void Received(const Resp &resp) override {
559 std::scoped_lock<std::recursive_mutex> guard(m_mutex);
560
561 Id id = Proto::KeyFor(resp);
562 auto it = m_pending_responses.find(id);
563 if (it == m_pending_responses.end()) {
564 OnError(llvm::createStringError(
565 llvm::formatv("no pending request for {0}", toJSON(resp))));
566 return;
567 }
568
569 it->second(resp);
570 m_pending_responses.erase(it);
571 }
572
573 void OnError(llvm::Error err) override {
574 std::scoped_lock<std::recursive_mutex> guard(m_mutex);
575 if (m_error_handler)
576 m_error_handler(std::move(err));
577 }
578
579 void OnClosed() override {
580 std::scoped_lock<std::recursive_mutex> guard(m_mutex);
583 }
584
585private:
586 template <typename T>
587 llvm::Expected<T> static Parse(const llvm::json::Value &raw,
588 llvm::StringRef method);
589
590 template <typename T> using Callback = llvm::unique_function<T>;
591
592 std::recursive_mutex m_mutex;
595 std::map<Id, Callback<void(const Resp &)>> m_pending_responses;
596 llvm::StringMap<Callback<void(const Req &, Callback<void(const Resp &)>)>>
598 llvm::StringMap<Callback<void(const Evt &)>> m_event_handlers;
600 Callback<void(llvm::Error)> m_error_handler;
601
602 /// Function object to reply to a call.
603 /// Each instance must be called exactly once, otherwise:
604 /// - the bug is logged, and (in debug mode) an assert will fire
605 /// - if there was no reply, an error reply is sent
606 /// - if there were multiple replies, only the first is sent
607 class ReplyOnce {
608 std::atomic<bool> replied = {false};
609 const Req req;
610 Transport *transport; // Null when moved-from.
611 MessageHandler *handler; // Null when moved-from.
612
613 public:
619 : replied(other.replied.load()), req(other.req),
620 transport(other.transport), handler(other.handler) {
621 other.transport = nullptr;
622 other.handler = nullptr;
623 }
625 ReplyOnce(const ReplyOnce &) = delete;
626 ReplyOnce &operator=(const ReplyOnce &) = delete;
627
629 if (transport && handler && !replied) {
630 assert(false && "must reply to all calls!");
631 (*this)(Proto::Make(req, llvm::createStringError("failed to reply")));
632 }
633 }
634
635 void operator()(const Resp &resp) {
636 assert(transport && handler && "moved-from!");
637 if (replied.exchange(true)) {
638 assert(false && "must reply to each call only once!");
639 return;
640 }
641
642 if (llvm::Error error = transport->Send(resp))
643 handler->OnError(std::move(error));
644 }
645 };
646};
647
648#if __cplusplus >= 202002L
649template <BindingBuilder Proto>
650#else
651template <typename Proto>
652#endif
653template <typename Fn, typename... Args>
654void Binder<Proto>::OnDisconnect(Fn &&fn, Args &&...args) {
655 m_disconnect_handler = [fn, args...]() mutable {
656 std::invoke(std::forward<Fn>(fn), std::forward<Args>(args)...);
657 };
658}
659
660#if __cplusplus >= 202002L
661template <BindingBuilder Proto>
662#else
663template <typename Proto>
664#endif
665template <typename Fn, typename... Args>
666void Binder<Proto>::OnError(Fn &&fn, Args &&...args) {
667 m_error_handler = [fn, args...](llvm::Error error) mutable {
668 std::invoke(std::forward<Fn>(fn), std::forward<Args>(args)...,
669 std::move(error));
670 };
671}
672
673#if __cplusplus >= 202002L
674template <BindingBuilder Proto>
675#else
676template <typename Proto>
677#endif
678template <typename Result, typename Params, typename Fn, typename... Args>
679void Binder<Proto>::Bind(llvm::StringLiteral method, Fn &&fn, Args &&...args) {
680 assert(m_request_handlers.find(method) == m_request_handlers.end() &&
681 "request already bound");
682 if constexpr (std::is_void_v<Result> && std::is_void_v<Params>) {
683 m_request_handlers[method] =
684 [fn, args...](const Req &req,
685 llvm::unique_function<void(const Resp &)> reply) mutable {
686 llvm::Error result =
687 std::invoke(std::forward<Fn>(fn), std::forward<Args>(args)...);
688 reply(Proto::Make(req, std::move(result)));
689 };
690 } else if constexpr (std::is_void_v<Params>) {
691 m_request_handlers[method] =
692 [fn, args...](const Req &req,
693 llvm::unique_function<void(const Resp &)> reply) mutable {
694 llvm::Expected<Result> result =
695 std::invoke(std::forward<Fn>(fn), std::forward<Args>(args)...);
696 if (!result)
697 return reply(Proto::Make(req, result.takeError()));
698 reply(Proto::Make(req, toJSON(*result)));
699 };
700 } else if constexpr (std::is_void_v<Result>) {
701 m_request_handlers[method] =
702 [method, fn,
703 args...](const Req &req,
704 llvm::unique_function<void(const Resp &)> reply) mutable {
705 llvm::Expected<Params> params =
706 Parse<Params>(Proto::Extract(req), method);
707 if (!params)
708 return reply(Proto::Make(req, params.takeError()));
709
710 llvm::Error result = std::invoke(
711 std::forward<Fn>(fn), std::forward<Args>(args)..., *params);
712 reply(Proto::Make(req, std::move(result)));
713 };
714 } else {
715 m_request_handlers[method] =
716 [method, fn,
717 args...](const Req &req,
718 llvm::unique_function<void(const Resp &)> reply) mutable {
719 llvm::Expected<Params> params =
720 Parse<Params>(Proto::Extract(req), method);
721 if (!params)
722 return reply(Proto::Make(req, params.takeError()));
723
724 llvm::Expected<Result> result = std::invoke(
725 std::forward<Fn>(fn), std::forward<Args>(args)..., *params);
726 if (!result)
727 return reply(Proto::Make(req, result.takeError()));
728
729 reply(Proto::Make(req, toJSON(*result)));
730 };
731 }
732}
733
734#if __cplusplus >= 202002L
735template <BindingBuilder Proto>
736#else
737template <typename Proto>
738#endif
739template <typename Params, typename Fn, typename... Args>
740void Binder<Proto>::Bind(llvm::StringLiteral method, Fn &&fn, Args &&...args) {
741 assert(m_event_handlers.find(method) == m_event_handlers.end() &&
742 "event already bound");
743 if constexpr (std::is_void_v<Params>) {
744 m_event_handlers[method] = [fn, args...](const Evt &) mutable {
745 std::invoke(std::forward<Fn>(fn), std::forward<Args>(args)...);
746 };
747 } else {
748 m_event_handlers[method] = [this, method, fn,
749 args...](const Evt &evt) mutable {
750 llvm::Expected<Params> params =
751 Parse<Params>(Proto::Extract(evt), method);
752 if (!params)
753 return OnError(params.takeError());
754 std::invoke(std::forward<Fn>(fn), std::forward<Args>(args)..., *params);
755 };
756 }
757}
758
759#if __cplusplus >= 202002L
760template <BindingBuilder Proto>
761#else
762template <typename Proto>
763#endif
764template <typename Result, typename Params>
766Binder<Proto>::Bind(llvm::StringLiteral method) {
767 if constexpr (std::is_void_v<Result> && std::is_void_v<Params>) {
768 return [this, method](Reply<Result> fn) {
769 std::scoped_lock<std::recursive_mutex> guard(m_mutex);
770 Id id = ++m_seq;
771 Req req = Proto::Make(id, method, std::nullopt);
772 m_pending_responses[id] = [fn = std::move(fn)](const Resp &resp) mutable {
773 llvm::Expected<llvm::json::Value> result = Proto::Extract(resp);
774 if (!result)
775 return fn(result.takeError());
776 fn(llvm::Error::success());
777 };
778 if (llvm::Error error = m_transport.Send(req))
779 OnError(std::move(error));
780 };
781 } else if constexpr (std::is_void_v<Params>) {
782 return [this, method](Reply<Result> fn) {
783 std::scoped_lock<std::recursive_mutex> guard(m_mutex);
784 Id id = ++m_seq;
785 Req req = Proto::Make(id, method, std::nullopt);
786 m_pending_responses[id] = [fn = std::move(fn),
787 method](const Resp &resp) mutable {
788 llvm::Expected<llvm::json::Value> result = Proto::Extract(resp);
789 if (!result)
790 return fn(result.takeError());
791 fn(Parse<Result>(*result, method));
792 };
793 if (llvm::Error error = m_transport.Send(req))
794 OnError(std::move(error));
795 };
796 } else if constexpr (std::is_void_v<Result>) {
797 return [this, method](const Params &params, Reply<Result> fn) {
798 std::scoped_lock<std::recursive_mutex> guard(m_mutex);
799 Id id = ++m_seq;
800 Req req = Proto::Make(id, method, llvm::json::Value(params));
801 m_pending_responses[id] = [fn = std::move(fn)](const Resp &resp) mutable {
802 llvm::Expected<llvm::json::Value> result = Proto::Extract(resp);
803 if (!result)
804 return fn(result.takeError());
805 fn(llvm::Error::success());
806 };
807 if (llvm::Error error = m_transport.Send(req))
808 OnError(std::move(error));
809 };
810 } else {
811 return [this, method](const Params &params, Reply<Result> fn) {
812 std::scoped_lock<std::recursive_mutex> guard(m_mutex);
813 Id id = ++m_seq;
814 Req req = Proto::Make(id, method, llvm::json::Value(params));
815 m_pending_responses[id] = [fn = std::move(fn),
816 method](const Resp &resp) mutable {
817 llvm::Expected<llvm::json::Value> result = Proto::Extract(resp);
818 if (llvm::Error err = result.takeError())
819 return fn(std::move(err));
820 fn(Parse<Result>(*result, method));
821 };
822 if (llvm::Error error = m_transport.Send(req))
823 OnError(std::move(error));
824 };
825 }
826}
827
828#if __cplusplus >= 202002L
829template <BindingBuilder Proto>
830#else
831template <typename Proto>
832#endif
833template <typename Params>
834OutgoingEvent<Params> Binder<Proto>::Bind(llvm::StringLiteral method) {
835 if constexpr (std::is_void_v<Params>) {
836 return [this, method]() {
837 if (llvm::Error error =
838 m_transport.Send(Proto::Make(method, std::nullopt)))
839 OnError(std::move(error));
840 };
841 } else {
842 return [this, method](const Params &params) {
843 if (llvm::Error error =
844 m_transport.Send(Proto::Make(method, toJSON(params))))
845 OnError(std::move(error));
846 };
847 }
848}
849
850#if __cplusplus >= 202002L
851template <BindingBuilder Proto>
852#else
853template <typename Proto>
854#endif
855template <typename T>
856llvm::Expected<T> Binder<Proto>::Parse(const llvm::json::Value &raw,
857 llvm::StringRef method) {
858 T result;
859 llvm::json::Path::Root root;
860 if (!fromJSON(raw, result, root)) {
861 // Dump the relevant parts of the broken message.
862 std::string context;
863 llvm::raw_string_ostream OS(context);
864 root.printErrorContext(raw, OS);
865 return llvm::make_error<InvalidParams>(method.str(), context);
866 }
867 return std::move(result);
868}
869
870} // namespace lldb_private::transport
871
872#endif
static llvm::raw_ostream & error(Stream &strm)
A command line argument class.
Definition Args.h:33
std::unique_ptr< ReadHandle > ReadHandleUP
An error handling class.
Definition Status.h:118
llvm::Error takeError()
Definition Status.h:170
ReplyOnce & operator=(const ReplyOnce &)=delete
ReplyOnce(const Req req, Transport *transport, MessageHandler *handler)
ReplyOnce & operator=(ReplyOnce &&)=delete
void Received(const Resp &resp) override
Called when a response is received.
JSONTransport< Proto > Transport
typename Transport::MessageHandler MessageHandler
void OnDisconnect(Fn &&fn, Args &&...args)
Bind a handler on transport disconnect.
void Bind(llvm::StringLiteral method, Fn &&fn, Args &&...args)
Bind a handler for an incoming request.
void Bind(llvm::StringLiteral method, Fn &&fn, Args &&...args)
Bind a handler for an incoming event.
llvm::StringMap< Callback< void(const Req &, Callback< void(const Resp &)>)> > m_request_handlers
void OnClosed() override
Called on EOF or client disconnect.
void OnError(Fn &&fn, Args &&...args)
Bind a handler on error when communicating with the transport.
void Received(const Evt &evt) override
Called when an event is received.
OutgoingRequest< Result, Params > Bind(llvm::StringLiteral method)
Bind a function object to be used for outgoing requests.
std::map< Id, Callback< void(const Resp &)> > m_pending_responses
Binder & operator=(const Binder &)=delete
Binder(Transport &transport)
void Received(const Req &req) override
Called when a request is received.
static llvm::Expected< T > Parse(const llvm::json::Value &raw, llvm::StringRef method)
OutgoingEvent< Params > Bind(llvm::StringLiteral method)
Bind a function object to be used for outgoing events.
Binder(const Binder &)=delete
void OnError(llvm::Error err) override
Called when an error occurs while reading from the transport.
llvm::unique_function< T > Callback
llvm::StringMap< Callback< void(const Evt &)> > m_event_handlers
A transport class for JSON with a HTTP header.
static constexpr llvm::StringLiteral kHeaderFieldSeparator
static constexpr llvm::StringLiteral kEndOfHeader
static constexpr llvm::StringLiteral kHeaderSeparator
std::string Encode(const llvm::json::Value &message) override
Encodes messages based on https://microsoft.github.io/debug-adapter-protocol/overview#base-protocol.
llvm::Expected< std::vector< std::string > > Parse() override
Parses messages based on https://microsoft.github.io/debug-adapter-protocol/overview#base-protocol.
static constexpr llvm::StringLiteral kHeaderContentLength
void OnRead(MainLoopBase &loop, MessageHandler &handler)
IOTransport(MainLoop &loop, lldb::IOObjectSP in, lldb::IOObjectSP out)
static constexpr size_t kReadBufferSize
Public for testing purposes, otherwise this should be an implementation detail.
typename JSONTransport< Proto >::MessageHandler MessageHandler
llvm::Error Send(const typename Proto::Resp &resp) override
typename JSONTransport< Proto >::Message Message
llvm::Error Send(const typename Proto::Evt &evt) override
virtual std::string Encode(const llvm::json::Value &message)=0
virtual llvm::Expected< std::vector< std::string > > Parse()=0
MainLoop::ReadHandleUP m_read_handle
llvm::Error Write(const llvm::json::Value &message)
llvm::Error Send(const typename Proto::Req &req) override
llvm::SmallString< kReadBufferSize > m_buffer
llvm::Error RegisterMessageHandler(MessageHandler &handler) override
RegisterMessageHandler registers the Transport with the given MainLoop and handles any incoming messa...
std::error_code convertToErrorCode() const override
std::string m_context
Additional context from the parsing failure, e.g.
InvalidParams(std::string method, std::string context)
std::string m_method
The JSONRPC remote method call.
void log(llvm::raw_ostream &OS) const override
A transport class for JSON RPC.
llvm::Expected< std::vector< std::string > > Parse() override
static constexpr llvm::StringLiteral kMessageSeparator
std::string Encode(const llvm::json::Value &message) override
Implemented to handle incoming messages.
virtual void OnError(llvm::Error)=0
Called when an error occurs while reading from the transport.
virtual void OnClosed()=0
Called on EOF or client disconnect.
virtual void Received(const Req &)=0
Called when a request is received.
virtual void Received(const Evt &)=0
Called when an event is received.
virtual void Received(const Resp &)=0
Called when a response is received.
A transport is responsible for maintaining the connection to a client application,...
virtual llvm::Error Send(const Resp &)=0
Sends a response to a specific request.
std::variant< Req, Resp, Evt > Message
virtual llvm::Error Send(const Evt &)=0
Sends an event, a message that does not require a response.
virtual llvm::Error RegisterMessageHandler(MessageHandler &handler)=0
RegisterMessageHandler registers the Transport with the given MainLoop and handles any incoming messa...
auto Logv(const char *Fmt, Ts &&...Vals)
virtual llvm::Error Send(const Req &)=0
Sends a request, a message that expects a response.
virtual void Log(llvm::StringRef message)=0
std::error_code convertToErrorCode() const override
void log(llvm::raw_ostream &OS) const override
void log(llvm::raw_ostream &OS) const override
TransportUnhandledContentsError(std::string unhandled_contents)
std::conditional_t< std::is_void_v< T >, llvm::unique_function< void(llvm::Error)>, llvm::unique_function< void(llvm::Expected< T >)> > Reply
A handler for the response to an outgoing request.
typename detail::event_t< P >::type OutgoingEvent
A function to send an outgoing event.
typename detail::request_t< R, P >::type OutgoingRequest
bool fromJSON(const llvm::json::Value &value, TraceSupportedResponse &info, llvm::json::Path path)
MainLoopPosix MainLoop
Definition MainLoop.h:20
llvm::json::Value toJSON(const TraceSupportedResponse &packet)
std::shared_ptr< lldb_private::IOObject > IOObjectSP
llvm::unique_function< void(const P &)> type
llvm::unique_function< void(Reply< R >)> type
llvm::unique_function< void(const P &, Reply< R >)> type