cache-swr 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: c60797ab5d9aa428607221b71552b7cad82249c4dcf80d942093b1e2e5714d3c
4
+ data.tar.gz: 69e9ee1382e71bb9e0aa40617870737fdf70a746f7560b1086679bec5fdcb093
5
+ SHA512:
6
+ metadata.gz: c2edf4a7279bc8ebe6bf07d35b7b95a193323e971e89eb07e14e700c8c712c2855065dad5046b934b55cfefb3bc60149a8764dca8f6543667c330ece34bc608c
7
+ data.tar.gz: 9f0686d8daee7cc91eb84d4774f791d97bc369b514e0e7dc7db6d503cf61785aa6a1f1430d3df5ec102c78180e750eda13ad762f80a847f953874db1ff9f079f
@@ -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 cache-swr.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,65 @@
1
+ # Cache SWR
2
+
3
+ Server-side stale-while-revalidate caching for Rails.
4
+
5
+ ## About
6
+ Cache SWR stores a value plus two time windows: a fresh window and a stale window. Within the fresh window, values are returned immediately. Within the stale window, stale values are returned while a refresh runs in the background (or inline if you prefer).
7
+
8
+ This pattern reduces tail latency and keeps caches warm without blocking callers.
9
+
10
+ ## Use Cases
11
+ - Reduce p99 latency for expensive reads with background refreshes
12
+ - Serve dashboards and reports without blocking on cache refresh
13
+ - Keep hot data warm while avoiding request pileups
14
+ - Provide smoother cache behavior under load
15
+
16
+ ## Compatibility
17
+ - Ruby 3.0+
18
+ - ActiveSupport 6.1+
19
+ - Works with ActiveSupport cache stores
20
+ - Redis-backed stores are recommended when locking is enabled
21
+
22
+ ## Installation
23
+ ```ruby
24
+ # Gemfile
25
+
26
+ gem "cache-swr"
27
+ ```
28
+
29
+ ## Usage
30
+ ```ruby
31
+ value = Cache::SWR.fetch("expensive-key", ttl: 60, swr: 300, store: Rails.cache) do
32
+ ExpensiveQuery.call
33
+ end
34
+ ```
35
+
36
+ Rails integration adds `Rails.cache.fetch_swr`:
37
+ ```ruby
38
+ Rails.cache.fetch_swr("expensive-key", ttl: 60, swr: 300) { ExpensiveQuery.call }
39
+ ```
40
+
41
+ If you are using an in-memory store, disable locking:
42
+ ```ruby
43
+ Cache::SWR.fetch("key", ttl: 30, swr: 120, store: ActiveSupport::Cache::MemoryStore.new, lock: false) do
44
+ compute
45
+ end
46
+ ```
47
+
48
+ ## Options
49
+ - `ttl` (Integer) fresh window in seconds
50
+ - `swr` (Integer) stale window in seconds
51
+ - `refresh` (`:async`, `:sync`, or `nil`) refresh strategy
52
+ - `lock` (Boolean) enable or disable locking
53
+ - `lock_ttl` (Integer) lock expiry in seconds
54
+ - `lock_client` Redis client for custom locking
55
+ - `store` ActiveSupport cache store (defaults to `Rails.cache` when available)
56
+
57
+ ## Notes
58
+ - During the SWR window, stale values are served while a refresh runs.
59
+ - `refresh: :async` uses a background thread; choose `:sync` for deterministic refresh.
60
+ - When `lock` is enabled, the store must expose `redis` or you must provide `lock_client`.
61
+
62
+ ## Release
63
+ ```bash
64
+ bundle exec rake release
65
+ ```
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 "cache/swr"
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
data/cache-swr.gemspec ADDED
@@ -0,0 +1,38 @@
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 "cache/swr/version"
6
+
7
+ Gem::Specification.new do |spec|
8
+ spec.name = "cache-swr"
9
+ spec.version = Cache::SWR::VERSION
10
+ spec.authors = ["MounirGaiby"]
11
+ spec.email = ["mounirgaiby@gmail.com"]
12
+
13
+ spec.summary = "Stale-while-revalidate caching for Rails with background refresh."
14
+ spec.description = "Serve stale cached values while recomputing in the background to reduce tail latency."
15
+ spec.homepage = "https://github.com/elysium-arc/cache-swr"
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/cache-swr"
21
+ spec.metadata["changelog_uri"] = "https://github.com/elysium-arc/cache-swr/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 "activesupport", ">= 6.1"
32
+ spec.add_dependency "redis", ">= 4.0"
33
+
34
+ spec.add_development_dependency "bundler", ">= 1.17"
35
+ spec.add_development_dependency "rake", ">= 13.0"
36
+ spec.add_development_dependency "rspec", "~> 3.12"
37
+ spec.add_development_dependency "simplecov", "~> 0.22"
38
+ end
@@ -0,0 +1,50 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Cache
4
+ module SWR
5
+ module Lock
6
+ LUA_RELEASE = <<~LUA
7
+ if redis.call("get", KEYS[1]) == ARGV[1] then
8
+ return redis.call("del", KEYS[1])
9
+ else
10
+ return 0
11
+ end
12
+ LUA
13
+
14
+ def self.default_for(store)
15
+ return RedisLock.new(store.redis) if store.respond_to?(:redis)
16
+ raise Cache::SWR::Error, "lock_client is required when store does not expose redis"
17
+ end
18
+
19
+ class RedisLock
20
+ def initialize(redis)
21
+ @redis = redis
22
+ end
23
+
24
+ def acquire(key, token, ttl)
25
+ with_redis do |conn|
26
+ conn.set(key, token, nx: true, px: (ttl * 1000).to_i)
27
+ end
28
+ end
29
+
30
+ def release(key, token)
31
+ with_redis do |conn|
32
+ conn.eval(LUA_RELEASE, keys: [key], argv: [token])
33
+ end
34
+ rescue StandardError
35
+ false
36
+ end
37
+
38
+ private
39
+
40
+ def with_redis
41
+ if @redis.respond_to?(:with)
42
+ @redis.with { |conn| yield conn }
43
+ else
44
+ yield @redis
45
+ end
46
+ end
47
+ end
48
+ end
49
+ end
50
+ end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ # :nocov:
4
+ begin
5
+ require "rails/railtie"
6
+ rescue LoadError
7
+ end
8
+
9
+ if defined?(Rails::Railtie)
10
+ module Cache
11
+ module SWR
12
+ module StoreExtension
13
+ def fetch_swr(key, ttl:, swr:, **options, &block)
14
+ Cache::SWR.fetch(key, ttl: ttl, swr: swr, store: self, **options, &block)
15
+ end
16
+ end
17
+
18
+ class Railtie < Rails::Railtie
19
+ initializer "cache_swr.extend_cache" do
20
+ require "active_support/cache"
21
+ ::ActiveSupport::Cache::Store.include(Cache::SWR::StoreExtension)
22
+ end
23
+ end
24
+ end
25
+ end
26
+ end
27
+ # :nocov:
@@ -0,0 +1,5 @@
1
+ module Cache
2
+ module SWR
3
+ VERSION = "0.1.0"
4
+ end
5
+ end
data/lib/cache/swr.rb ADDED
@@ -0,0 +1,104 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_support/notifications"
4
+ # ActiveSupport 8.1+ expects this constant when local cache is used.
5
+ begin
6
+ require "active_support/isolated_execution_state"
7
+ rescue LoadError
8
+ end
9
+ require "cache/swr/version"
10
+ require "cache/swr/lock"
11
+
12
+ module Cache
13
+ module SWR
14
+ class Error < StandardError; end
15
+
16
+ DEFAULT_LOCK_TTL = 5
17
+
18
+ def self.fetch(key, ttl:, swr:, store: nil, refresh: :async, lock: true, lock_ttl: DEFAULT_LOCK_TTL,
19
+ lock_client: nil, &block)
20
+ raise ArgumentError, "block required" unless block
21
+
22
+ store ||= default_store
23
+ payload = store.read(key)
24
+ now = Time.now
25
+
26
+ if valid_payload?(payload)
27
+ if now < payload[:expires_at]
28
+ return payload[:value]
29
+ end
30
+
31
+ if now < payload[:stale_until]
32
+ trigger_refresh(key, ttl, swr, store, refresh, lock, lock_ttl, lock_client, &block)
33
+ return payload[:value]
34
+ end
35
+ end
36
+
37
+ compute_and_store(key, ttl, swr, store, lock_ttl, lock_client, lock: lock, &block)
38
+ end
39
+
40
+ def self.default_store
41
+ return Rails.cache if defined?(Rails) && Rails.respond_to?(:cache)
42
+ raise Error, "store is required when Rails.cache is unavailable"
43
+ end
44
+
45
+ def self.valid_payload?(payload)
46
+ payload.is_a?(Hash) && payload.key?(:value) && payload.key?(:expires_at) && payload.key?(:stale_until)
47
+ end
48
+
49
+ def self.compute_and_store(key, ttl, swr, store, lock_ttl, lock_client, lock: true)
50
+ lock_key = lock_key_for(key)
51
+ acquired = false
52
+ if lock
53
+ lock_client ||= Lock.default_for(store) if lock_client.nil?
54
+ if lock_client
55
+ acquired = lock_client.acquire(lock_key, "compute", lock_ttl)
56
+ unless acquired
57
+ existing = store.read(key)
58
+ return existing[:value] if valid_payload?(existing)
59
+ end
60
+ end
61
+ end
62
+
63
+ value = yield
64
+ payload = {
65
+ value: value,
66
+ expires_at: Time.now + ttl,
67
+ stale_until: Time.now + ttl + swr
68
+ }
69
+ store.write(key, payload, expires_in: ttl + swr)
70
+ value
71
+ ensure
72
+ lock_client.release(lock_key, "compute") if lock_client && acquired
73
+ end
74
+
75
+ def self.trigger_refresh(key, ttl, swr, store, refresh, lock, lock_ttl, lock_client, &block)
76
+ return if refresh.nil?
77
+
78
+ lock_client ||= Lock.default_for(store) if lock && lock_client.nil?
79
+ lock_key = lock_key_for(key)
80
+
81
+ acquired = false
82
+ if lock && lock_client
83
+ acquired = lock_client.acquire(lock_key, "refresh", lock_ttl)
84
+ return unless acquired
85
+ end
86
+
87
+ if refresh == :async
88
+ Thread.new do
89
+ compute_and_store(key, ttl, swr, store, lock_ttl, lock_client, lock: lock, &block)
90
+ end
91
+ else
92
+ compute_and_store(key, ttl, swr, store, lock_ttl, lock_client, lock: lock, &block)
93
+ end
94
+ ensure
95
+ lock_client.release(lock_key, "refresh") if lock_client && acquired
96
+ end
97
+
98
+ def self.lock_key_for(key)
99
+ "cache-swr:lock:#{key}"
100
+ end
101
+ end
102
+ end
103
+
104
+ require "cache/swr/railtie"
metadata ADDED
@@ -0,0 +1,151 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: cache-swr
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: activesupport
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '6.1'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '6.1'
27
+ - !ruby/object:Gem::Dependency
28
+ name: redis
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '4.0'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '4.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: bundler
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '1.17'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '1.17'
55
+ - !ruby/object:Gem::Dependency
56
+ name: rake
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: '13.0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: '13.0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: rspec
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '3.12'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '3.12'
83
+ - !ruby/object:Gem::Dependency
84
+ name: simplecov
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - "~>"
88
+ - !ruby/object:Gem::Version
89
+ version: '0.22'
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - "~>"
95
+ - !ruby/object:Gem::Version
96
+ version: '0.22'
97
+ description: Serve stale cached values while recomputing in the background to reduce
98
+ tail latency.
99
+ email:
100
+ - mounirgaiby@gmail.com
101
+ executables:
102
+ - console
103
+ - setup
104
+ extensions: []
105
+ extra_rdoc_files: []
106
+ files:
107
+ - ".github/workflows/ci.yml"
108
+ - ".gitignore"
109
+ - ".rspec"
110
+ - CHANGELOG.md
111
+ - CODE_OF_CONDUCT.md
112
+ - CONTRIBUTING.md
113
+ - Gemfile
114
+ - LICENSE.txt
115
+ - README.md
116
+ - Rakefile
117
+ - bin/console
118
+ - bin/setup
119
+ - cache-swr.gemspec
120
+ - lib/cache/swr.rb
121
+ - lib/cache/swr/lock.rb
122
+ - lib/cache/swr/railtie.rb
123
+ - lib/cache/swr/version.rb
124
+ homepage: https://github.com/elysium-arc/cache-swr
125
+ licenses:
126
+ - MIT
127
+ metadata:
128
+ homepage_uri: https://github.com/elysium-arc/cache-swr
129
+ source_code_uri: https://github.com/elysium-arc/cache-swr
130
+ changelog_uri: https://github.com/elysium-arc/cache-swr/blob/main/CHANGELOG.md
131
+ rubygems_mfa_required: 'true'
132
+ post_install_message:
133
+ rdoc_options: []
134
+ require_paths:
135
+ - lib
136
+ required_ruby_version: !ruby/object:Gem::Requirement
137
+ requirements:
138
+ - - ">="
139
+ - !ruby/object:Gem::Version
140
+ version: '3.0'
141
+ required_rubygems_version: !ruby/object:Gem::Requirement
142
+ requirements:
143
+ - - ">="
144
+ - !ruby/object:Gem::Version
145
+ version: '0'
146
+ requirements: []
147
+ rubygems_version: 3.3.3
148
+ signing_key:
149
+ specification_version: 4
150
+ summary: Stale-while-revalidate caching for Rails with background refresh.
151
+ test_files: []