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.

60 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. return if DeliveryFailureTracker.unavailable?(inbox_url)
  10. @options = options.with_indifferent_access
  11. @json = json
  12. @source_account = Account.find(source_account_id)
  13. @inbox_url = inbox_url
  14. perform_request
  15. failure_tracker.track_success!
  16. rescue => e
  17. failure_tracker.track_failure!
  18. raise e.class, "Delivery failed for #{inbox_url}: #{e.message}", e.backtrace[0]
  19. end
  20. private
  21. def build_request
  22. request = Request.new(:post, @inbox_url, body: @json)
  23. request.on_behalf_of(@source_account, :uri, sign_with: @options[:sign_with])
  24. request.add_headers(HEADERS)
  25. end
  26. def perform_request
  27. light = Stoplight(@inbox_url) do
  28. build_request.perform do |response|
  29. raise Mastodon::UnexpectedResponseError, response unless response_successful?(response) || response_error_unsalvageable?(response)
  30. end
  31. end
  32. light.with_threshold(STOPLIGHT_FAILURE_THRESHOLD)
  33. .with_cool_off_time(STOPLIGHT_COOLDOWN)
  34. .run
  35. end
  36. def response_successful?(response)
  37. (200...300).cover?(response.code)
  38. end
  39. def response_error_unsalvageable?(response)
  40. (400...500).cover?(response.code) && ![401, 408, 429].include?(response.code)
  41. end
  42. def failure_tracker
  43. @failure_tracker ||= DeliveryFailureTracker.new(@inbox_url)
  44. end
  45. end