summaryrefslogtreecommitdiff
path: root/app/workers/mail_scheduler/notification_service_worker.rb
blob: 0d06dab3b2ef2bdd1f1a466ef28b495ddcd35b7c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# frozen_string_literal: true

require 'active_job/arguments'

module MailScheduler
  class NotificationServiceWorker
    include ApplicationWorker
    include MailSchedulerQueue

    feature_category :issue_tracking

    def perform(meth, *args)
      check_arguments!(args)

      deserialized_args = ActiveJob::Arguments.deserialize(args)
      notification_service.public_send(meth, *deserialized_args) # rubocop:disable GitlabSecurity/PublicSend
    rescue ActiveJob::DeserializationError
      # No-op.
      # This exception gets raised when an argument
      # is correct (deserializeable), but it still cannot be deserialized.
      # This can happen when an object has been deleted after
      # rails passes this job to sidekiq, but before
      # sidekiq gets it for execution.
      # In this case just do nothing.
    end

    def self.perform_async(*args)
      super(*Arguments.serialize(args))
    end

    private

    # If an argument is in the ActiveJob::Arguments::TYPE_WHITELIST list,
    # it means the argument cannot be deserialized.
    # Which means there's something wrong with our code.
    def check_arguments!(args)
      args.each do |arg|
        if arg.class.in?(ActiveJob::Arguments::TYPE_WHITELIST)
          raise(ArgumentError, "Argument `#{arg}` cannot be deserialized because of its type")
        end
      end
    end

    # Permit ActionController::Parameters for serializable Hash
    #
    # Port of
    # https://github.com/rails/rails/commit/945fdd76925c9f615bf016717c4c8db2b2955357#diff-fc90ec41ef75be8b2259526fe1a8b663
    module Arguments
      include ActiveJob::Arguments
      extend self

      private

      def serialize_argument(argument)
        case argument
        when -> (arg) { arg.respond_to?(:permitted?) }
          serialize_hash(argument.to_h).tap do |result|
            result[WITH_INDIFFERENT_ACCESS_KEY] = serialize_argument(true)
          end
        else
          super
        end
      end
    end

    # Make sure we remove this patch starting with Rails 6.0.
    if Rails.version.start_with?('6.0')
      raise <<~MSG
        Please remove the patch `Arguments` module and use `ActiveJob::Arguments` again.
      MSG
    end
  end
end