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.

67 lines
1.8 KiB

  1. # frozen_string_literal: true
  2. class ActivityPub::DeliveryWorker
  3. include Sidekiq::Worker
  4. include JsonLdHelper
  5. STOPLIGHT_FAILURE_THRESHOLD = 10
  6. STOPLIGHT_COOLDOWN = 60
  7. sidekiq_options queue: 'push', retry: 16, dead: false
  8. HEADERS = { 'Content-Type' => 'application/activity+json' }.freeze
  9. def perform(json, source_account_id, inbox_url, options = {})
  10. return unless DeliveryFailureTracker.available?(inbox_url)
  11. @options = options.with_indifferent_access
  12. @json = json
  13. @source_account = Account.find(source_account_id)
  14. @inbox_url = inbox_url
  15. @host = Addressable::URI.parse(inbox_url).normalized_site
  16. @performed = false
  17. perform_request
  18. ensure
  19. if @inbox_url.present?
  20. if @performed
  21. failure_tracker.track_success!
  22. else
  23. failure_tracker.track_failure!
  24. end
  25. end
  26. end
  27. private
  28. def build_request(http_client)
  29. Request.new(:post, @inbox_url, body: @json, http_client: http_client).tap do |request|
  30. request.on_behalf_of(@source_account, :uri, sign_with: @options[:sign_with])
  31. request.add_headers(HEADERS)
  32. end
  33. end
  34. def perform_request
  35. light = Stoplight(@inbox_url) do
  36. request_pool.with(@host) do |http_client|
  37. build_request(http_client).perform do |response|
  38. raise Mastodon::UnexpectedResponseError, response unless response_successful?(response) || response_error_unsalvageable?(response)
  39. @performed = true
  40. end
  41. end
  42. end
  43. light.with_threshold(STOPLIGHT_FAILURE_THRESHOLD)
  44. .with_cool_off_time(STOPLIGHT_COOLDOWN)
  45. .run
  46. end
  47. def failure_tracker
  48. @failure_tracker ||= DeliveryFailureTracker.new(@inbox_url)
  49. end
  50. def request_pool
  51. RequestPool.current
  52. end
  53. end