1
0

delay_agent.rb 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. module Agents
  2. class DelayAgent < Agent
  3. default_schedule "every_12h"
  4. description <<-MD
  5. The DelayAgent stores received Events and emits copies of them on a schedule. Use this as a buffer or queue of Events.
  6. `max_events` should be set to the maximum number of events that you'd like to hold in the buffer. When this number is
  7. reached, new events will either be ignored, or will displace the oldest event already in the buffer, depending on
  8. whether you set `keep` to `newest` or `oldest`.
  9. `expected_receive_period_in_days` is used to determine if the Agent is working. Set it to the maximum number of days
  10. that you anticipate passing without this Agent receiving an incoming Event.
  11. `max_emitted_events` is used to limit the number of the maximum events which should be created. If you omit this DelayAgent will create events for every event stored in the memory.
  12. MD
  13. def default_options
  14. {
  15. 'expected_receive_period_in_days' => "10",
  16. 'max_events' => "100",
  17. 'keep' => 'newest'
  18. }
  19. end
  20. def validate_options
  21. unless options['expected_receive_period_in_days'].present? && options['expected_receive_period_in_days'].to_i > 0
  22. errors.add(:base, "Please provide 'expected_receive_period_in_days' to indicate how many days can pass before this Agent is considered to be not working")
  23. end
  24. unless options['keep'].present? && options['keep'].in?(%w[newest oldest])
  25. errors.add(:base, "The 'keep' option is required and must be set to 'oldest' or 'newest'")
  26. end
  27. unless options['max_events'].present? && options['max_events'].to_i > 0
  28. errors.add(:base, "The 'max_events' option is required and must be an integer greater than 0")
  29. end
  30. end
  31. def working?
  32. last_receive_at && last_receive_at > options['expected_receive_period_in_days'].to_i.days.ago && !recent_error_logs?
  33. end
  34. def receive(incoming_events)
  35. incoming_events.each do |event|
  36. memory['event_ids'] ||= []
  37. memory['event_ids'] << event.id
  38. if memory['event_ids'].length > interpolated['max_events'].to_i
  39. if interpolated['keep'] == 'newest'
  40. memory['event_ids'].shift
  41. else
  42. memory['event_ids'].pop
  43. end
  44. end
  45. end
  46. end
  47. def check
  48. if memory['event_ids'] && memory['event_ids'].length > 0
  49. events = received_events.where(id: memory['event_ids']).reorder('events.id asc')
  50. if options['max_emitted_events'].present?
  51. events = events.limit(options['max_emitted_events'].to_i)
  52. end
  53. events.each do |event|
  54. create_event payload: event.payload
  55. memory['event_ids'].delete(event.id)
  56. end
  57. end
  58. end
  59. end
  60. end