ruby_language_server 0.4.2 → 0.9.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,16 +1,63 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require 'json'
4
+ require 'socket'
4
5
 
5
6
  module RubyLanguageServer
6
7
  class IO
7
- def initialize(server, mutex)
8
+ attr_reader :using_socket
9
+
10
+ def initialize(server)
8
11
  @server = server
9
- @mutex = mutex
10
12
  server.io = self
13
+
14
+ configure_io
15
+ run_loop
16
+ return unless @using_socket
17
+
18
+ begin
19
+ @in&.close
20
+ rescue StandardError => e
21
+ RubyLanguageServer.logger.error "Error closing socket: #{e}"
22
+ end
23
+ end
24
+
25
+ # JSON-RPC error codes.
26
+ INVALID_REQUEST = -32_600 # used for requests that arrive after shutdown
27
+ METHOD_NOT_FOUND = -32_601
28
+ INTERNAL_ERROR = -32_603 # used when a request handler raises
29
+
30
+ # The background scanner (ProjectManager#scan_all_project_files) writes to the same SQLite
31
+ # database. SQLite waits up to the connection's busy timeout for a lock; these cover the rare
32
+ # BUSY it returns without waiting.
33
+ BUSY_RETRIES = 2
34
+ BUSY_RETRY_DELAY = 0.1 # seconds
35
+
36
+ def send_notification(message, params)
37
+ body = write_message(jsonrpc: '2.0', method: message, params:)
38
+ RubyLanguageServer.logger.info "send_notification body: #{body}"
39
+ end
40
+
41
+ # Sends a request to the client and returns its id. The client's response is logged
42
+ # and otherwise ignored (see #process_request).
43
+ def send_request(message, params)
44
+ @next_request_id = (@next_request_id || 0) + 1
45
+ id = "ruby_language_server-#{@next_request_id}"
46
+ body = write_message(jsonrpc: '2.0', id:, method: message, params:)
47
+ RubyLanguageServer.logger.info "send_request body: #{body}"
48
+ id
49
+ end
50
+
51
+ private
52
+
53
+ attr_accessor :in, :out
54
+
55
+ def run_loop
11
56
  loop do
12
- (id, response) = process_request($stdin)
13
- return_response(id, response, $stdout) unless id.nil?
57
+ (id, response) = process_request
58
+ return_response(id, response) unless id.nil?
59
+ rescue SystemExit
60
+ raise # on_exit, or a signal below. Don't treat it as an error and keep looping.
14
61
  rescue SignalException => e
15
62
  RubyLanguageServer.logger.error "We received a signal. Let's bail: #{e}"
16
63
  exit
@@ -21,121 +68,158 @@ module RubyLanguageServer
21
68
  end
22
69
  end
23
70
 
24
- def return_response(id, response, io = $stdout)
25
- full_response = {
26
- jsonrpc: '2.0',
27
- id:,
28
- result: response
29
- }
30
- response_body = JSON.unparse(full_response)
31
- RubyLanguageServer.logger.info "return_response body: #{response_body}"
32
- io.write "Content-Length: #{response_body.length + 0}\r\n"
33
- io.write "\r\n"
34
- io.write response_body
35
- io.flush
36
- end
37
-
38
- def send_notification(message, params, io = $stdout)
39
- full_response = {
40
- jsonrpc: '2.0',
41
- method: message,
42
- params:
43
- }
44
- body = JSON.unparse(full_response)
45
- RubyLanguageServer.logger.info "send_notification body: #{body}"
46
- io.write "Content-Length: #{body.length + 0}\r\n"
47
- io.write "\r\n"
48
- io.write body
49
- io.flush
71
+ def configure_io
72
+ if ENV['LSP_PORT']
73
+ @tcp_server = TCPServer.new(ENV['LSP_PORT'].to_i)
74
+ RubyLanguageServer.logger.info "Listening on TCP port #{ENV['LSP_PORT']} for LSP connections"
75
+ self.in = @tcp_server.accept
76
+ self.out = self.in
77
+ @using_socket = true
78
+ RubyLanguageServer.logger.info 'Accepted LSP socket connection'
79
+ else
80
+ self.in = $stdin
81
+ # Keep the real stdout for protocol messages and send anything else written to
82
+ # $stdout (a stray puts, a gem warning) to stderr, so it can't corrupt the stream.
83
+ self.out = $stdout.dup
84
+ out.binmode
85
+ $stdout.reopen($stderr)
86
+ @using_socket = false
87
+ end
88
+ end
89
+
90
+ def return_response(id, response)
91
+ body = write_message(jsonrpc: '2.0', id:, result: response)
92
+ RubyLanguageServer.logger.info "return_response body: #{body}"
93
+ end
94
+
95
+ def return_error(id, code, message)
96
+ body = write_message(jsonrpc: '2.0', id:, error: { code:, message: })
97
+ RubyLanguageServer.logger.info "return_error body: #{body}"
98
+ end
99
+
100
+ def log_client_response(response)
101
+ if response['error']
102
+ RubyLanguageServer.logger.warn "Client returned an error for request #{response['id']}: #{response['error']}"
103
+ else
104
+ RubyLanguageServer.logger.info "Client replied to request #{response['id']}"
105
+ end
106
+ end
107
+
108
+ # Writes one framed LSP message and returns its JSON body.
109
+ # Content-Length is a byte count, not a character count.
110
+ def write_message(message)
111
+ body = JSON.generate(message)
112
+ out.write "Content-Length: #{body.bytesize}\r\n"
113
+ out.write "\r\n"
114
+ out.write body
115
+ out.flush if out.respond_to?(:flush)
116
+ body
50
117
  end
51
118
 
52
- def process_request(io = $stdin)
53
- request_body = get_request(io)
119
+ def process_request
120
+ request_body = read_request
54
121
  # RubyLanguageServer.logger.debug "request_body: #{request_body}"
55
122
  request_json = JSON.parse request_body
56
123
  id = request_json['id']
57
- method_name = request_json['method']
124
+ lsp_method = request_json['method']
58
125
  params = request_json['params']
59
- method_name = "on_#{method_name.gsub(/[^\w]/, '_')}"
126
+ if lsp_method.nil?
127
+ # A response to a request we sent the client, such as client/registerCapability.
128
+ log_client_response(request_json)
129
+ return nil
130
+ end
131
+ method_name = "on_#{lsp_method.gsub(/[^\w]/, '_')}"
132
+ if !id.nil? && @server.respond_to?(:shutdown_requested?) && @server.shutdown_requested?
133
+ RubyLanguageServer.logger.warn "Request #{lsp_method} after shutdown"
134
+ return_error(id, INVALID_REQUEST, "Server is shutting down; received #{lsp_method}")
135
+ return nil
136
+ end
60
137
  if @server.respond_to? method_name
61
- response = ActiveRecord::Base.connection_pool.with_connection do
62
- retries = 3
63
- begin
64
- @server.send(method_name, params)
65
- rescue StandardError => e
66
- RubyLanguageServer.logger.warn("Error updating: #{e}\n#{e.backtrace * "\n"}")
67
- sleep 5
68
- retries -= 1
69
- retry unless retries <= 0
70
- end
138
+ begin
139
+ [id, call_handler(method_name, params)]
140
+ rescue StandardError => e
141
+ RubyLanguageServer.logger.error("Error in #{lsp_method}: #{e.class}: #{e.message}\n#{e.backtrace * "\n"}")
142
+ # A request gets an error reply, so the client doesn't mistake it for an empty result.
143
+ # Notifications get none.
144
+ return_error(id, INTERNAL_ERROR, "#{e.class}: #{e.message}") unless id.nil?
145
+ nil
71
146
  end
72
- exit if response == 'EXIT'
73
- [id, response]
74
147
  else
75
148
  RubyLanguageServer.logger.warn "SERVER DOES NOT RESPOND TO #{method_name}"
149
+ # Every request needs a reply, or the client waits forever. Notifications get none.
150
+ return_error(id, METHOD_NOT_FOUND, "Method not found: #{lsp_method}") unless id.nil?
76
151
  nil
77
152
  end
78
153
  end
79
154
 
80
- def get_request(io = $stdin)
81
- initial_line = get_initial_request_line(io)
82
- RubyLanguageServer.logger.debug "initial_line: #{initial_line}"
83
- length = get_length(initial_line)
84
- content = ''
85
- while content.length < length + 2
155
+ # Calls the handler, retrying only when the database is locked.
156
+ def call_handler(method_name, params)
157
+ ActiveRecord::Base.connection_pool.with_connection do
158
+ attempts = 0
86
159
  begin
87
- content += get_content(length + 2, io) # Why + 2? CRLF?
88
- rescue Exception => e
89
- RubyLanguageServer.logger.error e
90
- # We have almost certainly been disconnected from the server
91
- exit!(1)
160
+ @server.send(method_name, params)
161
+ rescue ActiveRecord::StatementTimeout => e
162
+ attempts += 1
163
+ raise if attempts > BUSY_RETRIES
164
+
165
+ RubyLanguageServer.logger.warn("Database busy in #{method_name}, retrying: #{e.message}")
166
+ sleep busy_retry_delay
167
+ retry
92
168
  end
93
169
  end
94
- RubyLanguageServer.logger.debug "content.length: #{content.length}"
170
+ end
171
+
172
+ def busy_retry_delay
173
+ BUSY_RETRY_DELAY
174
+ end
175
+
176
+ # Reads one framed message: header lines up to the blank line that ends them, then
177
+ # exactly Content-Length bytes of body. Exits if the client has disconnected.
178
+ def read_request
179
+ length = read_content_length
180
+ content = read_content(length)
181
+ if content.nil? || content.bytesize < length
182
+ RubyLanguageServer.logger.error("Expected #{length} bytes, got #{content&.bytesize.to_i}; client disconnected")
183
+ exit!(1)
184
+ end
185
+ RubyLanguageServer.logger.debug "content.bytesize: #{content.bytesize}"
95
186
  content
96
187
  end
97
188
 
98
- def get_initial_request_line(io = $stdin)
99
- io.gets
100
- end
101
-
102
- def get_length(string)
103
- return 0 if string.nil?
104
-
105
- string.match(/Content-Length: (\d+)/)[1].to_i
106
- end
107
-
108
- def get_content(size, io = $stdin)
109
- io.read(size)
110
- end
111
-
112
- # http://www.alecjacobson.com/weblog/?p=75
113
- # def stdin_read_char
114
- # begin
115
- # # save previous state of stty
116
- # old_state = `stty -g`
117
- # # disable echoing and enable raw (not having to press enter)
118
- # system "stty raw -echo"
119
- # c = STDIN.getc.chr
120
- # # gather next two characters of special keys
121
- # if(c=="\e")
122
- # extra_thread = Thread.new{
123
- # c = c + STDIN.getc.chr
124
- # c = c + STDIN.getc.chr
125
- # }
126
- # # wait just long enough for special keys to get swallowed
127
- # extra_thread.join(0.00001)
128
- # # kill thread so not-so-long special keys don't wait on getc
129
- # extra_thread.kill
130
- # end
131
- # rescue Exception => ex
132
- # puts "#{ex.class}: #{ex.message}"
133
- # puts ex.backtrace
134
- # ensure
135
- # # restore previous state of stty
136
- # system "stty #{old_state}"
137
- # end
138
- # return c
139
- # end
189
+ # Reads the header block and returns its Content-Length. Other headers, such as
190
+ # Content-Type, are skipped. Header names are case-insensitive.
191
+ def read_content_length
192
+ length = nil
193
+ headers_seen = false
194
+ loop do
195
+ line = read_header_line
196
+ if line.nil?
197
+ RubyLanguageServer.logger.error('End of input while reading headers; client disconnected')
198
+ exit!(1)
199
+ end
200
+ line = line.chomp
201
+ RubyLanguageServer.logger.debug "header: #{line}"
202
+ # A blank line ends the headers. Tolerate stray blank lines before the first header.
203
+ if line.empty?
204
+ break if headers_seen
205
+
206
+ next
207
+ end
208
+ headers_seen = true
209
+ name, value = line.split(':', 2)
210
+ length = Integer(value.strip, 10) if value && name.strip.casecmp?('Content-Length')
211
+ end
212
+ raise ArgumentError, 'Message has no Content-Length header' if length.nil?
213
+
214
+ length
215
+ end
216
+
217
+ def read_header_line
218
+ self.in.gets
219
+ end
220
+
221
+ def read_content(size)
222
+ self.in.read(size)
223
+ end
140
224
  end # class
141
225
  end # module
@@ -17,6 +17,20 @@
17
17
 
18
18
  module RubyLanguageServer
19
19
  module LineContext
20
+ # LSP Position.character counts UTF-16 code units - NOT UTF-8.
21
+ # Returns the matching index into the
22
+ # Ruby string, which counts characters. They differ for characters outside the BMP,
23
+ # such as emoji, which take two code units.
24
+ def self.character_index(line, utf16_offset)
25
+ units = 0
26
+ line.each_char.with_index do |char, index|
27
+ return index if units >= utf16_offset
28
+
29
+ units += char.ord > 0xFFFF ? 2 : 1
30
+ end
31
+ line.length
32
+ end
33
+
20
34
  # This will not work if the search starts on the ending ? of "method?". Bummer.
21
35
  def self.for(line, position)
22
36
  # Grab just the last part of the line - from the index onward