dry_runnable.rb 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. module DryRunnable
  2. extend ActiveSupport::Concern
  3. def dry_run!(event = nil)
  4. @dry_run = true
  5. log = StringIO.new
  6. @dry_run_started_at = Time.zone.now
  7. @dry_run_logger = Logger.new(log).tap { |logger|
  8. logger.formatter = proc { |severity, datetime, progname, message|
  9. elapsed_time = '%02d:%02d:%02d' % 2.times.inject([datetime - @dry_run_started_at]) { |(x, *xs)|
  10. [*x.divmod(60), *xs]
  11. }
  12. "[#{elapsed_time}] #{severity} -- #{progname}: #{message}\n"
  13. }
  14. }
  15. @dry_run_results = {
  16. events: [],
  17. }
  18. begin
  19. raise "#{short_type} does not support dry-run" unless can_dry_run?
  20. readonly!
  21. @dry_run_started_at = Time.zone.now
  22. @dry_run_logger.info('Dry Run started')
  23. if event
  24. raise "This agent cannot receive an event!" unless can_receive_events?
  25. receive([event])
  26. else
  27. check
  28. end
  29. @dry_run_logger.info('Dry Run finished')
  30. rescue StandardError => e
  31. @dry_run_logger.info('Dry Run failed')
  32. error "Exception during dry-run. #{e.message}: #{e.backtrace.join("\n")}"
  33. end
  34. @dry_run_results.update(
  35. memory:,
  36. log: log.string,
  37. )
  38. ensure
  39. @dry_run = false
  40. end
  41. def dry_run?
  42. !!@dry_run
  43. end
  44. included do
  45. prepend Wrapper
  46. end
  47. module Wrapper
  48. attr_accessor :results
  49. def logger
  50. return super unless dry_run?
  51. @dry_run_logger
  52. end
  53. def save(**options)
  54. return super unless dry_run?
  55. perform_validations(options)
  56. end
  57. def save!(**options)
  58. return super unless dry_run?
  59. save(**options) or raise_record_invalid
  60. end
  61. def log(message, options = {})
  62. return super unless dry_run?
  63. sev =
  64. case options[:level] || 3
  65. when 0..2
  66. Logger::DEBUG
  67. when 3
  68. Logger::INFO
  69. else
  70. Logger::ERROR
  71. end
  72. logger.log(sev, message)
  73. end
  74. def create_event(event)
  75. return super unless dry_run?
  76. if can_create_events?
  77. event = build_event(event)
  78. @dry_run_results[:events] << event.payload
  79. event
  80. else
  81. error "This Agent cannot create events!"
  82. end
  83. end
  84. end
  85. end