You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

58 lines
1.6 KiB

  1. # frozen_string_literal: true
  2. class ActivityPub::DeliveryWorker
  3. include Sidekiq::Worker
  4. STOPLIGHT_FAILURE_THRESHOLD = 10
  5. STOPLIGHT_COOLDOWN = 60
  6. sidekiq_options queue: 'push', retry: 16, dead: false
  7. HEADERS = { 'Content-Type' => 'application/activity+json' }.freeze
  8. def perform(json, source_account_id, inbox_url, options = {})
  9. @options = options.with_indifferent_access
  10. @json = json
  11. @source_account = Account.find(source_account_id)
  12. @inbox_url = inbox_url
  13. perform_request
  14. failure_tracker.track_success!
  15. rescue => e
  16. failure_tracker.track_failure!
  17. raise e.class, "Delivery failed for #{inbox_url}: #{e.message}", e.backtrace[0]
  18. end
  19. private
  20. def build_request
  21. request = Request.new(:post, @inbox_url, body: @json)
  22. request.on_behalf_of(@source_account, :uri, sign_with: @options[:sign_with])
  23. request.add_headers(HEADERS)
  24. end
  25. def perform_request
  26. light = Stoplight(@inbox_url) do
  27. build_request.perform do |response|
  28. raise Mastodon::UnexpectedResponseError, response unless response_successful?(response) || response_error_unsalvageable?(response)
  29. end
  30. end
  31. light.with_threshold(STOPLIGHT_FAILURE_THRESHOLD)
  32. .with_cool_off_time(STOPLIGHT_COOLDOWN)
  33. .run
  34. end
  35. def response_successful?(response)
  36. (200...300).cover?(response.code)
  37. end
  38. def response_error_unsalvageable?(response)
  39. (400...500).cover?(response.code) && response.code != 429
  40. end
  41. def failure_tracker
  42. @failure_tracker ||= DeliveryFailureTracker.new(@inbox_url)
  43. end
  44. end