Class: AgentClientProtocol::Connection

Inherits:
Object
  • Object
show all
Defined in:
lib/agent_client_protocol/connection.rb

Constant Summary collapse

JSONRPC_VERSION =
"2.0"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(reader:, writer:, handler:) ⇒ Connection

Returns a new instance of Connection.



12
13
14
15
16
17
18
19
20
# File 'lib/agent_client_protocol/connection.rb', line 12

def initialize(reader:, writer:, handler:)
  @reader = reader
  @writer = writer
  @handler = handler
  @next_id = 0
  @pending = {} # id -> Async::Promise
  @mutex = Mutex.new
  @closed = false
end

Instance Attribute Details

#readerObject (readonly)

Returns the value of attribute reader.



10
11
12
# File 'lib/agent_client_protocol/connection.rb', line 10

def reader
  @reader
end

#writerObject (readonly)

Returns the value of attribute writer.



10
11
12
# File 'lib/agent_client_protocol/connection.rb', line 10

def writer
  @writer
end

Instance Method Details

#closeObject



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/agent_client_protocol/connection.rb', line 55

def close
  return if @closed

  @closed = true

  # Reject all pending requests
  @mutex.synchronize do
    @pending.each_value do |var|
      var.resolve({"__error__" => {"code" => -32603, "message" => "Connection closed"}}) unless var.resolved?
    end
    @pending.clear
  end

  @reader.close
  @writer.close
end

#closed?Boolean

Returns:

  • (Boolean)


72
73
74
# File 'lib/agent_client_protocol/connection.rb', line 72

def closed?
  @closed
end

#listenObject



45
46
47
48
49
50
51
52
53
# File 'lib/agent_client_protocol/connection.rb', line 45

def listen
  @reader.each do |message|
    process_message(message)
  end
rescue IOError, Errno::EPIPE
  # Connection closed
ensure
  close
end

#send_notification(method, params = nil) ⇒ Object



39
40
41
42
43
# File 'lib/agent_client_protocol/connection.rb', line 39

def send_notification(method, params = nil)
  msg = {"jsonrpc" => JSONRPC_VERSION, "method" => method}
  msg["params"] = params if params
  @writer.write(msg)
end

#send_request(method, params = nil) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/agent_client_protocol/connection.rb', line 22

def send_request(method, params = nil)
  id = next_id
  variable = Async::Promise.new

  @mutex.synchronize { @pending[id] = variable }

  msg = {"jsonrpc" => JSONRPC_VERSION, "id" => id, "method" => method}
  msg["params"] = params if params
  @writer.write(msg)

  result = variable.wait
  if result.is_a?(Hash) && result.key?("__error__")
    raise RequestError.from_hash(result["__error__"])
  end
  result
end