Module: NtiEventBus

Defined in:
lib/nti_event_bus.rb,
lib/nti_event_bus/dsl.rb,
lib/nti_event_bus/railtie.rb,
lib/nti_event_bus/version.rb,
lib/nti_event_bus/registry.rb,
lib/nti_event_bus/dispatchers.rb,
lib/nti_event_bus/handler_base.rb,
lib/nti_event_bus/configuration.rb,
lib/nti_event_bus/handle_event_job.rb

Overview

Publish/subscribe event bus.

NtiEventBus.publish('order.created', { order_id: 1 })

Handlers are declared in event files (see NtiEventBus::DSL) and executed asynchronously via a configurable dispatcher (see NtiEventBus::Dispatchers). The subscription registry is built once by setup!, deep-frozen, and read lock-free on the publish path.

Defined Under Namespace

Modules: Dispatchers Classes: Configuration, DSL, Error, HandleEventJob, HandlerBase, NotConfiguredError, Railtie, Registry

Constant Summary collapse

SETUP_MUTEX =

Guards registry (re)builds; reads of the frozen registry never take this lock.

Mutex.new
VERSION =
'0.1.0'

Class Method Summary collapse

Class Method Details

.configurationObject



37
38
39
# File 'lib/nti_event_bus.rb', line 37

def configuration
  @configuration ||= Configuration.new
end

.configure {|configuration| ... } ⇒ Object

Yields:



32
33
34
35
# File 'lib/nti_event_bus.rb', line 32

def configure
  yield(configuration) if block_given?
  configuration
end

.publish(event_name, payload) ⇒ Object

Fan an event out to every subscribed handler via the configured dispatcher. Returns nil. Unknown events (no handlers) are a no-op.



69
70
71
72
73
74
75
76
# File 'lib/nti_event_bus.rb', line 69

def publish(event_name, payload)
  handlers = registry.handlers_for(event_name)
  return if handlers.empty?

  dispatcher = configuration.dispatcher
  handlers.each { |handler| dispatcher.call(handler.name, payload) }
  nil
end

.registryObject



63
64
65
# File 'lib/nti_event_bus.rb', line 63

def registry
  @registry || raise(NotConfiguredError, 'NtiEventBus.setup! has not been run')
end

.reset_configuration!Object

Resets configuration to defaults. Intended for test suites.



42
43
44
# File 'lib/nti_event_bus.rb', line 42

def reset_configuration!
  @configuration = Configuration.new
end

.setup!Object

Build the subscription registry from the configured event files and atomically install it.

A fresh Registry is built, deep-frozen, then swapped in under SETUP_MUTEX. Readers always see a fully-frozen registry (the previous one or the new one) — never a half-built one.



50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/nti_event_bus.rb', line 50

def setup!
  SETUP_MUTEX.synchronize do
    registry = Registry.new
    path = configuration.root_events_file!
    DSL.new(registry, configuration.events_dir).instance_eval(File.read(path), path.to_s)
    registry.finalize!

    configuration.logger&.debug { "[NtiEventBus] registry built from #{path}" }
    @registry = registry
  end
  self
end