#pragma once #include "LibLsp/lsp/lsp_diagnostic.h" #include "LibLsp/JsonRpc/Cancellation.h" #include "LibLsp/JsonRpc/RequestError.h" #include "LibLsp/JsonRpc/lsResponseMessage.h" #include "LibLsp/JsonRpc/RequestInMessage.h" #include "LibLsp/JsonRpc/NotificationInMessage.h" #include "traits.h" #include #include #include #include #include #include #include #include #include #include "threaded_queue.h" #include #include "MessageIssue.h" #include "LibLsp/JsonRpc/MessageJsonHandler.h" #include "Endpoint.h" #include "future.h" #include #include #include "MessageProducer.h" class MessageJsonHandler; class Endpoint; struct LspMessage; class RemoteEndPoint; enum class RemoteEndPointOverloadPolicy { // Safest for a JSON-RPC stream: stop the current session instead of // silently dropping an ordered frame and corrupting protocol state. StopProcessing, // Intended for embedders that prefer best-effort processing under pressure. // Ordered gaps are converted to no-op parsed messages so routing can // continue, but request/notification semantics for the dropped frame are // not preserved. DropNewest, }; struct RemoteEndPointLimits { // Zero means unlimited for every field. size_t max_frame_size = 0; size_t max_parse_queue_size = 0; size_t max_reorder_buffer_size = 0; size_t max_notification_queue_size = 0; size_t max_parked_request_queue_size = 0; size_t max_pending_cancel_requests = 0; size_t max_seen_request_ids = 0; size_t max_pending_outgoing_requests = 0; RemoteEndPointOverloadPolicy overload_policy = RemoteEndPointOverloadPolicy::StopProcessing; }; namespace lsp { class ostream; class istream; //////////////////////////////////////////////////////////////////////////////// // ResponseOrError //////////////////////////////////////////////////////////////////////////////// // ResponseOrError holds either the response to a request or an error // message. template struct ResponseOrError { using Request = T; ResponseOrError(); ResponseOrError(T const& response); ResponseOrError(T&& response); ResponseOrError(Rsp_Error const& error); ResponseOrError(Rsp_Error&& error); ResponseOrError(ResponseOrError const& other); ResponseOrError(ResponseOrError&& other) noexcept; ResponseOrError& operator=(ResponseOrError const& other); ResponseOrError& operator=(ResponseOrError&& other) noexcept; bool IsError() const { return is_error; } std::string ToJson() { if (is_error) { return error.ToJson(); } return response.ToJson(); } T response; Rsp_Error error; // empty represents success. bool is_error; }; template ResponseOrError::ResponseOrError() : is_error(false) { } template ResponseOrError::ResponseOrError(T const& resp) : response(resp), is_error(false) { } template ResponseOrError::ResponseOrError(T&& resp) : response(std::move(resp)), is_error(false) { } template ResponseOrError::ResponseOrError(Rsp_Error const& err) : error(err), is_error(true) { } template ResponseOrError::ResponseOrError(Rsp_Error&& err) : error(std::move(err)), is_error(true) { } template ResponseOrError::ResponseOrError(ResponseOrError const& other) : response(other.response), error(other.error), is_error(other.is_error) { } template ResponseOrError::ResponseOrError(ResponseOrError&& other) noexcept : response(std::move(other.response)), error(std::move(other.error)), is_error(other.is_error) { } template ResponseOrError& ResponseOrError::operator=(ResponseOrError const& other) { response = other.response; error = other.error; is_error = other.is_error; return *this; } template ResponseOrError& ResponseOrError::operator=(ResponseOrError&& other) noexcept { response = std::move(other.response); error = std::move(other.error); is_error = other.is_error; return *this; } namespace detail { template struct is_lsp_future : std::false_type { }; template struct is_lsp_future> : std::true_type { }; template struct is_valid_async_request_return : std::false_type { }; template struct is_valid_async_request_return, ResponseType> : std::integral_constant< bool, std::is_same::value || std::is_same>::value> { }; template struct async_future_value { }; template struct async_future_value> { using type = V; }; template using handler_return_t = typename lsp::traits::SignatureOfT::ret; template using async_handler_value_t = typename async_future_value>::type; // Output state for one startProcessingMessages() session. // // Request handlers may finish after stop(), or even after the endpoint has // restarted with a different d_ptr->output. They must therefore write through // the session snapshot they were dispatched with, not by rereading the mutable // endpoint output. active=false means this session is no longer allowed to emit // late responses; output may still be kept alive only so in-flight handlers can // safely observe and drop their work. // // A global "endpoint is active" flag is not enough: after restart, d_ptr->output // may point at the new connection and be active again. The old handler must // check the active flag that belongs to its captured output snapshot, otherwise // an old-session response can be written to the new session. struct SessionOutputState { std::atomic active {true}; std::shared_ptr output; std::shared_ptr send_mutex; uint64_t generation = 0; }; template lsp::ResponseOrError normalizeHandlerResult(lsp::ResponseOrError const& result) { return result; } template lsp::ResponseOrError normalizeHandlerResult(lsp::ResponseOrError&& result) { return std::move(result); } template typename std::enable_if< !std::is_same::type, lsp::ResponseOrError>::value, lsp::ResponseOrError>::type normalizeHandlerResult(Result&& result) { return lsp::ResponseOrError(std::forward(result)); } } // namespace detail } // namespace lsp class RemoteEndPoint : MessageIssueHandler { template using ParamType = lsp::traits::ParameterType; template using IsRequest = lsp::traits::EnableIfIsType; template using IsResponse = lsp::traits::EnableIfIsType; template using IsNotify = lsp::traits::EnableIfIsType; template using EnableIfSyncRequestHandler = lsp::traits::EnableIf< !lsp::detail::is_lsp_future>::value && lsp::traits::CompatibleWith< F, std::function(RequestType const&)>>::value, bool>; template using EnableIfSyncRequestHandlerWithMonitor = lsp::traits::EnableIf< !lsp::detail::is_lsp_future>::value && lsp::traits::CompatibleWith< F, std::function(RequestType const&, CancelMonitor const&)>>::value, bool>; template using EnableIfAsyncRequestHandler = lsp::traits::EnableIf< lsp::detail::is_valid_async_request_return, ResponseType>::value && lsp::traits::CompatibleWith(RequestType const&)>>::value, bool>; template using EnableIfAsyncRequestHandlerWithMonitor = lsp::traits::EnableIf< lsp::detail::is_valid_async_request_return, ResponseType>::value && lsp::traits::CompatibleWith< F, std::function(RequestType const&, CancelMonitor const&)>>::value, bool>; enum class PendingCompletionPolicy { FastStateOnly, DeferredCallback, }; bool internalSendRequestWithPolicy( RequestInMessage& info, GenericResponseHandler handler, PendingCompletionPolicy policy ); public: RemoteEndPoint( std::shared_ptr const& json_handler, std::shared_ptr const& localEndPoint, lsp::Log& _log, lsp::JSONStreamStyle style = lsp::JSONStreamStyle::Standard, uint8_t max_workers = 2 ); RemoteEndPoint( std::shared_ptr const& json_handler, std::shared_ptr const& localEndPoint, lsp::Log& _log, lsp::JSONStreamStyle style, uint8_t max_workers, RemoteEndPointLimits limits ); ~RemoteEndPoint() override; template, typename ResponseType = typename RequestType::Response> EnableIfSyncRequestHandler registerHandler(F&& handler) { if (!canRegisterBeforeStart("registerHandler")) { return false; } registerSyncRequestHandler(std::forward(handler)); return true; } template, typename ResponseType = typename RequestType::Response> EnableIfSyncRequestHandlerWithMonitor registerHandler(F&& handler) { if (!canRegisterBeforeStart("registerHandler")) { return false; } registerSyncRequestHandlerWithMonitor(std::forward(handler)); return true; } template, typename ResponseType = typename RequestType::Response> EnableIfAsyncRequestHandler registerHandler(F&& handler) { if (!canRegisterBeforeStart("registerHandler")) { return false; } registerAsyncRequestHandler(std::forward(handler)); return true; } template, typename ResponseType = typename RequestType::Response> EnableIfAsyncRequestHandlerWithMonitor registerHandler(F&& handler) { if (!canRegisterBeforeStart("registerHandler")) { return false; } registerAsyncRequestHandlerWithMonitor(std::forward(handler)); return true; } using RequestErrorCallback = std::function; template> void send(T& request, F&& handler, RequestErrorCallback onError) { if (!ensureResponseJsonHandler()) { Rsp_Error error; error.id = request.id; error.error.code = lsErrorCodes::InternalError; error.error.message = "Response parser must be registered before startProcessingMessages()."; onError(error); return; } auto cb = [=](std::unique_ptr msg) { if (!msg) { return true; } auto const result = msg.get(); if (static_cast(result)->IsErrorType()) { auto const rsp_error = static_cast(result); onError(*rsp_error); } else { handler(*static_cast(result)); } return true; }; if (!internalSendRequest(request, cb)) { Rsp_Error error; error.id = request.id; error.error.code = lsErrorCodes::InternalError; error.error.message = "Failed to send request."; onError(error); } } template> lsp::traits::EnableIfIsType registerHandler(F&& handler) { if (!canRegisterBeforeStart("registerHandler")) { return false; } if (!jsonHandler->GetNotificationJsonHandler(NotifyType::kMethodInfo)) { jsonHandler->SetNotificationJsonHandler( NotifyType::kMethodInfo, [](Reader& visitor) { return NotifyType::ReflectReader(visitor); } ); } local_endpoint->registerNotifyHandler( NotifyType::kMethodInfo, [=](std::unique_ptr msg) { handler(*static_cast(msg.get())); return true; } ); return true; } template> bool allowConcurrentNotification() { return allowConcurrentNotification(NotifyType::kMethodInfo); } bool allowConcurrentNotification(std::string const& method); template> lsp::future> send(T& request) { bool const has_response_parser = ensureResponseJsonHandler(); using Response = typename T::Response; auto promise = std::make_shared>>(); auto cb = [=](std::unique_ptr msg) { if (!msg) { return true; } auto result = msg.get(); if (static_cast(result)->IsErrorType()) { Rsp_Error* rsp_error = static_cast(result); Rsp_Error temp; std::swap(temp, *rsp_error); promise->set_value(std::move(lsp::ResponseOrError(std::move(temp)))); } else { Response temp; std::swap(temp, *static_cast(result)); promise->set_value(std::move(lsp::ResponseOrError(std::move(temp)))); } return true; }; if (!has_response_parser || !internalSendRequestWithPolicy(request, cb, PendingCompletionPolicy::FastStateOnly)) { Rsp_Error error; error.id = request.id; error.error.code = lsErrorCodes::InternalError; error.error.message = has_response_parser ? "Failed to send request." : "Response parser must be registered before startProcessingMessages()."; promise->set_value(lsp::ResponseOrError(std::move(error))); } return promise->get_future(); } template> std::unique_ptr> waitResponse(T& request, unsigned const time_out = 0) { auto future_rsp = send(request); if (time_out == 0) { future_rsp.wait(); } else { auto state = future_rsp.wait_for(std::chrono::milliseconds(time_out)); if (lsp::future_status::timeout == state) { removeRequestInfo(request.id); return {}; } } using Response = typename T::Response; return std::make_unique>(std::move(future_rsp.get())); } void send(NotificationInMessage& msg) { sendMsg(msg); } void send(ResponseInMessage& msg) { sendMsg(msg); } void sendNotification(NotificationInMessage& msg) { send(msg); } void sendResponse(ResponseInMessage& msg) { send(msg); } template T createRequest() { auto req = T(); req.id.set(getNextRequestId()); return req; } bool overrideRequestParser(std::string const& method, GenericRequestJsonHandler handler) { if (!canRegisterBeforeStart("overrideRequestParser")) { return false; } jsonHandler->SetRequestJsonHandler(method, std::move(handler)); return true; } template> bool overrideRequestParser() { return overrideRequestParser( RequestType::kMethodInfo, [](Reader& visitor) { return RequestType::ReflectReader(visitor); } ); } bool overrideResponseParser(std::string const& method, GenericResponseJsonHandler handler) { if (!canRegisterBeforeStart("overrideResponseParser")) { return false; } jsonHandler->SetResponseJsonHandler(method, std::move(handler)); return true; } template> bool registerResponseParser() { if (!canRegisterBeforeStart("registerResponseParser")) { return false; } registerResponseJsonHandler(); return true; } int getNextRequestId(); bool cancelRequest(lsRequestId const&); void startProcessingMessages(std::shared_ptr r, std::shared_ptr w); bool isWorking() const; void stop(); std::unique_ptr internalWaitResponse(RequestInMessage&, unsigned time_out = 0); bool internalSendRequest(RequestInMessage& info, GenericResponseHandler handler); void handle(std::vector&&) override; void handle(MessageIssue&&) override; private: struct ParsedMessage; using PendingRequestToken = std::shared_ptr; std::shared_ptr getSessionOutputState() const; std::shared_ptr retainRequestCancellation(lsRequestId const& id); void postAsyncCompletion(std::function&& completion); static void sendSessionMessage(std::shared_ptr const& state, LspMessage& msg); void sendRspError(lsRequestId const& id, lsp::RequestError const& error) { Rsp_Error rsp = lsp::toRspError(id, error); sendSessionMessage(getSessionOutputState(), rsp); } void sendInternalError(lsRequestId const& id, std::string const& message) { Rsp_Error rsp; rsp.id = id; rsp.error.code = lsErrorCodes::InternalError; rsp.error.message = message; sendSessionMessage(getSessionOutputState(), rsp); } CancelMonitor getCancelMonitor(lsRequestId const&); void removeRequestInfo(lsRequestId const&); bool canRegisterBeforeStart(char const* operation); void sendMsg(LspMessage& msg); ParsedMessage parseAndClassify(std::string const& content); void mainLoopCatching( std::unique_ptr, uint64_t sequence, std::shared_ptr response_state, PendingRequestToken pending ); void routeIncoming(std::string&& content, uint64_t sequence) const; void routeParsedIncoming(ParsedMessage&& parsed, uint64_t sequence) const; void mainLoop( std::unique_ptr, uint64_t sequence, std::shared_ptr response_state, PendingRequestToken pending ); template static void sendAsyncHandlerResult( std::shared_ptr const& state, lsp::ResponseOrError&& res, lsRequestId const& id ) { if (res.is_error) { res.error.id = id; sendSessionMessage(state, res.error); } else { res.response.id = id; sendSessionMessage(state, res.response); } } template static void sendHandlerResult( std::shared_ptr const& state, lsp::ResponseOrError&& res, lsRequestId const& id ) { if (res.is_error) { res.error.id = id; sendSessionMessage(state, res.error); } else { res.response.id = id; sendSessionMessage(state, res.response); } } template void completeAsyncHandler(Future fut, lsRequestId const& id) { auto shared_future = std::make_shared(std::move(fut)); auto response_state = getSessionOutputState(); auto cancellation_retainer = retainRequestCancellation(id); postAsyncCompletion( [id, shared_future, response_state, cancellation_retainer]() mutable { if (shared_future->wait_for(std::chrono::milliseconds(0)) != lsp::future_status::ready) { return false; } try { sendAsyncHandlerResult( response_state, lsp::detail::normalizeHandlerResult(shared_future->get()), id ); } catch (lsp::RequestError const& error) { Rsp_Error rsp = lsp::toRspError(id, error); sendSessionMessage(response_state, rsp); } catch (std::exception const& error) { Rsp_Error rsp; rsp.id = id; rsp.error.code = lsErrorCodes::InternalError; rsp.error.message = error.what(); sendSessionMessage(response_state, rsp); } catch (...) { Rsp_Error rsp; rsp.id = id; rsp.error.code = lsErrorCodes::InternalError; rsp.error.message = "Unhandled exception."; sendSessionMessage(response_state, rsp); } return true; } ); } template void registerSyncRequestHandler(F&& handler) { registerRequestJsonHandlerIfMissing(); local_endpoint->registerRequestHandler( RequestType::kMethodInfo, [this, handler = std::forward(handler)](std::unique_ptr msg) mutable { auto req = static_cast(msg.get()); auto response_state = getSessionOutputState(); try { sendHandlerResult( response_state, lsp::detail::normalizeHandlerResult(handler(*req)), req->id ); } catch (lsp::RequestError const& error) { sendRspError(req->id, error); } catch (std::exception const& error) { sendInternalError(req->id, error.what()); } catch (...) { sendInternalError(req->id, "Unhandled exception."); } return true; } ); } template void registerSyncRequestHandlerWithMonitor(F&& handler) { registerRequestJsonHandlerIfMissing(); local_endpoint->registerRequestHandler( RequestType::kMethodInfo, [this, handler = std::forward(handler)](std::unique_ptr msg) mutable { auto req = static_cast(msg.get()); auto response_state = getSessionOutputState(); try { sendHandlerResult( response_state, lsp::detail::normalizeHandlerResult( handler(*req, getCancelMonitor(req->id)) ), req->id ); } catch (lsp::RequestError const& error) { sendRspError(req->id, error); } catch (std::exception const& error) { sendInternalError(req->id, error.what()); } catch (...) { sendInternalError(req->id, "Unhandled exception."); } return true; } ); } template void registerAsyncRequestHandler(F&& handler) { registerRequestJsonHandlerIfMissing(); local_endpoint->registerRequestHandler( RequestType::kMethodInfo, [this, handler = std::forward(handler)](std::unique_ptr msg) mutable { auto req = static_cast(msg.get()); try { completeAsyncHandler(handler(*req), req->id); } catch (lsp::RequestError const& error) { sendRspError(req->id, error); } catch (std::exception const& error) { sendInternalError(req->id, error.what()); } catch (...) { sendInternalError(req->id, "Unhandled exception."); } return true; } ); } template void registerAsyncRequestHandlerWithMonitor(F&& handler) { registerRequestJsonHandlerIfMissing(); local_endpoint->registerRequestHandler( RequestType::kMethodInfo, [this, handler = std::forward(handler)](std::unique_ptr msg) mutable { auto req = static_cast(msg.get()); try { completeAsyncHandler(handler(*req, getCancelMonitor(req->id)), req->id); } catch (lsp::RequestError const& error) { sendRspError(req->id, error); } catch (std::exception const& error) { sendInternalError(req->id, error.what()); } catch (...) { sendInternalError(req->id, "Unhandled exception."); } return true; } ); } template> void registerRequestJsonHandlerIfMissing() { if (!jsonHandler->GetRequestJsonHandler(RequestType::kMethodInfo)) { jsonHandler->SetRequestJsonHandler( RequestType::kMethodInfo, [](Reader& visitor) { return RequestType::ReflectReader(visitor); } ); } } template> bool ensureResponseJsonHandler() { if (jsonHandler->GetResponseJsonHandler(T::kMethodInfo)) { return true; } if (!canRegisterBeforeStart("registerResponseJsonHandler")) { return false; } registerResponseJsonHandler(); return true; } template> void registerResponseJsonHandler() { using Response = typename T::Response; if (!jsonHandler->GetResponseJsonHandler(T::kMethodInfo)) { jsonHandler->SetResponseJsonHandler( T::kMethodInfo, [](Reader& visitor) { if (visitor.HasMember("error")) { return Rsp_Error::ReflectReader(visitor); } return Response::ReflectReader(visitor); } ); } } struct Data; Data* d_ptr; std::shared_ptr jsonHandler; std::shared_ptr m_sendMutex {std::make_shared()}; std::shared_ptr local_endpoint; public: std::shared_ptr message_producer_thread_; }; .