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.

65 lines
1.7 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 if DeliveryFailureTracker.unavailable?(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 @performed
  20. failure_tracker.track_success!
  21. else
  22. failure_tracker.track_failure!
  23. end
  24. end
  25. private
  26. def build_request(http_client)
  27. Request.new(:post, @inbox_url, body: @json, http_client: http_client).tap do |request|
  28. request.on_behalf_of(@source_account, :uri, sign_with: @options[:sign_with])
  29. request.add_headers(HEADERS)
  30. end
  31. end
  32. def perform_request
  33. light = Stoplight(@inbox_url) do
  34. request_pool.with(@host) do |http_client|
  35. build_request(http_client).perform do |response|
  36. raise Mastodon::UnexpectedResponseError, response unless response_successful?(response) || response_error_unsalvageable?(response)
  37. @performed = true
  38. end
  39. end
  40. end
  41. light.with_threshold(STOPLIGHT_FAILURE_THRESHOLD)
  42. .with_cool_off_time(STOPLIGHT_COOLDOWN)
  43. .run
  44. end
  45. def failure_tracker
  46. @failure_tracker ||= DeliveryFailureTracker.new(@inbox_url)
  47. end
  48. def request_pool
  49. RequestPool.current
  50. end
  51. end