requester.rb 1.7 KB

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