# Copyright (c) 2015 Sqreen. All Rights Reserved. # Please refer to our terms for more information: https://www.sqreen.io/terms.html begin Process.clock_gettime Process::CLOCK_MONOTONIC SQREEN_MONO_TIME = Process::CLOCK_MONOTONIC rescue StandardError SQREEN_MONO_TIME = nil end module Sqreen # This module enable us to keep track of sqreen resource usage # # It is inspired by ActiveSupport::Notifications # module PerformanceNotifications @subscriptions_all = {} @subscription_id = 0 class << self # Subsribe to receive notificiations about an event # returns a subscription indentitifcation def subscribe(&block) id = (@subscription_id += 1) @subscriptions_all[id] = block id end if SQREEN_MONO_TIME def time Process.clock_gettime(SQREEN_MONO_TIME) end else def time Time.now end end # Is there a subscriber def listen_for? !@subscriptions_all.empty? end # Instrument a call identified by key def instrument(key, meta = {}, &block) return yield unless listen_for? _instrument(key, meta, &block) end def notify(key, start, stop, meta = {}) return unless listen_for? notifiers.each do |callable| callable.call(key, start, stop, meta) end end # Unsubscrube for a given subscription def unsubscribe(subscription) return unless @subscriptions_all.delete(subscription).nil? end # Unsubscribe from everything # not threadsafe def unsubscribe_all! @subscriptions_all.clear end private def notifiers @subscriptions_all.values end if SQREEN_MONO_TIME def _instrument(key, meta) start = Process.clock_gettime(SQREEN_MONO_TIME) yield ensure stop = Process.clock_gettime(SQREEN_MONO_TIME) notify(key, start, stop, meta) end else def _instrument(key, meta) start = Time.now yield ensure stop = Time.now notify(key, start, stop, meta) end end end end end