aboutsummaryrefslogtreecommitdiffstats
path: root/actioncable/lib/action_cable/connection/faye_event_loop.rb
blob: 9c44b38bc38909e30fbeb683d5067dd4828806ca (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
require 'thread'

require 'eventmachine'
EventMachine.epoll  if EventMachine.epoll?
EventMachine.kqueue if EventMachine.kqueue?

module ActionCable
  module Connection
    class FayeEventLoop
      @@mutex = Mutex.new

      def timer(interval, &block)
        ensure_reactor_running
        EMTimer.new(::EM::PeriodicTimer.new(interval, &block))
      end

      def post(task = nil, &block)
        task ||= block

        ensure_reactor_running
        ::EM.next_tick(&task)
      end

      private
        def ensure_reactor_running
          return if EventMachine.reactor_running?
          @@mutex.synchronize do
            Thread.new { EventMachine.run } unless EventMachine.reactor_running?
            Thread.pass until EventMachine.reactor_running?
          end
        end

        class EMTimer
          def initialize(inner)
            @inner = inner
          end

          def shutdown
            @inner.cancel
          end
        end
    end
  end
end