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 static constexpr int kErrorCode = -32602;
72
73 explicit InvalidParams(std::string method, std::string context)
74 : m_method(std::move(method)), m_context(std::move(context)) {}
75
76 void log(llvm::raw_ostream &OS) const override;
77 std::error_code convertToErrorCode() const override;
78
79private:
80 /// The JSONRPC remote method call.
81 std::string m_method;
82
83 /// Additional context from the parsing failure, e.g. "missing value at
84 /// (root)[1].str".
85 std::string m_context;
86};
87
88/// An error to indicate that an incoming message could not be parsed as a
89/// valid protocol message.
90class InvalidMessage : public llvm::ErrorInfo<InvalidMessage> {
91public:
92 static char ID;
93
94 static constexpr int kErrorCode = -32700;
95
96 explicit InvalidMessage(std::string raw_message, std::string reason)
97 : m_raw_message(std::move(raw_message)), m_reason(std::move(reason)) {}
98
99 void log(llvm::raw_ostream &OS) const override;
100 std::error_code convertToErrorCode() const override;
101
102private:
103 std::string m_raw_message;
104 std::string m_reason;
105};
106
107/// An error to indicate that no handler was registered for a given method.
108class MethodNotFound : public llvm::ErrorInfo<MethodNotFound> {
109public:
110 static char ID;
111
112 static constexpr int kErrorCode = -32601;
113
114 explicit MethodNotFound(std::string method) : m_method(std::move(method)) {}
115
116 void log(llvm::raw_ostream &OS) const override;
117 std::error_code convertToErrorCode() const override;
118
119private:
120 std::string m_method;
121};
122
123#if __cplusplus >= 202002L
124/// A ProtocolDescriptor details the types used in a JSONTransport for handling
125/// transport communication.
126template <typename T>
127concept ProtocolDescriptor = requires {
128 typename T::Id;
129 typename T::Req;
130 typename T::Resp;
131 typename T::Evt;
132};
133#endif
134
135/// A transport is responsible for maintaining the connection to a client
136/// application, and reading/writing structured messages to it.
137///
138/// JSONTransport have limited thread safety requirements:
139/// - Messages will not be sent concurrently.
140/// - Messages MAY be sent while Run() is reading, or its callback is active.
141///
142#if __cplusplus >= 202002L
143template <ProtocolDescriptor Proto>
144#else
145template <typename Proto>
146#endif
148public:
149 using Req = typename Proto::Req;
150 using Resp = typename Proto::Resp;
151 using Evt = typename Proto::Evt;
152 using Message = std::variant<Req, Resp, Evt>;
153
154 virtual ~JSONTransport() = default;
155
156 /// Sends an event, a message that does not require a response.
157 virtual llvm::Error Send(const Evt &) = 0;
158 /// Sends a request, a message that expects a response.
159 virtual llvm::Error Send(const Req &) = 0;
160 /// Sends a response to a specific request.
161 virtual llvm::Error Send(const Resp &) = 0;
162
163 /// Sends an error response for a message that failed to parse, described by
164 /// \p reason. Sends nothing if no request id can be recovered from it, since
165 /// there is then no request to respond to.
166 virtual llvm::Error ReplyWithParseError(llvm::StringRef raw_message,
167 llvm::StringRef reason) {
168 return llvm::Error::success();
169 }
170
171 /// Implemented to handle incoming messages. (See `RegisterMessageHandler()`
172 /// below).
174 public:
175 virtual ~MessageHandler() = default;
176 /// Called when an event is received.
177 virtual void Received(const Evt &) = 0;
178 /// Called when a request is received.
179 virtual void Received(const Req &) = 0;
180 /// Called when a response is received.
181 virtual void Received(const Resp &) = 0;
182
183 /// Called when an error occurs while reading from the transport.
184 ///
185 /// NOTE: This does *NOT* indicate that a specific request failed, but that
186 /// there was an error in the underlying transport.
187 virtual void OnError(llvm::Error) = 0;
188
189 /// Called on EOF or client disconnect.
190 virtual void OnClosed() = 0;
191 };
192
193 /// RegisterMessageHandler registers the Transport with the given MainLoop and
194 /// handles any incoming messages using the given MessageHandler.
195 ///
196 /// If an unexpected error occurs, the MainLoop will be terminated and a log
197 /// message will include additional information about the termination reason.
198 virtual llvm::Error RegisterMessageHandler(MessageHandler &handler) = 0;
199
200protected:
201 template <typename... Ts> inline auto Logv(const char *Fmt, Ts &&...Vals) {
202 Log(llvm::formatv(Fmt, std::forward<Ts>(Vals)...).str());
203 }
204 virtual void Log(llvm::StringRef message) = 0;
205};
206
207/// An IOTransport sends and receives messages using an IOObject.
208template <typename Proto> class IOTransport : public JSONTransport<Proto> {
209public:
212
214 : m_loop(loop), m_in(in), m_out(out) {}
215
216 llvm::Error Send(const typename Proto::Evt &evt) override {
217 return Write(evt);
218 }
219
220 llvm::Error Send(const typename Proto::Req &req) override {
221 return Write(req);
222 }
223
224 llvm::Error Send(const typename Proto::Resp &resp) override {
225 return Write(resp);
226 }
227
228 llvm::Error RegisterMessageHandler(MessageHandler &handler) override {
229 Status status;
230 m_read_handle = m_loop.RegisterReadObject(
231 m_in, [this, &handler](MainLoopBase &base) { OnRead(base, handler); },
232 status);
233 return status.takeError();
234 }
235
236 /// Public for testing purposes, otherwise this should be an implementation
237 /// detail.
238 static constexpr size_t kReadBufferSize = 1024;
239
240protected:
241 llvm::Error Write(const llvm::json::Value &message) {
242 this->Logv("<-- {0}", message);
243 std::string output = Encode(message);
244 size_t bytes_written = output.size();
245 return m_out->Write(output.data(), bytes_written).takeError();
246 }
247
248 virtual llvm::Expected<std::vector<std::string>> Parse() = 0;
249 virtual std::string Encode(const llvm::json::Value &message) = 0;
250
251 llvm::SmallString<kReadBufferSize> m_buffer;
252
253private:
254 void OnRead(MainLoopBase &loop, MessageHandler &handler) {
255 char buf[kReadBufferSize];
256 size_t num_bytes = sizeof(buf);
257 if (Status status = m_in->Read(buf, num_bytes); status.Fail()) {
258 handler.OnError(status.takeError());
259 return;
260 }
261
262 if (num_bytes)
263 m_buffer.append(llvm::StringRef(buf, num_bytes));
264
265 // If the buffer has contents, try parsing any pending messages.
266 if (!m_buffer.empty()) {
267 llvm::Expected<std::vector<std::string>> raw_messages = Parse();
268 if (llvm::Error error = raw_messages.takeError()) {
269 handler.OnError(std::move(error));
270 return;
271 }
272
273 for (const std::string &raw_message : *raw_messages) {
274 llvm::Expected<Message> message =
275 llvm::json::parse<Message>(raw_message);
276 if (!message) {
277 // Messages are independent, so one that fails to parse must not
278 // discard those already buffered behind it.
279 std::string reason = llvm::toString(message.takeError());
280 if (llvm::Error error =
281 this->ReplyWithParseError(raw_message, reason))
282 handler.OnError(std::move(error));
283 handler.OnError(
284 llvm::make_error<InvalidMessage>(raw_message, std::move(reason)));
285 continue;
286 }
287
288 std::visit([&handler](auto &&msg) { handler.Received(msg); }, *message);
289 }
290 }
291
292 // Check if we reached EOF.
293 if (num_bytes == 0) {
294 // EOF reached, but there may still be unhandled contents in the buffer.
295 if (!m_buffer.empty())
296 handler.OnError(llvm::make_error<TransportUnhandledContentsError>(
297 std::string(m_buffer.str())));
298 // Move the read handle to a local before notifying the handler. The
299 // handler may destroy this transport (e.g. by erasing it from a
300 // connection map), so accessing members after OnClosed() is unsafe.
301 auto read_handle = std::move(m_read_handle);
302 handler.OnClosed();
303 }
304 }
305
310};
311
312/// A transport class for JSON with a HTTP header.
313#if __cplusplus >= 202002L
314template <ProtocolDescriptor Proto>
315#else
316template <typename Proto>
317#endif
319public:
320 using IOTransport<Proto>::IOTransport;
321
322protected:
323 /// Encodes messages based on
324 /// https://microsoft.github.io/debug-adapter-protocol/overview#base-protocol
325 std::string Encode(const llvm::json::Value &message) override {
326 std::string output;
327 std::string raw_message = llvm::formatv("{0}", message).str();
328 llvm::raw_string_ostream OS(output);
330 << std::to_string(raw_message.size()) << kEndOfHeader << raw_message;
331 return output;
332 }
333
334 /// Parses messages based on
335 /// https://microsoft.github.io/debug-adapter-protocol/overview#base-protocol
336 llvm::Expected<std::vector<std::string>> Parse() override {
337 std::vector<std::string> messages;
338 llvm::StringRef buffer = this->m_buffer;
339 while (buffer.contains(kEndOfHeader)) {
340 auto [headers, rest] = buffer.split(kEndOfHeader);
341 size_t content_length = 0;
342 // HTTP Headers are formatted like `<field-name> ':' [<field-value>]`.
343 for (const llvm::StringRef &header :
344 llvm::split(headers, kHeaderSeparator)) {
345 auto [key, value] = header.split(kHeaderFieldSeparator);
346 // 'Content-Length' is the only meaningful key at the moment. Others
347 // are ignored.
348 if (!key.equals_insensitive(kHeaderContentLength))
349 continue;
350
351 value = value.trim();
352 if (!llvm::to_integer(value, content_length, 10)) {
353 // Clear the buffer to avoid re-parsing this malformed message.
354 this->m_buffer.clear();
355 return llvm::createStringError(std::errc::invalid_argument,
356 "invalid content length: %s",
357 value.str().c_str());
358 }
359 }
360
361 // Check if we have enough data.
362 if (content_length > rest.size())
363 break;
364
365 llvm::StringRef body = rest.take_front(content_length);
366 buffer = rest.drop_front(content_length);
367 messages.emplace_back(body.str());
368 this->Logv("--> {0}", body);
369 }
370
371 // Store the remainder of the buffer for the next read callback.
372 this->m_buffer = buffer.str();
373
374 return std::move(messages);
375 }
376
377 static constexpr llvm::StringLiteral kHeaderContentLength = "Content-Length";
378 static constexpr llvm::StringLiteral kHeaderFieldSeparator = ":";
379 static constexpr llvm::StringLiteral kHeaderSeparator = "\r\n";
380 static constexpr llvm::StringLiteral kEndOfHeader = "\r\n\r\n";
381};
382
383/// A transport class for JSON RPC.
384#if __cplusplus >= 202002L
385template <ProtocolDescriptor Proto>
386#else
387template <typename Proto>
388#endif
389class JSONRPCTransport : public IOTransport<Proto> {
390public:
391 using IOTransport<Proto>::IOTransport;
392
393protected:
394 std::string Encode(const llvm::json::Value &message) override {
395 return llvm::formatv("{0}{1}", message, kMessageSeparator).str();
396 }
397
398 llvm::Expected<std::vector<std::string>> Parse() override {
399 std::vector<std::string> messages;
400 llvm::StringRef buf = this->m_buffer;
401 while (buf.contains(kMessageSeparator)) {
402 auto [raw_json, rest] = buf.split(kMessageSeparator);
403 buf = rest;
404 messages.emplace_back(raw_json.str());
405 this->Logv("--> {0}", raw_json);
406 }
407
408 // Store the remainder of the buffer for the next read callback.
409 this->m_buffer = buf.str();
410
411 return messages;
412 }
413
414 static constexpr llvm::StringLiteral kMessageSeparator = "\n";
415};
416
417/// A handler for the response to an outgoing request.
418template <typename T>
419using Reply =
420 std::conditional_t<std::is_void_v<T>,
421 llvm::unique_function<void(llvm::Error)>,
422 llvm::unique_function<void(llvm::Expected<T>)>>;
423
424namespace detail {
425template <typename R, typename P> struct request_t final {
426 using type = llvm::unique_function<void(const P &, Reply<R>)>;
427};
428template <typename R> struct request_t<R, void> final {
429 using type = llvm::unique_function<void(Reply<R>)>;
430};
431template <typename P> struct event_t final {
432 using type = llvm::unique_function<void(const P &)>;
433};
434template <> struct event_t<void> final {
435 using type = llvm::unique_function<void()>;
436};
437} // namespace detail
438
439template <typename R, typename P>
441
442/// A function to send an outgoing event.
443template <typename P> using OutgoingEvent = typename detail::event_t<P>::type;
444
445#if __cplusplus >= 202002L
446/// This represents a protocol description that includes additional helpers
447/// for constructing requests, responses and events to work with `Binder`.
448template <typename T>
449concept BindingBuilder =
450 ProtocolDescriptor<T> &&
451 requires(T::Id id, T::Req req, T::Resp resp, T::Evt evt,
452 llvm::StringRef method, std::optional<llvm::json::Value> params,
453 std::optional<llvm::json::Value> result, llvm::Error err) {
454 /// For initializing the unique sequence identifier;
455 { T::InitialId() } -> std::same_as<typename T::Id>;
456 /// Incrementing the sequence identifier.
457 { id++ } -> std::same_as<typename T::Id>;
458
459 /// Constructing protocol types
460 /// @{
461 /// Construct a new request.
462 { T::Make(id, method, params) } -> std::same_as<typename T::Req>;
463 /// Construct a new error response.
464 { T::Make(req, std::move(err)) } -> std::same_as<typename T::Resp>;
465 /// Construct a new success response.
466 { T::Make(req, result) } -> std::same_as<typename T::Resp>;
467 /// Construct a new event.
468 { T::Make(method, params) } -> std::same_as<typename T::Evt>;
469 /// @}
470
471 /// Keys for associated types.
472 /// @{
473 /// Looking up in flight responses.
474 { T::KeyFor(resp) } -> std::same_as<typename T::Id>;
475 /// Extract method from request.
476 { T::KeyFor(req) } -> std::same_as<std::string>;
477 /// Extract method from event.
478 { T::KeyFor(evt) } -> std::same_as<std::string>;
479 /// @}
480
481 /// Extracting information from associated types.
482 /// @{
483 /// Extract parameters from a request.
484 { T::Extract(req) } -> std::same_as<std::optional<llvm::json::Value>>;
485 /// Extract result from a response.
486 { T::Extract(resp) } -> std::same_as<llvm::Expected<llvm::json::Value>>;
487 /// Extract parameters from an event.
488 { T::Extract(evt) } -> std::same_as<std::optional<llvm::json::Value>>;
489 /// @}
490 };
491#endif
492
493/// Binder collects a table of functions that handle calls.
494///
495/// The wrapper takes care of parsing/serializing responses.
496///
497/// This allows a JSONTransport to handle incoming and outgoing requests and
498/// events.
499///
500/// A bind of an incoming request to a lambda.
501/// \code{cpp}
502/// Binder binder{transport};
503/// binder.bind<int, vector<int>>("adder", [](const vector<int> &params) {
504/// int sum = 0;
505/// for (int v : params)
506/// sum += v;
507/// return sum;
508/// });
509/// \endcode
510///
511/// A bind of an outgoing request.
512/// \code{cpp}
513/// OutgoingRequest<int, vector<int>> call_add =
514/// binder.bind<int, vector<int>>("add");
515/// call_add({1,2,3}, [](Expected<int> result) {
516/// cout << *result << "\n";
517/// });
518/// \endcode
519#if __cplusplus >= 202002L
520template <BindingBuilder Proto>
521#else
522template <typename Proto>
523#endif
525 using Req = typename Proto::Req;
526 using Resp = typename Proto::Resp;
527 using Evt = typename Proto::Evt;
528 using Id = typename Proto::Id;
531
532public:
534
535 Binder(const Binder &) = delete;
536 Binder &operator=(const Binder &) = delete;
537
538 /// Bind a handler on transport disconnect.
539 template <typename Fn, typename... Args>
540 void OnDisconnect(Fn &&fn, Args &&...args);
541
542 /// Bind a handler on error when communicating with the transport.
543 template <typename Fn, typename... Args>
544 void OnError(Fn &&fn, Args &&...args);
545
546 /// Bind a handler for an incoming request.
547 /// e.g. `bind("peek", &ThisModule::peek, this);`.
548 /// Handler should be e.g. `Expected<PeekResult> peek(const PeekParams&);`
549 /// PeekParams must be JSON parsable and PeekResult must be serializable.
550 template <typename Result, typename Params, typename Fn, typename... Args>
551 void Bind(llvm::StringLiteral method, Fn &&fn, Args &&...args);
552
553 /// Bind an asynchronous handler for an incoming request. The handler receives
554 /// a Reply to invoke later instead of returning a result. This lets it defer
555 /// the response, e.g. until a request it forwarded elsewhere is answered.
556 /// Handler should be e.g. `void peek(const PeekParams&, Reply<PeekResult>);`
557 /// PeekParams must be JSON parsable and PeekResult must be serializable.
558 template <typename Result, typename Params, typename Fn, typename... Args>
559 void BindAsync(llvm::StringLiteral method, Fn &&fn, Args &&...args);
560
561 /// Bind a handler for an incoming event.
562 /// e.g. `bind("peek", &ThisModule::peek, this);`
563 /// Handler should be e.g. `void peek(const PeekParams&);`
564 /// PeekParams must be JSON parsable.
565 template <typename Params, typename Fn, typename... Args>
566 void Bind(llvm::StringLiteral method, Fn &&fn, Args &&...args);
567
568 /// Bind a function object to be used for outgoing requests.
569 /// e.g. `OutgoingRequest<Params, Result> Edit = bind("edit");`
570 /// Params must be JSON-serializable, Result must be parsable.
571 template <typename Result, typename Params>
572 OutgoingRequest<Result, Params> Bind(llvm::StringLiteral method);
573
574 /// Bind a function object to be used for outgoing events.
575 /// e.g. `OutgoingEvent<LogParams> Log = bind("log");`
576 /// LogParams must be JSON-serializable.
577 template <typename Params>
578 OutgoingEvent<Params> Bind(llvm::StringLiteral method);
579
580 void Received(const Evt &evt) override {
581 std::scoped_lock<std::recursive_mutex> guard(m_mutex);
582 auto it = m_event_handlers.find(Proto::KeyFor(evt));
583 if (it == m_event_handlers.end()) {
584 OnError(llvm::createStringError(
585 llvm::formatv("no handler for event {0}", toJSON(evt))));
586 return;
587 }
588 it->second(evt);
589 }
590
591 void Received(const Req &req) override {
592 ReplyOnce reply(req, &m_transport, this);
593
594 std::scoped_lock<std::recursive_mutex> guard(m_mutex);
595 auto it = m_request_handlers.find(Proto::KeyFor(req));
596 if (it == m_request_handlers.end()) {
597 reply(Proto::Make(req,
598 llvm::make_error<MethodNotFound>(Proto::KeyFor(req))));
599 return;
600 }
601
602 it->second(req, std::move(reply));
603 }
604
605 void Received(const Resp &resp) override {
606 std::scoped_lock<std::recursive_mutex> guard(m_mutex);
607
608 Id id = Proto::KeyFor(resp);
609 auto it = m_pending_responses.find(id);
610 if (it == m_pending_responses.end()) {
611 OnError(llvm::createStringError(
612 llvm::formatv("no pending request for {0}", toJSON(resp))));
613 return;
614 }
615
616 it->second(resp);
617 m_pending_responses.erase(it);
618 }
619
620 void OnError(llvm::Error err) override {
621 std::scoped_lock<std::recursive_mutex> guard(m_mutex);
622 if (m_error_handler)
623 m_error_handler(std::move(err));
624 }
625
626 void OnClosed() override {
627 // The disconnect handler may destroy this Binder -- e.g. the server
628 // removes the disconnected client, which owns the transport and, with it,
629 // this handler. Move the handler out and release the lock before invoking
630 // it, so we neither run the teardown while holding m_mutex nor destroy a
631 // still-locked mutex.
632 Callback<void()> disconnect_handler;
633 {
634 std::scoped_lock<std::recursive_mutex> guard(m_mutex);
635 disconnect_handler = std::move(m_disconnect_handler);
636 }
637 if (disconnect_handler)
638 disconnect_handler();
639 }
640
641 /// Fails every in-flight outgoing request, invoking its reply with an error.
642 /// Call when the connection is going away, so pending replies are satisfied
643 /// rather than destroyed unanswered.
644 void FailPendingRequests(llvm::StringRef reason) {
645 std::scoped_lock<std::recursive_mutex> guard(m_mutex);
646 std::map<Id, Callback<void(const Resp &)>> pending;
647 std::swap(pending, m_pending_responses);
648 for (auto &entry : pending) {
649 Req req = Proto::Make(entry.first, /*method=*/"", std::nullopt);
650 entry.second(Proto::Make(req, llvm::createStringError(reason)));
651 }
652 }
653
654private:
655 template <typename T>
656 llvm::Expected<T> static Parse(const llvm::json::Value &raw,
657 llvm::StringRef method);
658
659 template <typename T> using Callback = llvm::unique_function<T>;
660
661 std::recursive_mutex m_mutex;
664 std::map<Id, Callback<void(const Resp &)>> m_pending_responses;
665 llvm::StringMap<Callback<void(const Req &, Callback<void(const Resp &)>)>>
667 llvm::StringMap<Callback<void(const Evt &)>> m_event_handlers;
669 Callback<void(llvm::Error)> m_error_handler;
670
671 /// Function object to reply to a call.
672 /// Each instance must be called exactly once, otherwise:
673 /// - the bug is logged, and (in debug mode) an assert will fire
674 /// - if there was no reply, an error reply is sent
675 /// - if there were multiple replies, only the first is sent
676 class ReplyOnce {
677 std::atomic<bool> replied = {false};
678 const Req req;
679 Transport *transport; // Null when moved-from.
680 MessageHandler *handler; // Null when moved-from.
681
682 public:
688 : replied(other.replied.load()), req(other.req),
689 transport(other.transport), handler(other.handler) {
690 other.transport = nullptr;
691 other.handler = nullptr;
692 }
694 ReplyOnce(const ReplyOnce &) = delete;
695 ReplyOnce &operator=(const ReplyOnce &) = delete;
696
698 if (transport && handler && !replied) {
699 assert(false && "must reply to all calls!");
700 (*this)(Proto::Make(req, llvm::createStringError("failed to reply")));
701 }
702 }
703
704 void operator()(const Resp &resp) {
705 assert(transport && handler && "moved-from!");
706 if (replied.exchange(true)) {
707 assert(false && "must reply to each call only once!");
708 return;
709 }
710
711 if (llvm::Error error = transport->Send(resp))
712 handler->OnError(std::move(error));
713 }
714 };
715};
716
717#if __cplusplus >= 202002L
718template <BindingBuilder Proto>
719#else
720template <typename Proto>
721#endif
722template <typename Fn, typename... Args>
723void Binder<Proto>::OnDisconnect(Fn &&fn, Args &&...args) {
724 m_disconnect_handler = [fn, args...]() mutable {
725 std::invoke(std::forward<Fn>(fn), std::forward<Args>(args)...);
726 };
727}
728
729#if __cplusplus >= 202002L
730template <BindingBuilder Proto>
731#else
732template <typename Proto>
733#endif
734template <typename Fn, typename... Args>
735void Binder<Proto>::OnError(Fn &&fn, Args &&...args) {
736 m_error_handler = [fn, args...](llvm::Error error) mutable {
737 std::invoke(std::forward<Fn>(fn), std::forward<Args>(args)...,
738 std::move(error));
739 };
740}
741
742#if __cplusplus >= 202002L
743template <BindingBuilder Proto>
744#else
745template <typename Proto>
746#endif
747template <typename Result, typename Params, typename Fn, typename... Args>
748void Binder<Proto>::Bind(llvm::StringLiteral method, Fn &&fn, Args &&...args) {
749 assert(m_request_handlers.find(method) == m_request_handlers.end() &&
750 "request already bound");
751 if constexpr (std::is_void_v<Result> && std::is_void_v<Params>) {
752 m_request_handlers[method] =
753 [fn, args...](const Req &req,
754 llvm::unique_function<void(const Resp &)> reply) mutable {
755 llvm::Error result =
756 std::invoke(std::forward<Fn>(fn), std::forward<Args>(args)...);
757 reply(Proto::Make(req, std::move(result)));
758 };
759 } else if constexpr (std::is_void_v<Params>) {
760 m_request_handlers[method] =
761 [fn, args...](const Req &req,
762 llvm::unique_function<void(const Resp &)> reply) mutable {
763 llvm::Expected<Result> result =
764 std::invoke(std::forward<Fn>(fn), std::forward<Args>(args)...);
765 if (!result)
766 return reply(Proto::Make(req, result.takeError()));
767 reply(Proto::Make(req, toJSON(*result)));
768 };
769 } else if constexpr (std::is_void_v<Result>) {
770 m_request_handlers[method] =
771 [method, fn,
772 args...](const Req &req,
773 llvm::unique_function<void(const Resp &)> reply) mutable {
774 llvm::Expected<Params> params =
775 Parse<Params>(Proto::Extract(req), method);
776 if (!params)
777 return reply(Proto::Make(req, params.takeError()));
778
779 llvm::Error result = std::invoke(
780 std::forward<Fn>(fn), std::forward<Args>(args)..., *params);
781 reply(Proto::Make(req, std::move(result)));
782 };
783 } else {
784 m_request_handlers[method] =
785 [method, fn,
786 args...](const Req &req,
787 llvm::unique_function<void(const Resp &)> reply) mutable {
788 llvm::Expected<Params> params =
789 Parse<Params>(Proto::Extract(req), method);
790 if (!params)
791 return reply(Proto::Make(req, params.takeError()));
792
793 llvm::Expected<Result> result = std::invoke(
794 std::forward<Fn>(fn), std::forward<Args>(args)..., *params);
795 if (!result)
796 return reply(Proto::Make(req, result.takeError()));
797
798 reply(Proto::Make(req, toJSON(*result)));
799 };
800 }
801}
802
803#if __cplusplus >= 202002L
804template <BindingBuilder Proto>
805#else
806template <typename Proto>
807#endif
808template <typename Params, typename Fn, typename... Args>
809void Binder<Proto>::Bind(llvm::StringLiteral method, Fn &&fn, Args &&...args) {
810 assert(m_event_handlers.find(method) == m_event_handlers.end() &&
811 "event already bound");
812 if constexpr (std::is_void_v<Params>) {
813 m_event_handlers[method] = [fn, args...](const Evt &) mutable {
814 std::invoke(std::forward<Fn>(fn), std::forward<Args>(args)...);
815 };
816 } else {
817 m_event_handlers[method] = [this, method, fn,
818 args...](const Evt &evt) mutable {
819 llvm::Expected<Params> params =
820 Parse<Params>(Proto::Extract(evt), method);
821 if (!params)
822 return OnError(params.takeError());
823 std::invoke(std::forward<Fn>(fn), std::forward<Args>(args)..., *params);
824 };
825 }
826}
827
828#if __cplusplus >= 202002L
829template <BindingBuilder Proto>
830#else
831template <typename Proto>
832#endif
833template <typename Result, typename Params>
835Binder<Proto>::Bind(llvm::StringLiteral method) {
836 if constexpr (std::is_void_v<Result> && std::is_void_v<Params>) {
837 return [this, method](Reply<Result> fn) {
838 std::scoped_lock<std::recursive_mutex> guard(m_mutex);
839 Id id = ++m_seq;
840 Req req = Proto::Make(id, method, std::nullopt);
841 m_pending_responses[id] = [fn = std::move(fn)](const Resp &resp) mutable {
842 llvm::Expected<llvm::json::Value> result = Proto::Extract(resp);
843 if (!result)
844 return fn(result.takeError());
845 fn(llvm::Error::success());
846 };
847 if (llvm::Error error = m_transport.Send(req))
848 OnError(std::move(error));
849 };
850 } else if constexpr (std::is_void_v<Params>) {
851 return [this, method](Reply<Result> fn) {
852 std::scoped_lock<std::recursive_mutex> guard(m_mutex);
853 Id id = ++m_seq;
854 Req req = Proto::Make(id, method, std::nullopt);
855 m_pending_responses[id] = [fn = std::move(fn),
856 method](const Resp &resp) mutable {
857 llvm::Expected<llvm::json::Value> result = Proto::Extract(resp);
858 if (!result)
859 return fn(result.takeError());
860 fn(Parse<Result>(*result, method));
861 };
862 if (llvm::Error error = m_transport.Send(req))
863 OnError(std::move(error));
864 };
865 } else if constexpr (std::is_void_v<Result>) {
866 return [this, method](const Params &params, Reply<Result> fn) {
867 std::scoped_lock<std::recursive_mutex> guard(m_mutex);
868 Id id = ++m_seq;
869 Req req = Proto::Make(id, method, llvm::json::Value(params));
870 m_pending_responses[id] = [fn = std::move(fn)](const Resp &resp) mutable {
871 llvm::Expected<llvm::json::Value> result = Proto::Extract(resp);
872 if (!result)
873 return fn(result.takeError());
874 fn(llvm::Error::success());
875 };
876 if (llvm::Error error = m_transport.Send(req))
877 OnError(std::move(error));
878 };
879 } else {
880 return [this, method](const Params &params, Reply<Result> fn) {
881 std::scoped_lock<std::recursive_mutex> guard(m_mutex);
882 Id id = ++m_seq;
883 Req req = Proto::Make(id, method, llvm::json::Value(params));
884 m_pending_responses[id] = [fn = std::move(fn),
885 method](const Resp &resp) mutable {
886 llvm::Expected<llvm::json::Value> result = Proto::Extract(resp);
887 if (llvm::Error err = result.takeError())
888 return fn(std::move(err));
889 fn(Parse<Result>(*result, method));
890 };
891 if (llvm::Error error = m_transport.Send(req))
892 OnError(std::move(error));
893 };
894 }
895}
896
897#if __cplusplus >= 202002L
898template <BindingBuilder Proto>
899#else
900template <typename Proto>
901#endif
902template <typename Params>
903OutgoingEvent<Params> Binder<Proto>::Bind(llvm::StringLiteral method) {
904 if constexpr (std::is_void_v<Params>) {
905 return [this, method]() {
906 if (llvm::Error error =
907 m_transport.Send(Proto::Make(method, std::nullopt)))
908 OnError(std::move(error));
909 };
910 } else {
911 return [this, method](const Params &params) {
912 if (llvm::Error error =
913 m_transport.Send(Proto::Make(method, toJSON(params))))
914 OnError(std::move(error));
915 };
916 }
917}
918
919#if __cplusplus >= 202002L
920template <BindingBuilder Proto>
921#else
922template <typename Proto>
923#endif
924template <typename T>
925llvm::Expected<T> Binder<Proto>::Parse(const llvm::json::Value &raw,
926 llvm::StringRef method) {
927 T result;
928 llvm::json::Path::Root root;
929 if (!fromJSON(raw, result, root)) {
930 // Dump the relevant parts of the broken message.
931 std::string context;
932 llvm::raw_string_ostream OS(context);
933 root.printErrorContext(raw, OS);
934 return llvm::make_error<InvalidParams>(method.str(), context);
935 }
936 return std::move(result);
937}
938
939#if __cplusplus >= 202002L
940template <BindingBuilder Proto>
941#else
942template <typename Proto>
943#endif
944template <typename Result, typename Params, typename Fn, typename... Args>
945void Binder<Proto>::BindAsync(llvm::StringLiteral method, Fn &&fn,
946 Args &&...args) {
947 assert(m_request_handlers.find(method) == m_request_handlers.end() &&
948 "request already bound");
949 // The handler is captured by value and may be invoked once per incoming
950 // request, so it is invoked as an lvalue (never forwarded) to avoid moving
951 // from it between calls.
952 if constexpr (std::is_void_v<Params>) {
953 m_request_handlers[method] =
954 [fn, args...](const Req &req,
955 Callback<void(const Resp &)> reply) mutable {
956 Reply<Result> typed_reply =
957 [req, reply = std::move(reply)](
958 llvm::Expected<Result> result) mutable {
959 if (!result)
960 return reply(Proto::Make(req, result.takeError()));
961 reply(Proto::Make(req, toJSON(*result)));
962 };
963 std::invoke(fn, args..., std::move(typed_reply));
964 };
965 } else {
966 m_request_handlers[method] =
967 [method, fn, args...](const Req &req,
968 Callback<void(const Resp &)> reply) mutable {
969 Reply<Result> typed_reply =
970 [req, reply = std::move(reply)](
971 llvm::Expected<Result> result) mutable {
972 if (!result)
973 return reply(Proto::Make(req, result.takeError()));
974 reply(Proto::Make(req, toJSON(*result)));
975 };
976 llvm::Expected<Params> params =
977 Parse<Params>(Proto::Extract(req), method);
978 if (!params)
979 return typed_reply(params.takeError());
980 std::invoke(fn, args..., *params, std::move(typed_reply));
981 };
982 }
983}
984
985} // namespace lldb_private::transport
986
987#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 BindAsync(llvm::StringLiteral method, Fn &&fn, Args &&...args)
Bind an asynchronous 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 FailPendingRequests(llvm::StringRef reason)
Fails every in-flight outgoing request, invoking its reply with an error.
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::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...
void log(llvm::raw_ostream &OS) const override
InvalidMessage(std::string raw_message, std::string reason)
std::error_code convertToErrorCode() const override
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 ReplyWithParseError(llvm::StringRef raw_message, llvm::StringRef reason)
Sends an error response for a message that failed to parse, described by reason.
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
llvm::json::Value toJSON(const Diagnostics::Report &report)
Render a diagnostics report as JSON, for diagnostics dump's terminal output.
bool fromJSON(const llvm::json::Value &value, SymbolValue &data, llvm::json::Path path)
MainLoopPosix MainLoop
Definition MainLoop.h:20
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