Class: MilkTea::DAP::Protocol

Inherits:
Object
  • Object
show all
Defined in:
lib/milk_tea/dap/protocol.rb

Overview

Handles DAP framing over stdin/stdout using Content-Length headers.

Constant Summary collapse

INVALID_MESSAGE =
Object.new.freeze

Instance Method Summary collapse

Constructor Details

#initialize(input: $stdin, output: $stdout, error_output: nil) ⇒ Protocol

Returns a new instance of Protocol.



11
12
13
14
15
# File 'lib/milk_tea/dap/protocol.rb', line 11

def initialize(input: $stdin, output: $stdout, error_output: nil)
  @input = input
  @output = output
  @error_output = error_output
end

Instance Method Details

#read_messageObject



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/milk_tea/dap/protocol.rb', line 17

def read_message
  headers = {}
  loop do
    line = @input.gets
    return nil if line.nil?

    stripped = line.chomp
    break if stripped.empty?

    key, value = stripped.split(":", 2)
    headers[key&.strip] = value&.strip
  end

  content_length = headers["Content-Length"]&.to_i
  return INVALID_MESSAGE if content_length.nil? || content_length <= 0

  body = @input.read(content_length)
  JSON.parse(body)
rescue StandardError => e
  log_error("DAP protocol read error: #{e.message}")
  INVALID_MESSAGE
end

#write_message(message) ⇒ Object



40
41
42
43
44
45
46
47
# File 'lib/milk_tea/dap/protocol.rb', line 40

def write_message(message)
  json = JSON.dump(message)
  @output.write("Content-Length: #{json.bytesize}\r\n\r\n")
  @output.write(json)
  @output.flush
rescue StandardError => e
  log_error("DAP protocol write error: #{e.message}")
end