Class: Dalli::Protocol::ServerConfigParser

Inherits:
Object
  • Object
show all
Defined in:
lib/dalli/protocol/server_config_parser.rb

Overview

Dalli::Protocol::ServerConfigParser parses a server string passed to a Dalli::Protocol::Binary instance into the hostname, port, weight, and socket_type.

Constant Summary collapse

SERVER_CONFIG_REGEXP =

TODO: Revisit this, especially the IP/domain part. Likely can limit character set to LDH + ‘.’. Hex digit section appears to have been added to support IPv6, but as far as I can tell it doesn’t work

/\A(\[([\h:]+)\]|[^:]+)(?::(\d+))?(?::(\d+))?\z/.freeze
DEFAULT_PORT =
11_211
DEFAULT_WEIGHT =
1

Class Method Summary collapse

Class Method Details

.attributes_for_tcp_socket(res) ⇒ Object



48
49
50
# File 'lib/dalli/protocol/server_config_parser.rb', line 48

def self.attributes_for_tcp_socket(res)
  [normalize_port(res[3]), normalize_weight(res[4])]
end

.attributes_for_unix_socket(res) ⇒ Object

Raises:



41
42
43
44
45
46
# File 'lib/dalli/protocol/server_config_parser.rb', line 41

def self.attributes_for_unix_socket(res)
  # in case of unix socket, allow only setting of weight, not port
  raise Dalli::DalliError, "Could not parse hostname #{res[0]}" if res[4]

  [nil, normalize_weight(res[3])]
end

.deconstruct_string(str) ⇒ Object

Raises:



34
35
36
37
38
39
# File 'lib/dalli/protocol/server_config_parser.rb', line 34

def self.deconstruct_string(str)
  mtch = str.match(SERVER_CONFIG_REGEXP)
  raise Dalli::DalliError, "Could not parse hostname #{str}" if mtch.nil? || mtch[1] == '[]'

  mtch
end

.normalize_hostname(str, res) ⇒ Object

Raises:



52
53
54
55
56
# File 'lib/dalli/protocol/server_config_parser.rb', line 52

def self.normalize_hostname(str, res)
  raise Dalli::DalliError, "Could not parse hostname #{str}" if res.nil? || res[1] == '[]'

  res[2] || res[1]
end

.normalize_port(port) ⇒ Object



58
59
60
# File 'lib/dalli/protocol/server_config_parser.rb', line 58

def self.normalize_port(port)
  Integer(port || DEFAULT_PORT)
end

.normalize_weight(weight) ⇒ Object



62
63
64
# File 'lib/dalli/protocol/server_config_parser.rb', line 62

def self.normalize_weight(weight)
  Integer(weight || DEFAULT_WEIGHT)
end

.parse(str) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/dalli/protocol/server_config_parser.rb', line 20

def self.parse(str)
  res = deconstruct_string(str)

  hostname = normalize_hostname(str, res)
  if hostname.start_with?('/')
    socket_type = :unix
    port, weight = attributes_for_unix_socket(res)
  else
    socket_type = :tcp
    port, weight = attributes_for_tcp_socket(res)
  end
  [hostname, port, weight, socket_type]
end