1
0
Fork 0
mirror of https://github.com/mperham/sidekiq.git synced 2022-11-09 13:52:34 -05:00
mperham--sidekiq/lib/sidekiq/util.rb

109 lines
2.3 KiB
Ruby
Raw Normal View History

# frozen_string_literal: true
require "forwardable"
require "socket"
require "securerandom"
require "sidekiq/exception_handler"
2012-01-22 11:32:38 -08:00
module Sidekiq
2012-02-17 13:39:36 -08:00
##
# This module is part of Sidekiq core and not intended for extensions.
#
class RingBuffer
include Enumerable
extend Forwardable
def_delegators :@buf, :[], :each, :size
2021-03-30 16:47:01 -07:00
def initialize(size, default = 0)
@size = size
@buf = Array.new(size, default)
@index = 0
end
def <<(element)
@buf[@index % @size] = element
@index += 1
element
end
def buffer
@buf
end
2021-03-30 16:47:01 -07:00
def reset(default = 0)
@buf.fill(default)
end
end
2012-01-22 11:32:38 -08:00
module Util
include ExceptionHandler
2012-01-22 11:32:38 -08:00
# hack for quicker development / testing environment #2774
PAUSE_TIME = $stdout.tty? ? 0.1 : 0.5
# Wait for the orblock to be true or the deadline passed.
def wait_for(deadline, &condblock)
remaining = deadline - ::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
while remaining > PAUSE_TIME
return if condblock.call
sleep PAUSE_TIME
remaining = deadline - ::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
end
end
2012-01-22 11:32:38 -08:00
def watchdog(last_words)
yield
2012-08-29 20:20:20 -07:00
rescue Exception => ex
handle_exception(ex, {context: last_words})
raise ex
2012-01-22 11:32:38 -08:00
end
2015-10-02 15:44:29 -07:00
def safe_thread(name, &block)
Thread.new do
Thread.current.name = name
2015-10-02 15:44:29 -07:00
watchdog(name, &block)
end
end
def logger
Sidekiq.logger
2012-01-22 16:01:46 -08:00
end
def redis(&block)
Sidekiq.redis(&block)
end
def tid
Thread.current["sidekiq_tid"] ||= (Thread.current.object_id ^ ::Process.pid).to_s(36)
end
2012-09-16 07:27:49 -07:00
def hostname
ENV["DYNO"] || Socket.gethostname
2012-09-16 07:27:49 -07:00
end
def process_nonce
2019-04-26 12:36:33 -07:00
@@process_nonce ||= SecureRandom.hex(6)
end
def identity
2019-04-26 12:36:33 -07:00
@@identity ||= "#{hostname}:#{::Process.pid}:#{process_nonce}"
end
2014-05-13 21:41:40 -07:00
def fire_event(event, options = {})
reverse = options[:reverse]
reraise = options[:reraise]
arr = Sidekiq.options[:lifecycle_events][event]
arr.reverse! if reverse
arr.each do |block|
block.call
rescue => ex
handle_exception(ex, {context: "Exception during Sidekiq lifecycle event.", event: event})
raise ex if reraise
2014-05-13 21:41:40 -07:00
end
2015-10-13 09:46:06 -07:00
arr.clear
2014-05-13 21:41:40 -07:00
end
2012-01-22 11:32:38 -08:00
end
end