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.

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