Module: Monus::Engine::EventMachine

Extended by:
EventMachine
Included in:
EventMachine
Defined in:
lib/monus/engines/eventmachine.rb

Instance Method Summary collapse

Instance Method Details

#every(interval, fire_immediately: true, on_error: nil, &block) ⇒ Object



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/monus/engines/eventmachine.rb', line 62

def every(interval, fire_immediately: true, on_error: nil, &block)
  EM.schedule do
    block.call if fire_immediately

    EM.add_periodic_timer(interval) do
      begin
        block.call
      rescue => error
        interval_binding = binding
        Array(on_error).each do |handler|
          handler.call error, :interval, interval_binding
        end
      end
    end
  end
end

#invalidate_dns_cache!Object



57
58
59
60
# File 'lib/monus/engines/eventmachine.rb', line 57

def invalidate_dns_cache!
  keys = @dns_cache.keys.reject { |key| key =~ Resolv::IPv4::Regex || key =~ Resolv::IPv6::Regex }
  keys.each { |key| @dns_cache.delete(key) }
end

#load_httpObject



25
26
27
28
29
30
31
32
# File 'lib/monus/engines/eventmachine.rb', line 25

def load_http
  @http_loaded ||= begin
    require 'em-http-request'
    true
  rescue LoadError
    raise LoadError, 'in order to use HTTP requests in EventMachine engine you should add `em-http-request` gem to your Gemfile'
  end
end

#make_http_connection(host, port) ⇒ Object



9
10
11
12
# File 'lib/monus/engines/eventmachine.rb', line 9

def make_http_connection(host, port)
  load_http
  EM::HttpRequest.new("http://#{host}:#{port}")
end

#prepareObject



4
5
6
7
# File 'lib/monus/engines/eventmachine.rb', line 4

def prepare
  @dns_cache = {}
  @prepared = true
end

#send_http_request(uri, method: :get, body: nil, connection: nil) ⇒ Object



14
15
16
17
18
19
20
21
22
23
# File 'lib/monus/engines/eventmachine.rb', line 14

def send_http_request(uri, method: :get, body: nil, connection: nil)
  load_http
  EM.schedule do
    if connection
      connection.setup_request(method, path: uri, keepalive: true)
    else
      EM::HttpRequest.new(uri).send(method)
    end
  end
end

#send_udp_datagram(message, host, port) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/monus/engines/eventmachine.rb', line 34

def send_udp_datagram(message, host, port)
  EM.schedule do
    @udp_socket ||= EM.open_datagram_socket '0.0.0.0', 0

    ip = @dns_cache[host]

    if ip.nil? and (host =~ Resolv::IPv4::Regex or host =~ Resolv::IPv6::Regex)
      ip = host
      @dns_cache[host] = ip
    end

    if ip
      @udp_socket.send_datagram message, ip, port
    else
      EM::DNS::Resolver.resolve(host).callback do |ip_list|
        ip = ip_list.first
        @dns_cache[host] = ip
        send_udp_datagram(message, host, port)
      end
    end
  end
end