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;
172 template <
typename... Ts>
inline auto Logv(
const char *Fmt, Ts &&...Vals) {
173 Log(llvm::formatv(Fmt, std::forward<Ts>(Vals)...).str());
175 virtual void Log(llvm::StringRef message) = 0;
187 llvm::Error
Send(
const typename Proto::Evt &evt)
override {
191 llvm::Error
Send(
const typename Proto::Req &req)
override {
195 llvm::Error
Send(
const typename Proto::Resp &resp)
override {
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();
219 virtual llvm::Expected<std::vector<std::string>>
Parse() = 0;
220 virtual std::string
Encode(
const llvm::json::Value &message) = 0;
227 size_t num_bytes =
sizeof(buf);
228 if (
Status status =
m_in->Read(buf, num_bytes); status.Fail()) {
229 handler.OnError(status.takeError());
234 m_buffer.append(llvm::StringRef(buf, num_bytes));
238 llvm::Expected<std::vector<std::string>> raw_messages =
Parse();
239 if (llvm::Error
error = raw_messages.takeError()) {
240 handler.OnError(std::move(
error));
244 for (
const std::string &raw_message : *raw_messages) {
245 llvm::Expected<Message> message =
246 llvm::json::parse<Message>(raw_message);
248 handler.OnError(message.takeError());
252 std::visit([&handler](
auto &&msg) { handler.Received(msg); }, *message);
257 if (num_bytes == 0) {
260 handler.OnError(llvm::make_error<TransportUnhandledContentsError>(
277#if __cplusplus >= 202002L
278template <ProtocolDescriptor Proto>
280template <
typename Proto>
289 std::string
Encode(
const llvm::json::Value &message)
override {
291 std::string raw_message = llvm::formatv(
"{0}", message).str();
292 llvm::raw_string_ostream
OS(output);
294 << std::to_string(raw_message.size()) <<
kEndOfHeader << raw_message;
300 llvm::Expected<std::vector<std::string>>
Parse()
override {
301 std::vector<std::string> messages;
302 llvm::StringRef buffer = this->
m_buffer;
305 size_t content_length = 0;
307 for (
const llvm::StringRef &header :
315 value = value.trim();
316 if (!llvm::to_integer(value, content_length, 10)) {
319 return llvm::createStringError(std::errc::invalid_argument,
320 "invalid content length: %s",
321 value.str().c_str());
326 if (content_length > rest.size())
329 llvm::StringRef body = rest.take_front(content_length);
330 buffer = rest.drop_front(content_length);
331 messages.emplace_back(body.str());
332 this->
Logv(
"--> {0}", body);
338 return std::move(messages);
348#if __cplusplus >= 202002L
349template <ProtocolDescriptor Proto>
351template <
typename Proto>
358 std::string
Encode(
const llvm::json::Value &message)
override {
362 llvm::Expected<std::vector<std::string>>
Parse()
override {
363 std::vector<std::string> messages;
364 llvm::StringRef buf = this->
m_buffer;
368 messages.emplace_back(raw_json.str());
369 this->
Logv(
"--> {0}", raw_json);
384 std::conditional_t<std::is_void_v<T>,
385 llvm::unique_function<void(llvm::Error)>,
386 llvm::unique_function<void(llvm::Expected<T>)>>;
389template <
typename R,
typename P>
struct request_t final {
396 using type = llvm::unique_function<void(
const P &)>;
399 using type = llvm::unique_function<void()>;
403template <
typename R,
typename P>
409#if __cplusplus >= 202002L
413concept BindingBuilder =
414 ProtocolDescriptor<T> &&
415 requires(T::Id
id, T::Req req, T::Resp resp, T::Evt evt,
416 llvm::StringRef method, std::optional<llvm::json::Value> params,
417 std::optional<llvm::json::Value> result, llvm::Error err) {
419 { T::InitialId() } -> std::same_as<typename T::Id>;
421 {
id++ } -> std::same_as<typename T::Id>;
426 { T::Make(
id, method, params) } -> std::same_as<typename T::Req>;
428 { T::Make(req, std::move(err)) } -> std::same_as<typename T::Resp>;
430 { T::Make(req, result) } -> std::same_as<typename T::Resp>;
432 { T::Make(method, params) } -> std::same_as<typename T::Evt>;
438 { T::KeyFor(resp) } -> std::same_as<typename T::Id>;
440 { T::KeyFor(req) } -> std::same_as<std::string>;
442 { T::KeyFor(evt) } -> std::same_as<std::string>;
448 { T::Extract(req) } -> std::same_as<std::optional<llvm::json::Value>>;
450 { T::Extract(resp) } -> std::same_as<llvm::Expected<llvm::json::Value>>;
452 { T::Extract(evt) } -> std::same_as<std::optional<llvm::json::Value>>;
483#if __cplusplus >= 202002L
484template <BindingBuilder Proto>
486template <
typename Proto>
489 using Req =
typename Proto::Req;
490 using Resp =
typename Proto::Resp;
491 using Evt =
typename Proto::Evt;
492 using Id =
typename Proto::Id;
503 template <
typename Fn,
typename...
Args>
507 template <
typename Fn,
typename...
Args>
514 template <
typename Result,
typename Params,
typename Fn,
typename...
Args>
515 void Bind(llvm::StringLiteral method, Fn &&fn,
Args &&...args);
521 template <
typename Params,
typename Fn,
typename...
Args>
522 void Bind(llvm::StringLiteral method, Fn &&fn,
Args &&...args);
527 template <
typename Result,
typename Params>
533 template <
typename Params>
537 std::scoped_lock<std::recursive_mutex> guard(
m_mutex);
540 OnError(llvm::createStringError(
541 llvm::formatv(
"no handled for event {0}",
toJSON(evt))));
550 std::scoped_lock<std::recursive_mutex> guard(
m_mutex);
553 reply(Proto::Make(req, llvm::createStringError(
"method not found")));
557 it->second(req, std::move(reply));
561 std::scoped_lock<std::recursive_mutex> guard(
m_mutex);
563 Id id = Proto::KeyFor(resp);
566 OnError(llvm::createStringError(
567 llvm::formatv(
"no pending request for {0}",
toJSON(resp))));
576 std::scoped_lock<std::recursive_mutex> guard(
m_mutex);
582 std::scoped_lock<std::recursive_mutex> guard(
m_mutex);
588 template <
typename T>
589 llvm::Expected<T>
static Parse(
const llvm::json::Value &raw,
590 llvm::StringRef method);
592 template <
typename T>
using Callback = llvm::unique_function<T>;
623 other.transport =
nullptr;
624 other.handler =
nullptr;
632 assert(
false &&
"must reply to all calls!");
633 (*this)(Proto::Make(
req, llvm::createStringError(
"failed to reply")));
640 assert(
false &&
"must reply to each call only once!");
650#if __cplusplus >= 202002L
651template <BindingBuilder Proto>
653template <
typename Proto>
655template <
typename Fn,
typename...
Args>
658 std::invoke(std::forward<Fn>(fn), std::forward<Args>(args)...);
662#if __cplusplus >= 202002L
663template <BindingBuilder Proto>
665template <
typename Proto>
667template <
typename Fn,
typename...
Args>
670 std::invoke(std::forward<Fn>(fn), std::forward<Args>(args)...,
675#if __cplusplus >= 202002L
676template <BindingBuilder Proto>
678template <
typename Proto>
680template <
typename Result,
typename Params,
typename Fn,
typename...
Args>
683 "request already bound");
684 if constexpr (std::is_void_v<Result> && std::is_void_v<Params>) {
686 [fn, args...](
const Req &req,
687 llvm::unique_function<void(
const Resp &)> reply)
mutable {
689 std::invoke(std::forward<Fn>(fn), std::forward<Args>(args)...);
690 reply(Proto::Make(req, std::move(result)));
692 }
else if constexpr (std::is_void_v<Params>) {
694 [fn, args...](
const Req &req,
695 llvm::unique_function<void(
const Resp &)> reply)
mutable {
696 llvm::Expected<Result> result =
697 std::invoke(std::forward<Fn>(fn), std::forward<Args>(args)...);
699 return reply(Proto::Make(req, result.takeError()));
700 reply(Proto::Make(req,
toJSON(*result)));
702 }
else if constexpr (std::is_void_v<Result>) {
705 args...](
const Req &req,
706 llvm::unique_function<void(
const Resp &)> reply)
mutable {
707 llvm::Expected<Params> params =
710 return reply(Proto::Make(req, params.takeError()));
712 llvm::Error result = std::invoke(
713 std::forward<Fn>(fn), std::forward<Args>(args)..., *params);
714 reply(Proto::Make(req, std::move(result)));
719 args...](
const Req &req,
720 llvm::unique_function<void(
const Resp &)> reply)
mutable {
721 llvm::Expected<Params> params =
724 return reply(Proto::Make(req, params.takeError()));
726 llvm::Expected<Result> result = std::invoke(
727 std::forward<Fn>(fn), std::forward<Args>(args)..., *params);
729 return reply(Proto::Make(req, result.takeError()));
731 reply(Proto::Make(req,
toJSON(*result)));
736#if __cplusplus >= 202002L
737template <BindingBuilder Proto>
739template <
typename Proto>
741template <
typename Params,
typename Fn,
typename...
Args>
744 "event already bound");
745 if constexpr (std::is_void_v<Params>) {
747 std::invoke(std::forward<Fn>(fn), std::forward<Args>(args)...);
751 args...](
const Evt &evt)
mutable {
752 llvm::Expected<Params> params =
755 return OnError(params.takeError());
756 std::invoke(std::forward<Fn>(fn), std::forward<Args>(args)..., *params);
761#if __cplusplus >= 202002L
762template <BindingBuilder Proto>
764template <
typename Proto>
766template <
typename Result,
typename Params>
769 if constexpr (std::is_void_v<Result> && std::is_void_v<Params>) {
771 std::scoped_lock<std::recursive_mutex> guard(
m_mutex);
773 Req req = Proto::Make(
id, method, std::nullopt);
775 llvm::Expected<llvm::json::Value> result = Proto::Extract(resp);
777 return fn(result.takeError());
778 fn(llvm::Error::success());
783 }
else if constexpr (std::is_void_v<Params>) {
785 std::scoped_lock<std::recursive_mutex> guard(
m_mutex);
787 Req req = Proto::Make(
id, method, std::nullopt);
789 method](
const Resp &resp)
mutable {
790 llvm::Expected<llvm::json::Value> result = Proto::Extract(resp);
792 return fn(result.takeError());
798 }
else if constexpr (std::is_void_v<Result>) {
799 return [
this, method](
const Params ¶ms,
Reply<Result> fn) {
800 std::scoped_lock<std::recursive_mutex> guard(
m_mutex);
802 Req req = Proto::Make(
id, method, llvm::json::Value(params));
804 llvm::Expected<llvm::json::Value> result = Proto::Extract(resp);
806 return fn(result.takeError());
807 fn(llvm::Error::success());
813 return [
this, method](
const Params ¶ms,
Reply<Result> fn) {
814 std::scoped_lock<std::recursive_mutex> guard(
m_mutex);
816 Req req = Proto::Make(
id, method, llvm::json::Value(params));
818 method](
const Resp &resp)
mutable {
819 llvm::Expected<llvm::json::Value> result = Proto::Extract(resp);
820 if (llvm::Error err = result.takeError())
821 return fn(std::move(err));
830#if __cplusplus >= 202002L
831template <BindingBuilder Proto>
833template <
typename Proto>
835template <
typename Params>
837 if constexpr (std::is_void_v<Params>) {
838 return [
this, method]() {
839 if (llvm::Error
error =
840 m_transport.Send(Proto::Make(method, std::nullopt)))
844 return [
this, method](
const Params ¶ms) {
845 if (llvm::Error
error =
852#if __cplusplus >= 202002L
853template <BindingBuilder Proto>
855template <
typename Proto>
859 llvm::StringRef method) {
861 llvm::json::Path::Root root;
865 llvm::raw_string_ostream
OS(context);
866 root.printErrorContext(raw,
OS);
867 return llvm::make_error<InvalidParams>(method.str(), context);
869 return std::move(result);
static llvm::raw_ostream & error(Stream &strm)
A command line argument class.
std::unique_ptr< ReadHandle > ReadHandleUP
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)
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 ~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::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.
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
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, AcceleratorActions &data, llvm::json::Path path)
llvm::json::Value toJSON(const AcceleratorActions &data)
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