rack-cargo 0.9.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
+ SHA1:
3
+ metadata.gz: 74705fb4f2b4e71ae109218d020b4a656ecee186
4
+ data.tar.gz: 53678530b07f570861049feed0169459d528a9ae
5
+ SHA512:
6
+ metadata.gz: d39972558dd1a23a65c1f676ff0156861126ce4520a7532d34a0412356bfb75fbcb6788ce6d8520988887279a63ea9189beac0fdb5efce04f6094964a354b227
7
+ data.tar.gz: 5fb134a797e14a55506dcac06f0a8bf6782859100e23a5fb34e0bda3d5e9767b8b6105feb87f7a08f2a663a13fc64a3052cd005e4bf539bdc03ed1afe32f3a76
data/.gitignore ADDED
@@ -0,0 +1,9 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
data/.rubocop.yml ADDED
@@ -0,0 +1,20 @@
1
+ AllCops:
2
+ Exclude:
3
+ - test/**/*
4
+ - rack-cargo.gemspec
5
+
6
+ Style/StringLiterals:
7
+ EnforcedStyle: double_quotes
8
+ SupportedStyles:
9
+ - double_quotes
10
+ # If `true`, strings which span multiple lines using `\` for continuation must
11
+ # use the same type of quotes on each line.
12
+ ConsistentQuotesInMultiline: true
13
+
14
+ Style/StringLiteralsInInterpolation:
15
+ EnforcedStyle: double_quotes
16
+ SupportedStyles:
17
+ - double_quotes
18
+
19
+ Style/RescueModifier:
20
+ Enabled: false
data/.ruby-gemset ADDED
@@ -0,0 +1 @@
1
+ rack-cargo
data/.ruby-version ADDED
@@ -0,0 +1 @@
1
+ 2.3.0
data/.travis.yml ADDED
@@ -0,0 +1,6 @@
1
+ sudo: false
2
+ language: ruby
3
+ rvm:
4
+ - 2.3.0
5
+ - 2.4.0
6
+ before_install: gem install bundler -v 1.15.3
@@ -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 murdho@murdho.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
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in rack-cargo.gemspec
6
+ gemspec
data/Guardfile ADDED
@@ -0,0 +1,32 @@
1
+ # frozen_string_literal: true
2
+
3
+ # A sample Guardfile
4
+ # More info at https://github.com/guard/guard#readme
5
+
6
+ ## Uncomment and set this to only include directories you want to watch
7
+ # directories %w(app lib config test spec features) \
8
+ # .select{|d| Dir.exists?(d) ? d : UI.warning("Directory #{d} does not exist")}
9
+
10
+ ## Note: if you are using the `directories` clause above and you are not
11
+ ## watching the project directory ('.'), then you will want to move
12
+ ## the Guardfile to a watched dir and symlink it back, e.g.
13
+ #
14
+ # $ mkdir config
15
+ # $ mv Guardfile config/
16
+ # $ ln -s config/Guardfile .
17
+ #
18
+ # and, you'll have to watch "config/Guardfile" instead of "Guardfile"
19
+
20
+ guard :minitest do
21
+ # with Minitest::Unit
22
+ watch(%r{^test/(.*)\/?(.*)_test\.rb$})
23
+ watch(%r{^lib/(.*/)?([^/]+)\.rb$}) { |m| "test/#{m[1]}#{m[2]}_test.rb" }
24
+ watch(%r{^test/test_helper\.rb$}) { "test" }
25
+
26
+ # with Minitest::Spec
27
+ # watch(%r{^spec/(.*)_spec\.rb$})
28
+ # watch(%r{^lib/(.+)\.rb$}) { |m| "spec/#{m[1]}_spec.rb" }
29
+ # watch(%r{^spec/spec_helper\.rb$}) { 'spec' }
30
+ end
31
+
32
+ notification :terminal_notifier if `uname` =~ /Darwin/
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2017 Murdho
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,173 @@
1
+ # Rack::Cargo
2
+
3
+ [![Build Status](https://travis-ci.org/murdho/rack-cargo.svg?branch=master)](https://travis-ci.org/murdho/rack-cargo)
4
+ [![Codacy Badge](https://api.codacy.com/project/badge/Grade/96d334fdbe7b4bed975c1e344523f926)](https://www.codacy.com/app/murdho/rack-cargo?utm_source=github.com&utm_medium=referral&utm_content=murdho/rack-cargo&utm_campaign=Badge_Grade)
5
+ [![Codacy Badge](https://api.codacy.com/project/badge/Coverage/96d334fdbe7b4bed975c1e344523f926)](https://www.codacy.com/app/murdho/rack-cargo?utm_source=github.com&utm_medium=referral&utm_content=murdho/rack-cargo&utm_campaign=Badge_Coverage)
6
+
7
+ Have you built nice RESTful APIs? I believe you have.
8
+
9
+ Then you are also familiar with the situation, where API consumer needs to perform multiple actions at once. Maybe in the client application, multiple resources get created on one page. Creating multiple resources means making multiple HTTP requests.
10
+
11
+ What if you could **batch the requests** together and send in one HTTP requests, wouldn't that be more efficient? I believe it would be! That's where **Rack::Cargo** comes in.
12
+
13
+ Figuratively speaking, load your HTTP-request ship with the request cargo and put it on the way and enjoy your RESTful API! ☀️
14
+
15
+ > ***You:** I want to know more about RESTful. Where should I look?*
16
+ >
17
+ > ***Me:** Cool! I recommend this awesome talk: [In Relentless Pursuit of REST by Derek Prior](https://youtu.be/HctYHe-YjnE)*
18
+
19
+ ## Installation
20
+
21
+ Add this line to your Rack-based application's (Rails, Sinatra, etc.) Gemfile:
22
+
23
+ ```ruby
24
+ gem 'rack-cargo'
25
+ ```
26
+
27
+ And then execute:
28
+
29
+ $ bundle
30
+
31
+ Or install it yourself as:
32
+
33
+ $ gem install rack-cargo
34
+
35
+ ## Usage (TODO)
36
+
37
+ ### Configuration
38
+
39
+ Initialize the middleware:
40
+
41
+ ```ruby
42
+ Rack::Cargo.configure do |config|
43
+ config.batch_path = '/batch'
44
+ end
45
+ ```
46
+
47
+ Instruct `rack` to use the middleware:
48
+
49
+ ```ruby
50
+ use Rack::Cargo::Middleware
51
+ ```
52
+
53
+ ### Referencing requests
54
+
55
+ Requests in batch have access to the responses of executed (named) requests. This is useful, when creating resources and using the reference to it in the same batch.
56
+
57
+ References can be used in `path` and `body` elements.
58
+
59
+ Example shows both usages with `order.uuid` from the `order` response:
60
+
61
+ ```javascript
62
+ // This is batch request payload:
63
+ {
64
+ "requests": [
65
+ {
66
+ "name": "order",
67
+ "path": "/orders",
68
+ "method": "POST",
69
+ "body": {
70
+ "address": "Home, 12345"
71
+ }
72
+ },
73
+ {
74
+ "name": "order_item",
75
+ "path": "/orders/{{ order.uuid }}/items", // <-- here
76
+ "method": "POST",
77
+ "body": {
78
+ "title": "A Book"
79
+ }
80
+ },
81
+ {
82
+ "name": "payment",
83
+ "path": "/payments",
84
+ "method": "POST",
85
+ "body": {
86
+ "orders": [
87
+ "{{ order.uuid }}" // <-- and here
88
+ ]
89
+ }
90
+ }
91
+ ]
92
+ }
93
+
94
+ // This is a possible response:
95
+ [
96
+ {
97
+ "name": "order", // <-- "order" part of "order.uuid"
98
+ "status": 201,
99
+ "headers": {},
100
+ "body": {
101
+ "uuid": "bf52fdb5-d1c3-4c66-ba7d-bdf4cd83f265", // <-- "uuid" part of "order.uuid"
102
+ "address": "Home, 12345"
103
+ }
104
+ },
105
+ {
106
+ "name": "order_item",
107
+ "status": 201,
108
+ "headers": {},
109
+ "body": {
110
+ "uuid": "38bc4576-3b7e-40be-a1d6-ca795fe462c8",
111
+ "title": "A Book"
112
+ }
113
+ },
114
+ {
115
+ "name": "payment",
116
+ "status": 201,
117
+ "headers": {},
118
+ "body": {
119
+ "uuid": "c4f9f261-7822-4217-80a2-06cf92934bf9",
120
+ "orders": [
121
+ "bf52fdb5-d1c3-4c66-ba7d-bdf4cd83f265"
122
+ ]
123
+ }
124
+ }
125
+ ]
126
+ ```
127
+
128
+ ### Modifying batch processing pipeline
129
+
130
+ Batch processing is composed of steps that perform some concrete action on the request and/or state of the processing.
131
+
132
+ To insert processor in the pipeline, define the processor and inject it to the processors list:
133
+
134
+ ```ruby
135
+ module MyFeeder
136
+ def self.call(request, state)
137
+ # calculate something
138
+ state.store(:data, "Useful data to MyEater")
139
+ end
140
+ end
141
+
142
+ module MyEater
143
+ def self.call(request, state)
144
+ data = state.fetch(:data)
145
+ # do something with the data
146
+ end
147
+ end
148
+
149
+ Rack::Cargo.configure do |config|
150
+ config.processors.insert(2, MyFeeder) # insert into third position
151
+ config.processors.insert(3, MyEater) # insert into fourth position
152
+ end
153
+ ```
154
+
155
+ Now your processors will be included in the pipeline.
156
+
157
+ ## Development
158
+
159
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
160
+
161
+ 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).
162
+
163
+ ## Contributing
164
+
165
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/rack-cargo. 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.
166
+
167
+ ## License
168
+
169
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
170
+
171
+ ## Code of Conduct
172
+
173
+ Everyone interacting in the Rack::Cargo project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/rack-cargo/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rake/testtask"
5
+
6
+ Rake::TestTask.new(:test) do |t|
7
+ t.libs << "test"
8
+ t.libs << "lib"
9
+ t.test_files = FileList["test/**/*_test.rb"]
10
+ end
11
+
12
+ task default: :test
data/bin/console ADDED
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "bundler/setup"
5
+ require "rack/cargo"
6
+
7
+ # You can add fixtures and/or initialization code here to make experimenting
8
+ # with your gem easier. You can also use a different console, if you like.
9
+
10
+ # (If you use this, don't forget to add pry to your Gemfile!)
11
+ # require "pry"
12
+ # Pry.start
13
+
14
+ require "irb"
15
+ 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,66 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Rack
4
+ module Cargo
5
+ module BatchProcessor
6
+ ERROR_INVALID_BATCH = "Invalid batch request"
7
+
8
+ class << self
9
+ def process(app, env)
10
+ requests = RequestPayloadJSON.from_env(env)
11
+
12
+ if RequestValidator.valid?(requests)
13
+ results = process_requests(app, env, requests)
14
+ success(results)
15
+ else
16
+ failure([ERROR_INVALID_BATCH])
17
+ end
18
+ end
19
+
20
+ private
21
+
22
+ def process_requests(app, env, requests)
23
+ previous_responses = {}
24
+
25
+ requests.each do |request|
26
+ response = process_request(
27
+ app,
28
+ env,
29
+ request,
30
+ previous_responses
31
+ )
32
+ previous_responses[response.fetch("name")] = response
33
+ end
34
+
35
+ previous_responses.values
36
+ end
37
+
38
+ def process_request(app, env, request, previous_responses)
39
+ initial_state = {
40
+ app: app,
41
+ env: env,
42
+ previous_responses: previous_responses
43
+ }
44
+
45
+ result = processors.each_with_object(initial_state) do |proc, state|
46
+ proc.call(request, state)
47
+ end
48
+
49
+ result[:response]
50
+ end
51
+
52
+ def success(responses)
53
+ { success: true, responses: responses }
54
+ end
55
+
56
+ def failure(errors)
57
+ { success: false, errors: errors }
58
+ end
59
+
60
+ def processors
61
+ Rack::Cargo.config.processors
62
+ end
63
+ end
64
+ end
65
+ end
66
+ end
@@ -0,0 +1,24 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Rack
4
+ module Cargo
5
+ module BatchResponse
6
+ class << self
7
+ def from_result(result)
8
+ if result[:success]
9
+ respond_with(200, result[:responses])
10
+ else
11
+ respond_with(422, errors: result[:errors])
12
+ end
13
+ end
14
+
15
+ private
16
+
17
+ def respond_with(status, body)
18
+ response_headers = { "Content-Type" => "application/json" }
19
+ [status, response_headers, [body.to_json]]
20
+ end
21
+ end
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Rack
4
+ module Cargo
5
+ class Configuration
6
+ attr_accessor :batch_path
7
+ attr_accessor :processors
8
+
9
+ def initialize
10
+ self.batch_path = "/batch"
11
+ self.processors = [
12
+ ReferenceResolver,
13
+ RequestEnvBuilder,
14
+ RequestExecutor,
15
+ ResponseBuilder
16
+ ]
17
+ end
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,60 @@
1
+ # frozen_string_literal: true
2
+
3
+ # This file is copied from ActiveSupport source code.
4
+ #
5
+ # Original:
6
+ # https://github.com/rails/rails/blob/master/activesupport/lib/active_support/core_ext/object/deep_dup.rb
7
+
8
+ require_relative "duplicable"
9
+
10
+ class Object
11
+ # Returns a deep copy of object if it's duplicable. If it's
12
+ # not duplicable, returns +self+.
13
+ #
14
+ # object = Object.new
15
+ # dup = object.deep_dup
16
+ # dup.instance_variable_set(:@a, 1)
17
+ #
18
+ # object.instance_variable_defined?(:@a) # => false
19
+ # dup.instance_variable_defined?(:@a) # => true
20
+ def deep_dup
21
+ duplicable? ? dup : self
22
+ end
23
+ end
24
+
25
+ class Array
26
+ # Returns a deep copy of array.
27
+ #
28
+ # array = [1, [2, 3]]
29
+ # dup = array.deep_dup
30
+ # dup[1][2] = 4
31
+ #
32
+ # array[1][2] # => nil
33
+ # dup[1][2] # => 4
34
+ def deep_dup
35
+ map(&:deep_dup)
36
+ end
37
+ end
38
+
39
+ class Hash
40
+ # Returns a deep copy of hash.
41
+ #
42
+ # hash = { a: { b: 'b' } }
43
+ # dup = hash.deep_dup
44
+ # dup[:a][:c] = 'c'
45
+ #
46
+ # hash[:a][:c] # => nil
47
+ # dup[:a][:c] # => "c"
48
+ def deep_dup
49
+ hash = dup
50
+ each_pair do |key, value|
51
+ if key.frozen? && ::String === key
52
+ hash[key] = value.deep_dup
53
+ else
54
+ hash.delete(key)
55
+ hash[key.deep_dup] = value.deep_dup
56
+ end
57
+ end
58
+ hash
59
+ end
60
+ end
@@ -0,0 +1,154 @@
1
+ # frozen_string_literal: true
2
+
3
+ # This file is copied from ActiveSupport source code.
4
+ #
5
+ # Original:
6
+ # https://github.com/rails/rails/blob/master/activesupport/lib/active_support/core_ext/object/duplicable.rb
7
+
8
+ #--
9
+ # Most objects are cloneable, but not all. For example you can't dup methods:
10
+ #
11
+ # method(:puts).dup # => TypeError: allocator undefined for Method
12
+ #
13
+ # Classes may signal their instances are not duplicable removing +dup+/+clone+
14
+ # or raising exceptions from them. So, to dup an arbitrary object you normally
15
+ # use an optimistic approach and are ready to catch an exception, say:
16
+ #
17
+ # arbitrary_object.dup rescue object
18
+ #
19
+ # Rails dups objects in a few critical spots where they are not that arbitrary.
20
+ # That rescue is very expensive (like 40 times slower than a predicate), and it
21
+ # is often triggered.
22
+ #
23
+ # That's why we hardcode the following cases and check duplicable? instead of
24
+ # using that rescue idiom.
25
+ #++
26
+ class Object
27
+ # Can you safely dup this object?
28
+ #
29
+ # False for method objects;
30
+ # true otherwise.
31
+ def duplicable?
32
+ true
33
+ end
34
+ end
35
+
36
+ class NilClass
37
+ begin
38
+ nil.dup
39
+ rescue TypeError
40
+ # +nil+ is not duplicable:
41
+ #
42
+ # nil.duplicable? # => false
43
+ # nil.dup # => TypeError: can't dup NilClass
44
+ def duplicable?
45
+ false
46
+ end
47
+ end
48
+ end
49
+
50
+ class FalseClass
51
+ begin
52
+ false.dup
53
+ rescue TypeError
54
+ # +false+ is not duplicable:
55
+ #
56
+ # false.duplicable? # => false
57
+ # false.dup # => TypeError: can't dup FalseClass
58
+ def duplicable?
59
+ false
60
+ end
61
+ end
62
+ end
63
+
64
+ class TrueClass
65
+ begin
66
+ true.dup
67
+ rescue TypeError
68
+ # +true+ is not duplicable:
69
+ #
70
+ # true.duplicable? # => false
71
+ # true.dup # => TypeError: can't dup TrueClass
72
+ def duplicable?
73
+ false
74
+ end
75
+ end
76
+ end
77
+
78
+ class Symbol
79
+ begin
80
+ :symbol.dup # Ruby 2.4.x.
81
+ "symbol_from_string".to_sym.dup # Some symbols can't `dup` in Ruby 2.4.0.
82
+ rescue TypeError
83
+ # Symbols are not duplicable:
84
+ #
85
+ # :my_symbol.duplicable? # => false
86
+ # :my_symbol.dup # => TypeError: can't dup Symbol
87
+ def duplicable?
88
+ false
89
+ end
90
+ end
91
+ end
92
+
93
+ class Numeric
94
+ begin
95
+ 1.dup
96
+ rescue TypeError
97
+ # Numbers are not duplicable:
98
+ #
99
+ # 3.duplicable? # => false
100
+ # 3.dup # => TypeError: can't dup Integer
101
+ def duplicable?
102
+ false
103
+ end
104
+ end
105
+ end
106
+
107
+ require "bigdecimal"
108
+ class BigDecimal
109
+ # BigDecimals are duplicable:
110
+ #
111
+ # BigDecimal.new("1.2").duplicable? # => true
112
+ # BigDecimal.new("1.2").dup # => #<BigDecimal:...,'0.12E1',18(18)>
113
+ def duplicable?
114
+ true
115
+ end
116
+ end
117
+
118
+ class Method
119
+ # Methods are not duplicable:
120
+ #
121
+ # method(:puts).duplicable? # => false
122
+ # method(:puts).dup # => TypeError: allocator undefined for Method
123
+ def duplicable?
124
+ false
125
+ end
126
+ end
127
+
128
+ class Complex
129
+ begin
130
+ Complex(1).dup
131
+ rescue TypeError
132
+ # Complexes are not duplicable:
133
+ #
134
+ # Complex(1).duplicable? # => false
135
+ # Complex(1).dup # => TypeError: can't copy Complex
136
+ def duplicable?
137
+ false
138
+ end
139
+ end
140
+ end
141
+
142
+ class Rational
143
+ begin
144
+ Rational(1).dup
145
+ rescue TypeError
146
+ # Rationals are not duplicable:
147
+ #
148
+ # Rational(1).duplicable? # => false
149
+ # Rational(1).dup # => TypeError: can't copy Rational
150
+ def duplicable?
151
+ false
152
+ end
153
+ end
154
+ end
@@ -0,0 +1,26 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Rack
4
+ module Cargo
5
+ class Middleware
6
+ attr_accessor :app
7
+
8
+ def initialize(app)
9
+ self.app = app
10
+ end
11
+
12
+ def call(env)
13
+ if batch_request?(env[ENV_PATH])
14
+ result = BatchProcessor.process(app, env)
15
+ BatchResponse.from_result(result)
16
+ else
17
+ @app.call(env)
18
+ end
19
+ end
20
+
21
+ def batch_request?(path)
22
+ path == Rack::Cargo.config.batch_path
23
+ end
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,66 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Rack
4
+ module Cargo
5
+ module ReferenceResolver
6
+ REFERENCING_ENABLED = [REQUEST_PATH, REQUEST_BODY].freeze
7
+
8
+ PLACEHOLDER_START = "{{\s*"
9
+ PLACEHOLDER_END = "\s*}}"
10
+ PLACEHOLDER_PATTERN = /#{PLACEHOLDER_START}(.*?)#{PLACEHOLDER_END}/
11
+
12
+ class << self
13
+ def call(request, state)
14
+ REFERENCING_ENABLED.each do |attribute_key|
15
+ element, converted_to_json = get_json_element(request, attribute_key)
16
+ placeholders = find_placeholders(element)
17
+
18
+ element = replace_placeholders(element, placeholders, state)
19
+ element = JSON.parse(element) if converted_to_json
20
+
21
+ request.store(attribute_key, element)
22
+ end
23
+ end
24
+
25
+ private
26
+
27
+ def replace_placeholders(element, placeholders, state)
28
+ previous_responses = state.fetch(:previous_responses)
29
+
30
+ placeholders.each do |placeholder|
31
+ value_path = value_path_for(placeholder)
32
+ value = previous_responses.dig(*value_path)
33
+ next unless value
34
+
35
+ replacement_regex = replacement_regex_for(placeholder)
36
+ element = element.gsub(replacement_regex, value.to_s)
37
+ end
38
+
39
+ element
40
+ end
41
+
42
+ def value_path_for(placeholder)
43
+ placeholder.split(".").map(&:to_s).insert(1, REQUEST_BODY)
44
+ end
45
+
46
+ def replacement_regex_for(placeholder)
47
+ /#{PLACEHOLDER_START}#{placeholder}#{PLACEHOLDER_END}/
48
+ end
49
+
50
+ def find_placeholders(element)
51
+ element.scan(PLACEHOLDER_PATTERN).flatten
52
+ end
53
+
54
+ def get_json_element(request, attribute_key)
55
+ element_copy = request.fetch(attribute_key).dup
56
+
57
+ if element_copy.is_a?(String)
58
+ [element_copy, false]
59
+ else
60
+ [element_copy.to_json, true]
61
+ end
62
+ end
63
+ end
64
+ end
65
+ end
66
+ end
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rack/cargo/core_ext/deep_dup"
4
+
5
+ module Rack
6
+ module Cargo
7
+ module RequestEnvBuilder
8
+ def self.call(request, state)
9
+ request_env = state.fetch(:env).deep_dup
10
+ request_env[ENV_PATH] = request[REQUEST_PATH]
11
+ request_env[ENV_METHOD] = request[REQUEST_METHOD]
12
+ request_env[ENV_INPUT] = StringIO.new(request[REQUEST_BODY].to_json)
13
+ state[:request_env] = request_env
14
+ end
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Rack
4
+ module Cargo
5
+ module RequestExecutor
6
+ def self.call(_request, state)
7
+ app = state.fetch(:app)
8
+ request_env = state.fetch(:request_env)
9
+
10
+ status, headers, body = app.call(request_env)
11
+ body.close if body.respond_to?(:close)
12
+
13
+ state[:app_response] = {
14
+ status: status,
15
+ headers: headers,
16
+ body: body
17
+ }
18
+ end
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Rack
4
+ module Cargo
5
+ module RequestPayloadJSON
6
+ def self.from_env(env)
7
+ io = env[ENV_INPUT]
8
+ return unless io
9
+
10
+ payload = io.read
11
+ return if payload.empty?
12
+
13
+ json_payload = JSON.parse(payload) rescue nil
14
+ return unless json_payload
15
+
16
+ json_payload[REQUESTS_KEY]
17
+ end
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Rack
4
+ module Cargo
5
+ module RequestValidator
6
+ REQUIRED_KEYS = [
7
+ REQUEST_PATH,
8
+ REQUEST_METHOD,
9
+ REQUEST_BODY
10
+ ].freeze
11
+
12
+ def self.valid?(requests)
13
+ return unless requests
14
+
15
+ requests.all? do |request|
16
+ REQUIRED_KEYS.all? { |key| request.key?(key) }
17
+ end
18
+ end
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,26 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Rack
4
+ module Cargo
5
+ module ResponseBuilder
6
+ class << self
7
+ def call(request, state)
8
+ app_response = state.fetch(:app_response)
9
+
10
+ name = request.fetch("name", autogenerated_name)
11
+
12
+ state[:response] = {
13
+ RESPONSE_NAME => name,
14
+ RESPONSE_STATUS => app_response.fetch(:status),
15
+ RESPONSE_HEADERS => app_response.fetch(:headers),
16
+ RESPONSE_BODY => JSON.parse(app_response.fetch(:body).join)
17
+ }
18
+ end
19
+
20
+ def autogenerated_name
21
+ "unnamed_#{SecureRandom.hex(6)}"
22
+ end
23
+ end
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Rack
4
+ module Cargo
5
+ VERSION = "0.9.0"
6
+ end
7
+ end
data/lib/rack/cargo.rb ADDED
@@ -0,0 +1,50 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "securerandom"
5
+
6
+ require "rack/cargo/version"
7
+
8
+ module Rack
9
+ module Cargo
10
+ REQUESTS_KEY = "requests"
11
+
12
+ ENV_PATH = "PATH_INFO"
13
+ ENV_INPUT = "rack.input"
14
+ ENV_METHOD = "REQUEST_METHOD"
15
+
16
+ REQUEST_NAME = "name"
17
+ REQUEST_PATH = "path"
18
+ REQUEST_METHOD = "method"
19
+ REQUEST_BODY = "body"
20
+
21
+ RESPONSE_NAME = "name"
22
+ RESPONSE_STATUS = "status"
23
+ RESPONSE_HEADERS = "headers"
24
+ RESPONSE_BODY = "body"
25
+
26
+ autoload :Middleware, "rack/cargo/middleware"
27
+ autoload :Configuration, "rack/cargo/configuration"
28
+
29
+ autoload :BatchProcessor, "rack/cargo/batch_processor"
30
+
31
+ autoload :RequestPayloadJSON, "rack/cargo/request_payload_json"
32
+ autoload :RequestValidator, "rack/cargo/request_validator"
33
+ autoload :ReferenceResolver, "rack/cargo/reference_resolver"
34
+ autoload :RequestEnvBuilder, "rack/cargo/request_env_builder"
35
+ autoload :RequestExecutor, "rack/cargo/request_executor"
36
+ autoload :ResponseBuilder, "rack/cargo/response_builder"
37
+
38
+ autoload :BatchResponse, "rack/cargo/batch_response"
39
+
40
+ class << self
41
+ def config
42
+ @config ||= Configuration.new
43
+ end
44
+
45
+ def configure
46
+ yield(config)
47
+ end
48
+ end
49
+ end
50
+ end
@@ -0,0 +1,42 @@
1
+ # coding: utf-8
2
+ # frozen_string_literal: true
3
+
4
+ lib = File.expand_path("../lib", __FILE__)
5
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
6
+ require "rack/cargo/version"
7
+
8
+ Gem::Specification.new do |spec|
9
+ spec.name = "rack-cargo"
10
+ spec.version = Rack::Cargo::VERSION
11
+ spec.authors = ["Murdho"]
12
+ spec.email = ["murdho@murdho.com"]
13
+
14
+ spec.summary = "Batch requests for Rack apps."
15
+ spec.description = <<~DESC
16
+ Enables creating batch requests to Rack apps.
17
+ Requests can reference each other.
18
+ Makes life easier for API consumers and builders.
19
+ DESC
20
+ spec.homepage = "https://github.com/murdho/rack-cargo"
21
+ spec.license = "MIT"
22
+
23
+ spec.files = `git ls-files -z`.split("\x0").reject do |f|
24
+ 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_development_dependency "bundler", "~> 1.15"
31
+ spec.add_development_dependency "rake", "~> 10.0"
32
+ spec.add_development_dependency "minitest", "~> 5.0"
33
+ spec.add_development_dependency "minitest-reporters", "~> 1.1"
34
+ spec.add_development_dependency "guard", "~> 2.14"
35
+ spec.add_development_dependency "guard-minitest", "~> 2.4"
36
+ spec.add_development_dependency "terminal-notifier-guard", "~> 1.6"
37
+ spec.add_development_dependency "rubocop"
38
+ spec.add_development_dependency "reek"
39
+ spec.add_development_dependency "rack-test"
40
+ spec.add_development_dependency "awesome_print"
41
+ spec.add_development_dependency "codacy-coverage"
42
+ end
metadata ADDED
@@ -0,0 +1,243 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: rack-cargo
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.9.0
5
+ platform: ruby
6
+ authors:
7
+ - Murdho
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2017-07-24 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.15'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.15'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '10.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '10.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: minitest
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '5.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '5.0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: minitest-reporters
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '1.1'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '1.1'
69
+ - !ruby/object:Gem::Dependency
70
+ name: guard
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '2.14'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '2.14'
83
+ - !ruby/object:Gem::Dependency
84
+ name: guard-minitest
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - "~>"
88
+ - !ruby/object:Gem::Version
89
+ version: '2.4'
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - "~>"
95
+ - !ruby/object:Gem::Version
96
+ version: '2.4'
97
+ - !ruby/object:Gem::Dependency
98
+ name: terminal-notifier-guard
99
+ requirement: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - "~>"
102
+ - !ruby/object:Gem::Version
103
+ version: '1.6'
104
+ type: :development
105
+ prerelease: false
106
+ version_requirements: !ruby/object:Gem::Requirement
107
+ requirements:
108
+ - - "~>"
109
+ - !ruby/object:Gem::Version
110
+ version: '1.6'
111
+ - !ruby/object:Gem::Dependency
112
+ name: rubocop
113
+ requirement: !ruby/object:Gem::Requirement
114
+ requirements:
115
+ - - ">="
116
+ - !ruby/object:Gem::Version
117
+ version: '0'
118
+ type: :development
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: reek
127
+ requirement: !ruby/object:Gem::Requirement
128
+ requirements:
129
+ - - ">="
130
+ - !ruby/object:Gem::Version
131
+ version: '0'
132
+ type: :development
133
+ prerelease: false
134
+ version_requirements: !ruby/object:Gem::Requirement
135
+ requirements:
136
+ - - ">="
137
+ - !ruby/object:Gem::Version
138
+ version: '0'
139
+ - !ruby/object:Gem::Dependency
140
+ name: rack-test
141
+ requirement: !ruby/object:Gem::Requirement
142
+ requirements:
143
+ - - ">="
144
+ - !ruby/object:Gem::Version
145
+ version: '0'
146
+ type: :development
147
+ prerelease: false
148
+ version_requirements: !ruby/object:Gem::Requirement
149
+ requirements:
150
+ - - ">="
151
+ - !ruby/object:Gem::Version
152
+ version: '0'
153
+ - !ruby/object:Gem::Dependency
154
+ name: awesome_print
155
+ requirement: !ruby/object:Gem::Requirement
156
+ requirements:
157
+ - - ">="
158
+ - !ruby/object:Gem::Version
159
+ version: '0'
160
+ type: :development
161
+ prerelease: false
162
+ version_requirements: !ruby/object:Gem::Requirement
163
+ requirements:
164
+ - - ">="
165
+ - !ruby/object:Gem::Version
166
+ version: '0'
167
+ - !ruby/object:Gem::Dependency
168
+ name: codacy-coverage
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: |
182
+ Enables creating batch requests to Rack apps.
183
+ Requests can reference each other.
184
+ Makes life easier for API consumers and builders.
185
+ email:
186
+ - murdho@murdho.com
187
+ executables: []
188
+ extensions: []
189
+ extra_rdoc_files: []
190
+ files:
191
+ - ".gitignore"
192
+ - ".rubocop.yml"
193
+ - ".ruby-gemset"
194
+ - ".ruby-version"
195
+ - ".travis.yml"
196
+ - CODE_OF_CONDUCT.md
197
+ - Gemfile
198
+ - Guardfile
199
+ - LICENSE.txt
200
+ - README.md
201
+ - Rakefile
202
+ - bin/console
203
+ - bin/setup
204
+ - lib/rack/cargo.rb
205
+ - lib/rack/cargo/batch_processor.rb
206
+ - lib/rack/cargo/batch_response.rb
207
+ - lib/rack/cargo/configuration.rb
208
+ - lib/rack/cargo/core_ext/deep_dup.rb
209
+ - lib/rack/cargo/core_ext/duplicable.rb
210
+ - lib/rack/cargo/middleware.rb
211
+ - lib/rack/cargo/reference_resolver.rb
212
+ - lib/rack/cargo/request_env_builder.rb
213
+ - lib/rack/cargo/request_executor.rb
214
+ - lib/rack/cargo/request_payload_json.rb
215
+ - lib/rack/cargo/request_validator.rb
216
+ - lib/rack/cargo/response_builder.rb
217
+ - lib/rack/cargo/version.rb
218
+ - rack-cargo.gemspec
219
+ homepage: https://github.com/murdho/rack-cargo
220
+ licenses:
221
+ - MIT
222
+ metadata: {}
223
+ post_install_message:
224
+ rdoc_options: []
225
+ require_paths:
226
+ - lib
227
+ required_ruby_version: !ruby/object:Gem::Requirement
228
+ requirements:
229
+ - - ">="
230
+ - !ruby/object:Gem::Version
231
+ version: '0'
232
+ required_rubygems_version: !ruby/object:Gem::Requirement
233
+ requirements:
234
+ - - ">="
235
+ - !ruby/object:Gem::Version
236
+ version: '0'
237
+ requirements: []
238
+ rubyforge_project:
239
+ rubygems_version: 2.5.1
240
+ signing_key:
241
+ specification_version: 4
242
+ summary: Batch requests for Rack apps.
243
+ test_files: []