Benjamin Kramer | bb1cdb6 | 2017-02-07 10:28:20 +0000 | [diff] [blame] | 1 | //===--- JSONRPCDispatcher.cpp - Main JSON parser entry point -------------===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | |
| 10 | #include "JSONRPCDispatcher.h" |
Kadir Cetinkaya | 689bf93 | 2018-08-24 13:09:41 +0000 | [diff] [blame] | 11 | #include "Cancellation.h" |
Benjamin Kramer | bb1cdb6 | 2017-02-07 10:28:20 +0000 | [diff] [blame] | 12 | #include "ProtocolHandlers.h" |
Sam McCall | 8567cb3 | 2017-11-02 09:21:51 +0000 | [diff] [blame] | 13 | #include "Trace.h" |
Sam McCall | dc8f3cf | 2018-10-17 07:32:05 +0000 | [diff] [blame^] | 14 | #include "Transport.h" |
Sam McCall | 45be5cf | 2018-09-13 12:58:36 +0000 | [diff] [blame] | 15 | #include "llvm/ADT/ScopeExit.h" |
Benjamin Kramer | bb1cdb6 | 2017-02-07 10:28:20 +0000 | [diff] [blame] | 16 | #include "llvm/ADT/SmallString.h" |
Sam McCall | 94362c6 | 2017-11-07 14:45:31 +0000 | [diff] [blame] | 17 | #include "llvm/ADT/StringExtras.h" |
Sam McCall | a90f257 | 2018-02-16 16:41:42 +0000 | [diff] [blame] | 18 | #include "llvm/Support/Chrono.h" |
Sam McCall | 27a07cf | 2018-06-05 09:34:46 +0000 | [diff] [blame] | 19 | #include "llvm/Support/Errno.h" |
Sam McCall | bed5885 | 2018-07-11 10:35:11 +0000 | [diff] [blame] | 20 | #include "llvm/Support/FormatVariadic.h" |
Sam McCall | d20d798 | 2018-07-09 14:25:59 +0000 | [diff] [blame] | 21 | #include "llvm/Support/JSON.h" |
Sam McCall | 45be5cf | 2018-09-13 12:58:36 +0000 | [diff] [blame] | 22 | #include "llvm/Support/ScopedPrinter.h" |
Benjamin Kramer | bb1cdb6 | 2017-02-07 10:28:20 +0000 | [diff] [blame] | 23 | #include "llvm/Support/SourceMgr.h" |
Ilya Biryukov | 687b92a | 2017-05-16 15:23:55 +0000 | [diff] [blame] | 24 | #include <istream> |
| 25 | |
Sam McCall | d20d798 | 2018-07-09 14:25:59 +0000 | [diff] [blame] | 26 | using namespace llvm; |
Benjamin Kramer | bb1cdb6 | 2017-02-07 10:28:20 +0000 | [diff] [blame] | 27 | using namespace clang; |
| 28 | using namespace clangd; |
| 29 | |
Ilya Biryukov | 940901e | 2017-12-13 12:51:22 +0000 | [diff] [blame] | 30 | namespace { |
Sam McCall | d20d798 | 2018-07-09 14:25:59 +0000 | [diff] [blame] | 31 | static Key<json::Value> RequestID; |
Sam McCall | dc8f3cf | 2018-10-17 07:32:05 +0000 | [diff] [blame^] | 32 | static Key<Transport *> CurrentTransport; |
Sam McCall | 1b475a1 | 2018-01-26 09:00:30 +0000 | [diff] [blame] | 33 | |
Fangrui Song | 445bdd1 | 2018-09-05 08:01:37 +0000 | [diff] [blame] | 34 | // When tracing, we trace a request and attach the response in reply(). |
Sam McCall | 1b475a1 | 2018-01-26 09:00:30 +0000 | [diff] [blame] | 35 | // Because the Span isn't available, we find the current request using Context. |
| 36 | class RequestSpan { |
Sam McCall | d20d798 | 2018-07-09 14:25:59 +0000 | [diff] [blame] | 37 | RequestSpan(llvm::json::Object *Args) : Args(Args) {} |
Sam McCall | 1b475a1 | 2018-01-26 09:00:30 +0000 | [diff] [blame] | 38 | std::mutex Mu; |
Sam McCall | d20d798 | 2018-07-09 14:25:59 +0000 | [diff] [blame] | 39 | llvm::json::Object *Args; |
Sam McCall | 24f0fa3 | 2018-01-26 11:23:33 +0000 | [diff] [blame] | 40 | static Key<std::unique_ptr<RequestSpan>> RSKey; |
Sam McCall | 1b475a1 | 2018-01-26 09:00:30 +0000 | [diff] [blame] | 41 | |
| 42 | public: |
| 43 | // Return a context that's aware of the enclosing request, identified by Span. |
| 44 | static Context stash(const trace::Span &Span) { |
Sam McCall | d1a7a37 | 2018-01-31 13:40:48 +0000 | [diff] [blame] | 45 | return Context::current().derive( |
| 46 | RSKey, std::unique_ptr<RequestSpan>(new RequestSpan(Span.Args))); |
Sam McCall | 1b475a1 | 2018-01-26 09:00:30 +0000 | [diff] [blame] | 47 | } |
| 48 | |
| 49 | // If there's an enclosing request and the tracer is interested, calls \p F |
Sam McCall | d20d798 | 2018-07-09 14:25:59 +0000 | [diff] [blame] | 50 | // with a json::Object where request info can be added. |
Sam McCall | d1a7a37 | 2018-01-31 13:40:48 +0000 | [diff] [blame] | 51 | template <typename Func> static void attach(Func &&F) { |
| 52 | auto *RequestArgs = Context::current().get(RSKey); |
Sam McCall | 1b475a1 | 2018-01-26 09:00:30 +0000 | [diff] [blame] | 53 | if (!RequestArgs || !*RequestArgs || !(*RequestArgs)->Args) |
| 54 | return; |
| 55 | std::lock_guard<std::mutex> Lock((*RequestArgs)->Mu); |
| 56 | F(*(*RequestArgs)->Args); |
| 57 | } |
| 58 | }; |
Sam McCall | 24f0fa3 | 2018-01-26 11:23:33 +0000 | [diff] [blame] | 59 | Key<std::unique_ptr<RequestSpan>> RequestSpan::RSKey; |
Ilya Biryukov | 940901e | 2017-12-13 12:51:22 +0000 | [diff] [blame] | 60 | } // namespace |
| 61 | |
Sam McCall | bed5885 | 2018-07-11 10:35:11 +0000 | [diff] [blame] | 62 | void JSONOutput::log(Logger::Level Level, |
| 63 | const llvm::formatv_object_base &Message) { |
| 64 | if (Level < MinLevel) |
| 65 | return; |
Sam McCall | a90f257 | 2018-02-16 16:41:42 +0000 | [diff] [blame] | 66 | llvm::sys::TimePoint<> Timestamp = std::chrono::system_clock::now(); |
Sam McCall | d1a7a37 | 2018-01-31 13:40:48 +0000 | [diff] [blame] | 67 | trace::log(Message); |
Benjamin Kramer | e14bd42 | 2017-02-15 16:44:11 +0000 | [diff] [blame] | 68 | std::lock_guard<std::mutex> Guard(StreamMutex); |
Sam McCall | bed5885 | 2018-07-11 10:35:11 +0000 | [diff] [blame] | 69 | Logs << llvm::formatv("{0}[{1:%H:%M:%S.%L}] {2}\n", indicator(Level), |
| 70 | Timestamp, Message); |
Benjamin Kramer | e14bd42 | 2017-02-15 16:44:11 +0000 | [diff] [blame] | 71 | Logs.flush(); |
| 72 | } |
| 73 | |
Sam McCall | d20d798 | 2018-07-09 14:25:59 +0000 | [diff] [blame] | 74 | void clangd::reply(json::Value &&Result) { |
Kadir Cetinkaya | 689bf93 | 2018-08-24 13:09:41 +0000 | [diff] [blame] | 75 | auto ID = getRequestId(); |
Sam McCall | dd0566b | 2017-11-06 15:40:30 +0000 | [diff] [blame] | 76 | if (!ID) { |
Sam McCall | bed5885 | 2018-07-11 10:35:11 +0000 | [diff] [blame] | 77 | elog("Attempted to reply to a notification!"); |
Sam McCall | 8a5dded | 2017-10-12 13:29:58 +0000 | [diff] [blame] | 78 | return; |
| 79 | } |
Sam McCall | d20d798 | 2018-07-09 14:25:59 +0000 | [diff] [blame] | 80 | RequestSpan::attach([&](json::Object &Args) { Args["Reply"] = Result; }); |
Sam McCall | 8d7760c | 2018-07-12 11:52:18 +0000 | [diff] [blame] | 81 | log("--> reply({0})", *ID); |
Sam McCall | d1a7a37 | 2018-01-31 13:40:48 +0000 | [diff] [blame] | 82 | Context::current() |
Sam McCall | dc8f3cf | 2018-10-17 07:32:05 +0000 | [diff] [blame^] | 83 | .getExisting(CurrentTransport) |
| 84 | ->reply(std::move(*ID), std::move(Result)); |
Benjamin Kramer | bb1cdb6 | 2017-02-07 10:28:20 +0000 | [diff] [blame] | 85 | } |
| 86 | |
Ilya Biryukov | 74f2655 | 2018-07-26 12:05:31 +0000 | [diff] [blame] | 87 | void clangd::replyError(ErrorCode Code, const llvm::StringRef &Message) { |
| 88 | elog("Error {0}: {1}", static_cast<int>(Code), Message); |
Sam McCall | d20d798 | 2018-07-09 14:25:59 +0000 | [diff] [blame] | 89 | RequestSpan::attach([&](json::Object &Args) { |
Ilya Biryukov | 74f2655 | 2018-07-26 12:05:31 +0000 | [diff] [blame] | 90 | Args["Error"] = json::Object{{"code", static_cast<int>(Code)}, |
Sam McCall | d20d798 | 2018-07-09 14:25:59 +0000 | [diff] [blame] | 91 | {"message", Message.str()}}; |
Sam McCall | 1b475a1 | 2018-01-26 09:00:30 +0000 | [diff] [blame] | 92 | }); |
Ilya Biryukov | 940901e | 2017-12-13 12:51:22 +0000 | [diff] [blame] | 93 | |
Kadir Cetinkaya | 689bf93 | 2018-08-24 13:09:41 +0000 | [diff] [blame] | 94 | if (auto ID = getRequestId()) { |
Sam McCall | 8d7760c | 2018-07-12 11:52:18 +0000 | [diff] [blame] | 95 | log("--> reply({0}) error: {1}", *ID, Message); |
Sam McCall | d1a7a37 | 2018-01-31 13:40:48 +0000 | [diff] [blame] | 96 | Context::current() |
Sam McCall | dc8f3cf | 2018-10-17 07:32:05 +0000 | [diff] [blame^] | 97 | .getExisting(CurrentTransport) |
| 98 | ->reply(std::move(*ID), make_error<LSPError>(Message, Code)); |
Sam McCall | 8a5dded | 2017-10-12 13:29:58 +0000 | [diff] [blame] | 99 | } |
Benjamin Kramer | bb1cdb6 | 2017-02-07 10:28:20 +0000 | [diff] [blame] | 100 | } |
| 101 | |
Kadir Cetinkaya | 689bf93 | 2018-08-24 13:09:41 +0000 | [diff] [blame] | 102 | void clangd::replyError(Error E) { |
| 103 | handleAllErrors(std::move(E), |
| 104 | [](const CancelledError &TCE) { |
| 105 | replyError(ErrorCode::RequestCancelled, TCE.message()); |
| 106 | }, |
| 107 | [](const ErrorInfoBase &EIB) { |
| 108 | replyError(ErrorCode::InvalidParams, EIB.message()); |
| 109 | }); |
| 110 | } |
| 111 | |
Sam McCall | d20d798 | 2018-07-09 14:25:59 +0000 | [diff] [blame] | 112 | void clangd::call(StringRef Method, json::Value &&Params) { |
Sam McCall | d20d798 | 2018-07-09 14:25:59 +0000 | [diff] [blame] | 113 | RequestSpan::attach([&](json::Object &Args) { |
| 114 | Args["Call"] = json::Object{{"method", Method.str()}, {"params", Params}}; |
Sam McCall | 1b475a1 | 2018-01-26 09:00:30 +0000 | [diff] [blame] | 115 | }); |
Sam McCall | 8d7760c | 2018-07-12 11:52:18 +0000 | [diff] [blame] | 116 | // FIXME: Generate/Increment IDs for every request so that we can get proper |
| 117 | // replies once we need to. |
| 118 | auto ID = 1; |
| 119 | log("--> {0}({1})", Method, ID); |
Sam McCall | d1a7a37 | 2018-01-31 13:40:48 +0000 | [diff] [blame] | 120 | Context::current() |
Sam McCall | dc8f3cf | 2018-10-17 07:32:05 +0000 | [diff] [blame^] | 121 | .getExisting(CurrentTransport) |
| 122 | ->call(Method, std::move(Params), ID); |
Marc-Andre Laperle | e7ec16a | 2017-11-03 13:39:15 +0000 | [diff] [blame] | 123 | } |
| 124 | |
Sam McCall | 45be5cf | 2018-09-13 12:58:36 +0000 | [diff] [blame] | 125 | JSONRPCDispatcher::JSONRPCDispatcher(Handler UnknownHandler) |
| 126 | : UnknownHandler(std::move(UnknownHandler)) { |
| 127 | registerHandler("$/cancelRequest", [this](const json::Value &Params) { |
| 128 | if (auto *O = Params.getAsObject()) |
Sam McCall | dc8f3cf | 2018-10-17 07:32:05 +0000 | [diff] [blame^] | 129 | if (auto *ID = O->get("id")) { |
| 130 | cancelRequest(*ID); |
| 131 | return true; |
| 132 | } |
Sam McCall | 45be5cf | 2018-09-13 12:58:36 +0000 | [diff] [blame] | 133 | log("Bad cancellation request: {0}", Params); |
Sam McCall | dc8f3cf | 2018-10-17 07:32:05 +0000 | [diff] [blame^] | 134 | return true; |
Sam McCall | 45be5cf | 2018-09-13 12:58:36 +0000 | [diff] [blame] | 135 | }); |
| 136 | } |
| 137 | |
Sam McCall | 8a5dded | 2017-10-12 13:29:58 +0000 | [diff] [blame] | 138 | void JSONRPCDispatcher::registerHandler(StringRef Method, Handler H) { |
Benjamin Kramer | bb1cdb6 | 2017-02-07 10:28:20 +0000 | [diff] [blame] | 139 | assert(!Handlers.count(Method) && "Handler already registered!"); |
| 140 | Handlers[Method] = std::move(H); |
| 141 | } |
| 142 | |
Sam McCall | dc8f3cf | 2018-10-17 07:32:05 +0000 | [diff] [blame^] | 143 | bool JSONRPCDispatcher::onCall(StringRef Method, json::Value Params, |
| 144 | json::Value ID) { |
| 145 | log("<-- {0}({1})", Method, ID); |
| 146 | auto I = Handlers.find(Method); |
Sam McCall | ec10902 | 2017-11-28 09:37:43 +0000 | [diff] [blame] | 147 | auto &Handler = I != Handlers.end() ? I->second : UnknownHandler; |
Ilya Biryukov | 940901e | 2017-12-13 12:51:22 +0000 | [diff] [blame] | 148 | |
Ilya Biryukov | ee27d2e | 2017-12-14 15:04:59 +0000 | [diff] [blame] | 149 | // Create a Context that contains request information. |
Sam McCall | dc8f3cf | 2018-10-17 07:32:05 +0000 | [diff] [blame^] | 150 | WithContextValue WithID(RequestID, ID); |
Ilya Biryukov | ee27d2e | 2017-12-14 15:04:59 +0000 | [diff] [blame] | 151 | |
| 152 | // Create a tracing Span covering the whole request lifetime. |
Sam McCall | dc8f3cf | 2018-10-17 07:32:05 +0000 | [diff] [blame^] | 153 | trace::Span Tracer(Method); |
| 154 | SPAN_ATTACH(Tracer, "ID", ID); |
Sam McCall | 1b475a1 | 2018-01-26 09:00:30 +0000 | [diff] [blame] | 155 | SPAN_ATTACH(Tracer, "Params", Params); |
Ilya Biryukov | 940901e | 2017-12-13 12:51:22 +0000 | [diff] [blame] | 156 | |
Sam McCall | dc8f3cf | 2018-10-17 07:32:05 +0000 | [diff] [blame^] | 157 | // Calls can be canceled by the client. Add cancellation context. |
| 158 | WithContext WithCancel(cancelableRequestContext(ID)); |
Sam McCall | 45be5cf | 2018-09-13 12:58:36 +0000 | [diff] [blame] | 159 | |
Sam McCall | 1b475a1 | 2018-01-26 09:00:30 +0000 | [diff] [blame] | 160 | // Stash a reference to the span args, so later calls can add metadata. |
Sam McCall | d1a7a37 | 2018-01-31 13:40:48 +0000 | [diff] [blame] | 161 | WithContext WithRequestSpan(RequestSpan::stash(Tracer)); |
Sam McCall | dc8f3cf | 2018-10-17 07:32:05 +0000 | [diff] [blame^] | 162 | return Handler(std::move(Params)); |
| 163 | } |
| 164 | |
| 165 | bool JSONRPCDispatcher::onNotify(StringRef Method, json::Value Params) { |
| 166 | log("<-- {0}", Method); |
| 167 | auto I = Handlers.find(Method); |
| 168 | auto &Handler = I != Handlers.end() ? I->second : UnknownHandler; |
| 169 | |
| 170 | // Create a tracing Span covering the whole request lifetime. |
| 171 | trace::Span Tracer(Method); |
| 172 | SPAN_ATTACH(Tracer, "Params", Params); |
| 173 | |
| 174 | // Stash a reference to the span args, so later calls can add metadata. |
| 175 | WithContext WithRequestSpan(RequestSpan::stash(Tracer)); |
| 176 | return Handler(std::move(Params)); |
| 177 | } |
| 178 | |
| 179 | bool JSONRPCDispatcher::onReply(json::Value ID, Expected<json::Value> Result) { |
| 180 | // We ignore replies, just log them. |
| 181 | if (Result) |
| 182 | log("<-- reply({0})", ID); |
| 183 | else |
| 184 | log("<-- reply({0}) error: {1}", ID, llvm::toString(Result.takeError())); |
Benjamin Kramer | bb1cdb6 | 2017-02-07 10:28:20 +0000 | [diff] [blame] | 185 | return true; |
| 186 | } |
Ilya Biryukov | afb5554 | 2017-05-16 14:40:30 +0000 | [diff] [blame] | 187 | |
Sam McCall | 45be5cf | 2018-09-13 12:58:36 +0000 | [diff] [blame] | 188 | // We run cancelable requests in a context that does two things: |
| 189 | // - allows cancellation using RequestCancelers[ID] |
| 190 | // - cleans up the entry in RequestCancelers when it's no longer needed |
| 191 | // If a client reuses an ID, the last one wins and the first cannot be canceled. |
| 192 | Context JSONRPCDispatcher::cancelableRequestContext(const json::Value &ID) { |
| 193 | auto Task = cancelableTask(); |
| 194 | auto StrID = llvm::to_string(ID); // JSON-serialize ID for map key. |
| 195 | auto Cookie = NextRequestCookie++; // No lock, only called on main thread. |
| 196 | { |
| 197 | std::lock_guard<std::mutex> Lock(RequestCancelersMutex); |
| 198 | RequestCancelers[StrID] = {std::move(Task.second), Cookie}; |
| 199 | } |
| 200 | // When the request ends, we can clean up the entry we just added. |
| 201 | // The cookie lets us check that it hasn't been overwritten due to ID reuse. |
| 202 | return Task.first.derive(make_scope_exit([this, StrID, Cookie] { |
| 203 | std::lock_guard<std::mutex> Lock(RequestCancelersMutex); |
| 204 | auto It = RequestCancelers.find(StrID); |
| 205 | if (It != RequestCancelers.end() && It->second.second == Cookie) |
| 206 | RequestCancelers.erase(It); |
| 207 | })); |
| 208 | } |
| 209 | |
| 210 | void JSONRPCDispatcher::cancelRequest(const json::Value &ID) { |
| 211 | auto StrID = llvm::to_string(ID); |
| 212 | std::lock_guard<std::mutex> Lock(RequestCancelersMutex); |
| 213 | auto It = RequestCancelers.find(StrID); |
| 214 | if (It != RequestCancelers.end()) |
| 215 | It->second.first(); // Invoke the canceler. |
| 216 | } |
| 217 | |
Sam McCall | dc8f3cf | 2018-10-17 07:32:05 +0000 | [diff] [blame^] | 218 | llvm::Error JSONRPCDispatcher::runLanguageServerLoop(Transport &Transport) { |
| 219 | // Propagate transport to all handlers so they can reply. |
| 220 | WithContextValue WithTransport(CurrentTransport, &Transport); |
| 221 | return Transport.loop(*this); |
Ilya Biryukov | afb5554 | 2017-05-16 14:40:30 +0000 | [diff] [blame] | 222 | } |
Kadir Cetinkaya | 689bf93 | 2018-08-24 13:09:41 +0000 | [diff] [blame] | 223 | |
| 224 | const json::Value *clangd::getRequestId() { |
| 225 | return Context::current().get(RequestID); |
| 226 | } |