13#ifndef LLDB_HOST_JSONTRANSPORT_H
14#define LLDB_HOST_JSONTRANSPORT_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"
34#include <system_error>
39#if __cplusplus >= 202002L
48 :
public llvm::ErrorInfo<TransportUnhandledContentsError> {
54 void log(llvm::raw_ostream &
OS)
const override;
74 void log(llvm::raw_ostream &
OS)
const override;
95 void log(llvm::raw_ostream &
OS)
const override;
102#if __cplusplus >= 202002L
106concept ProtocolDescriptor =
requires {
121#if __cplusplus >= 202002L
122template <ProtocolDescriptor Proto>
124template <
typename Proto>
128 using Req =
typename Proto::Req;
129 using Resp =
typename Proto::Resp;
130 using Evt =
typename Proto::Evt;
169 virtual llvm::Expected<MainLoop::ReadHandleUP>
173 template <
typename... Ts>
inline auto Logv(
const char *Fmt, Ts &&...Vals) {
174 Log(llvm::formatv(Fmt, std::forward<Ts>(Vals)...).str());
176 virtual void Log(llvm::StringRef message) = 0;
188 llvm::Error
Send(
const typename Proto::Evt &evt)
override {
191 llvm::Error
Send(
const typename Proto::Req &req)
override {
194 llvm::Error
Send(
const typename Proto::Resp &resp)
override {
198 llvm::Expected<MainLoop::ReadHandleUP>
215 llvm::Error
Write(
const llvm::json::Value &message) {
216 this->
Logv(
"<-- {0}", message);
217 std::string output =
Encode(message);
218 size_t bytes_written = output.size();
219 return m_out->Write(output.data(), bytes_written).takeError();
222 virtual llvm::Expected<std::vector<std::string>>
Parse() = 0;
223 virtual std::string
Encode(
const llvm::json::Value &message) = 0;
230 size_t num_bytes =
sizeof(buf);
231 if (
Status status =
m_in->Read(buf, num_bytes); status.Fail()) {
232 handler.OnError(status.takeError());
237 m_buffer.append(llvm::StringRef(buf, num_bytes));
241 llvm::Expected<std::vector<std::string>> raw_messages =
Parse();
242 if (llvm::Error
error = raw_messages.takeError()) {
243 handler.OnError(std::move(
error));
247 for (
const std::string &raw_message : *raw_messages) {
248 llvm::Expected<Message> message =
249 llvm::json::parse<Message>(raw_message);
251 handler.OnError(message.takeError());
255 std::visit([&handler](
auto &&msg) { handler.Received(msg); }, *message);
260 if (num_bytes == 0) {
263 handler.OnError(llvm::make_error<TransportUnhandledContentsError>(
274#if __cplusplus >= 202002L
275template <ProtocolDescriptor Proto>
277template <
typename Proto>
286 std::string
Encode(
const llvm::json::Value &message)
override {
288 std::string raw_message = llvm::formatv(
"{0}", message).str();
289 llvm::raw_string_ostream
OS(output);
291 << std::to_string(raw_message.size()) <<
kEndOfHeader << raw_message;
297 llvm::Expected<std::vector<std::string>>
Parse()
override {
298 std::vector<std::string> messages;
299 llvm::StringRef buffer = this->
m_buffer;
302 size_t content_length = 0;
304 for (
const llvm::StringRef &header :
312 value = value.trim();
313 if (!llvm::to_integer(value, content_length, 10)) {
316 return llvm::createStringError(std::errc::invalid_argument,
317 "invalid content length: %s",
318 value.str().c_str());
323 if (content_length > rest.size())
326 llvm::StringRef body = rest.take_front(content_length);
327 buffer = rest.drop_front(content_length);
328 messages.emplace_back(body.str());
329 this->
Logv(
"--> {0}", body);
335 return std::move(messages);
345#if __cplusplus >= 202002L
346template <ProtocolDescriptor Proto>
348template <
typename Proto>
355 std::string
Encode(
const llvm::json::Value &message)
override {
359 llvm::Expected<std::vector<std::string>>
Parse()
override {
360 std::vector<std::string> messages;
361 llvm::StringRef buf = this->
m_buffer;
365 messages.emplace_back(raw_json.str());
366 this->
Logv(
"--> {0}", raw_json);
381 std::conditional_t<std::is_void_v<T>,
382 llvm::unique_function<void(llvm::Error)>,
383 llvm::unique_function<void(llvm::Expected<T>)>>;
386template <
typename R,
typename P>
struct request_t final {
393 using type = llvm::unique_function<void(
const P &)>;
396 using type = llvm::unique_function<void()>;
400template <
typename R,
typename P>
406#if __cplusplus >= 202002L
410concept BindingBuilder =
411 ProtocolDescriptor<T> &&
412 requires(T::Id
id, T::Req req, T::Resp resp, T::Evt evt,
413 llvm::StringRef method, std::optional<llvm::json::Value> params,
414 std::optional<llvm::json::Value> result, llvm::Error err) {
416 { T::InitialId() } -> std::same_as<typename T::Id>;
418 {
id++ } -> std::same_as<typename T::Id>;
423 { T::Make(
id, method, params) } -> std::same_as<typename T::Req>;
425 { T::Make(req, std::move(err)) } -> std::same_as<typename T::Resp>;
427 { T::Make(req, result) } -> std::same_as<typename T::Resp>;
429 { T::Make(method, params) } -> std::same_as<typename T::Evt>;
435 { T::KeyFor(resp) } -> std::same_as<typename T::Id>;
437 { T::KeyFor(req) } -> std::same_as<std::string>;
439 { T::KeyFor(evt) } -> std::same_as<std::string>;
445 { T::Extract(req) } -> std::same_as<std::optional<llvm::json::Value>>;
447 { T::Extract(resp) } -> std::same_as<llvm::Expected<llvm::json::Value>>;
449 { T::Extract(evt) } -> std::same_as<std::optional<llvm::json::Value>>;
480#if __cplusplus >= 202002L
481template <BindingBuilder Proto>
483template <
typename Proto>
486 using Req =
typename Proto::Req;
487 using Resp =
typename Proto::Resp;
488 using Evt =
typename Proto::Evt;
489 using Id =
typename Proto::Id;
500 template <
typename Fn,
typename...
Args>
504 template <
typename Fn,
typename...
Args>
511 template <
typename Result,
typename Params,
typename Fn,
typename...
Args>
512 void Bind(llvm::StringLiteral method, Fn &&fn,
Args &&...args);
518 template <
typename Params,
typename Fn,
typename...
Args>
519 void Bind(llvm::StringLiteral method, Fn &&fn,
Args &&...args);
524 template <
typename Result,
typename Params>
530 template <
typename Params>
534 std::scoped_lock<std::recursive_mutex> guard(
m_mutex);
537 OnError(llvm::createStringError(
538 llvm::formatv(
"no handled for event {0}",
toJSON(evt))));
547 std::scoped_lock<std::recursive_mutex> guard(
m_mutex);
550 reply(Proto::Make(req, llvm::createStringError(
"method not found")));
554 it->second(req, std::move(reply));
558 std::scoped_lock<std::recursive_mutex> guard(
m_mutex);
560 Id id = Proto::KeyFor(resp);
563 OnError(llvm::createStringError(
564 llvm::formatv(
"no pending request for {0}",
toJSON(resp))));
573 std::scoped_lock<std::recursive_mutex> guard(
m_mutex);
579 std::scoped_lock<std::recursive_mutex> guard(
m_mutex);
585 template <
typename T>
586 llvm::Expected<T>
static Parse(
const llvm::json::Value &raw,
587 llvm::StringRef method);
589 template <
typename T>
using Callback = llvm::unique_function<T>;
620 other.transport =
nullptr;
621 other.handler =
nullptr;
629 assert(
false &&
"must reply to all calls!");
630 (*this)(Proto::Make(
req, llvm::createStringError(
"failed to reply")));
637 assert(
false &&
"must reply to each call only once!");
647#if __cplusplus >= 202002L
648template <BindingBuilder Proto>
650template <
typename Proto>
652template <
typename Fn,
typename...
Args>
655 std::invoke(std::forward<Fn>(fn), std::forward<Args>(args)...);
659#if __cplusplus >= 202002L
660template <BindingBuilder Proto>
662template <
typename Proto>
664template <
typename Fn,
typename...
Args>
667 std::invoke(std::forward<Fn>(fn), std::forward<Args>(args)...,
672#if __cplusplus >= 202002L
673template <BindingBuilder Proto>
675template <
typename Proto>
677template <
typename Result,
typename Params,
typename Fn,
typename...
Args>
680 "request already bound");
681 if constexpr (std::is_void_v<Result> && std::is_void_v<Params>) {
683 [fn, args...](
const Req &req,
684 llvm::unique_function<void(
const Resp &)> reply)
mutable {
686 std::invoke(std::forward<Fn>(fn), std::forward<Args>(args)...);
687 reply(Proto::Make(req, std::move(result)));
689 }
else if constexpr (std::is_void_v<Params>) {
691 [fn, args...](
const Req &req,
692 llvm::unique_function<void(
const Resp &)> reply)
mutable {
693 llvm::Expected<Result> result =
694 std::invoke(std::forward<Fn>(fn), std::forward<Args>(args)...);
696 return reply(Proto::Make(req, result.takeError()));
697 reply(Proto::Make(req,
toJSON(*result)));
699 }
else if constexpr (std::is_void_v<Result>) {
702 args...](
const Req &req,
703 llvm::unique_function<void(
const Resp &)> reply)
mutable {
704 llvm::Expected<Params> params =
707 return reply(Proto::Make(req, params.takeError()));
709 llvm::Error result = std::invoke(
710 std::forward<Fn>(fn), std::forward<Args>(args)..., *params);
711 reply(Proto::Make(req, std::move(result)));
716 args...](
const Req &req,
717 llvm::unique_function<void(
const Resp &)> reply)
mutable {
718 llvm::Expected<Params> params =
721 return reply(Proto::Make(req, params.takeError()));
723 llvm::Expected<Result> result = std::invoke(
724 std::forward<Fn>(fn), std::forward<Args>(args)..., *params);
726 return reply(Proto::Make(req, result.takeError()));
728 reply(Proto::Make(req,
toJSON(*result)));
733#if __cplusplus >= 202002L
734template <BindingBuilder Proto>
736template <
typename Proto>
738template <
typename Params,
typename Fn,
typename...
Args>
741 "event already bound");
742 if constexpr (std::is_void_v<Params>) {
744 std::invoke(std::forward<Fn>(fn), std::forward<Args>(args)...);
748 args...](
const Evt &evt)
mutable {
749 llvm::Expected<Params> params =
752 return OnError(params.takeError());
753 std::invoke(std::forward<Fn>(fn), std::forward<Args>(args)..., *params);
758#if __cplusplus >= 202002L
759template <BindingBuilder Proto>
761template <
typename Proto>
763template <
typename Result,
typename Params>
766 if constexpr (std::is_void_v<Result> && std::is_void_v<Params>) {
768 std::scoped_lock<std::recursive_mutex> guard(
m_mutex);
770 Req req = Proto::Make(
id, method, std::nullopt);
772 llvm::Expected<llvm::json::Value> result = Proto::Extract(resp);
774 return fn(result.takeError());
775 fn(llvm::Error::success());
780 }
else if constexpr (std::is_void_v<Params>) {
782 std::scoped_lock<std::recursive_mutex> guard(
m_mutex);
784 Req req = Proto::Make(
id, method, std::nullopt);
786 method](
const Resp &resp)
mutable {
787 llvm::Expected<llvm::json::Value> result = Proto::Extract(resp);
789 return fn(result.takeError());
795 }
else if constexpr (std::is_void_v<Result>) {
796 return [
this, method](
const Params ¶ms,
Reply<Result> fn) {
797 std::scoped_lock<std::recursive_mutex> guard(
m_mutex);
799 Req req = Proto::Make(
id, method, llvm::json::Value(params));
801 llvm::Expected<llvm::json::Value> result = Proto::Extract(resp);
803 return fn(result.takeError());
804 fn(llvm::Error::success());
810 return [
this, method](
const Params ¶ms,
Reply<Result> fn) {
811 std::scoped_lock<std::recursive_mutex> guard(
m_mutex);
813 Req req = Proto::Make(
id, method, llvm::json::Value(params));
815 method](
const Resp &resp)
mutable {
816 llvm::Expected<llvm::json::Value> result = Proto::Extract(resp);
817 if (llvm::Error err = result.takeError())
818 return fn(std::move(err));
827#if __cplusplus >= 202002L
828template <BindingBuilder Proto>
830template <
typename Proto>
832template <
typename Params>
834 if constexpr (std::is_void_v<Params>) {
835 return [
this, method]() {
836 if (llvm::Error
error =
837 m_transport.Send(Proto::Make(method, std::nullopt)))
841 return [
this, method](
const Params ¶ms) {
842 if (llvm::Error
error =
849#if __cplusplus >= 202002L
850template <BindingBuilder Proto>
852template <
typename Proto>
856 llvm::StringRef method) {
858 llvm::json::Path::Root root;
862 llvm::raw_string_ostream
OS(context);
863 root.printErrorContext(raw,
OS);
864 return llvm::make_error<InvalidParams>(method.str(), context);
866 return std::move(result);
static llvm::raw_ostream & error(Stream &strm)
A command line argument class.
std::unique_ptr< ReadHandle > ReadHandleUP
ReadHandleUP RegisterReadObject(const lldb::IOObjectSP &object_sp, const Callback &callback, Status &error) override
bool Fail() const
Test for error condition.
void operator()(const Resp &resp)
ReplyOnce & operator=(const ReplyOnce &)=delete
std::atomic< bool > replied
ReplyOnce(const Req req, Transport *transport, MessageHandler *handler)
ReplyOnce & operator=(ReplyOnce &&)=delete
ReplyOnce(ReplyOnce &&other)
ReplyOnce(const 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.
std::recursive_mutex m_mutex
llvm::StringMap< Callback< void(const Req &, Callback< void(const Resp &)>)> > m_request_handlers
void OnClosed() override
Called on EOF or client disconnect.
Callback< void(llvm::Error)> m_error_handler
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.
typename Proto::Resp Resp
llvm::unique_function< T > Callback
llvm::StringMap< Callback< void(const Evt &)> > m_event_handlers
Callback< void()> m_disconnect_handler
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)
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
IOTransport(lldb::IOObjectSP in, lldb::IOObjectSP out)
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
llvm::Error Write(const llvm::json::Value &message)
llvm::Error Send(const typename Proto::Req &req) override
llvm::Expected< MainLoop::ReadHandleUP > RegisterMessageHandler(MainLoop &loop, MessageHandler &handler) override
RegisterMessageHandler registers the Transport with the given MainLoop and handles any incoming messa...
llvm::SmallString< kReadBufferSize > m_buffer
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 ~MessageHandler()=default
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::Expected< MainLoop::ReadHandleUP > RegisterMessageHandler(MainLoop &loop, MessageHandler &handler)=0
RegisterMessageHandler registers the Transport with the given MainLoop and handles any incoming messa...
virtual llvm::Error Send(const Resp &)=0
Sends a response to a specific request.
virtual ~JSONTransport()=default
std::variant< Req, Resp, Evt > Message
virtual llvm::Error Send(const Evt &)=0
Sends an event, a message that does not require a response.
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
typename Proto::Resp Resp
static constexpr int kErrorCode
std::error_code convertToErrorCode() const override
MethodNotFound(std::string method)
void log(llvm::raw_ostream &OS) const override
const std::string & getUnhandledContents() const
void log(llvm::raw_ostream &OS) const override
TransportUnhandledContentsError(std::string unhandled_contents)
std::error_code convertToErrorCode() const override
std::string m_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)
llvm::json::Value toJSON(const TraceSupportedResponse &packet)
std::shared_ptr< lldb_private::IOObject > IOObjectSP
llvm::unique_function< void()> type
llvm::unique_function< void(const P &)> type
llvm::unique_function< void(Reply< R >)> type
llvm::unique_function< void(const P &, Reply< R >)> type