rack-idempotency-kit 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 726d1af381b92f655f2ca9d8972dd612512c9309299cb9ff1e3a9a19b9fd5b53
4
+ data.tar.gz: b8ec74b5d608096b9653601e018fbc7fc9d1828a1fffdd39d2c4d67fc67ae67a
5
+ SHA512:
6
+ metadata.gz: 66bc089bfff594e054c76ffa68478755883fcd23a704fc351fc70de2135c486f6456bd912a9573b32c110d55ad0df8d7c365995ceacb299ea5a0e68aa434f33e
7
+ data.tar.gz: 9d55ec3527558c7637aaf0ae27139116dc92886592b09c7444f1ee513e657fed1110c23181af248c4f50f1ecb8eb5db43cdc7f6ea67fe4462fbcef86dd6acb84
@@ -0,0 +1,19 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ pull_request:
6
+
7
+ jobs:
8
+ test:
9
+ runs-on: ubuntu-latest
10
+ strategy:
11
+ matrix:
12
+ ruby: ["3.0", "3.1", "3.2", "3.3"]
13
+ steps:
14
+ - uses: actions/checkout@v4
15
+ - uses: ruby/setup-ruby@v1
16
+ with:
17
+ ruby-version: ${{ matrix.ruby }}
18
+ bundler-cache: true
19
+ - run: bundle exec rspec
data/.gitignore ADDED
@@ -0,0 +1,15 @@
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
12
+
13
+ # bundler
14
+ Gemfile.lock
15
+
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/CHANGELOG.md ADDED
@@ -0,0 +1,4 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0
4
+ - Initial release.
@@ -0,0 +1,26 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+ We pledge to make participation in our community a harassment-free experience for everyone.
5
+
6
+ ## Our Standards
7
+ Examples of behavior that contributes to a positive environment include:
8
+ - Using welcoming and inclusive language
9
+ - Respecting differing viewpoints and experiences
10
+ - Gracefully accepting constructive criticism
11
+
12
+ Examples of unacceptable behavior include:
13
+ - Trolling, insulting/derogatory comments, and personal or political attacks
14
+ - Public or private harassment
15
+
16
+ ## Enforcement Responsibilities
17
+ Project maintainers are responsible for clarifying and enforcing standards of acceptable behavior.
18
+
19
+ ## Scope
20
+ This Code of Conduct applies within all project spaces and in public spaces when representing the project.
21
+
22
+ ## Enforcement
23
+ Instances of abusive behavior may be reported to the maintainer listed in the gemspec.
24
+
25
+ ## Attribution
26
+ This Code of Conduct is adapted from the Contributor Covenant, version 1.4.
data/CONTRIBUTING.md ADDED
@@ -0,0 +1,10 @@
1
+ # Contributing
2
+
3
+ ## Development setup
4
+ - Run `bundle install`
5
+ - Run `bundle exec rspec`
6
+
7
+ ## Release
8
+ 1. Update `CHANGELOG.md`
9
+ 2. Bump version in `lib/**/version.rb`
10
+ 3. Run `bundle exec rake release`
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 rack-idempotency-kit.gemspec
6
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 MounirGaiby
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,66 @@
1
+ # Rack Idempotency Kit
2
+
3
+ Stripe-style idempotency for Rack and Rails APIs.
4
+
5
+ ## About
6
+ Rack Idempotency Kit ensures that repeated requests with the same idempotency key replay the original response instead of executing the action twice. It protects against retries, network timeouts, and client-side duplications.
7
+
8
+ The middleware stores a fingerprint of the request and a completed response. If the same key is used with different request parameters, it returns a conflict.
9
+
10
+ ## Use Cases
11
+ - Payment, checkout, and webhook endpoints with retries
12
+ - API clients with timeouts and automatic replays
13
+ - Protecting side-effecting endpoints from duplicate writes
14
+ - Reducing p99 spikes caused by retry storms
15
+
16
+ ## Compatibility
17
+ - Ruby 3.0+
18
+ - Rack 2.2+
19
+ - Works with Rails middleware stack
20
+
21
+ ## Installation
22
+ ```ruby
23
+ # Gemfile
24
+
25
+ gem "rack-idempotency-kit"
26
+ ```
27
+
28
+ ## Usage (Rails)
29
+ ```ruby
30
+ # config/application.rb
31
+ config.middleware.use Rack::Idempotency::Kit,
32
+ store: Rails.cache,
33
+ ttl: 86_400,
34
+ header: "Idempotency-Key"
35
+ ```
36
+
37
+ ## Usage (Rack)
38
+ ```ruby
39
+ use Rack::Idempotency::Kit,
40
+ store: MyStore.new,
41
+ ttl: 86_400,
42
+ header: "Idempotency-Key"
43
+ ```
44
+
45
+ ## Options
46
+ - `store` storage backend
47
+ - `ttl` (Integer) response retention in seconds
48
+ - `header` (String) idempotency header name
49
+ - `methods` (Array) HTTP methods to protect
50
+ - `wait_timeout` (Float) wait time for in-flight requests
51
+ - `lock_ttl` (Integer) in-flight lock TTL in seconds
52
+ - `max_body_bytes` (Integer) maximum body size to store
53
+
54
+ ## Store Backends
55
+ - ActiveSupport cache stores (`read`/`write`)
56
+ - Redis-style stores (`get`/`set`)
57
+
58
+ ## Behavior
59
+ - Replays stored responses for repeated idempotency keys
60
+ - Returns `409` if the same key is reused with a different request fingerprint
61
+ - Returns `409` if a request is still in flight after `wait_timeout`
62
+
63
+ ## Release
64
+ ```bash
65
+ bundle exec rake release
66
+ ```
data/Rakefile ADDED
@@ -0,0 +1,6 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "rack/idempotency/kit"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,7 @@
1
+ module Rack
2
+ module Idempotency
3
+ class Kit
4
+ VERSION = "0.1.0"
5
+ end
6
+ end
7
+ end
@@ -0,0 +1,173 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "digest"
5
+ require "rack"
6
+ require "rack/idempotency/kit/version"
7
+
8
+ module Rack
9
+ module Idempotency
10
+ class Kit
11
+ class Error < StandardError; end
12
+
13
+ DEFAULT_TTL = 86_400
14
+ DEFAULT_WAIT_TIMEOUT = 2
15
+ DEFAULT_LOCK_TTL = 10
16
+ DEFAULT_MAX_BODY_BYTES = 1_000_000
17
+
18
+ def initialize(app, store:, ttl: DEFAULT_TTL, header: "Idempotency-Key", methods: %i[post put patch],
19
+ wait_timeout: DEFAULT_WAIT_TIMEOUT, lock_ttl: DEFAULT_LOCK_TTL,
20
+ max_body_bytes: DEFAULT_MAX_BODY_BYTES)
21
+ @app = app
22
+ @store = StoreAdapter.for(store)
23
+ @ttl = ttl
24
+ @header = header
25
+ @methods = Array(methods).map { |m| m.to_s.downcase.to_sym }
26
+ @wait_timeout = wait_timeout
27
+ @lock_ttl = lock_ttl
28
+ @max_body_bytes = max_body_bytes
29
+ end
30
+
31
+ def call(env)
32
+ req = ::Rack::Request.new(env)
33
+ method = req.request_method.downcase.to_sym
34
+ return @app.call(env) unless @methods.include?(method)
35
+
36
+ key = req.get_header(header_env_key)
37
+ return @app.call(env) if key.nil? || key.strip.empty?
38
+
39
+ fingerprint = fingerprint_for(req)
40
+ stored = @store.read(key)
41
+ return replay_or_conflict(key, stored, fingerprint) if stored
42
+
43
+ unless @store.write_if_absent(key, { state: "in_flight", fingerprint: fingerprint }, ttl: @lock_ttl)
44
+ stored = @store.read(key)
45
+ return replay_or_conflict(key, stored, fingerprint) if stored
46
+ end
47
+
48
+ body = nil
49
+ status, headers, body = @app.call(env)
50
+ body_str = normalize_body(body)
51
+
52
+ if body_str.bytesize <= @max_body_bytes
53
+ record = {
54
+ state: "completed",
55
+ fingerprint: fingerprint,
56
+ status: status,
57
+ headers: headers,
58
+ body: body_str
59
+ }
60
+ @store.write(key, record, ttl: @ttl)
61
+ end
62
+
63
+ [status, headers, [body_str]]
64
+ ensure
65
+ body.close if body.respond_to?(:close)
66
+ end
67
+
68
+ private
69
+
70
+ def header_env_key
71
+ "HTTP_#{@header.upcase.tr('-', '_')}"
72
+ end
73
+
74
+ def fingerprint_for(req)
75
+ io = req.body
76
+ body = io ? io.read : ""
77
+ io.rewind if io && io.respond_to?(:rewind)
78
+ Digest::SHA256.hexdigest([req.request_method, req.path, req.query_string, body].join("\n"))
79
+ end
80
+
81
+ def replay_or_conflict(key, stored, fingerprint)
82
+ if stored[:fingerprint] != fingerprint
83
+ return [409, { "Content-Type" => "application/json" }, [JSON.dump(error: "idempotency_key_conflict")]]
84
+ end
85
+
86
+ if stored[:state] == "in_flight"
87
+ deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + @wait_timeout
88
+ loop do
89
+ sleep 0.05
90
+ stored = @store.read(key)
91
+ break unless stored && stored[:state] == "in_flight"
92
+ break if Process.clock_gettime(Process::CLOCK_MONOTONIC) >= deadline
93
+ end
94
+ end
95
+
96
+ return [409, { "Content-Type" => "application/json" }, [JSON.dump(error: "idempotency_key_in_flight")]] if stored.nil? || stored[:state] == "in_flight"
97
+
98
+ [stored[:status], stored[:headers], [stored[:body]]]
99
+ end
100
+
101
+ def normalize_body(body)
102
+ if body.respond_to?(:each)
103
+ chunks = []
104
+ body.each { |part| chunks << part }
105
+ chunks.join
106
+ else
107
+ body.to_s
108
+ end
109
+ end
110
+ end
111
+
112
+ class StoreAdapter
113
+ def self.for(store)
114
+ if store.respond_to?(:read) && store.respond_to?(:write)
115
+ ActiveSupportAdapter.new(store)
116
+ elsif store.respond_to?(:get) && store.respond_to?(:set)
117
+ RedisAdapter.new(store)
118
+ else
119
+ raise Kit::Error, "store must support read/write or get/set"
120
+ end
121
+ end
122
+ end
123
+
124
+ class ActiveSupportAdapter
125
+ def initialize(store)
126
+ @store = store
127
+ end
128
+
129
+ def read(key)
130
+ @store.read(storage_key(key))
131
+ end
132
+
133
+ def write(key, value, ttl:)
134
+ @store.write(storage_key(key), value, expires_in: ttl)
135
+ end
136
+
137
+ def write_if_absent(key, value, ttl:)
138
+ @store.write(storage_key(key), value, expires_in: ttl, unless_exist: true)
139
+ end
140
+
141
+ private
142
+
143
+ def storage_key(key)
144
+ "idempotency:#{key}"
145
+ end
146
+ end
147
+
148
+ class RedisAdapter
149
+ def initialize(redis)
150
+ @redis = redis
151
+ end
152
+
153
+ def read(key)
154
+ data = @redis.get(storage_key(key))
155
+ data ? JSON.parse(data, symbolize_names: true) : nil
156
+ end
157
+
158
+ def write(key, value, ttl:)
159
+ @redis.set(storage_key(key), JSON.dump(value), px: ttl * 1000)
160
+ end
161
+
162
+ def write_if_absent(key, value, ttl:)
163
+ @redis.set(storage_key(key), JSON.dump(value), nx: true, px: ttl * 1000)
164
+ end
165
+
166
+ private
167
+
168
+ def storage_key(key)
169
+ "idempotency:#{key}"
170
+ end
171
+ end
172
+ end
173
+ end
@@ -0,0 +1,37 @@
1
+ # frozen_string_literal: true
2
+
3
+ lib = File.expand_path("lib", __dir__)
4
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
5
+ require "rack/idempotency/kit/version"
6
+
7
+ Gem::Specification.new do |spec|
8
+ spec.name = "rack-idempotency-kit"
9
+ spec.version = Rack::Idempotency::Kit::VERSION
10
+ spec.authors = ["MounirGaiby"]
11
+ spec.email = ["mounirgaiby@gmail.com"]
12
+
13
+ spec.summary = "Stripe-style idempotency middleware for Rack and Rails APIs."
14
+ spec.description = "Provide idempotency keys with conflict detection and response replay."
15
+ spec.homepage = "https://github.com/elysium-arc/rack-idempotency-kit"
16
+ spec.license = "MIT"
17
+ spec.required_ruby_version = ">= 3.0"
18
+
19
+ spec.metadata["homepage_uri"] = spec.homepage
20
+ spec.metadata["source_code_uri"] = "https://github.com/elysium-arc/rack-idempotency-kit"
21
+ spec.metadata["changelog_uri"] = "https://github.com/elysium-arc/rack-idempotency-kit/blob/main/CHANGELOG.md"
22
+ spec.metadata["rubygems_mfa_required"] = "true"
23
+
24
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
25
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
26
+ end
27
+ spec.bindir = "bin"
28
+ spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
29
+ spec.require_paths = ["lib"]
30
+
31
+ spec.add_dependency "rack", ">= 2.2"
32
+
33
+ spec.add_development_dependency "bundler", ">= 1.17"
34
+ spec.add_development_dependency "rake", ">= 13.0"
35
+ spec.add_development_dependency "rspec", "~> 3.12"
36
+ spec.add_development_dependency "simplecov", "~> 0.22"
37
+ end
metadata ADDED
@@ -0,0 +1,134 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: rack-idempotency-kit
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - MounirGaiby
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2026-02-03 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: rack
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '2.2'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '2.2'
27
+ - !ruby/object:Gem::Dependency
28
+ name: bundler
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '1.17'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '1.17'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rake
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '13.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '13.0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: rspec
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '3.12'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '3.12'
69
+ - !ruby/object:Gem::Dependency
70
+ name: simplecov
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '0.22'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '0.22'
83
+ description: Provide idempotency keys with conflict detection and response replay.
84
+ email:
85
+ - mounirgaiby@gmail.com
86
+ executables:
87
+ - console
88
+ - setup
89
+ extensions: []
90
+ extra_rdoc_files: []
91
+ files:
92
+ - ".github/workflows/ci.yml"
93
+ - ".gitignore"
94
+ - ".rspec"
95
+ - CHANGELOG.md
96
+ - CODE_OF_CONDUCT.md
97
+ - CONTRIBUTING.md
98
+ - Gemfile
99
+ - LICENSE.txt
100
+ - README.md
101
+ - Rakefile
102
+ - bin/console
103
+ - bin/setup
104
+ - lib/rack/idempotency/kit.rb
105
+ - lib/rack/idempotency/kit/version.rb
106
+ - rack-idempotency-kit.gemspec
107
+ homepage: https://github.com/elysium-arc/rack-idempotency-kit
108
+ licenses:
109
+ - MIT
110
+ metadata:
111
+ homepage_uri: https://github.com/elysium-arc/rack-idempotency-kit
112
+ source_code_uri: https://github.com/elysium-arc/rack-idempotency-kit
113
+ changelog_uri: https://github.com/elysium-arc/rack-idempotency-kit/blob/main/CHANGELOG.md
114
+ rubygems_mfa_required: 'true'
115
+ post_install_message:
116
+ rdoc_options: []
117
+ require_paths:
118
+ - lib
119
+ required_ruby_version: !ruby/object:Gem::Requirement
120
+ requirements:
121
+ - - ">="
122
+ - !ruby/object:Gem::Version
123
+ version: '3.0'
124
+ required_rubygems_version: !ruby/object:Gem::Requirement
125
+ requirements:
126
+ - - ">="
127
+ - !ruby/object:Gem::Version
128
+ version: '0'
129
+ requirements: []
130
+ rubygems_version: 3.3.3
131
+ signing_key:
132
+ specification_version: 4
133
+ summary: Stripe-style idempotency middleware for Rack and Rails APIs.
134
+ test_files: []