foucault_http 0.4.8

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.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 230f82f3bcdc3ad709f3a2eb94d44b58c560cdf06ca68f6531c0a9687657e399
4
+ data.tar.gz: e258866c64df1ca8f8274e81df9a4515d7e5bbd9cc79b1fca7dec1ab2319a825
5
+ SHA512:
6
+ metadata.gz: 3709b74c8248071487dc0dea1f32a5a4b0237c910134effc9e186ec3660316ac8147cec74867b6a4b43d21d3c792f7a3fa8fcdcc43dc35e8ab95dcc0e42144e5
7
+ data.tar.gz: 895c4695e88caa9191e7ab85beb034028b07b2ee4b0b625c587192e2a65a690911860fb14f425e0353b4bef2207fe87843e66f8c06aa58f329a8dc362cdc4ba5
@@ -0,0 +1,14 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
10
+
11
+ # rspec failure tracking
12
+ .rspec_status
13
+
14
+ .ds_store
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 wild.fauve@gmail.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 foucault.gemspec
6
+ gemspec
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2018 Col Perks
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,127 @@
1
+ # Foucault
2
+
3
+ Foucault plays with a functional interface for wrapping network service calls. Not exactly very functional, as the network is a touch mutating. However, its an attempt to leverage a little of that Ruby lambda magic to describe another method of wrapping classes.
4
+
5
+
6
+ ## Installation
7
+
8
+ Add this line to your application's Gemfile:
9
+
10
+ ```ruby
11
+ gem 'foucault_http'
12
+ ```
13
+
14
+ And then execute:
15
+
16
+ $ bundle
17
+
18
+ Or install it yourself as:
19
+
20
+ $ gem install foucault_http
21
+
22
+ ## Usage
23
+
24
+ `FoucaultHttp::Net` contains the main functions for HTTP wrappers. All the wrappers are defined as curried functions. So it is OK to partially apply in the argument order.
25
+
26
+ ## Configuration
27
+
28
+ You provide configuration through the object
29
+
30
+ ```ruby
31
+ FoucaultHttp::Configuration.configure do |config|
32
+ config.logger = SomeLogger # Any class that responds to the log level methods with a single param
33
+ # (a string or hash if you're using a structured log format)
34
+ config.network_log_formatter = SomeLogFormatter # A class which inherits from Faraday::Logging::Formatter
35
+ config.logging_level = :info
36
+ end
37
+ ```
38
+
39
+ ### HTTP
40
+
41
+ #### Post
42
+
43
+ The `post` fn takes the following arguments in this order:
44
+ + `correlation`. A hash of name value pairs to be logged. Default is `{}`
45
+ + `service`. The http host. It will be combined with the `resource` to form a url.
46
+ + `resource`. The resource making up the URL.
47
+ + `hdrs`. A hash of HTTP headers.
48
+ + `enc`. The default encoding for the body.
49
+ + `body_fn`. A fn with which to serialise the body. The functions are available in the `FoucaultHttp::Net` class. They are:
50
+ + `json_body_fn`. Converts the body to JSON.
51
+ + `body`. The body to send to the service/resource
52
+
53
+ Example: This shows the use of partial application. You can just as easily combine the arguments into a single argument list.
54
+
55
+ ```ruby
56
+ FoucaultHttp::Net.post.({}, "http://api.example.com").("/resource").(nil).(nil).(FoucaultHttp::Net.json_body_fn).({message: "some message"})
57
+ ```
58
+
59
+ #### Get
60
+
61
+ The `get` fn takes the following arguments in this order:
62
+ + `correlation`
63
+ + `service`
64
+ + `resource`
65
+ + `hdrs`
66
+ + `enc`
67
+ + `query`
68
+
69
+ For example:
70
+
71
+ ```ruby
72
+ FoucaultHttp::Net.get.({}, "http://api.example.com", "/resource").({authorization: "uid:pwd"}).(:url_encoded).({param1: 1})
73
+ ```
74
+
75
+ #### Helper Functions
76
+
77
+ 1. Basic Authentication Header Encoder. Creates an `Authorization` header appropriately encoded for basic auth.
78
+
79
+ ```ruby
80
+ FoucaultHttp::Net.basic_auth_header.("client_id").("secret")
81
+ ```
82
+
83
+ 2. Header builder. Takes any number of individual arguments which evaluate to Hashes and combines them into a single hash. Not really that interesting, you can always throw in your own `merge`
84
+
85
+ ```ruby
86
+ FoucaultHttp::Net.header_builder.(FoucaultHttp::Net.basic_auth_header.("userid", "password"), {content_type: "application/json"})
87
+ ```
88
+
89
+ ### Return Object
90
+
91
+ All network functions return a `FoucaultHttp::NetResponseValue` wrapped in a `Result` monad.
92
+
93
+ So, for example, you might test and extract the results as follows:
94
+
95
+ ```ruby
96
+ result = FoucaultHttp::Net.post.("http://api.example.com").("/resource").({}).(nil).(FoucaultHttp::Net.json_body_fn).({message: "some message"})
97
+
98
+ result.success? # or result.failure?
99
+ result.value_or.status # => :ok
100
+ result.value_or.body # => some returned structure.
101
+ ```
102
+
103
+ The `FoucaultHttp::NetResponseValue` generalises the network states as follows:
104
+
105
+ + `:ok`; its all good.
106
+ + `:fail`; the network request happened, but failed for some reason (such as resource not found)
107
+ + `:unauthorised`; no access to the service.
108
+ + `:system_failure`; a failures before the service; such as network problems.
109
+
110
+
111
+ ## Development
112
+
113
+ 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.
114
+
115
+ 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).
116
+
117
+ ## Contributing
118
+
119
+ Bug reports and pull requests are welcome on GitHub at https://github.com/wildfauve/foucault_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.
120
+
121
+ ## License
122
+
123
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
124
+
125
+ ## Code of Conduct
126
+
127
+ Everyone interacting in the Foucault project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/foucault/blob/master/CODE_OF_CONDUCT.md).
@@ -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 "foucault"
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 "pry"
14
+ Pry.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,46 @@
1
+
2
+ lib = File.expand_path("../lib", __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require "foucault_http/version"
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "foucault_http"
8
+ spec.version = FoucaultHttp::VERSION
9
+ spec.authors = ["Col Perks"]
10
+ spec.email = ["wild.fauve@gmail.com"]
11
+
12
+ spec.summary = %q{Http Network Functions}
13
+ spec.description = %q{Http Network Functions.}
14
+ spec.homepage = "https://github.com/wildfauve/foucault_http"
15
+ spec.license = "MIT"
16
+
17
+ # Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
18
+ # to allow pushing to a single host or delete this section to allow pushing to any host.
19
+ if spec.respond_to?(:metadata)
20
+ # spec.metadata["allowed_push_host"] = "TODO: Set to 'http://mygemserver.com'"
21
+ else
22
+ raise "RubyGems 2.0 or newer is required to protect against " \
23
+ "public gem pushes."
24
+ end
25
+
26
+ spec.files = `git ls-files -z`.split("\x0").reject do |f|
27
+ f.match(%r{^(test|spec|features)/})
28
+ end
29
+ spec.bindir = "exe"
30
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
31
+ spec.require_paths = ["lib"]
32
+
33
+ spec.add_dependency 'stoplight'
34
+ spec.add_dependency 'dry-monads', "~> 1.0"
35
+ spec.add_dependency 'dry-configurable'
36
+ spec.add_dependency 'funcify'
37
+ spec.add_dependency 'typhoeus'
38
+ spec.add_dependency 'faraday', '~> 1.0'
39
+ spec.add_dependency "dry-types"
40
+ spec.add_dependency "dry-struct"
41
+
42
+ spec.add_development_dependency "bundler", "~> 2.0"
43
+ spec.add_development_dependency "rake", "~> 13.0"
44
+ spec.add_development_dependency "rspec", "~> 3.0"
45
+ spec.add_development_dependency "pry"
46
+ end
@@ -0,0 +1,11 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # rspec failure tracking
11
+ .rspec_status
@@ -0,0 +1,27 @@
1
+ require "foucault_http/version"
2
+ require 'dry/monads/result'
3
+ require 'dry/monads/maybe'
4
+ require 'dry-struct'
5
+ require 'dry-types'
6
+ require 'dry-configurable'
7
+ require 'funcify'
8
+
9
+ module Types
10
+ include Dry.Types
11
+ end
12
+
13
+ module FoucaultHttp
14
+ require 'foucault_http/logger'
15
+ require 'foucault_http/logging'
16
+
17
+ require 'foucault_http/net'
18
+ require 'foucault_http/circuit'
19
+ require 'foucault_http/configuration'
20
+ require 'foucault_http/http_connection'
21
+ require 'foucault_http/http_port'
22
+ require 'foucault_http/net_response_value'
23
+ require 'foucault_http/monad_exception'
24
+
25
+ Fn = Funcify::Fn
26
+ Monad = Funcify::Monad
27
+ end
@@ -0,0 +1,81 @@
1
+ require 'stoplight'
2
+
3
+ module FoucaultHttp
4
+
5
+ class Circuit
6
+
7
+ include Dry::Monads::Result::Mixin
8
+
9
+ class MonadFailure < StandardError ; end
10
+
11
+ MAX_RETRIES = 3
12
+
13
+ include Logging
14
+
15
+ attr_reader :circuit
16
+
17
+ class << self
18
+
19
+ # Provides a wrapper fn that allows a monad result to be thrown as an exception so that
20
+ # Stoplight can execute retry behaviour.
21
+ def monad_circuit_wrapper_fn
22
+ -> caller { result = caller.(); result.success? ? result : raise(FoucaultHttp::MonadException.new(result: result)) }
23
+ end
24
+ end
25
+
26
+ def initialize(name:, max_retries: MAX_RETRIES)
27
+ # redis = Redis.new
28
+ # datastore = Stoplight::DataStore::Redis.new(redis)
29
+ # Stoplight::Light.default_data_store = datastore
30
+ @name = name
31
+ @max_retries = max_retries
32
+ end
33
+
34
+ def call(circuit_fn: , caller: nil)
35
+ info(msg: "CircuitBreaker: #{circuit_to_s}", service_name: @name)
36
+ @circuit = if caller.nil?
37
+ Stoplight(@name) { circuit_fn.() }.with_threshold(@max_retries).with_cool_off_time(10)
38
+ else
39
+ Stoplight(@name) { circuit_fn.(caller) }.with_threshold(@max_retries).with_cool_off_time(10)#.with_fallback {|e| binding.pry; e.result}
40
+ end
41
+ run(@circuit)
42
+ end
43
+
44
+ def run(circuit)
45
+ begin
46
+ circuit.run
47
+ rescue Stoplight::Error::RedLight => e
48
+ info({msg: "CircuitBreaker: #{circuit_to_s}", service_name: @name, circuit_state: "red"})
49
+ @last_error
50
+ rescue FoucaultHttp::MonadException => e
51
+ @last_error = e.result
52
+ retry
53
+ rescue StandardError => e
54
+ @last_error = e
55
+ retry
56
+ end
57
+ end
58
+
59
+ def failures
60
+ Stoplight::Light.default_data_store.get_failures(@circuit)
61
+ end
62
+
63
+ def colour
64
+ @circuit.color
65
+ end
66
+
67
+ def circuit_failure
68
+ NetResponseValue.new(
69
+ status: NetResponseValue::CIRCUIT_RED,
70
+ body: nil,
71
+ code: 500
72
+ )
73
+ end
74
+
75
+ def circuit_to_s
76
+ "Circuit: #{@name}"
77
+ end
78
+
79
+ end
80
+
81
+ end
@@ -0,0 +1,15 @@
1
+ module FoucaultHttp
2
+
3
+ class Configuration
4
+
5
+ extend Dry::Configurable
6
+
7
+ setting :type_parsers, {}
8
+ setting :logger
9
+ setting :log_formatter
10
+ setting :network_log_formatter
11
+ setting :logging_level
12
+
13
+ end # class Configuration
14
+
15
+ end # module ScoreCard
@@ -0,0 +1,71 @@
1
+ require 'faraday'
2
+ require 'faraday/logging/formatter'
3
+ require 'typhoeus'
4
+
5
+ module FoucaultHttp
6
+
7
+ class HttpConnection
8
+
9
+ include Dry::Monads::Try::Mixin
10
+ include Dry::Monads::Result::Mixin
11
+
12
+ HTTP_CONNECTION_FAILURE = :http_connection_failure
13
+
14
+ def connection(address, encoding, cache_store = nil, instrumenter = nil)
15
+ @http_connection = Try { http_connection(address, encoding, cache_store, instrumenter) }
16
+ self
17
+ end
18
+
19
+ def get(hdrs, params)
20
+ return @http_connection.to_result if @http_connection.failure?
21
+ Try {
22
+ @http_connection.value_or.get do |r|
23
+ r.headers = hdrs if hdrs
24
+ r.params = params if params
25
+ end
26
+ }.to_result
27
+ end
28
+
29
+ def post(hdrs, body)
30
+ return @http_connection.to_result if @http_connection.failure?
31
+ Try {
32
+ @http_connection.value_or.post do |r|
33
+ r.body = body
34
+ r.headers = hdrs
35
+ end
36
+ }.to_result
37
+ end
38
+
39
+ def delete(hdrs)
40
+ return @http_connection.to_result if @http_connection.failure?
41
+ Try {
42
+ @http_connection.value_or.delete do |r|
43
+ r.headers = hdrs
44
+ end
45
+ }.to_result
46
+ end
47
+
48
+ private
49
+
50
+ def http_connection(address, encoding, cache_store, instrumenter)
51
+ faraday_connection = Faraday.new(:url => address) do |faraday|
52
+ # faraday.use :http_cache, caching if caching
53
+ faraday.request encoding if encoding
54
+ if Configuration.config.logger && Configuration.config.log_formatter
55
+ faraday.response :logger, Configuration.config.logger, formatter: Configuration.config.network_log_formatter
56
+ elsif Configuration.config.logger
57
+ faraday.response :logger, Configuration.config.logger
58
+ else
59
+ faraday.response :logger do |log|
60
+ log.filter(/(Bearer.)(.+)/, '\1[REMOVED]')
61
+ log.filter(/(Basic.)(.+)/, '\1[REMOVED]')
62
+ end
63
+ end
64
+ faraday.adapter :typhoeus
65
+ end
66
+ faraday_connection
67
+ end
68
+
69
+ end
70
+
71
+ end
@@ -0,0 +1,222 @@
1
+ module FoucaultHttp
2
+
3
+ class HttpPort
4
+
5
+ class NoContentTypeError < StandardError; end
6
+
7
+ extend Dry::Monads::Try::Mixin
8
+ extend Logging
9
+
10
+ FAIL = :fail
11
+ OK = :ok
12
+ BAD_REQUEST = :bad_request
13
+ UNAUTHORISED = :unauthorised
14
+ NOT_FOUND = :not_found
15
+ SYSTEM_FAILURE = :system_failure
16
+ UNPROCESSABLE_ENTITY = :unprocessable_entity
17
+
18
+ class << self
19
+
20
+ def post
21
+ -> correlation, service, resource, hdrs, body_fn, enc, body {
22
+ ( Fn.either.(net_ok).(Monad.success).(Monad.failure) <<
23
+ log_response.(correlation, service, resource, __method__) <<
24
+ response_value <<
25
+ run_post.(hdrs, body_fn, body) <<
26
+ addressed.(service, resource)).(connection.(enc))
27
+ }
28
+ end
29
+
30
+ def get
31
+ -> correlation, service, resource, hdrs, enc, query {
32
+ ( Fn.either.(net_ok).(Monad.success).(Monad.failure) <<
33
+ log_response.(correlation, service, resource, __method__) <<
34
+ response_value <<
35
+ run_get.(hdrs, query) <<
36
+ addressed.(service, resource)).(connection.(enc))
37
+ }
38
+ end
39
+
40
+ def delete
41
+ -> correlation, service, resource, hdrs {
42
+ ( Fn.either.(net_ok).(Monad.success).(Monad.failure) <<
43
+ log_response.([], service, resource, __method__) <<
44
+ response_value <<
45
+ run_delete.(hdrs) <<
46
+ addressed.(service, resource)).(connection.(nil))
47
+ }
48
+ end
49
+
50
+
51
+ def run_post
52
+ -> hdrs, body_fn, body, connection {
53
+ connection.post(hdrs, body_fn.(body))
54
+ }.curry
55
+ end
56
+
57
+ def run_get
58
+ -> hdrs, query, connection {
59
+ connection.get(hdrs, query)
60
+ }.curry
61
+ end
62
+
63
+ def run_delete
64
+ -> hdrs, connection {
65
+ connection.delete(hdrs)
66
+ }.curry
67
+ end
68
+
69
+ def addressed
70
+ -> service, resource, connection {
71
+ connection.(address.(service, resource))
72
+ }.curry
73
+ end
74
+
75
+ def connection
76
+ -> encoding, address { HttpConnection.new.connection(address, encoding) }.curry
77
+ end
78
+
79
+ def address
80
+ -> service, resource {
81
+ (service || "") + (resource || "")
82
+ }.curry
83
+ end
84
+
85
+ def response_value
86
+ -> response {
87
+ response.success? ? try_handle_response(response) : catastrophic_failure(response)
88
+ }
89
+ end
90
+
91
+ def log_response
92
+ -> correlation, service, resource, api, response {
93
+ info(structured_log(service, resource, api, response, correlation))
94
+ response
95
+ }.curry
96
+ end
97
+
98
+ def try_handle_response(response)
99
+ result = Try { returned_response(response) }
100
+ result.success? ? result.value_or : catastrophic_failure(result)
101
+ end
102
+
103
+ def evalulate_status
104
+ -> status {
105
+ case status
106
+ when 200..300
107
+ OK
108
+ when 400
109
+ BAD_REQUEST
110
+ when 401, 403
111
+ UNAUTHORISED
112
+ when 404
113
+ NOT_FOUND
114
+ when 422
115
+ UNPROCESSABLE_ENTITY
116
+ when 500..530
117
+ SYSTEM_FAILURE
118
+ else
119
+ FAIL
120
+ end
121
+ }
122
+ end
123
+
124
+ # takes a content type and returns a parser; e.g. "application/json; charset=utf-8" returns the json_parser
125
+ def response_body_parser
126
+ parser_fn <<
127
+ Fn.at.(0) <<
128
+ Fn.split.(";")
129
+ end
130
+
131
+ def parser_fn
132
+ -> type {
133
+ case type
134
+ when "text/html"
135
+ nil_parser
136
+ when "text/plain"
137
+ text_parser
138
+ when "text/csv"
139
+ text_parser
140
+ when "application/json"
141
+ json_parser
142
+ when "application/xml", "application/soap+xml", "text/xml"
143
+ nil_parser
144
+ else
145
+ nil_parser
146
+ end
147
+ }
148
+ end
149
+
150
+ def returned_response(response)
151
+ raise(NoContentTypeError.new("Content Type in response is nil")) unless response.value_or.headers["content-type"]
152
+ OpenStruct.new(
153
+ status: evalulate_status.(response.value_or.status),
154
+ code: response.value_or.status,
155
+ body: response_body_parser.(response.value_or.headers["content-type"]).(response.value_or)
156
+ )
157
+ end
158
+
159
+ def catastrophic_failure(response)
160
+ OpenStruct.new(
161
+ status: SYSTEM_FAILURE,
162
+ exception: parse_error_response(response),
163
+ code: 418
164
+ )
165
+ end
166
+
167
+ def parse_error_response(response)
168
+ result = response.to_result
169
+ if result.failure.respond_to?(:exception)
170
+ {exception_class: result.failure.exception.class.name, exception: result.failure.message}
171
+ else
172
+ {execepton: "not-determined"}
173
+ end
174
+ end
175
+
176
+ def json_parser
177
+ -> response { JSON.parse(response.body) }
178
+ end
179
+
180
+ def text_parser
181
+ -> response { response.body }
182
+ end
183
+
184
+ def text_csv
185
+ -> response { response.body }
186
+ end
187
+
188
+ def nil_parser
189
+ -> response { response.body }
190
+ end
191
+
192
+ def net_ok
193
+ -> value { value.status == OK }
194
+ end
195
+
196
+ def structured_log(service, resource, api, response, correlation={})
197
+ {
198
+ msg: "Common::Network::Net",
199
+ context: context_for_log(service, resource, response, correlation),
200
+ step: api,
201
+ status: response.status
202
+ }
203
+ end
204
+
205
+ def context_for_log(service, resource, response, correlation={})
206
+ {
207
+ http_code: response.code,
208
+ resource: address.(service, resource),
209
+ fail_response: log_of_failure(response)
210
+ }.merge(correlation || {})
211
+ end
212
+
213
+ def log_of_failure(response)
214
+ return nil if net_ok.(response)
215
+ response.body.inspect
216
+ end
217
+
218
+ end
219
+
220
+ end
221
+
222
+ end
@@ -0,0 +1,37 @@
1
+ module FoucaultHttp
2
+
3
+ class Logger
4
+
5
+ FILTERS = ["password"]
6
+
7
+ def call(level, message)
8
+ logger.send(level, filtered(message)) if ( logger && logger.respond_to?(level) )
9
+ end
10
+
11
+ def configured_logger
12
+ logger
13
+ end
14
+
15
+ private
16
+
17
+ def logger
18
+ @logger ||= configuration.config.logger
19
+ end
20
+
21
+ def filtered(msg)
22
+ return unless msg.instance_of?(String)
23
+ filters = FILTERS.map { |f| msg.downcase.include? f }
24
+ if filters.any?
25
+ "[FILTERED]"
26
+ else
27
+ msg
28
+ end
29
+ end
30
+
31
+ def configuration
32
+ Configuration
33
+ end
34
+
35
+ end
36
+
37
+ end
@@ -0,0 +1,27 @@
1
+ module FoucaultHttp
2
+
3
+ module Logging
4
+
5
+ def error(message)
6
+ logger.(:debug, message)
7
+ end
8
+
9
+ def debug(message)
10
+ logger.(:debug, message)
11
+ end
12
+
13
+ def info(message)
14
+ logger.(:info, message)
15
+ end
16
+
17
+ def fatal(message)
18
+ logger.(:fatal, message)
19
+ end
20
+
21
+ def logger
22
+ Logger.new
23
+ end
24
+
25
+ end
26
+
27
+ end
@@ -0,0 +1,24 @@
1
+ module FoucaultHttp
2
+
3
+ class MonadException < StandardError
4
+
5
+ attr_reader :error_code, :retryable, :result
6
+
7
+ def initialize(result: , code: nil, retryable: true)
8
+ self.error_code = code
9
+ @retryable = retryable
10
+ @result = result
11
+ super(nil)
12
+ end
13
+
14
+ def error_code=(code)
15
+ if code
16
+ @error_code = code
17
+ else
18
+ @error_code = "urn:port:error:#{self.class.to_s.downcase.gsub("::",":")}"
19
+ end
20
+ end
21
+
22
+ end
23
+
24
+ end
@@ -0,0 +1,93 @@
1
+ require 'base64'
2
+
3
+ module FoucaultHttp
4
+
5
+ class Net
6
+
7
+ extend Dry::Monads::Try::Mixin
8
+
9
+ class << self
10
+
11
+ # Client interface
12
+ def post
13
+ -> correlation, service, resource, hdrs, enc, body_fn, body {
14
+ HttpPort.post.(correlation, service, resource, hdrs, body_fn, enc, body)
15
+ }.curry
16
+ end
17
+
18
+ def delete
19
+ -> correlation, service, resource, hdrs {
20
+ HttpPort.delete.(correlation, service, resource, hdrs)
21
+ }.curry
22
+ end
23
+
24
+ # @param service String
25
+ # @param resource String
26
+ # @param hdrs []
27
+ # @param enc String
28
+ # @param query
29
+ # @return Result(NetResponseValue)
30
+ # Example
31
+ # > get.(@env[:host], "/userinfo", {authorization: "Bearer <token> }, :url_encoded, {} )
32
+ def get
33
+ -> correlation, service, resource, hdrs, enc, query {
34
+ HttpPort.get.(correlation, service, resource, hdrs, enc, query)
35
+ }.curry
36
+ end
37
+
38
+ # That is, not a circuit breaker
39
+ # @param fn(Llambda) : A partially applied fn
40
+ # @param args : The function's arguments as either an array or hash
41
+ # @param retries(Integer) : The max number of retries
42
+ def retryer
43
+ -> fn, args, retries {
44
+ result = fn.(*args)
45
+ return result if result.success?
46
+ return result if retries == 0
47
+ retryer.(fn, args, retries - 1)
48
+ }.curry
49
+ end
50
+
51
+ def bearer_token_header
52
+ -> token {
53
+ { authorization: "Bearer #{token}"}
54
+ }
55
+ end
56
+ # (a -> a) -> Hash
57
+ # @param c [String] : Client or user
58
+ # @param s [String] : secret or password
59
+ # @return [Hash{Symbol=>String}]
60
+ def basic_auth_header
61
+ -> c, s {
62
+ { authorization: ("Basic " + Base64::strict_encode64("#{c}:#{s}")).chomp }
63
+ }.curry
64
+ end
65
+
66
+ def decode_basic_auth
67
+ -> encoded_auth {
68
+ result = Try { Base64::strict_decode64(encoded_auth.split(/\s+/).last) }
69
+ case result.success?
70
+ when true
71
+ Try { result.value_or.split(":") }
72
+ else
73
+ result
74
+ end
75
+ }
76
+ end
77
+
78
+ # @param Array[Hash]
79
+ # @return [Hash{Symbol=>String}]
80
+ def header_builder
81
+ -> *hdrs { Fn.inject.({}).(Fn.merge).(hdrs) }
82
+ end
83
+
84
+ def json_body_fn
85
+ -> body { body.to_json }
86
+ end
87
+
88
+
89
+ end # class self
90
+
91
+ end
92
+
93
+ end
@@ -0,0 +1,22 @@
1
+ module FoucaultHttp
2
+
3
+ class NetResponseValue < Dry::Struct
4
+
5
+ FAIL = :fail
6
+ OK = :ok
7
+ BAD_REQUEST = :bad_request
8
+ UNAUTHORISED = :unauthorised
9
+ NOT_FOUND = :not_found
10
+ SYSTEM_FAILURE = :system_failure
11
+ UNPROCESSABLE_ENTITY = :unprocessable_entity
12
+ CIRCUIT_RED = :circuit_red
13
+
14
+ NET_STATUS = Types::Strict::Symbol.enum(OK, FAIL, BAD_REQUEST, UNAUTHORISED, NOT_FOUND, SYSTEM_FAILURE, UNPROCESSABLE_ENTITY, CIRCUIT_RED)
15
+
16
+ attribute :status, NET_STATUS
17
+ attribute :code, Types::Integer.optional
18
+ attribute :body, Types::Nominal::Any.optional
19
+
20
+ end
21
+
22
+ end
@@ -0,0 +1,3 @@
1
+ module FoucaultHttp
2
+ VERSION = "0.4.8"
3
+ end
metadata ADDED
@@ -0,0 +1,233 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: foucault_http
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.4.8
5
+ platform: ruby
6
+ authors:
7
+ - Col Perks
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2020-04-18 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: stoplight
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: dry-monads
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '1.0'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '1.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: dry-configurable
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '0'
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: funcify
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: '0'
62
+ type: :runtime
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: typhoeus
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - ">="
74
+ - !ruby/object:Gem::Version
75
+ version: '0'
76
+ type: :runtime
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: faraday
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - "~>"
88
+ - !ruby/object:Gem::Version
89
+ version: '1.0'
90
+ type: :runtime
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - "~>"
95
+ - !ruby/object:Gem::Version
96
+ version: '1.0'
97
+ - !ruby/object:Gem::Dependency
98
+ name: dry-types
99
+ requirement: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - ">="
102
+ - !ruby/object:Gem::Version
103
+ version: '0'
104
+ type: :runtime
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: dry-struct
113
+ requirement: !ruby/object:Gem::Requirement
114
+ requirements:
115
+ - - ">="
116
+ - !ruby/object:Gem::Version
117
+ version: '0'
118
+ type: :runtime
119
+ prerelease: false
120
+ version_requirements: !ruby/object:Gem::Requirement
121
+ requirements:
122
+ - - ">="
123
+ - !ruby/object:Gem::Version
124
+ version: '0'
125
+ - !ruby/object:Gem::Dependency
126
+ name: bundler
127
+ requirement: !ruby/object:Gem::Requirement
128
+ requirements:
129
+ - - "~>"
130
+ - !ruby/object:Gem::Version
131
+ version: '2.0'
132
+ type: :development
133
+ prerelease: false
134
+ version_requirements: !ruby/object:Gem::Requirement
135
+ requirements:
136
+ - - "~>"
137
+ - !ruby/object:Gem::Version
138
+ version: '2.0'
139
+ - !ruby/object:Gem::Dependency
140
+ name: rake
141
+ requirement: !ruby/object:Gem::Requirement
142
+ requirements:
143
+ - - "~>"
144
+ - !ruby/object:Gem::Version
145
+ version: '13.0'
146
+ type: :development
147
+ prerelease: false
148
+ version_requirements: !ruby/object:Gem::Requirement
149
+ requirements:
150
+ - - "~>"
151
+ - !ruby/object:Gem::Version
152
+ version: '13.0'
153
+ - !ruby/object:Gem::Dependency
154
+ name: rspec
155
+ requirement: !ruby/object:Gem::Requirement
156
+ requirements:
157
+ - - "~>"
158
+ - !ruby/object:Gem::Version
159
+ version: '3.0'
160
+ type: :development
161
+ prerelease: false
162
+ version_requirements: !ruby/object:Gem::Requirement
163
+ requirements:
164
+ - - "~>"
165
+ - !ruby/object:Gem::Version
166
+ version: '3.0'
167
+ - !ruby/object:Gem::Dependency
168
+ name: pry
169
+ requirement: !ruby/object:Gem::Requirement
170
+ requirements:
171
+ - - ">="
172
+ - !ruby/object:Gem::Version
173
+ version: '0'
174
+ type: :development
175
+ prerelease: false
176
+ version_requirements: !ruby/object:Gem::Requirement
177
+ requirements:
178
+ - - ">="
179
+ - !ruby/object:Gem::Version
180
+ version: '0'
181
+ description: Http Network Functions.
182
+ email:
183
+ - wild.fauve@gmail.com
184
+ executables: []
185
+ extensions: []
186
+ extra_rdoc_files: []
187
+ files:
188
+ - ".gitignore"
189
+ - ".rspec"
190
+ - CODE_OF_CONDUCT.md
191
+ - Gemfile
192
+ - LICENSE.txt
193
+ - README.md
194
+ - Rakefile
195
+ - bin/console
196
+ - bin/setup
197
+ - foucault_http.gemspec
198
+ - lib/.gitignore
199
+ - lib/foucault_http.rb
200
+ - lib/foucault_http/circuit.rb
201
+ - lib/foucault_http/configuration.rb
202
+ - lib/foucault_http/http_connection.rb
203
+ - lib/foucault_http/http_port.rb
204
+ - lib/foucault_http/logger.rb
205
+ - lib/foucault_http/logging.rb
206
+ - lib/foucault_http/monad_exception.rb
207
+ - lib/foucault_http/net.rb
208
+ - lib/foucault_http/net_response_value.rb
209
+ - lib/foucault_http/version.rb
210
+ homepage: https://github.com/wildfauve/foucault_http
211
+ licenses:
212
+ - MIT
213
+ metadata: {}
214
+ post_install_message:
215
+ rdoc_options: []
216
+ require_paths:
217
+ - lib
218
+ required_ruby_version: !ruby/object:Gem::Requirement
219
+ requirements:
220
+ - - ">="
221
+ - !ruby/object:Gem::Version
222
+ version: '0'
223
+ required_rubygems_version: !ruby/object:Gem::Requirement
224
+ requirements:
225
+ - - ">="
226
+ - !ruby/object:Gem::Version
227
+ version: '0'
228
+ requirements: []
229
+ rubygems_version: 3.0.3
230
+ signing_key:
231
+ specification_version: 4
232
+ summary: Http Network Functions
233
+ test_files: []