Class: CollavreOpenclaw::EmReactor

Inherits:
Object
  • Object
show all
Defined in:
app/services/collavre_openclaw/em_reactor.rb

Overview

Manages a single EventMachine reactor thread shared by all WebSocket connections. Thread-safe: multiple Rails threads can schedule work via .next_tick.

Class Method Summary collapse

Class Method Details

.ensure_running!Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'app/services/collavre_openclaw/em_reactor.rb', line 8

def ensure_running!
  @mutex ||= Mutex.new
  @mutex.synchronize do
    return if EM.reactor_running?

    @thread = Thread.new do
      Thread.current.name = "openclaw-em-reactor"
      EM.run
    end

    # Wait until the reactor is actually running
    deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 5
    until EM.reactor_running?
      if Process.clock_gettime(Process::CLOCK_MONOTONIC) > deadline
        raise "EventMachine reactor failed to start within 5 seconds"
      end
      sleep 0.01
    end
  end
end

.next_tick(&block) ⇒ Object

Schedule a block to run in the EM reactor thread. Safe to call from any thread.



46
47
48
49
# File 'app/services/collavre_openclaw/em_reactor.rb', line 46

def next_tick(&block)
  ensure_running!
  EM.next_tick(&block)
end

.running?Boolean

Returns:

  • (Boolean)


40
41
42
# File 'app/services/collavre_openclaw/em_reactor.rb', line 40

def running?
  EM.reactor_running?
end

.stop!Object



29
30
31
32
33
34
35
36
37
38
# File 'app/services/collavre_openclaw/em_reactor.rb', line 29

def stop!
  @mutex&.synchronize do
    return unless EM.reactor_running?

    # Must stop EM from within the reactor thread
    EM.next_tick { EM.stop }
    @thread&.join(5)
    @thread = nil
  end
end