Module: Karafka::Embedded

Defined in:
lib/karafka/embedded.rb

Overview

Allows to start and stop Karafka as part of a different process Following limitations and restrictions apply:

  • ‘#start` cannot be called from a trap context - non blocking

  • ‘#quiet` - can be called from a trap context - non blocking

  • ‘#stop` - can be called from a trap context - blocking

Class Method Summary collapse

Class Method Details

.quietObject

Note:

This method is not blocking and will not wait for Karafka to fully quiet.

Note:

This method can be called from a trap context.

Note:

Please keep in mind you need to ‘#stop` to actually stop the server anyhow.

Quiets Karafka upon any event

It will trigger the quiet procedure but won’t wait.



76
77
78
# File 'lib/karafka/embedded.rb', line 76

def quiet
  Karafka::Server.quiet
end

.startObject

Starts Karafka without supervision and without ownership of signals in a background thread so it won’t interrupt other things running



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/karafka/embedded.rb', line 19

def start
  MUTEX.synchronize do
    # Prevent from double-starting
    return if @started

    @started = true
  end

  Thread.new do
    Thread.current.name = 'karafka.embedded'

    Karafka::Process.tags.add(:execution_mode, 'mode:embedded')
    Karafka::Server.execution_mode = :embedded
    Karafka::Server.start
  end
end

.stopObject

Note:

This method is blocking because we want to wait until Karafka is stopped with final process shutdown

Note:

This method is safe to run from a trap context.

Stops Karafka upon any event



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
# File 'lib/karafka/embedded.rb', line 42

def stop
  # Prevent from double stopping
  unless @stopping
    Thread.new do
      Thread.current.name = 'karafka.embedded.stopping'

      stop = false

      # We spawn a new thread because `#stop` may be called from a trap context
      MUTEX.synchronize do
        break if @stopping

        @stopping = true
        stop = true
      end

      next unless stop

      Karafka::Server.stop
    end
  end

  # Since we want to have this blocking, we wait for the background thread
  sleep(0.1) until Karafka::App.terminated?
end