requester.rb 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. # Copyright (C) 2012-2022 Zammad Foundation, https://zammad-foundation.org/
  2. class Sequencer
  3. class Unit
  4. module Import
  5. module Freshdesk
  6. module Requester
  7. def request(api_path:, params: nil)
  8. 10.times do |iteration|
  9. response = perform_request(
  10. api_path: api_path,
  11. params: params,
  12. )
  13. return response if response.is_a? Net::HTTPOK
  14. handle_error response, iteration
  15. rescue Net::HTTPClientError => e
  16. handle_exception e, iteration
  17. end
  18. nil
  19. end
  20. def handle_error(response, iteration)
  21. sleep_for = 10
  22. case response
  23. when Net::HTTPTooManyRequests
  24. sleep_for = response.header['retry-after'].to_i + 10
  25. logger.info "Rate limit: #{response.header.to_hash} (429 Too Many Requests). Sleeping #{sleep_for} seconds and retry (##{iteration + 1}/10)."
  26. else
  27. logger.info "Unknown response: #{response.inspect}. Sleeping 10 seconds and retry (##{iteration + 1}/10)."
  28. end
  29. sleep sleep_for
  30. end
  31. def handle_exception(e, iteration)
  32. logger.error e
  33. logger.info "Sleeping 10 seconds after #{e.class.name} and retry (##{iteration + 1}/10)."
  34. sleep 10
  35. end
  36. def perform_request(api_path:, params: nil)
  37. uri = URI("#{Setting.get('import_freshdesk_endpoint')}/#{api_path}")
  38. uri.query = URI.encode_www_form(params) if params.present?
  39. headers = { 'Content-Type' => 'application/json' }
  40. Net::HTTP.start(uri.host, uri.port, use_ssl: true, read_timeout: 600) do |http|
  41. # for those special moments...
  42. # http.set_debug_output($stdout)
  43. request = Net::HTTP::Get.new(uri, headers)
  44. request.basic_auth(Setting.get('import_freshdesk_endpoint_key'), 'X')
  45. return http.request(request)
  46. end
  47. end
  48. end
  49. end
  50. end
  51. end
  52. end