weathercock 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: 69167dba72d21575ef52f1c799423a78ff435b8fa42a8ea60eac368a1dbe680b
4
+ data.tar.gz: 586f93c2471f63dc178de81ee96c3d39dd205c41ba69984535d2d14012b04f2c
5
+ SHA512:
6
+ metadata.gz: 362d33770a45bbf057ee4907dd978ce032444e134972f841dc903c52f7df2511aa2c5556abfe1d31008b6e10b0841c0b98ab8ae0aabc34564af1cbd7fbce642c
7
+ data.tar.gz: d4d6f1434f014a87a0906732960217ba1ebbbe9d8ab3660e70544da151a856696f08fa2b07f938ced057440a6ab5d1677eec21ae4820a3ecac735bb2a5950d2f
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 Takafumi ONAKA
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,100 @@
1
+ # Weathercock
2
+
3
+ Hit counter and popularity tracking using Valkey/Redis Sorted Sets.
4
+
5
+ Records hit counts for arbitrary resources across hourly, daily, and monthly time windows. Aggregates them with `ZUNIONSTORE` to build popularity rankings.
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ bundle add weathercock
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ ### Configuration
16
+
17
+ ```ruby
18
+ Weathercock.configure do |c|
19
+ c.redis = RedisClient.new(host: "localhost", port: 6379)
20
+ c.namespace = "myapp" # default: "weathercock"
21
+ end
22
+ ```
23
+
24
+ ### Tracking
25
+
26
+ Include `Weathercock::Scorable` in any class that has an `id`:
27
+
28
+ ```ruby
29
+ class Article
30
+ include Weathercock::Scorable
31
+ end
32
+ ```
33
+
34
+ Record a hit:
35
+
36
+ ```ruby
37
+ article.hit(:views)
38
+ article.hit(:views, increment: 5)
39
+ ```
40
+
41
+ Each call writes to four Sorted Sets:
42
+
43
+ ```
44
+ myapp:article:views:total # all-time (no TTL)
45
+ myapp:article:views:2026-04-15-09 # hourly (TTL: 3 days)
46
+ myapp:article:views:2026-04-15 # daily (TTL: 90 days)
47
+ myapp:article:views:2026-04 # monthly (TTL: 3 years)
48
+ ```
49
+
50
+ ### Ranking
51
+
52
+ `top` returns IDs ordered by total score. Without a window, it reads from the all-time key. With a window, it aggregates via `ZUNIONSTORE`.
53
+
54
+ ```ruby
55
+ # All-time ranking
56
+ Article.top(:views)
57
+ # => ["42", "7", "133", ...]
58
+
59
+ # Top article IDs by views over the last 7 days
60
+ Article.top(:views, days: 7)
61
+
62
+ # Using hours or months
63
+ Article.top(:views, hours: 24)
64
+ Article.top(:views, months: 3)
65
+
66
+ # Exponential time decay (recent hits weighted higher)
67
+ Article.top(:views, days: 7, decay_factor: 0.9)
68
+ ```
69
+
70
+ ### Counting
71
+
72
+ Get the hit count for a single instance:
73
+
74
+ ```ruby
75
+ article.hit_count(:views) # all-time
76
+ article.hit_count(:views, days: 7)
77
+ # => 42
78
+ ```
79
+
80
+ Get hit counts for multiple instances at once (useful for list views):
81
+
82
+ ```ruby
83
+ Article.hit_counts(:views, ids: [1, 2, 3]) # all-time
84
+ Article.hit_counts(:views, ids: [1, 2, 3], days: 7)
85
+ # => {"1" => 42, "2" => 15, "3" => 7}
86
+ ```
87
+
88
+ ## Development
89
+
90
+ 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.
91
+
92
+ 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 the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
93
+
94
+ ## Contributing
95
+
96
+ Bug reports and pull requests are welcome on GitHub at https://github.com/onk/weathercock.
97
+
98
+ ## License
99
+
100
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
data/compose.yaml ADDED
@@ -0,0 +1,5 @@
1
+ services:
2
+ valkey:
3
+ image: valkey/valkey:9.0-alpine@sha256:e1095c6c76ee982cb2d1e07edbb7fb2a53606630a1d810d5a47c9f646b708bf5
4
+ ports:
5
+ - "6379:6379"
@@ -0,0 +1,101 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "date"
4
+ require_relative "../weathercock"
5
+
6
+ module Weathercock
7
+ module Scorable
8
+ WEATHERCOCK_BUCKET_TTLS = {
9
+ hours: 3 * 24 * 3600,
10
+ days: 3 * 30 * 86400,
11
+ months: 3 * 12 * 30 * 86400
12
+ }.freeze
13
+
14
+ def self.included(base)
15
+ base.extend(ClassMethods)
16
+ end
17
+
18
+ module ClassMethods
19
+ def top(event, decay_factor: nil, **window)
20
+ return Weathercock.config.redis.call("ZRANGE", "#{weathercock_base_key(event)}:total", 0, -1, "REV") if window.empty?
21
+
22
+ dest = weathercock_union(event, window, decay_factor: decay_factor)
23
+ Weathercock.config.redis.call("ZRANGE", dest, 0, -1, "REV")
24
+ end
25
+
26
+ def hit_counts(event, ids:, **window)
27
+ redis = Weathercock.config.redis
28
+ dest = window.empty? ? "#{weathercock_base_key(event)}:total" : weathercock_union(event, window)
29
+ ids.to_h { |id| [id.to_s, (redis.call("ZSCORE", dest, id.to_s) || "0").to_i] }
30
+ end
31
+
32
+ def weathercock_base_key(event)
33
+ "#{Weathercock.config.namespace}:#{name.gsub("::", "_").downcase}:#{event}"
34
+ end
35
+
36
+ private
37
+
38
+ def weathercock_union(event, window, decay_factor: nil)
39
+ redis = Weathercock.config.redis
40
+ base = weathercock_base_key(event)
41
+ type, count = window.first
42
+ keys = weathercock_window_keys(base, type, count)
43
+
44
+ dest = "#{base}:top:#{type}:#{count}"
45
+ weights = decay_factor ? count.times.map { |i| (decay_factor**i).round(10) } : nil
46
+ zunionstore_args = ["ZUNIONSTORE", dest, keys.size, *keys]
47
+ zunionstore_args += ["WEIGHTS", *weights] if weights
48
+ redis.call(*zunionstore_args)
49
+ redis.call("EXPIRE", dest, 900)
50
+ dest
51
+ end
52
+
53
+ def weathercock_window_keys(base, type, count)
54
+ now = Time.now
55
+ case type
56
+ when :hours
57
+ count.times.map { |i| weathercock_bucket_key(base, type, now - (i * 3600)) }
58
+ when :days
59
+ count.times.map { |i| weathercock_bucket_key(base, type, now - (i * 86400)) }
60
+ when :months
61
+ d = Date.new(now.year, now.month)
62
+ count.times.map { |i| weathercock_bucket_key(base, type, d << i) }
63
+ end
64
+ end
65
+
66
+ def weathercock_bucket_key(base, type, time)
67
+ case type
68
+ when :hours then "#{base}:#{time.strftime("%Y-%m-%d-%H")}"
69
+ when :days then "#{base}:#{time.strftime("%Y-%m-%d")}"
70
+ when :months then "#{base}:#{time.strftime("%Y-%m")}"
71
+ end
72
+ end
73
+ end
74
+
75
+ def hit(event, increment: 1)
76
+ now = Time.now
77
+ redis = Weathercock.config.redis
78
+ base = self.class.weathercock_base_key(event)
79
+
80
+ redis.pipelined do |p|
81
+ p.call("ZINCRBY", "#{base}:total", increment, id.to_s)
82
+ WEATHERCOCK_BUCKET_TTLS.each do |type, ttl|
83
+ key = self.class.send(:weathercock_bucket_key, base, type, now)
84
+ p.call("ZINCRBY", key, increment, id.to_s)
85
+ p.call("EXPIRE", key, ttl)
86
+ end
87
+ end
88
+ end
89
+
90
+ def hit_count(event, **window)
91
+ if window.empty?
92
+ score = Weathercock.config.redis.call("ZSCORE", "#{self.class.weathercock_base_key(event)}:total", id.to_s)
93
+ return score ? score.to_i : 0
94
+ end
95
+
96
+ dest = self.class.send(:weathercock_union, event, window)
97
+ score = Weathercock.config.redis.call("ZSCORE", dest, id.to_s)
98
+ score ? score.to_i : 0
99
+ end
100
+ end
101
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Weathercock
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,25 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "weathercock/version"
4
+
5
+ module Weathercock
6
+ class Error < StandardError; end
7
+
8
+ class Config
9
+ attr_accessor :namespace, :redis
10
+
11
+ def initialize
12
+ @namespace = "weathercock"
13
+ end
14
+ end
15
+
16
+ class << self
17
+ def configure
18
+ yield config
19
+ end
20
+
21
+ def config
22
+ @config ||= Config.new
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,4 @@
1
+ module Weathercock
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,80 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: weathercock
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Takafumi ONAKA
8
+ bindir: exe
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: redis-client
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - ">="
17
+ - !ruby/object:Gem::Version
18
+ version: '0'
19
+ type: :development
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - ">="
24
+ - !ruby/object:Gem::Version
25
+ version: '0'
26
+ - !ruby/object:Gem::Dependency
27
+ name: timecop
28
+ requirement: !ruby/object:Gem::Requirement
29
+ requirements:
30
+ - - ">="
31
+ - !ruby/object:Gem::Version
32
+ version: '0'
33
+ type: :development
34
+ prerelease: false
35
+ version_requirements: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - ">="
38
+ - !ruby/object:Gem::Version
39
+ version: '0'
40
+ description: Track hit counts for arbitrary resources and aggregate them with zunionstore
41
+ to build popularity rankings across time windows.
42
+ email:
43
+ - takafumi.onaka@gmail.com
44
+ executables: []
45
+ extensions: []
46
+ extra_rdoc_files: []
47
+ files:
48
+ - LICENSE.txt
49
+ - README.md
50
+ - Rakefile
51
+ - compose.yaml
52
+ - lib/weathercock.rb
53
+ - lib/weathercock/scorable.rb
54
+ - lib/weathercock/version.rb
55
+ - sig/weathercock.rbs
56
+ homepage: https://github.com/onk/weathercock
57
+ licenses:
58
+ - MIT
59
+ metadata:
60
+ homepage_uri: https://github.com/onk/weathercock
61
+ source_code_uri: https://github.com/onk/weathercock
62
+ rubygems_mfa_required: 'true'
63
+ rdoc_options: []
64
+ require_paths:
65
+ - lib
66
+ required_ruby_version: !ruby/object:Gem::Requirement
67
+ requirements:
68
+ - - ">="
69
+ - !ruby/object:Gem::Version
70
+ version: 3.2.0
71
+ required_rubygems_version: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - ">="
74
+ - !ruby/object:Gem::Version
75
+ version: '0'
76
+ requirements: []
77
+ rubygems_version: 4.0.6
78
+ specification_version: 4
79
+ summary: Hit counter and popularity tracking using Valkey/Redis Sorted Sets
80
+ test_files: []