Class: Ibex::LSP::Transport

Inherits:
Object
  • Object
show all
Defined in:
lib/ibex/lsp/transport.rb

Overview

Reads and writes bounded LSP JSON-RPC messages over Content-Length framing.

Constant Summary collapse

HEADER_SEPARATOR =
"\r\n\r\n"

Instance Method Summary collapse

Constructor Details

#initialize(input, output) ⇒ Transport

Returns a new instance of Transport.



10
11
12
13
14
# File 'lib/ibex/lsp/transport.rb', line 10

def initialize(input, output)
  @input = input
  @output = output
  @buffer = String.new(encoding: Encoding::BINARY)
end

Instance Method Details

#read_messageObject



17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/ibex/lsp/transport.rb', line 17

def read_message
  header = read_header
  return unless header

  length = content_length(header)
  body = read_bytes(length)
  parsed = JSON.parse(body)
  raise ProtocolError.new("JSON-RPC message must be an object", code: -32_600) unless parsed.is_a?(Hash)

  parsed
rescue JSON::ParserError => e
  raise ProtocolError.new("malformed JSON: #{e.message}", code: -32_700)
end

#write_message(message) ⇒ Object



32
33
34
35
36
37
38
39
40
41
# File 'lib/ibex/lsp/transport.rb', line 32

def write_message(message)
  body = JSON.generate(message)
  if body.bytesize > Limits::MAX_OUTPUT_BYTES
    raise ProtocolError.new("JSON-RPC output exceeds #{Limits::MAX_OUTPUT_BYTES} bytes", code: -32_603)
  end

  @output.write("Content-Length: #{body.bytesize}\r\n\r\n")
  @output.write(body)
  @output.flush if @output.respond_to?(:flush)
end