Class: EventTimeline::RotationService
- Inherits:
-
Object
- Object
- EventTimeline::RotationService
- Defined in:
- lib/event_timeline/rotation_service.rb
Constant Summary collapse
- CLEANUP_CHECK_INTERVAL =
Only check every N flushes
100
Class Method Summary collapse
- .cleanup_if_needed(force: false) ⇒ Object
- .enforce_correlation_limit(correlation_id, buffer_size = 0, force: false) ⇒ Object
- .reset_counters! ⇒ Object
Class Method Details
.cleanup_if_needed(force: false) ⇒ Object
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
# File 'lib/event_timeline/rotation_service.rb', line 8 def cleanup_if_needed(force: false) return unless EventTimeline.configuration unless force # Probabilistic check - only run expensive Session.count every N requests @flush_counter ||= 0 @flush_counter += 1 return unless (@flush_counter % CLEANUP_CHECK_INTERVAL).zero? end total_count = Session.count max_total = EventTimeline.configuration.max_total_events threshold = (max_total * EventTimeline.configuration.cleanup_threshold).to_i return unless total_count >= threshold perform_cleanup(total_count, max_total) end |
.enforce_correlation_limit(correlation_id, buffer_size = 0, force: false) ⇒ Object
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
# File 'lib/event_timeline/rotation_service.rb', line 27 def enforce_correlation_limit(correlation_id, buffer_size = 0, force: false) return unless EventTimeline.configuration max_per_correlation = EventTimeline.configuration.max_events_per_correlation unless force # Track in-memory counts to avoid DB query on every flush @correlation_counts ||= {} @correlation_counts[correlation_id] ||= 0 @correlation_counts[correlation_id] += buffer_size # Only hit DB when we think we might be near the limit return unless @correlation_counts[correlation_id] >= (max_per_correlation * 0.9) end current_count = Session.where(correlation_id: correlation_id).count @correlation_counts[correlation_id] = current_count if @correlation_counts # Sync with reality return unless current_count >= max_per_correlation # Remove oldest events for this correlation, keeping last 80% keep_count = (max_per_correlation * 0.8).to_i oldest_events = Session.where(correlation_id: correlation_id) .order(:occurred_at) .limit(current_count - keep_count) Session.where(id: oldest_events.pluck(:id)).delete_all @correlation_counts[correlation_id] = keep_count if @correlation_counts Rails.logger.info "EventTimeline: Rotated #{current_count - keep_count} events for correlation #{correlation_id}" if defined?(Rails.logger) end |
.reset_counters! ⇒ Object
59 60 61 62 |
# File 'lib/event_timeline/rotation_service.rb', line 59 def reset_counters! @flush_counter = 0 @correlation_counts = {} end |