Class: FeatBit::EventProcessor

Inherits:
Object
  • Object
show all
Defined in:
lib/featbit/event_processor.rb

Defined Under Namespace

Classes: DeliveryRejected

Constant Summary collapse

FLUSH =
"__flush__"
STOP =
"__stop__"
CONTROL_TIMEOUT =
5.0

Instance Method Summary collapse

Constructor Details

#initialize(options, sender: nil) ⇒ EventProcessor

Returns a new instance of EventProcessor.



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/featbit/event_processor.rb', line 16

def initialize(options, sender: nil)
  @options = options
  @sender = sender || method(:post_batch)
  @queue = SizedQueue.new(options.events_capacity)
  @control_queue = Queue.new
  @dropped_events = 0
  @drop_mutex = Mutex.new
  @state_mutex = Mutex.new
  @close_mutex = Mutex.new
  @closed = false
  @close_result = nil
  @thread = Thread.new { run }
  @thread.name = "featbit-event-processor" if @thread.respond_to?(:name=)
rescue StandardError => e
  options.logger&.error("FeatBit event processor failed to start: #{e.message}")
  @closed = true
end

Instance Method Details

#closeObject



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/featbit/event_processor.rb', line 65

def close
  @close_mutex.synchronize do
    return @close_result unless @close_result.nil?

    ack = Queue.new
    worker_alive = @thread&.alive?
    @state_mutex.synchronize do
      @closed = true
      @control_queue << { type: STOP, ack: ack } if worker_alive
    end
    return @close_result = true unless worker_alive

    delivered = Timeout.timeout(CONTROL_TIMEOUT) { ack.pop } != false
    @thread&.join(CONTROL_TIMEOUT)
    @close_result = delivered && !@thread&.alive?
  end
rescue StandardError => e
  @options.logger&.warn("FeatBit event processor close failed: #{e.message}")
  false
end

#dropped_eventsObject



86
87
88
89
90
# File 'lib/featbit/event_processor.rb', line 86

def dropped_events
  @drop_mutex.synchronize { @dropped_events }
rescue StandardError
  0
end

#enqueue(event) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/featbit/event_processor.rb', line 34

def enqueue(event)
  return false if event.nil?

  @state_mutex.synchronize do
    return false if @closed

    @queue.push(event, true)
    true
  end
rescue ThreadError
  @drop_mutex.synchronize { @dropped_events += 1 }
  false
rescue StandardError => e
  @options.logger&.warn("FeatBit event enqueue failed: #{e.message}")
  false
end

#flushObject



51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/featbit/event_processor.rb', line 51

def flush
  ack = Queue.new
  @state_mutex.synchronize do
    return false if @closed

    @control_queue << { type: FLUSH, ack: ack }
  end

  Timeout.timeout(CONTROL_TIMEOUT) { ack.pop } != false
rescue StandardError => e
  @options.logger&.warn("FeatBit event flush failed: #{e.message}")
  false
end