Class: Manceps::Transport::Stdio

Inherits:
Base
  • Object
show all
Defined in:
lib/manceps/transport/stdio.rb

Overview

Stdio transport: communicates with a local subprocess via stdin/stdout.

Instance Method Summary collapse

Methods inherited from Base

#on_notification, #request_streaming

Constructor Details

#initialize(command, args: [], env: {}) ⇒ Stdio

Returns a new instance of Stdio.



10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/manceps/transport/stdio.rb', line 10

def initialize(command, args: [], env: {})
  super()
  @command = command
  @args = args
  @env = env
  @stdin = nil
  @stdout = nil
  @stderr = nil
  @wait_thread = nil
  @mutex = Mutex.new
  @notification_callback = nil
end

Instance Method Details

#closeObject



66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/manceps/transport/stdio.rb', line 66

def close
  return unless @wait_thread

  begin
    @stdin&.close
  rescue StandardError
    nil
  end

  if @wait_thread.alive?
    begin
      Process.kill('TERM', @wait_thread.pid)
    rescue StandardError
      nil
    end

    unless @wait_thread.join(5)
      begin
        Process.kill('KILL', @wait_thread.pid)
      rescue StandardError
        nil
      end
      begin
        @wait_thread.join(1)
      rescue StandardError
        nil
      end
    end
  end

  begin
    @stdout&.close
  rescue StandardError
    nil
  end
  begin
    @stderr&.close
  rescue StandardError
    nil
  end
  @stdin = nil
  @stdout = nil
  @stderr = nil
  @wait_thread = nil
end

#listen(&block) ⇒ Object

Raises:



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/manceps/transport/stdio.rb', line 50

def listen(&block)
  raise ConnectionError, 'Stdio transport not open' unless @stdout

  loop do
    line = @stdout.gets
    break if line.nil?

    parsed = begin
      JSON.parse(line)
    rescue StandardError
      next
    end
    block.call(parsed) if parsed['method']
  end
end

#notify(body) ⇒ Object



40
41
42
43
44
# File 'lib/manceps/transport/stdio.rb', line 40

def notify(body)
  @mutex.synchronize do
    write_message(body)
  end
end

#openObject



23
24
25
26
27
28
29
30
31
# File 'lib/manceps/transport/stdio.rb', line 23

def open
  close if @wait_thread # Clean up any existing process

  @stdin, @stdout, @stderr, @wait_thread = Open3.popen3(@env, @command, *@args)

  at_exit { close }

  self
end

#request(body) ⇒ Object



33
34
35
36
37
38
# File 'lib/manceps/transport/stdio.rb', line 33

def request(body)
  @mutex.synchronize do
    write_message(body)
    read_response
  end
end

#terminate_session(_session_id) ⇒ Object



46
47
48
# File 'lib/manceps/transport/stdio.rb', line 46

def terminate_session(_session_id)
  # No-op for stdio -- session ends when the process exits
end