The code powering m.abunchtell.com https://m.abunchtell.com
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.
 
 
 
 

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