Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add instrumentation to command bus #3

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 31 additions & 9 deletions lib/arkency/command_bus.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,23 +6,45 @@ class CommandBus
UnregisteredHandler = Class.new(StandardError)
MultipleHandlers = Class.new(StandardError)

def initialize
@handlers =
Concurrent::Map.new
def initialize(instrumentation = nil)
@handlers = Concurrent::Map.new
@instrumentation = instrumentation || NoOpInstrumentation.new
end

def register(klass, handler)
raise MultipleHandlers.new("Multiple handlers not allowed for #{klass}") if handlers[klass]
handlers[klass] = handler
raise MultipleHandlers, "Multiple handlers not allowed for #{klass}" if handlers[klass]

instrumentation.instrument(
'register.command_bus',
handler: handler,
klass: klass
) do
handlers[klass] = handler
end
end

def call(command)
handlers
.fetch(command.class) { raise UnregisteredHandler.new("Missing handler for #{command.class}") }
.(command)
handler = handlers.fetch(command.class) do
raise UnregisteredHandler, "Missing handler for #{command.class}"
end

instrumentation.instrument(
'call.command_bus',
handler: handler,
command: command
) do
handler.call(command)
end
end

private
attr_reader :handlers

attr_reader :handlers, :instrumentation

class NoOpInstrumentation
def instrument(_name, payload = {})
yield payload if block_given?
end
end
end
end