Class: Sentry::ThreadedPeriodicWorker

Inherits:
Object
  • Object
show all
Includes:
LoggingHelper
Defined in:
lib/sentry/threaded_periodic_worker.rb

Direct Known Subclasses

BackpressureMonitor, SessionFlusher

Instance Method Summary collapse

Constructor Details

#initialize(sdk_logger, interval) ⇒ ThreadedPeriodicWorker

Returns a new instance of ThreadedPeriodicWorker.



10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/sentry/threaded_periodic_worker.rb', line 10

def initialize(sdk_logger, interval)
  @process_id = Process.pid
  @thread = nil
  @exited = false
  @interval = interval
  @sdk_logger = sdk_logger

  @thread_mutex = Mutex.new
  @wake_condition = ConditionVariable.new
  @idle_condition = ConditionVariable.new

  @woken = false
  @running = false
end

Instance Method Details

#ensure_thread ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/sentry/threaded_periodic_worker.rb', line 25

def ensure_thread
  reset_if_forked

  @thread_mutex.synchronize do
    return false if @exited
    return true if @thread&.alive?

    @thread = Thread.new { worker_loop }

    true
  end
rescue ThreadError
  @thread_mutex.synchronize { @exited = true }
  log_debug("[#{self.class.name}] thread creation failed")
  false
end

#kill ⇒ Object



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/sentry/threaded_periodic_worker.rb', line 67

def kill
  thread = @thread_mutex.synchronize do
    @exited = true
    @woken = false
    @idle_condition.broadcast
    @thread
  end

  # Only a started worker has a thread to kill (and to log about).
  # Guarding here keeps a never-started worker's teardown silent, so
  # killing one during test reset can't emit a stray debug line.
  return unless thread

  log_debug("[#{self.class.name}] thread killed")
  thread.kill
end

#wait_until_idle(timeout = nil) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/sentry/threaded_periodic_worker.rb', line 52

def wait_until_idle(timeout = nil)
  deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + timeout if timeout

  @thread_mutex.synchronize do
    while !@exited && (@running || @woken)
      remaining = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC) if deadline
      return false if remaining && remaining <= 0

      @idle_condition.wait(@thread_mutex, remaining)
    end

    true
  end
end

#wake ⇒ Object



42
43
44
45
46
47
48
49
50
# File 'lib/sentry/threaded_periodic_worker.rb', line 42

def wake
  @thread_mutex.synchronize do
    next false if @exited

    @woken = true
    @wake_condition.signal
    true
  end
end