delivery_worker.rb 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. HEADERS = { 'Content-Type' => 'application/activity+json' }.freeze
  10. def perform(json, source_account_id, inbox_url, options = {})
  11. return unless DeliveryFailureTracker.available?(inbox_url)
  12. @options = options.with_indifferent_access
  13. @json = json
  14. @source_account = Account.find(source_account_id)
  15. @inbox_url = inbox_url
  16. @host = Addressable::URI.parse(inbox_url).normalized_site
  17. @performed = false
  18. perform_request
  19. ensure
  20. if @inbox_url.present?
  21. if @performed
  22. failure_tracker.track_success!
  23. else
  24. failure_tracker.track_failure!
  25. end
  26. end
  27. end
  28. private
  29. def build_request(http_client)
  30. Request.new(:post, @inbox_url, body: @json, http_client: http_client).tap do |request|
  31. request.on_behalf_of(@source_account, :uri, sign_with: @options[:sign_with])
  32. request.add_headers(HEADERS)
  33. request.add_headers({ 'Collection-Synchronization' => synchronization_header }) if ENV['DISABLE_FOLLOWERS_SYNCHRONIZATION'] != 'true' && @options[:synchronize_followers]
  34. end
  35. end
  36. def synchronization_header
  37. "collectionId=\"#{account_followers_url(@source_account)}\", digest=\"#{@source_account.remote_followers_hash(@inbox_url)}\", url=\"#{account_followers_synchronization_url(@source_account)}\""
  38. end
  39. def perform_request
  40. light = Stoplight(@inbox_url) do
  41. request_pool.with(@host) do |http_client|
  42. build_request(http_client).perform do |response|
  43. raise Mastodon::UnexpectedResponseError, response unless response_successful?(response) || response_error_unsalvageable?(response)
  44. @performed = true
  45. end
  46. end
  47. end
  48. light.with_threshold(STOPLIGHT_FAILURE_THRESHOLD)
  49. .with_cool_off_time(STOPLIGHT_COOLDOWN)
  50. .run
  51. end
  52. def failure_tracker
  53. @failure_tracker ||= DeliveryFailureTracker.new(@inbox_url)
  54. end
  55. def request_pool
  56. RequestPool.current
  57. end
  58. end