class ZuoraConnect::AppInstanceBase
def refresh_oauth
def refresh_oauth refresh_oauth_count ||= 0 error_type = "" start = Time.now params = { :grant_type => "refresh_token", :redirect_uri => ZuoraConnect.configuration.oauth_client_redirect_uri, :refresh_token => self.refresh_token } response = HTTParty.post("#{ZuoraConnect.configuration.url}/oauth/token",:body => params) response_time = Time.now - start Rails.logger.info("[#{self.id}] REFRESH OAUTH - In #{response_time.round(2).to_s}") if response.code == 200 response_body = JSON.parse(response.body) self.refresh_token = response_body["refresh_token"] self.access_token = response_body["access_token"] self.oauth_expires_at = Time.at(response_body["created_at"].to_i) + response_body["expires_in"].seconds self.save(:validate => false) else Rails.logger.fatal("[#{self.id}] REFRESH OAUTH - Failed Code #{response.code}") raise ZuoraConnect::Exceptions::ConnectCommunicationError.new("Error Refreshing Access Token", response.body, response.code) end rescue Net::ReadTimeout, Net::OpenTimeout, Errno::EPIPE, Errno::ECONNRESET, Errno::ECONNREFUSED, SocketError => ex if (refresh_oauth_count += 1) < 3 Rails.logger.info("[#{self.id}] REFRESH OAUTH - #{ex.class} Retrying(#{refresh_oauth_count})") retry else error_type = "#{ex.class}" Rails.logger.fatal("[#{self.id}] REFRESH OAUTH - #{ex.class} Failed #{refresh_oauth_count}x") raise end rescue ZuoraConnect::Exceptions::ConnectCommunicationError => ex sleep(5) self.reload_attributes([:refresh_token, :oauth_expires_at, :access_token]) #Reload only the refresh token for retry #After reload, if nolonger expired return return if !self.oauth_expired? if (refresh_oauth_count += 1) < 3 Rails.logger.info("[#{self.id}] REFRESH OAUTH - Failed Retrying(#{refresh_oauth_count})") retry else error_type = "#{ex.class}" Rails.logger.fatal("[#{self.id}] REFRESH OAUTH - Failed #{refresh_oauth_count}x") raise end ensure status_code = response.code if response endpoint_name = URI(ZuoraConnect.configuration.url).host Thread.current[:appinstance].present? ? app_instance = Thread.current[:appinstance].id : app_instance = 0 ZuoraConnect::AppInstanceBase.write_to_telegraf("response_time": response_time, "status_code": status_code, "endpoint_name": endpoint_name, "direction": "outbound", "error_type": error_type, "function_name": "#{self.class}##{__method__}", "method_name": "POST", "app_instance": app_instance) end