ja 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 84d8b0344c6243bfa25097dff532fcddf4f7740a3e070c63f8d46024f17aeb1c
4
+ data.tar.gz: 7e35c57cf0ed3256f09435c03708c41ca87092d2ebc710425701f94d5fc229a9
5
+ SHA512:
6
+ metadata.gz: 766c2be6dc11b4954dc63b814096460833901fb722d332587c26984cd5a971dd8745f855d41257a6ca93befd44db40ef1d3fa1a1dc13264c2574807141a70591
7
+ data.tar.gz: 95db36417c832d8fa8d4a7eba5fe3386e8dfff79c6ccffd876c80bccbc9d87254b57125c3f630ea25cc617f82737bf8eeb67ef83d857fc6ccee7fbbeb46617d0
@@ -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
+ .rspec_status
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
@@ -0,0 +1,5 @@
1
+ sudo: false
2
+ language: ruby
3
+ rvm:
4
+ - 2.4.2
5
+ before_install: gem install bundler -v 1.16.0
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 ja.gemspec
6
+ gemspec
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2017 iain
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.
@@ -0,0 +1,124 @@
1
+ # Ja
2
+
3
+ A wrapper around the [http.rb](https://github.com/httprb/http) gem.
4
+
5
+ The features so far:
6
+
7
+ * Logging (with multiple levels, depending on the response status)
8
+ * Automatically raising errors
9
+ * Automatically adding the `X-Request-Id` header (from `Thread.current[:request_id]`)
10
+
11
+ ## Usage
12
+
13
+ Without options, you will get simple logging as a result:
14
+
15
+ ``` ruby
16
+ response = Ja.api.get("http://example.com/widgets")
17
+ [INFO] (1.12ms) GET http://example.com/widgets responded with 200 OK
18
+ ```
19
+
20
+ You can customize this, for instance by setting part of the url:
21
+
22
+ ``` ruby
23
+ my_service = Ja.api(url: "http://my-service.com")
24
+ respoonse = my_service.get("widgets")
25
+ ```
26
+
27
+
28
+ Or by setting your own HTTP options:
29
+
30
+ ``` ruby
31
+ client = HTTP.basic_auth(user: "alice", pass: "secret")
32
+ my_authenticated_service = Ja.api(client: client)
33
+ my_authenticated_service.get("my-private-widgets")
34
+ ```
35
+
36
+ ### Raising errors
37
+
38
+ If you want to automatically raise an error when a request fails, you can use `get!`, `post!`, etc instead of the version without a bang.
39
+
40
+ ``` ruby
41
+ my_service = Ja.api(url: "http://my-service.com")
42
+
43
+ # raises no error:
44
+ my_service.get("not-found")
45
+
46
+ # raises Ja::Error::NotFound
47
+ my_service.get!("not-found")
48
+ ```
49
+
50
+ Most HTTP status have their own error class. They inherit from `Ja::Error::ClientError` for 4xx responses and `Ja::Error::ServerError` for 5xx responses. All inherit from `Ja::Error`.
51
+
52
+ ### Logging
53
+
54
+ Requests are automatically logged. We detect Rails.logger, Hanami.logger or SemanticLogger by default.
55
+
56
+ If the request is successful (i.e. 2xx), the log level is `info`. If the response is a redirect (i.e. 3xx), it will use the `warn` log level. For client errors (4xx) and server errors (5xx) the `error` log level is used.
57
+
58
+ You can set a logger per service:
59
+
60
+ ``` ruby
61
+ my_service = Ja.api(logger: Logger.new("log/my-service.log"))
62
+ ```
63
+
64
+ Or configure a logger globally (it will automatically recognize Rails, Hanami and SemanticLogger):
65
+
66
+ ```
67
+ Ja.logger = Logger.new("log/http.log")
68
+ ```
69
+
70
+ To log the full request and full response, we need to do some monkey patching, so it is disabled by default. To enable it, call `Ja.enable_debug_logging!`. You may want to do this only for development/test but not on production, because it might mess with streaming responses. Full request logging will always log in `debug` log level and will always use the globally configered logger.
71
+
72
+ ### Request ID
73
+
74
+ One very helpful way to manage multiple services is to pass along a "request id". If you tag your logs with that value, you can use a centralized logging service to track a request as it propagates through your fleet of microservices.
75
+
76
+ You are responsible for making sure it gets set, but if you set `Thread.current[:request_id]` it will automatically be added as a header.
77
+
78
+ Here's an example in Rack middleware:
79
+
80
+ ``` ruby
81
+ class RequestIdMiddleware
82
+
83
+ def initialize(app)
84
+ @app = app
85
+ end
86
+
87
+ def call(env)
88
+ request_id = (env["HTTP_X_REQUEST_ID"] || SecureRandom.uuid.delete("-"))
89
+ Thread.current[:request_id] = request_id
90
+ @app.call(env)
91
+ end
92
+
93
+ end
94
+ ```
95
+
96
+ ## Installation
97
+
98
+ Add this line to your application's Gemfile:
99
+
100
+ ```ruby
101
+ gem 'ja'
102
+ ```
103
+
104
+ And then execute:
105
+
106
+ $ bundle
107
+
108
+ Or install it yourself as:
109
+
110
+ $ gem install ja
111
+
112
+ ## Development
113
+
114
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
115
+
116
+ 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).
117
+
118
+ ## Contributing
119
+
120
+ Bug reports and pull requests are welcome on GitHub at https://github.com/iain/ja.
121
+
122
+ ## License
123
+
124
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
@@ -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
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "ja"
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__)
@@ -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,31 @@
1
+ lib = File.expand_path("../lib", __FILE__)
2
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
3
+ require "ja/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "ja"
7
+ spec.version = Ja::VERSION
8
+ spec.authors = ["iain"]
9
+ spec.email = ["iain@iain.nl"]
10
+ spec.summary = "Opinionated helpers for making JSON calls with the http.rb gem"
11
+ spec.description = "Opinionated helpers for making JSON calls with the http.rb gem"
12
+ spec.homepage = "https://github.com/iain/ja"
13
+ spec.license = "MIT"
14
+ spec.files = `git ls-files -z`.split("\x0").reject do |f|
15
+ f.match(%r{^(test|spec|features)/})
16
+ end
17
+ spec.bindir = "exe"
18
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
19
+ spec.require_paths = ["lib"]
20
+
21
+ spec.add_development_dependency "bundler", "~> 1.16"
22
+ spec.add_development_dependency "rake", "~> 12.0"
23
+ spec.add_development_dependency "rspec", "~> 3.0"
24
+
25
+ spec.add_development_dependency "pry"
26
+ spec.add_development_dependency "semantic_logger"
27
+ spec.add_development_dependency "nokogiri"
28
+ spec.add_development_dependency "webmock"
29
+
30
+ spec.add_dependency "http", "~> 3.0"
31
+ end
@@ -0,0 +1,71 @@
1
+ require "http"
2
+ require "logger"
3
+
4
+ require "ja/version"
5
+
6
+ require "ja/methods"
7
+ require "ja/error"
8
+ require "ja/api"
9
+ require "ja/debug_logger"
10
+
11
+ module Ja
12
+
13
+ def self.logger
14
+ @logger ||= default_logger
15
+ end
16
+
17
+ def self.logger=(logger)
18
+ @logger = logger
19
+ end
20
+
21
+ def self.api(*args, &block)
22
+ API.new(*args, &block)
23
+ end
24
+
25
+ def self.default_logger
26
+ if defined?(Rails) && Rails.logger
27
+ Rails.logger
28
+ elsif defined?(Hanami) && Hanami.logger
29
+ Hanami.logger
30
+ elsif defined?(SemanticLogger)
31
+ SemanticLogger[self]
32
+ else
33
+ Logger.new($stdout)
34
+ end
35
+ end
36
+
37
+ # TODO detect streaming
38
+ def self.format_body(headers, &body)
39
+ mime_type = parse_mime_type(headers)
40
+ case mime_type
41
+ when /\bjson$/
42
+ str = body.call
43
+ begin
44
+ JSON.pretty_generate(JSON.parse(str))
45
+ rescue JSON::ParserError
46
+ str
47
+ end
48
+ when /\bhtml$/, /\bxml$/
49
+ str = body.call
50
+ if defined?(Nokogiri)
51
+ Nokogiri::XML(str).to_xhtml.chomp
52
+ else
53
+ str
54
+ end
55
+ when /\bplain$/
56
+ body.call
57
+ else
58
+ "«body ommitted: unsupported Content-Type: #{mime_type.inspect}»"
59
+ end
60
+ end
61
+
62
+ def self.parse_mime_type(headers)
63
+ HTTP::ContentType.parse(headers[HTTP::Headers::CONTENT_TYPE]).mime_type
64
+ end
65
+
66
+ def self.enable_debug_logging!
67
+ return if HTTP::Client.ancestors.include?(DebugLogger)
68
+ HTTP::Client.prepend(DebugLogger)
69
+ end
70
+
71
+ end
@@ -0,0 +1,78 @@
1
+ module Ja
2
+ class API
3
+
4
+ LOG_LINE = "%{verb} %{url} responded with %{status} %{reason}"
5
+
6
+ include Methods
7
+
8
+ def initialize(client: HTTP,
9
+ url: nil,
10
+ logger: Ja.logger,
11
+ log_line: LOG_LINE)
12
+
13
+ @client = client
14
+ @logger = logger
15
+ @log_line = log_line
16
+ @url = url
17
+ end
18
+
19
+ attr_reader :client, :logger, :log_line, :url
20
+
21
+ def request(verb, uri, options = {})
22
+ full_uri = full_url(uri)
23
+ start_time = Time.now
24
+ client_with_request_id = client.headers("X-Request-Id" => Thread.current[:request_id])
25
+ response = client_with_request_id.request(verb, full_uri, options)
26
+ log_response(response, start_time, verb, full_uri, options)
27
+ response
28
+ end
29
+
30
+ def request!(verb, uri, options = {})
31
+ response = request(verb, uri, options)
32
+ if (100..399).cover?(response.status)
33
+ response
34
+ else
35
+ fail Error.to_exception(verb, full_url(uri), response)
36
+ end
37
+ end
38
+
39
+ def full_url(path)
40
+ if url
41
+ File.join(url, path)
42
+ else
43
+ path
44
+ end
45
+ end
46
+
47
+ private
48
+
49
+ def log_response(response, start_time, verb, uri, _options)
50
+ duration = (Time.now - start_time) * 1000.0
51
+
52
+ log_level = case response.status
53
+ when 100..299
54
+ :info
55
+ when 300..399
56
+ :warn
57
+ else
58
+ :error
59
+ end
60
+
61
+ payload = {
62
+ verb: verb.to_s.upcase,
63
+ url: uri.to_s,
64
+ status: response.status.to_i,
65
+ reason: response.status.reason.to_s,
66
+ }
67
+
68
+ message = log_line % payload
69
+
70
+ if defined?(SemanticLogger) && logger.is_a?(SemanticLogger::Logger)
71
+ logger.public_send(log_level, message: message, duration: duration, payload: payload)
72
+ else
73
+ logger.public_send(log_level, "(%.2fms) %s" % [ duration, message ])
74
+ end
75
+ end
76
+
77
+ end
78
+ end
@@ -0,0 +1,33 @@
1
+ module Ja
2
+ module DebugLogger
3
+
4
+ def perform(req, options)
5
+ Ja.logger.debug {
6
+ lines = ["Sending #{req.verb.to_s.upcase} to #{req.uri.to_s.inspect}"]
7
+ lines << "\e[36m"
8
+ lines << req.headline
9
+ lines += req.headers.map { |key, value| "#{key}: #{value}" }
10
+ body = Ja.format_body(req.headers) {
11
+ buffer = ""
12
+ req.body.each { |chunk| buffer << chunk }
13
+ buffer
14
+ }
15
+ lines.join("\n") + "\n\n" + body + "\n\e[0m\n"
16
+ }
17
+
18
+ res = super
19
+
20
+ Ja.logger.debug {
21
+ lines = ["Response from #{req.verb.to_s.upcase} to #{req.uri.to_s.inspect}"]
22
+ lines << "\e[35m"
23
+ lines << "HTTP/#{res.instance_variable_get(:@version)} #{res.status}"
24
+ lines += res.headers.map { |key, value| "#{key}: #{value}" }
25
+ body = Ja.format_body(res.headers) { res.body.to_s }
26
+ lines.join("\n") + "\n\n" + body + "\n\e[0m\n"
27
+ }
28
+
29
+ res
30
+ end
31
+
32
+ end
33
+ end
@@ -0,0 +1,53 @@
1
+ module Ja
2
+ class Error < StandardError
3
+
4
+ def self.to_exception(verb, uri, response)
5
+ Error.fetch_error_class(response.status).new(verb, uri, response)
6
+ end
7
+
8
+ def self.fetch_error_class(status)
9
+ const_get(HTTP::Response::Status::REASONS.fetch(status, "ResponseError").gsub(/\W/, ""))
10
+ end
11
+
12
+ attr_reader :response, :verb, :uri
13
+
14
+ def initialize(verb, uri, response)
15
+ @response = response
16
+ @verb = verb
17
+ @uri = uri
18
+
19
+ @headline = "%{verb} %{url} responded with %{status}" % {
20
+ status: response.status,
21
+ verb: verb.to_s.upcase,
22
+ url: uri.to_s,
23
+ }
24
+
25
+ @response_body = Ja.format_body(response.headers) { response.body.to_s }
26
+
27
+ @message = @response_body ? "#{@headline}\n\n#{@response_body}" : @headline
28
+ end
29
+
30
+ attr_reader :message, :response_body, :headline
31
+
32
+ alias_method :to_s, :message
33
+
34
+ def status
35
+ response.status
36
+ end
37
+
38
+ # Base class for all errors
39
+ ResponseError = Class.new(Error)
40
+
41
+ # Base class for errors in the 4xx range
42
+ ClientError = Class.new(ResponseError)
43
+
44
+ # Base class for errors in the 5xx range
45
+ ServerError = Class.new(ResponseError)
46
+
47
+ HTTP::Response::Status::REASONS.each do |status, name|
48
+ parent = status >= 500 ? ServerError : ClientError
49
+ const_set(name.gsub(/\W/, ""), Class.new(parent))
50
+ end
51
+
52
+ end
53
+ end
@@ -0,0 +1,19 @@
1
+ module Ja
2
+ module Methods
3
+
4
+ verbs = %i[head get post put delete trace options connect patch]
5
+
6
+ verbs.each do |verb|
7
+
8
+ define_method verb do |*args, &block|
9
+ request verb, *args, &block
10
+ end
11
+
12
+ define_method "#{verb}!" do |*args, &block|
13
+ request! verb, *args, &block
14
+ end
15
+
16
+ end
17
+
18
+ end
19
+ end
@@ -0,0 +1,3 @@
1
+ module Ja
2
+ VERSION = "0.1.0"
3
+ end
metadata ADDED
@@ -0,0 +1,172 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: ja
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - iain
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2017-11-30 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.16'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.16'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '12.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '12.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rspec
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '3.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '3.0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: pry
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: '0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: '0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: semantic_logger
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - ">="
74
+ - !ruby/object:Gem::Version
75
+ version: '0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - ">="
81
+ - !ruby/object:Gem::Version
82
+ version: '0'
83
+ - !ruby/object:Gem::Dependency
84
+ name: nokogiri
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - ">="
88
+ - !ruby/object:Gem::Version
89
+ version: '0'
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - ">="
95
+ - !ruby/object:Gem::Version
96
+ version: '0'
97
+ - !ruby/object:Gem::Dependency
98
+ name: webmock
99
+ requirement: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - ">="
102
+ - !ruby/object:Gem::Version
103
+ version: '0'
104
+ type: :development
105
+ prerelease: false
106
+ version_requirements: !ruby/object:Gem::Requirement
107
+ requirements:
108
+ - - ">="
109
+ - !ruby/object:Gem::Version
110
+ version: '0'
111
+ - !ruby/object:Gem::Dependency
112
+ name: http
113
+ requirement: !ruby/object:Gem::Requirement
114
+ requirements:
115
+ - - "~>"
116
+ - !ruby/object:Gem::Version
117
+ version: '3.0'
118
+ type: :runtime
119
+ prerelease: false
120
+ version_requirements: !ruby/object:Gem::Requirement
121
+ requirements:
122
+ - - "~>"
123
+ - !ruby/object:Gem::Version
124
+ version: '3.0'
125
+ description: Opinionated helpers for making JSON calls with the http.rb gem
126
+ email:
127
+ - iain@iain.nl
128
+ executables: []
129
+ extensions: []
130
+ extra_rdoc_files: []
131
+ files:
132
+ - ".gitignore"
133
+ - ".rspec"
134
+ - ".travis.yml"
135
+ - Gemfile
136
+ - LICENSE.txt
137
+ - README.md
138
+ - Rakefile
139
+ - bin/console
140
+ - bin/setup
141
+ - ja.gemspec
142
+ - lib/ja.rb
143
+ - lib/ja/api.rb
144
+ - lib/ja/debug_logger.rb
145
+ - lib/ja/error.rb
146
+ - lib/ja/methods.rb
147
+ - lib/ja/version.rb
148
+ homepage: https://github.com/iain/ja
149
+ licenses:
150
+ - MIT
151
+ metadata: {}
152
+ post_install_message:
153
+ rdoc_options: []
154
+ require_paths:
155
+ - lib
156
+ required_ruby_version: !ruby/object:Gem::Requirement
157
+ requirements:
158
+ - - ">="
159
+ - !ruby/object:Gem::Version
160
+ version: '0'
161
+ required_rubygems_version: !ruby/object:Gem::Requirement
162
+ requirements:
163
+ - - ">="
164
+ - !ruby/object:Gem::Version
165
+ version: '0'
166
+ requirements: []
167
+ rubyforge_project:
168
+ rubygems_version: 2.7.2
169
+ signing_key:
170
+ specification_version: 4
171
+ summary: Opinionated helpers for making JSON calls with the http.rb gem
172
+ test_files: []