delivery_worker.rb 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. # frozen_string_literal: true
  2. class ActivityPub::DeliveryWorker
  3. include Sidekiq::Worker
  4. include RoutingHelper
  5. include JsonLdHelper
  6. STOPLIGHT_FAILURE_THRESHOLD = 10
  7. STOPLIGHT_COOLDOWN = 60
  8. sidekiq_options queue: 'push', retry: 16, dead: false
  9. # Unfortunately, we cannot control Sidekiq's jitter, so add our own
  10. sidekiq_retry_in do |count|
  11. # This is Sidekiq's default delay
  12. delay = (count**4) + 15
  13. # Our custom jitter, that will be added to Sidekiq's built-in one.
  14. # Sidekiq's built-in jitter is `rand(10) * (count + 1)`
  15. jitter = rand(0.5 * (count**4))
  16. delay + jitter
  17. end
  18. HEADERS = { 'Content-Type' => 'application/activity+json' }.freeze
  19. def perform(json, source_account_id, inbox_url, options = {})
  20. @options = options.with_indifferent_access
  21. return unless @options[:bypass_availability] || DeliveryFailureTracker.available?(inbox_url)
  22. @json = json
  23. @source_account = Account.find(source_account_id)
  24. @inbox_url = inbox_url
  25. @host = Addressable::URI.parse(inbox_url).normalized_site
  26. @performed = false
  27. perform_request
  28. ensure
  29. if @inbox_url.present?
  30. if @performed
  31. failure_tracker.track_success!
  32. else
  33. failure_tracker.track_failure!
  34. end
  35. end
  36. end
  37. private
  38. def build_request(http_client)
  39. Request.new(:post, @inbox_url, body: @json, http_client: http_client).tap do |request|
  40. request.on_behalf_of(@source_account, sign_with: @options[:sign_with])
  41. request.add_headers(HEADERS)
  42. request.add_headers({ 'Collection-Synchronization' => synchronization_header }) if ENV['DISABLE_FOLLOWERS_SYNCHRONIZATION'] != 'true' && @options[:synchronize_followers]
  43. end
  44. end
  45. def synchronization_header
  46. "collectionId=\"#{account_followers_url(@source_account)}\", digest=\"#{@source_account.remote_followers_hash(@inbox_url)}\", url=\"#{account_followers_synchronization_url(@source_account)}\""
  47. end
  48. def perform_request
  49. light = Stoplight(@inbox_url) do
  50. request_pool.with(@host) do |http_client|
  51. build_request(http_client).perform do |response|
  52. raise Mastodon::UnexpectedResponseError, response unless response_successful?(response) || response_error_unsalvageable?(response)
  53. @performed = true
  54. end
  55. end
  56. end
  57. light.with_threshold(STOPLIGHT_FAILURE_THRESHOLD)
  58. .with_cool_off_time(STOPLIGHT_COOLDOWN)
  59. .run
  60. end
  61. def failure_tracker
  62. @failure_tracker ||= DeliveryFailureTracker.new(@inbox_url)
  63. end
  64. def request_pool
  65. RequestPool.current
  66. end
  67. end