Class: NATS::Protocol::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/nats/io/parser.rb

Instance Method Summary collapse

Constructor Details

#initialize(nc) ⇒ Parser

Returns a new instance of Parser.



25
26
27
28
29
30
31
32
33
34
35
# File 'lib/nats/io/parser.rb', line 25

def initialize(nc)
  @nc = nc
  @buf = nil
  @needed = nil
  @parse_state = AWAITING_CONTROL_LINE

  @sub = nil
  @sid = nil
  @reply = nil
  @needed = nil
end

Instance Method Details

#parse(data) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/nats/io/parser.rb', line 37

def parse(data)
  @buf = @buf ? @buf << data : data
  while (@buf)
    case @parse_state
    when AWAITING_CONTROL_LINE
      case @buf
      when MSG
        @buf = $'
        @sub, @sid, @reply, @needed = $1, $2.to_i, $4, $5.to_i
        @parse_state = AWAITING_MSG_PAYLOAD
      when OK # No-op right now
        @buf = $'
      when ERR
        @buf = $'
        @nc.process_err($1)
      when PING
        @buf = $'
        @nc.process_ping
      when PONG
        @buf = $'
        @nc.process_pong
      when INFO
        @buf = $'
        # First INFO message is processed synchronously on connect,
        # and onwards we would be receiving asynchronously INFO commands
        # signaling possible changes in the topology of the NATS cluster.
        @nc.process_info($1)
      when UNKNOWN
        @buf = $'
        @nc.process_err("Unknown protocol: #{$1}")
      else
        # If we are here we do not have a complete line yet that we understand.
        return
      end
      @buf = nil if (@buf && @buf.empty?)

    when AWAITING_MSG_PAYLOAD
      return unless (@needed && @buf.bytesize >= (@needed + CR_LF_SIZE))
      @nc.process_msg(@sub, @sid, @reply, @buf.slice(0, @needed))
      @buf = @buf.slice((@needed + CR_LF_SIZE), @buf.bytesize)
      @sub = @sid = @reply = @needed = nil
      @parse_state = AWAITING_CONTROL_LINE
      @buf = nil if (@buf && @buf.empty?)
    end
  end
end