Sha256: 65f836ffbf15ef7a3c29db6c1bb9ece31e869d718b56ad6d7a37bae08f671a93

Contents?: true

Size: 1.06 KB

Versions: 2

Compression:

Stored size: 1.06 KB

Contents

require 'dry/events/publisher'

module Dry
  module Monitor
    class Clock
      def measure
        start = current
        result = yield
        [result, current - start]
      end

      def current
        Process.clock_gettime(Process::CLOCK_MONOTONIC, :millisecond)
      end
    end

    CLOCK = Clock.new

    class Notifications
      include Events::Publisher['Dry::Monitor::Notifications']

      attr_reader :id

      attr_reader :clock

      def initialize(id)
        @id = id
        @clock = CLOCK
      end

      def start(event_id, payload)
        instrument(event_id, payload)
      end

      def stop(event_id, payload)
        instrument(event_id, payload)
      end

      def instrument(event_id, payload = EMPTY_HASH)
        if block_given?
          result, time = @clock.measure { yield }
        end

        process(event_id, payload) do |event, listener|
          if time
            listener.(event.payload(payload.merge(time: time)))
          else
            listener.(event)
          end
        end

        result
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
dry-monitor-0.3.0 lib/dry/monitor/notifications.rb
dry-monitor-0.2.0 lib/dry/monitor/notifications.rb