lib/fastly/client.rb in fastly-2.2.0 vs lib/fastly/client.rb in fastly-2.3.0

- old
+ new

@@ -1,5 +1,7 @@ +# frozen_string_literal: true + require 'json' require 'cgi' require 'net/http' # also requires uri require 'openssl' @@ -7,33 +9,24 @@ # The UserAgent to communicate with the API class Client #:nodoc: all DEFAULT_URL = 'https://api.fastly.com'.freeze - attr_accessor :http, :api_key, :user, :password, :cookie, :customer + attr_accessor :api_key, :base_url, :debug, :user, :password, :cookie, :customer def initialize(opts) - @api_key = opts.fetch(:api_key, nil) - @user = opts.fetch(:user, nil) - @password = opts.fetch(:password, nil) - @customer = opts.fetch(:customer, nil) - @oldpurge = opts.fetch(:use_old_purge_method, false) + @api_key = opts.fetch(:api_key, nil) + @base_url = opts.fetch(:base_url, DEFAULT_URL) + @customer = opts.fetch(:customer, nil) + @oldpurge = opts.fetch(:use_old_purge_method, false) + @password = opts.fetch(:password, nil) + @user = opts.fetch(:user, nil) + @debug = opts.fetch(:debug, nil) + @thread_http_client = if defined?(Concurrent::ThreadLocalVar) + Concurrent::ThreadLocalVar.new { build_http_client } + end - base = opts.fetch(:base_url, DEFAULT_URL) - uri = URI.parse(base) - - @http = Net::HTTP.new(uri.host, uri.port, :ENV, nil, nil, nil) - - # handle TLS connections outside of development - @http.verify_mode = OpenSSL::SSL::VERIFY_PEER - @http.use_ssl = uri.scheme.downcase == 'https' - - # debug http interactions if specified - @http.set_debug_output(opts[:debug]) if opts[:debug] - - @http.start - return self unless fully_authed? # If full auth creds (user/pass) then log in and set a cookie resp = http.post('/login', make_params(user: user, password: password)) @@ -112,10 +105,31 @@ fail Error, resp.body unless resp.kind_of?(Net::HTTPSuccess) JSON.parse(resp.body) end + def http + return @thread_http_client.value if @thread_http_client + return Thread.current[:fastly_net_http] if Thread.current[:fastly_net_http] + + Thread.current[:fastly_net_http] = build_http_client + end + private + + def build_http_client + uri = URI.parse(base_url) + net_http = Net::HTTP.new(uri.host, uri.port, :ENV, nil, nil, nil) + + # handle TLS connections outside of development + net_http.verify_mode = OpenSSL::SSL::VERIFY_PEER + net_http.use_ssl = uri.scheme.downcase == 'https' + + # debug http interactions if specified + net_http.set_debug_output(debug) if debug + + net_http + end def post_and_put(method, path, params = {}) extras = params.delete(:headers) || {} query = make_params(params) resp = http.send(method, path, query, headers(extras).merge('Content-Type' => 'application/x-www-form-urlencoded'))