Blame view

lib/syspro/syspro_client.rb 11.7 KB
51fb5579   Isaac Lewis   add client test, ...
1
2
  module Syspro
    class SysproClient
db76748d   Isaac Lewis   cop a bunch of St...
3
4
      attr_accessor :conn, :api_base
  
697a8854   Isaac Lewis   update tests
5
6
      @verify_ssl_warned = false
  
51fb5579   Isaac Lewis   add client test, ...
7
8
9
10
11
      def initialize(conn = nil)
        self.conn = conn || self.class.default_conn
        @system_profiler = SystemProfiler.new
      end
  
49716587   Isaac Lewis   refactor object s...
12
      def logon(username, password, company_id, company_password)
697a8854   Isaac Lewis   update tests
13
        Syspro::Logon.logon(username, password, company_id, company_password)
49716587   Isaac Lewis   refactor object s...
14
15
16
      end
  
      def get_syspro_version
697a8854   Isaac Lewis   update tests
17
        Syspro::GetVersion.get_version
49716587   Isaac Lewis   refactor object s...
18
19
      end
  
51fb5579   Isaac Lewis   add client test, ...
20
21
22
23
24
25
26
27
      def self.active_client
        Thread.current[:syspro_client] || default_client
      end
  
      def self.default_client
        Thread.current[:syspro_client_default_client] ||= SysproClient.new(default_conn)
      end
  
db76748d   Isaac Lewis   cop a bunch of St...
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
      # A default Faraday connection to be used when one isn't configured. This
      # object should never be mutated, and instead instantiating your own
      # connection and wrapping it in a SysproClient object should be preferred.
      def self.default_conn
        # We're going to keep connections around so that we can take advantage
        # of connection re-use, so make sure that we have a separate connection
        # object per thread.
        Thread.current[:syspro_client_default_conn] ||= begin
          conn = Faraday.new do |c|
            c.use Faraday::Request::Multipart
            c.use Faraday::Request::UrlEncoded
            c.use Faraday::Response::RaiseError
            c.adapter Faraday.default_adapter
          end
  
0c0af54a   Isaac Lewis   error handling; c...
43
          # For now, we're not verifying SSL certificates. The warning will appear.
db76748d   Isaac Lewis   cop a bunch of St...
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
          #if Syspro.verify_ssl_certs
            #conn.ssl.verify = true
            #conn.ssl.cert_store = Syspro.ca_store
          #else
          conn.ssl.verify = false
  
          unless @verify_ssl_warned
            @verify_ssl_warned = true
            $stderr.puts("WARNING: Running without SSL cert verification. " \
              "You should never do this in production. " \
              "Execute 'Syspro.verify_ssl_certs = true' to enable verification.")
          end
          #end
  
          conn
        end
      end
  
3d0157a5   Isaac Lewis   add logoff
62
63
      # Executes the API call within the given block. Usage looks like:
      #
4a8bba96   Isaac Lewis   cleanup
64
      #     client = SysproClient.new
3d0157a5   Isaac Lewis   add logoff
65
66
67
68
      #     charge, resp = client.request { Charge.create }
      #
      def request
        @last_response = nil
4a8bba96   Isaac Lewis   cleanup
69
70
        old_syspro_client = Thread.current[:syspro_client]
        Thread.current[:syspro_client] = self
3d0157a5   Isaac Lewis   add logoff
71
72
73
74
75
  
        begin
          res = yield
          [res, @last_response]
        ensure
4a8bba96   Isaac Lewis   cleanup
76
          Thread.current[:syspro_client] = old_syspro_client
3d0157a5   Isaac Lewis   add logoff
77
78
79
80
        end
      end
  
      def execute_request(method, path, user_id: nil, api_base: nil, headers: {}, params: {})
db76748d   Isaac Lewis   cop a bunch of St...
81
        api_base ||= Syspro.api_base
3d0157a5   Isaac Lewis   add logoff
82
        user_id  ||= ""
db76748d   Isaac Lewis   cop a bunch of St...
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
  
        params = Util.objects_to_ids(params)
        url = api_url(path, api_base)
  
        body = nil
        query_params = nil
  
        case method.to_s.downcase.to_sym
        when :get, :head, :delete
          query_params = params
        else
          body = if headers[:content_type] && headers[:content_type] == "multipart/form-data"
                   params
                 else
                   Util.encode_parameters(params)
                 end
        end
  
        headers = request_headers(method)
                  .update(Util.normalize_headers(headers))
  
        # stores information on the request we're about to make so that we don't
        # have to pass as many parameters around for logging.
        context = RequestLogContext.new
        context.body            = body
        context.method          = method
        context.path            = path
3d0157a5   Isaac Lewis   add logoff
110
        context.user_id         = user_id
db76748d   Isaac Lewis   cop a bunch of St...
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
        context.query_params    = query_params ? Util.encode_parameters(query_params) : nil
  
        http_resp = execute_request_with_rescues(api_base, context) do
          conn.run_request(method, url, body, headers) do |req|
            req.options.open_timeout = Syspro.open_timeout
            req.options.timeout = Syspro.read_timeout
            req.params = query_params unless query_params.nil?
          end
        end
  
        begin
          resp = SysproResponse.from_faraday_response(http_resp)
        rescue JSON::ParserError
          raise general_api_error(http_resp.status, http_resp.body)
        end
  
        # Allows SysproClient#request to return a response object to a caller.
        @last_response = resp
        [resp]
      end
  
      def general_api_error(status, body)
0c0af54a   Isaac Lewis   error handling; c...
133
        ApiError.new("Invalid response object from API: #{body.inspect} " \
db76748d   Isaac Lewis   cop a bunch of St...
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
                     "(HTTP response code was #{status})",
                     http_status: status, http_body: body)
      end
  
      def api_url(url = "", api_base = nil)
        (api_base || Syspro.api_base) + url
      end
  
      def request_headers(method)
        user_agent = "Syspro/7 RubyBindings/#{Syspro::VERSION}"
  
        headers = {
          "User-Agent" => user_agent,
          "Content-Type" => "application/x-www-form-urlencoded",
        }
  
        headers
      end
  
      def execute_request_with_rescues(api_base, context)
        num_retries = 0
        begin
          request_start = Time.now
          log_request(context, num_retries)
          resp = yield
db76748d   Isaac Lewis   cop a bunch of St...
159
160
161
162
163
164
          log_response(context, request_start, resp.status, resp.body)
  
        # We rescue all exceptions from a request so that we have an easy spot to
        # implement our retry logic across the board. We'll re-raise if it's a type
        # of exception that we didn't expect to handle.
        rescue StandardError => e
db76748d   Isaac Lewis   cop a bunch of St...
165
          if e.respond_to?(:response) && e.response
e3484f8f   Isaac Lewis   remove dup check
166
            log_response(context, request_start,
db76748d   Isaac Lewis   cop a bunch of St...
167
168
                         e.response[:status], e.response[:body])
          else
e3484f8f   Isaac Lewis   remove dup check
169
            log_response_error(context, request_start, e)
db76748d   Isaac Lewis   cop a bunch of St...
170
171
172
173
174
175
176
177
178
179
180
          end
  
          if self.class.should_retry?(e, num_retries)
            num_retries += 1
            sleep self.class.sleep_time(num_retries)
            retry
          end
  
          case e
          when Faraday::ClientError
            if e.response
96149efa   Isaac Lewis   working query browse
181
              handle_error_response(e.response, context)
db76748d   Isaac Lewis   cop a bunch of St...
182
            else
96149efa   Isaac Lewis   working query browse
183
              handle_network_error(e, context, num_retries, api_base)
db76748d   Isaac Lewis   cop a bunch of St...
184
185
186
187
188
189
190
191
192
193
194
195
            end
  
          # Only handle errors when we know we can do so, and re-raise otherwise.
          # This should be pretty infrequent.
          else
            raise
          end
        end
  
        resp
      end
  
96149efa   Isaac Lewis   working query browse
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
      def handle_network_error(e, context, num_retries, api_base = nil)
        Util.log_error("Syspro network error",
                       error_message: e.message,
                       request_id: context.request_id)
  
        case e
        when Faraday::ConnectionFailed
          message = "Unexpected error communicating when trying to connect to Syspro."
  
        when Faraday::SSLError
          message = "Could not establish a secure connection to Syspro."
  
        when Faraday::TimeoutError
          api_base ||= Syspro.api_base
          message = "Could not connect to Syspro (#{api_base}). " \
            "Please check your internet connection and try again. " \
            "If this problem persists, you should check your Syspro service status."
  
        else
          message = "Unexpected error communicating with Syspro. " \
            "If this problem persists, talk to your Syspro implementation team."
  
        end
  
        message += " Request was retried #{num_retries} times." if num_retries > 0
  
        raise ApiConnectionError, message + "\n\n(Network error: #{e.message})"
      end
  
db76748d   Isaac Lewis   cop a bunch of St...
225
      def self.should_retry?(e, num_retries)
eef01045   Isaac Lewis   re-implement max_...
226
227
        return false if num_retries >= Syspro.max_network_retries
  
db76748d   Isaac Lewis   cop a bunch of St...
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
        # Retry on timeout-related problems (either on open or read).
        return true if e.is_a?(Faraday::TimeoutError)
  
        # Destination refused the connection, the connection was reset, or a
        # variety of other connection failures. This could occur from a single
        # saturated server, so retry in case it's intermittent.
        return true if e.is_a?(Faraday::ConnectionFailed)
  
        if e.is_a?(Faraday::ClientError) && e.response
          # 409 conflict
          return true if e.response[:status] == 409
        end
  
        false
      end
  
      def log_request(context, num_retries)
        Util.log_info("Request to Syspro API",
                      account: context.account,
                      api_version: context.api_version,
                      method: context.method,
                      num_retries: num_retries,
                      path: context.path)
        Util.log_debug("Request details",
                       body: context.body,
                       query_params: context.query_params)
      end
      private :log_request
  
      def log_response(context, request_start, status, body)
        Util.log_info("Response from Syspro API",
                      account: context.account,
                      api_version: context.api_version,
                      elapsed: Time.now - request_start,
                      method: context.method,
                      path: context.path,
                      request_id: context.request_id,
                      status: status)
        Util.log_debug("Response details",
                       body: body,
                       request_id: context.request_id)
      end
      private :log_response
  
      def log_response_error(context, request_start, e)
        Util.log_error("Request error",
                       elapsed: Time.now - request_start,
                       error_message: e.message,
                       method: context.method,
                       path: context.path)
      end
      private :log_response_error
  
96149efa   Isaac Lewis   working query browse
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
      def handle_error_response(http_resp, context)
        begin
          resp = SysproResponse.from_faraday_hash(http_resp)
          error_data = resp.data[:error]
  
          raise SysproError, "Indeterminate error" unless error_data
        rescue Nokogiri::XML::SyntaxError, SysproError
          raise general_api_error(http_resp[:status], http_resp[:body])
        end
  
        error = if error_data.is_a?(String)
                  specific_oauth_error(resp, error_data, context)
                else
                  specific_api_error(resp, error_data, context)
                end
  
        error.response = resp
        raise(error)
      end
  
db76748d   Isaac Lewis   cop a bunch of St...
301
302
303
304
305
306
307
308
309
310
311
      # RequestLogContext stores information about a request that's begin made so
      # that we can log certain information. It's useful because it means that we
      # don't have to pass around as many parameters.
      class RequestLogContext
        attr_accessor :body
        attr_accessor :account
        attr_accessor :api_version
        attr_accessor :method
        attr_accessor :path
        attr_accessor :query_params
        attr_accessor :request_id
3d0157a5   Isaac Lewis   add logoff
312
        attr_accessor :user_id
db76748d   Isaac Lewis   cop a bunch of St...
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
      end
  
      # SystemProfiler extracts information about the system that we're running
      # in so that we can generate a rich user agent header to help debug
      # integrations.
      class SystemProfiler
        def self.uname
          if File.exist?("/proc/version")
            File.read("/proc/version").strip
          else
            case RbConfig::CONFIG["host_os"]
            when /linux|darwin|bsd|sunos|solaris|cygwin/i
              uname_from_system
            when /mswin|mingw/i
              uname_from_system_ver
            else
              "unknown platform"
            end
          end
        end
  
        def self.uname_from_system
          (`uname -a 2>/dev/null` || "").strip
        rescue Errno::ENOENT
          "uname executable not found"
        rescue Errno::ENOMEM # couldn't create subprocess
          "uname lookup failed"
        end
  
        def self.uname_from_system_ver
          (`ver` || "").strip
        rescue Errno::ENOENT
          "ver executable not found"
        rescue Errno::ENOMEM # couldn't create subprocess
          "uname lookup failed"
        end
  
        def initialize
          @uname = self.class.uname
        end
  
        def user_agent
          lang_version = "#{RUBY_VERSION} p#{RUBY_PATCHLEVEL} (#{RUBY_RELEASE_DATE})"
51fb5579   Isaac Lewis   add client test, ...
356
  
db76748d   Isaac Lewis   cop a bunch of St...
357
358
359
360
361
362
363
364
365
366
367
          {
            application: Syspro.app_info,
            bindings_version: Syspro::VERSION,
            lang: "ruby",
            lang_version: lang_version,
            platform: RUBY_PLATFORM,
            engine: defined?(RUBY_ENGINE) ? RUBY_ENGINE : "",
            uname: @uname,
            hostname: Socket.gethostname,
          }.delete_if { |_k, v| v.nil? }
        end
51fb5579   Isaac Lewis   add client test, ...
368
369
370
      end
    end
  end