Debian Codegraph @

testsuite/systemtap.language_server/jsonrpc.py

raw
1 # jsonrpc implementation of https://www.jsonrpc.org/specification
2 # Copyright (c) 2016 Sourcegraph
3 # Copyright (c) 2019 Seven Bridges
4 # Copyright (C) 2022 Red Hat Inc.
5 #
6 # Retrieved from: https://github.com/rabix/benten/blob/master/benten/langserver/jsonrpc.py
7 #
8 # This file is part of systemtap, and is free software. You can
9 # redistribute it and/or modify it under the terms of the GNU General
10 # Public License (GPL); either version 2, or (at your option) any
11 # later version.
12
13 import json
14 import logging
15 import queue
16 import threading
17 from collections import deque
18
19
20 class JSONRPC2ProtocolError(Exception):
21 pass
22
23
24 class ReadWriter:
25 def __init__(self, reader, writer):
26 self.reader = reader
27 self.writer = writer
28
29 def readline(self, *args):
30 return self.reader.readline(*args).decode("utf-8")
31
32 def read(self, *args):
33 return self.reader.read(*args).decode("utf-8")
34
35 def write(self, out):
36 self.writer.write(out.encode("utf-8"))
37 self.writer.flush()
38
39
40 class JSONRPC2Connection:
41 def __init__(self, conn=None):
42 self.conn = conn
43 self._msg_buffer = deque()
44 self._next_id = 1
45
46 def _read_header_content_length(self, line):
47 if len(line) < 2 or line[-2:] != "\r\n":
48 raise JSONRPC2ProtocolError("Line endings must be \\r\\n")
49 if line.startswith("Content-Length: "):
50 _, value = line.split("Content-Length: ")
51 value = value.strip()
52 try:
53 return int(value)
54 except ValueError:
55 raise JSONRPC2ProtocolError(
56 "Invalid Content-Length header: {}".format(value))
57
58 def _receive(self):
59 line = self.conn.readline()
60 if line == "":
61 raise EOFError()
62 length = self._read_header_content_length(line)
63 # Keep reading headers until we find the sentinel line for the JSON
64 # request.
65 while line != "\r\n":
66 line = self.conn.readline()
67 body = self.conn.read(length)
68 return json.loads(body)
69
70 def read_message(self, want=None):
71 """Read a JSON RPC message sent over the current connection.
72 If id is None, the next available message is returned.
73 """
74 if want is None:
75 if self._msg_buffer:
76 return self._msg_buffer.popleft()
77 return self._receive()
78
79 # First check if our buffer contains something we want.
80 msg = deque_find_and_pop(self._msg_buffer, want)
81 if msg:
82 return msg
83
84 # We need to keep receiving until we find something we want.
85 # Things we don't want are put into the buffer for future callers.
86 while True:
87 msg = self._receive()
88 if want(msg):
89 return msg
90 self._msg_buffer.append(msg)
91
92 def _send(self, body):
93 body = json.dumps(body, separators=(",", ":"))
94 content_length = len(body)
95 response = (
96 "Content-Length: {}\r\n"
97 "Content-Type: application/vscode-jsonrpc; charset=utf-8\r\n\r\n"
98 "{}".format(content_length, body))
99 self.conn.write(response)
100
101 def write_response(self, rid, result):
102 body = {
103 "jsonrpc": "2.0",
104 "id": rid,
105 "result": result,
106 }
107 self._send(body)
108
109 def write_error(self, rid, code, message, data=None):
110 e = {
111 "code": code,
112 "message": message,
113 }
114 if data is not None:
115 e["data"] = data
116 body = {
117 "jsonrpc": "2.0",
118 "id": rid,
119 "error": e,
120 }
121 self._send(body)
122
123 def send_request(self, method: str, params):
124 rid = self._next_id
125 self._next_id += 1
126 body = {
127 "jsonrpc": "2.0",
128 "id": rid,
129 "method": method,
130 "params": params,
131 }
132 self._send(body)
133 return self.read_message(want=lambda msg: msg.get("id") == rid)
134
135 def send_notification(self, method: str, params):
136 body = {
137 "jsonrpc": "2.0",
138 "method": method,
139 "params": params,
140 }
141 self._send(body)
142
143 def send_request_batch(self, requests):
144 """Pipelines requests and returns responses.
145 The responses is a generator where the nth response corresponds
146 with the nth request. Users must read the generator until the
147 end, otherwise you will leak a thread.
148 """
149
150 # We communicate the request ids using a thread safe queue.
151 # It also allows us to bound the number of concurrent requests.
152 q = queue.Queue(100)
153
154 def send():
155 for method, params in requests:
156 rid = self._next_id
157 self._next_id += 1
158 q.put(rid)
159 body = {
160 "jsonrpc": "2.0",
161 "id": rid,
162 "method": method,
163 "params": params,
164 }
165 self._send(body)
166
167 # Sentinel value to indicate we are done
168 q.put(None)
169
170 threading.Thread(target=send).start()
171
172 while True:
173 rid = q.get()
174 if rid is None:
175 break
176 yield self.read_message(want=lambda msg: msg.get("id") == rid)
177
178
179 def deque_find_and_pop(d, f):
180 idx = None
181 for i, v in enumerate(d):
182 if f(v):
183 idx = i
184 break
185 if idx is None:
186 return None
187 d.rotate(-idx)
188 v = d.popleft()
189 d.rotate(idx)
190 return v