loogi_http 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 1f1ffdc2eb3eb29ab5fe10e612b5a4289e28fa82fcae6af5b71117f29c486306
4
+ data.tar.gz: 99829cb003c44288e7268dc92d5c84b68b477fc87f0b72e30d3e22b8d2f19917
5
+ SHA512:
6
+ metadata.gz: 69639f94f6691ff4ae76a65f915a83f27a825f5c90786c1d385a1f4a5aeb337dc15279d63c0bbe92bdbf9336bee76993fa0312fbea8b946fada9c55662c142ea
7
+ data.tar.gz: 74ab8aeb5a5b2f6923ed07db03dcc003555cb5672cae23b25d8ecec9c5b40928628b8fc3762b384268c2240e8bab950d691f9648683ce4d526b1a97c95ad8e07
@@ -0,0 +1,33 @@
1
+ name: Ruby Gem
2
+
3
+ on:
4
+ push:
5
+ branches: [ "main" ]
6
+ pull_request:
7
+ branches: [ "main" ]
8
+
9
+ jobs:
10
+ build:
11
+ name: Build + Publish
12
+ runs-on: ubuntu-latest
13
+ permissions:
14
+ contents: read
15
+ packages: write
16
+
17
+ steps:
18
+ - uses: actions/checkout@v3
19
+ - name: Set up Ruby 2.6
20
+ uses: actions/setup-ruby@v1
21
+ with:
22
+ ruby-version: 2.6.x
23
+
24
+ - name: Publish to RubyGems
25
+ run: |
26
+ mkdir -p $HOME/.gem
27
+ touch $HOME/.gem/credentials
28
+ chmod 0600 $HOME/.gem/credentials
29
+ printf -- "---\n:rubygems_api_key: ${GEM_HOST_API_KEY}\n" > $HOME/.gem/credentials
30
+ gem build *.gemspec
31
+ gem push *.gem
32
+ env:
33
+ GEM_HOST_API_KEY: "${{secrets.RUBYGEMS_AUTH_TOKEN}}"
@@ -0,0 +1,35 @@
1
+ # This workflow uses actions that are not certified by GitHub.
2
+ # They are provided by a third-party and are governed by
3
+ # separate terms of service, privacy policy, and support
4
+ # documentation.
5
+ # This workflow will download a prebuilt Ruby version, install dependencies and run tests with Rake
6
+ # For more information see: https://github.com/marketplace/actions/setup-ruby-jruby-and-truffleruby
7
+
8
+ name: Specs
9
+
10
+ on:
11
+ push:
12
+ branches: [ main ]
13
+ pull_request:
14
+ branches: [ main ]
15
+
16
+ jobs:
17
+ test:
18
+
19
+ runs-on: ubuntu-latest
20
+ strategy:
21
+ matrix:
22
+ ruby-version: ['2.6', '2.7', '3.0']
23
+
24
+ steps:
25
+ - uses: actions/checkout@v2
26
+ - name: Set up Ruby
27
+ # To automatically get bug fixes and new Ruby versions for ruby/setup-ruby,
28
+ # change this to (see https://github.com/ruby/setup-ruby#versioning):
29
+ # uses: ruby/setup-ruby@v1
30
+ uses: ruby/setup-ruby@473e4d8fe5dd94ee328fdfca9f8c9c7afc9dae5e
31
+ with:
32
+ ruby-version: ${{ matrix.ruby-version }}
33
+ bundler-cache: true # runs 'bundle install' and caches installed gems automatically
34
+ - name: Run tests
35
+ run: bundle exec rake spec
data/.gitignore ADDED
@@ -0,0 +1,12 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+ Gemfile.lock
10
+
11
+ # rspec failure tracking
12
+ spec/examples.txt
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at alessandro@juul.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,6 @@
1
+ source 'https://rubygems.org'
2
+
3
+ git_source(:github) { |repo_name| "https://github.com/#{repo_name}" }
4
+
5
+ # Specify your gem's dependencies in loogi_http.gemspec
6
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2022 JUUL Labs
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,41 @@
1
+ # LoogiHttp
2
+
3
+ [![Specs](https://github.com/JuulLabs-OSS/loogi_http/actions/workflows/specs.yml/badge.svg)](https://github.com/JuulLabs-OSS/loogi_http/actions/workflows/specs.yml)
4
+
5
+ Provides a wrapper to external requests providing JSON parsing, logging, metrics, and more.
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'loogi_http'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install loogi_http
22
+
23
+ ## Development
24
+
25
+ After checking out the repo, run `bin/setup` to install dependencies. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
26
+
27
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
28
+
29
+ To execute tests, run `bundle exec rake spec`.
30
+
31
+ ## Contributing
32
+
33
+ Bug reports and pull requests are welcome on GitHub at https://github.com/JuulLabs-OSS/loogi_http. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
34
+
35
+ ## License
36
+
37
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
38
+
39
+ ## Code of Conduct
40
+
41
+ Everyone interacting in the Test project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/JuulLabs-OSS/loogi_http/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,6 @@
1
+ require 'bundler/gem_tasks'
2
+ require 'rspec/core/rake_task'
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task default: :spec
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require 'bundler/setup'
4
+ require 'loogi_http'
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require 'irb'
14
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,39 @@
1
+ require 'loogi_http/configuration'
2
+ require 'loogi_http/connection'
3
+
4
+ module LoogiHttp
5
+ # Conveniently configure `Faraday` stacks.
6
+ class Builder
7
+ # Configure a JSON stack.
8
+ #
9
+ # @return [LoogiHttp::Connection]
10
+ def self.json
11
+ new.build(&:json)
12
+ end
13
+
14
+ # Customize a stack with a configuration block.
15
+ #
16
+ # Example:
17
+ #
18
+ # LoogiHttp::Builder.new.configure do |config|
19
+ # config.json
20
+ # end
21
+ #
22
+ # @yield [config] Customize the stack within this block
23
+ # @yieldparam config [LoogiHttp::Configuration] Configuration to customize
24
+ # @return [LoogiHttp::Connection]
25
+ def build(&block)
26
+ LoogiHttp::Connection.new(
27
+ faraday_connection do |conn|
28
+ LoogiHttp::Configuration.new(conn).configure(&block)
29
+ end
30
+ )
31
+ end
32
+
33
+ private
34
+
35
+ def faraday_connection(&block)
36
+ Faraday.new(&block)
37
+ end
38
+ end
39
+ end
@@ -0,0 +1,92 @@
1
+ require 'faraday_middleware'
2
+ require 'forwardable'
3
+
4
+ module LoogiHttp
5
+ # Configure a `Faraday::Connection` (aka a _stack_).
6
+ class Configuration
7
+ extend Forwardable
8
+
9
+ # @param faraday_connection [Faraday::Connection] Stack to be
10
+ # configured
11
+ def initialize(faraday_connection)
12
+ @faraday_connection = faraday_connection
13
+ end
14
+
15
+ # Custom configuration of the stack in a block. By default, the
16
+ # stack is configured to:
17
+ #
18
+ # * instrument call with `ActiveSupport::Notifications`
19
+ # * follow redirects
20
+ # * use `Net::HTTP` adapter
21
+ #
22
+ # Example:
23
+ #
24
+ # config.configure do |config|
25
+ # config.json
26
+ # end
27
+ #
28
+ # @yield [config] Customize the stack within this block
29
+ # @yieldparam config [LoogiHttp::Configuration] Configuration to customize
30
+ # @return [Faraday::Connection]
31
+ def configure(&_block)
32
+ use :instrumentation if defined? ::ActiveSupport::Notifications
33
+
34
+ logger = LoogiHttp.logger
35
+ level = LoogiHttp.log_level
36
+ use :log_request, logger: logger, level: level if logger
37
+
38
+ response :follow_redirects
39
+
40
+ yield self if block_given?
41
+
42
+ use :debug_http
43
+ faraday_connection.adapter(*adapter_args, &adapter_block)
44
+
45
+ faraday_connection
46
+ end
47
+
48
+ # Configure the adapter to be used by the stack. The default stack is
49
+ # `Net::HTTP`.
50
+ #
51
+ # Example customization of `Net::HTTP`:
52
+ #
53
+ # config.adapter :net_http do |http| # yields Net::HTTP
54
+ # http.idle_timeout = 100
55
+ # http.verify_callback = lambda do | preverify_ok, cert_store |
56
+ # # do something here...
57
+ # end
58
+ # end
59
+ #
60
+ # More details in the Faraday docs
61
+ # @see https://github.com/lostisland/faraday#ad-hoc-adapters-customization
62
+ #
63
+ # @param args [Array<Object>] Adapter arguments, name first, defaults to
64
+ # `:net_http`
65
+ # @yield [adapter] Configure the adapter before use
66
+ def adapter(*args, &block)
67
+ @adapter_args = args
68
+ @adapter_block = block
69
+ end
70
+
71
+ # Configure the stack for JSON, using three middlewares:
72
+ #
73
+ # * Set the `Accept` header
74
+ # * ensure the body sent is JSON (converts non-String via `to_json`)
75
+ # * parse result body as JSON for JSON content type
76
+ def json
77
+ request :accept_json
78
+ request :json
79
+ response :json, content_type: 'application/json'
80
+ end
81
+
82
+ private
83
+
84
+ attr_reader :adapter_block, :faraday_connection
85
+
86
+ def_delegators :@faraday_connection, :request, :response, :use
87
+
88
+ def adapter_args
89
+ @adapter_args ||= %i[net_http]
90
+ end
91
+ end
92
+ end
@@ -0,0 +1,94 @@
1
+ require 'loogi_http/response'
2
+ require 'loogi_http/error'
3
+
4
+ module LoogiHttp
5
+ # HTTP connection over a configured `Faraday::Connection` (aka a _stack_).
6
+ # Methods supported are:
7
+ #
8
+ # {#get}
9
+ # {#post}
10
+ class Connection
11
+ # @param faraday_connection [Faraday::Connection] The configured
12
+ # `Faraday::Connection`
13
+ def initialize(faraday_connection)
14
+ @faraday_connection = faraday_connection
15
+ end
16
+
17
+ # HTTP GET request.
18
+ #
19
+ # @param url [String] URL
20
+ # @param params [Hash] Query params to be sent, defaults to `{}`
21
+ # @return [LoogiHttp::Response]
22
+ def get(url, params: {})
23
+ response faraday_connection.get(url, params)
24
+ rescue Faraday::TimeoutError => e
25
+ raise LoogiHttp::TimeoutError, e
26
+ rescue Faraday::ConnectionFailed => e
27
+ raise LoogiHttp::ConnectionFailed, e
28
+ end
29
+
30
+ # HTTP POST request.
31
+ #
32
+ # @param url [String] URL
33
+ # @param params [Hash] Query params to be sent, defaults to `{}`
34
+ # @param data [Object] POST body that will eventually be converted into a
35
+ # `String`, defaults to `nil`
36
+ # @param options [Hash] Faraday options, defaults to `{}`
37
+ # @param headers [Hash] Headers for the POST, defaults to `{}`
38
+ # @return [LoogiHttp::Response]
39
+ def post(url, params: {}, data: nil, options: {}, headers: {})
40
+ response(faraday_connection.post(url, data, headers) do |request|
41
+ request.params.update params if params
42
+ if (debug = options.delete(:debug))
43
+ options[:context] ||= {}
44
+ options[:context][:debug] = debug
45
+ end
46
+ request.options.update options if options
47
+ end)
48
+ rescue Faraday::TimeoutError => e
49
+ raise LoogiHttp::TimeoutError, e
50
+ rescue Faraday::ConnectionFailed => e
51
+ raise LoogiHttp::ConnectionFailed, e
52
+ end
53
+
54
+ # HTTP PUT request.
55
+ #
56
+ # @param url [String] URL
57
+ # @param params [Hash] Query params to be sent, defaults to `{}`
58
+ # @param data [Object] PUT body that will eventually be converted into a
59
+ # `String`, defaults to `nil`
60
+ # @param options [Hash] Faraday options, defaults to `{}`
61
+ # @param headers [Hash] Headers for the PUT, defaults to `{}`
62
+ # @return [LoogiHttp::Response]
63
+ def put(url, params: {}, data: nil, options: {}, headers: {})
64
+ response(faraday_connection.put(url, data, headers) do |request|
65
+ request.params.update params if params
66
+ if (debug = options.delete(:debug))
67
+ options[:context] ||= {}
68
+ options[:context][:debug] = debug
69
+ end
70
+ request.options.update options if options
71
+ end)
72
+ rescue Faraday::TimeoutError => e
73
+ raise LoogiHttp::TimeoutError, e
74
+ end
75
+
76
+ # Basic Authentication
77
+ #
78
+ # @param username [String]
79
+ # @param password [String]
80
+ #
81
+ # @return [void]
82
+ def basic_auth(username:, password:)
83
+ faraday_connection.basic_auth(username, password)
84
+ end
85
+
86
+ private
87
+
88
+ attr_reader :faraday_connection
89
+
90
+ def response(faraday_response)
91
+ Response.new(faraday_response)
92
+ end
93
+ end
94
+ end
@@ -0,0 +1,20 @@
1
+ module LoogiHttp
2
+ class Error < RuntimeError; end
3
+
4
+ class ServerError < Error
5
+ attr_reader :error
6
+
7
+ def initialize(error)
8
+ @error = error
9
+ set_backtrace(error.backtrace)
10
+ end
11
+
12
+ def message
13
+ error.message
14
+ end
15
+ end
16
+
17
+ class TimeoutError < ServerError; end
18
+
19
+ class ConnectionFailed < ServerError; end
20
+ end
@@ -0,0 +1,124 @@
1
+ require 'faraday'
2
+
3
+ module LoogiHttp
4
+ module Middleware
5
+ # Faraday middleware to debug the request and response.
6
+ #
7
+ # Turn on per request by passing a Logger as the `:debug` option:
8
+ #
9
+ # LoogiHttp.json_post url, params, data, debug: Rails.logger
10
+ class DebugHttp < Faraday::Middleware
11
+ class DebugOutput
12
+ def initialize(env, response, exception)
13
+ @env = env
14
+ @response = response
15
+ @exception = exception
16
+ end
17
+
18
+ def debug
19
+ debug_request
20
+
21
+ if response
22
+ debug_line
23
+ debug_response
24
+ end
25
+
26
+ return if exception.nil?
27
+
28
+ debug_line
29
+ debug_exception
30
+ end
31
+
32
+ private
33
+
34
+ attr_reader :env, :exception, :response
35
+
36
+ def debug_exception
37
+ klass = exception.class
38
+ error = exception.message
39
+ trace = exception.backtrace.join("\n")
40
+ exception_message = format(
41
+ "%<klass>s %<error>s\n%<trace>s",
42
+ klass: klass,
43
+ error: error,
44
+ trace: trace
45
+ )
46
+ logger.info exception_message
47
+ end
48
+
49
+ def debug_line
50
+ logger.info ''
51
+ end
52
+
53
+ def debug_request
54
+ url = env.url
55
+ method = env.method.to_s.upcase
56
+
57
+ logger.info "#{method} #{url.path}"
58
+ logger.info "Host: #{url.host}"
59
+ log_headers env.request_headers
60
+ log_body env.body if needs_body?
61
+ end
62
+
63
+ def debug_response
64
+ logger.info "Status: #{response.status}"
65
+ log_headers response.headers
66
+ log_body response.body
67
+ end
68
+
69
+ def log_body(body)
70
+ logger.info 'BODY' + '-' * 10
71
+ logger.info body
72
+ logger.info 'BODY' + '-' * 10
73
+ end
74
+
75
+ def log_headers(headers_hash)
76
+ headers_hash.each do |key, value|
77
+ logger.info "#{key}: #{value}"
78
+ end
79
+ end
80
+
81
+ def logger
82
+ @logger ||= env.request.context[:debug]
83
+ end
84
+
85
+ def needs_body?
86
+ Faraday::Env::MethodsWithBodies.include? env.method
87
+ end
88
+ end
89
+
90
+ # Emit debug output for every request. If an exception is raised, emit the
91
+ # exception and backtrace.
92
+ #
93
+ # @param env [Faraday::Env]
94
+ # @return [Faraday::Request]
95
+ def call(env)
96
+ if debug?(env)
97
+ debug_call env
98
+ else
99
+ @app.call env
100
+ end
101
+ end
102
+
103
+ private
104
+
105
+ def debug?(env)
106
+ env.request.context&.send(:[], :debug)
107
+ end
108
+
109
+ def debug_call(env)
110
+ exception = nil
111
+ response = @app.call(env)
112
+ rescue StandardError => e
113
+ exception = e
114
+ raise
115
+ ensure
116
+ debug_output env, response, exception
117
+ end
118
+
119
+ def debug_output(env, response, exception)
120
+ DebugOutput.new(env, response, exception).debug
121
+ end
122
+ end
123
+ end
124
+ end
@@ -0,0 +1,74 @@
1
+ require 'faraday'
2
+
3
+ module LoogiHttp
4
+ module Middleware
5
+ # Faraday middleware to log request to `Logger`.
6
+ class LogRequest < Faraday::Middleware
7
+ # @param logger [Logger] Logger instance to log to
8
+ # @param level [Symbol | String] Log level to use
9
+ def initialize(app, logger:, level: :info)
10
+ super app
11
+ @level = level
12
+ @logger = logger
13
+ end
14
+
15
+ # Log the following for every request made:
16
+ #
17
+ # * host
18
+ # * HTTP method
19
+ # * uri
20
+ # * status
21
+ # * duration
22
+ #
23
+ # If an exception is raised, log the exception and backtrace.
24
+ #
25
+ # @param env [Faraday::Env]
26
+ # @return [Faraday::Request]
27
+ def call(env)
28
+ start_time = Time.now
29
+ exception = nil
30
+ @app.call env
31
+ rescue StandardError => e
32
+ exception = e
33
+ raise
34
+ ensure
35
+ duration = Time.now - start_time
36
+ log_message env, duration
37
+ log_exception(exception) if exception
38
+ end
39
+
40
+ private
41
+
42
+ attr_reader :level, :logger
43
+
44
+ def log_exception(exception)
45
+ klass = exception.class
46
+ error = exception.message
47
+ trace = exception.backtrace.join("\n")
48
+ exception_message = format(
49
+ "%<klass>s %<error>s\n%<trace>s",
50
+ klass: klass,
51
+ error: error,
52
+ trace: trace
53
+ )
54
+ logger.send level, exception_message
55
+ end
56
+
57
+ def log_message(env, duration)
58
+ url = env.url
59
+ method = env.method.to_s.upcase
60
+ status = env.status || 500
61
+
62
+ message = format(
63
+ '[%<host>s] %<method>s %<uri>s %<status>d (%<duration>.3f s)',
64
+ host: url.host,
65
+ method: method,
66
+ uri: url.path,
67
+ status: status,
68
+ duration: duration
69
+ )
70
+ logger.send level, message
71
+ end
72
+ end
73
+ end
74
+ end
@@ -0,0 +1,19 @@
1
+ require 'faraday'
2
+
3
+ module LoogiHttp
4
+ module Middleware
5
+ # Faraday middleware to set `Accept` header to `application/json`.
6
+ class AcceptJson < Faraday::Middleware
7
+ # Set the `Accept` header to `application/json`. Overwrites existing
8
+ # header.
9
+ #
10
+ # @param env [Faraday::Env]
11
+ # @return [Faraday::Response]
12
+ def call(env)
13
+ headers = env[:request_headers]
14
+ headers['Accept'] = 'application/json'
15
+ @app.call env
16
+ end
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,7 @@
1
+ module LoogiHttp
2
+ module Middleware
3
+ autoload :AcceptJson, 'loogi_http/middleware/request/accept_json'
4
+ autoload :DebugHttp, 'loogi_http/middleware/debug_http'
5
+ autoload :LogRequest, 'loogi_http/middleware/log_request'
6
+ end
7
+ end
@@ -0,0 +1,16 @@
1
+ require 'forwardable'
2
+
3
+ module LoogiHttp
4
+ # Wraps a `Faraday::Response`.
5
+ class Response
6
+ extend Forwardable
7
+
8
+ def_delegators :@faraday_response, :body, :finished?, :headers, :status,
9
+ :success?
10
+
11
+ # @param faraday_response [Faraday::Response] The wrapped `Response`
12
+ def initialize(faraday_response)
13
+ @faraday_response = faraday_response
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,25 @@
1
+ require 'faraday'
2
+
3
+ # Monkey patches to properly delegate Faraday 1.0 keyword arguments on Ruby 3
4
+ # See https://eregon.me/blog/2021/02/13/correct-delegation-in-ruby-2-27-3.html
5
+
6
+ Faraday::DependencyLoader.module_eval do
7
+ def new(*args, &block)
8
+ raise "missing dependency for #{self}: #{load_error.message}" unless loaded?
9
+
10
+ super(*args, &block)
11
+ end
12
+
13
+ ruby2_keywords :new if respond_to?(:ruby2_keywords, true)
14
+ end
15
+
16
+ Faraday::RackBuilder::Handler.class_eval do
17
+ def initialize(klass, *args, &block)
18
+ @name = klass.to_s
19
+ Faraday::RackBuilder::Handler::REGISTRY.set(klass) if klass.respond_to?(:name)
20
+ @args = args
21
+ @block = block
22
+ end
23
+
24
+ ruby2_keywords :initialize if respond_to?(:ruby2_keywords, true)
25
+ end
@@ -0,0 +1,3 @@
1
+ module LoogiHttp
2
+ VERSION = '1.0.0'.freeze
3
+ end
data/lib/loogi_http.rb ADDED
@@ -0,0 +1,48 @@
1
+ require 'loogi_http/ruby2_keywords'
2
+ require 'loogi_http/builder'
3
+ require 'loogi_http/version'
4
+ require 'loogi_http/middleware'
5
+ require 'faraday'
6
+
7
+ module LoogiHttp
8
+ # The log level to use with the logger. Defaults to `info`.
9
+ def self.log_level
10
+ @log_level ||= :info
11
+ end
12
+
13
+ # Set the log level to use with the logger
14
+ #
15
+ # @param log_level [Symbol | String] Logging level
16
+ def self.log_level=(log_level)
17
+ @log_level = log_level
18
+ end
19
+
20
+ # The Logger to use when logging
21
+ def self.logger
22
+ @logger ||= nil # Silence warning
23
+ end
24
+
25
+ # Set the Logger to use when logging
26
+ #
27
+ # @param logger [Logger] The logger to log to
28
+ def self.logger=(logger)
29
+ @logger = logger
30
+ end
31
+
32
+ # HTTP POST with JSON data sent and expected as the response.
33
+ #
34
+ # (see LoogiHttp::Connection#post)
35
+ # @param options [Hash] Options for the JSON POST
36
+ def self.json_post(url, params: {}, data: nil, options: {})
37
+ LoogiHttp::Builder.json.post(
38
+ url,
39
+ params: params,
40
+ data: data,
41
+ options: options
42
+ )
43
+ end
44
+
45
+ Faraday::Request.register_middleware accept_json: -> { Middleware::AcceptJson }
46
+ Faraday::Middleware.register_middleware log_request: -> { Middleware::LogRequest }
47
+ Faraday::Middleware.register_middleware debug_http: -> { Middleware::DebugHttp }
48
+ end
@@ -0,0 +1,39 @@
1
+ lib = File.expand_path('lib', __dir__)
2
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
3
+ require 'loogi_http/version'
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.required_ruby_version = '>= 2.6'
7
+ spec.name = 'loogi_http'
8
+ spec.version = LoogiHttp::VERSION
9
+ spec.authors = ['Juul Labs, Inc.']
10
+ spec.email = ['opensource@juul.com']
11
+
12
+ spec.summary = 'External requests wrapper.'
13
+ spec.description = 'Provides a wrapper to external requests providing ' \
14
+ 'JSON parsing, logging, metrics, and more.'
15
+ spec.homepage = 'https://github.com/JuulLabs-OSS/loogi_http'
16
+ spec.license = 'MIT'
17
+
18
+ # Specify which files should be added to the gem when it is released.
19
+ # The `git ls-files -z` loads the files in the RubyGem that have been added
20
+ # into git.
21
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
22
+ `git ls-files -z`.
23
+ split("\x0").
24
+ reject { |f| f.match(%r{^(test|spec|features)/}) }
25
+ end
26
+ spec.bindir = 'exe'
27
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
28
+ spec.require_paths = ['lib']
29
+
30
+ spec.add_dependency 'faraday', '~> 1.0.1'
31
+ spec.add_dependency 'faraday-cookie_jar', '~> 0.0.6'
32
+ spec.add_dependency 'faraday_middleware', '~> 1.0.0'
33
+
34
+ spec.add_development_dependency 'bundler', '>= 2.0'
35
+ spec.add_development_dependency 'byebug', '~> 10.0.2'
36
+ spec.add_development_dependency 'rake', '~> 10.0'
37
+ spec.add_development_dependency 'rspec', '~> 3.0'
38
+ spec.add_development_dependency 'webmock', '~> 3.5.1'
39
+ end
metadata ADDED
@@ -0,0 +1,180 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: loogi_http
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.0
5
+ platform: ruby
6
+ authors:
7
+ - Juul Labs, Inc.
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2022-06-21 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: faraday
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: 1.0.1
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: 1.0.1
27
+ - !ruby/object:Gem::Dependency
28
+ name: faraday-cookie_jar
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: 0.0.6
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: 0.0.6
41
+ - !ruby/object:Gem::Dependency
42
+ name: faraday_middleware
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: 1.0.0
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: 1.0.0
55
+ - !ruby/object:Gem::Dependency
56
+ name: bundler
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: '2.0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: '2.0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: byebug
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: 10.0.2
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: 10.0.2
83
+ - !ruby/object:Gem::Dependency
84
+ name: rake
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - "~>"
88
+ - !ruby/object:Gem::Version
89
+ version: '10.0'
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - "~>"
95
+ - !ruby/object:Gem::Version
96
+ version: '10.0'
97
+ - !ruby/object:Gem::Dependency
98
+ name: rspec
99
+ requirement: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - "~>"
102
+ - !ruby/object:Gem::Version
103
+ version: '3.0'
104
+ type: :development
105
+ prerelease: false
106
+ version_requirements: !ruby/object:Gem::Requirement
107
+ requirements:
108
+ - - "~>"
109
+ - !ruby/object:Gem::Version
110
+ version: '3.0'
111
+ - !ruby/object:Gem::Dependency
112
+ name: webmock
113
+ requirement: !ruby/object:Gem::Requirement
114
+ requirements:
115
+ - - "~>"
116
+ - !ruby/object:Gem::Version
117
+ version: 3.5.1
118
+ type: :development
119
+ prerelease: false
120
+ version_requirements: !ruby/object:Gem::Requirement
121
+ requirements:
122
+ - - "~>"
123
+ - !ruby/object:Gem::Version
124
+ version: 3.5.1
125
+ description: Provides a wrapper to external requests providing JSON parsing, logging,
126
+ metrics, and more.
127
+ email:
128
+ - opensource@juul.com
129
+ executables: []
130
+ extensions: []
131
+ extra_rdoc_files: []
132
+ files:
133
+ - ".github/workflows/gem-push.yml"
134
+ - ".github/workflows/specs.yml"
135
+ - ".gitignore"
136
+ - ".rspec"
137
+ - CODE_OF_CONDUCT.md
138
+ - Gemfile
139
+ - LICENSE.txt
140
+ - README.md
141
+ - Rakefile
142
+ - bin/console
143
+ - bin/setup
144
+ - lib/loogi_http.rb
145
+ - lib/loogi_http/builder.rb
146
+ - lib/loogi_http/configuration.rb
147
+ - lib/loogi_http/connection.rb
148
+ - lib/loogi_http/error.rb
149
+ - lib/loogi_http/middleware.rb
150
+ - lib/loogi_http/middleware/debug_http.rb
151
+ - lib/loogi_http/middleware/log_request.rb
152
+ - lib/loogi_http/middleware/request/accept_json.rb
153
+ - lib/loogi_http/response.rb
154
+ - lib/loogi_http/ruby2_keywords.rb
155
+ - lib/loogi_http/version.rb
156
+ - loogi_http.gemspec
157
+ homepage: https://github.com/JuulLabs-OSS/loogi_http
158
+ licenses:
159
+ - MIT
160
+ metadata: {}
161
+ post_install_message:
162
+ rdoc_options: []
163
+ require_paths:
164
+ - lib
165
+ required_ruby_version: !ruby/object:Gem::Requirement
166
+ requirements:
167
+ - - ">="
168
+ - !ruby/object:Gem::Version
169
+ version: '2.6'
170
+ required_rubygems_version: !ruby/object:Gem::Requirement
171
+ requirements:
172
+ - - ">="
173
+ - !ruby/object:Gem::Version
174
+ version: '0'
175
+ requirements: []
176
+ rubygems_version: 3.0.3.1
177
+ signing_key:
178
+ specification_version: 4
179
+ summary: External requests wrapper.
180
+ test_files: []