keyed_coalescer 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: e42ef706d2d0304cf541dccfee4d2d9a57bb3c08d6b8141933bde3eb617f9f99
4
+ data.tar.gz: a5ddfa06045d13db2f49638cb0fd8285baccf0ccfa6a1940998538f0b6aec003
5
+ SHA512:
6
+ metadata.gz: 629bc7ddedb8b6be1dd71559741738ced6c22d4498aeb862752061dd383547508aacdb1b510d32706e62fa25701b118f2fd321727f37f3b31573316798f0aa39
7
+ data.tar.gz: be61581f9558d74320d4b09ef65119042987c5454cc3c3111e0fe7d94a5c06cfa9fb3ac8fe497ee731d78c0d4e3eb9dd6c61b016760d92c13e18e00d338c24df
data/CHANGELOG.md ADDED
@@ -0,0 +1,7 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0
4
+
5
+ - Add `KeyedCoalescer::Group#call` to share one execution and its exact result among overlapping calls for the same key.
6
+ - Give followers explicit errors when the leader raises or exits early. Reject same-key recursion and support follower-only timeouts.
7
+ - Support Ruby 3.4 and later with zero third-party runtime dependencies.
data/LICENSE-MIT ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Small Primitives
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 all
13
+ 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 THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,37 @@
1
+ # Keyed Coalescer
2
+
3
+ Share one execution and its result among overlapping Ruby calls with the same key.
4
+
5
+ ```ruby
6
+ require "keyed_coalescer"
7
+
8
+ requests = KeyedCoalescer::Group.new
9
+ user = requests.call("user:42") { api.fetch_user(42) }
10
+ ```
11
+
12
+ The first call for a key runs its block. Overlapping calls on the same group and key
13
+ share the result object. Calls with other keys can run independently. Once the first
14
+ call finishes, a later call can start new work for that key.
15
+
16
+ Requires Ruby 3.4 or later. The gem has zero third-party runtime dependencies.
17
+
18
+ ## Failures and timeouts
19
+
20
+ - If the first call raises, it receives its original exception. Waiting callers
21
+ each receive a `KeyedCoalescer::SharedCallError` whose `cause` is that exception.
22
+ If the block exits early without raising, such as with `throw`, waiting callers
23
+ receive `KeyedCoalescer::FlightAbortedError`. Subsequent callers can try again.
24
+ - Pass `timeout:` in seconds to limit how long a caller waits for existing work.
25
+ The value must be a finite nonnegative real number or `nil` for no limit.
26
+ Expiration raises `KeyedCoalescer::TimeoutError` for that caller. It leaves
27
+ the running block and other callers alone. Zero permits no waiting. A caller
28
+ that runs its own block has no execution deadline. If a result or failure has
29
+ been published when the waiter checks the deadline, the published outcome wins.
30
+ - A thread already running work for a key receives
31
+ `KeyedCoalescer::RecursiveCallError` if it calls that key again on the same group.
32
+ Callers are responsible for avoiding cycles across keys or threads.
33
+
34
+ Use stable keys with nonblocking `hash` and `eql?` methods. Callers that mutate
35
+ a shared result must coordinate those changes. The group is designed for threads
36
+ in one Ruby process. Fiber schedulers, Ractors, and abrupt thread or process
37
+ termination are outside its supported contract.
@@ -0,0 +1,103 @@
1
+ # frozen_string_literal: true
2
+
3
+ module KeyedCoalescer
4
+ class Error < StandardError; end
5
+ class SharedCallError < Error; end
6
+ class FlightAbortedError < Error; end
7
+ class RecursiveCallError < Error; end
8
+ class TimeoutError < Error; end
9
+
10
+ class Group
11
+ Flight = Struct.new(:leader, :ready, :state, :value)
12
+ MAX_WAIT_INTERVAL = 86_400
13
+ private_constant :Flight, :MAX_WAIT_INTERVAL
14
+
15
+ def initialize
16
+ @mutex = Mutex.new
17
+ @flights = {}
18
+ end
19
+
20
+ def call(key, timeout: nil)
21
+ raise ArgumentError, "a block is required" unless block_given?
22
+
23
+ timeout = timeout_seconds(timeout)
24
+ flight, leader = @mutex.synchronize do
25
+ if (existing = @flights[key])
26
+ if existing.leader.equal?(Thread.current)
27
+ raise RecursiveCallError, "the current thread is already executing a call for this key"
28
+ end
29
+
30
+ wait_for(existing, timeout)
31
+ [existing, false]
32
+ else
33
+ [@flights[key] = Flight.new(Thread.current, ConditionVariable.new, :pending, nil), true]
34
+ end
35
+ end
36
+
37
+ return shared_outcome(flight) unless leader
38
+
39
+ run(key, flight) { yield }
40
+ end
41
+
42
+ private
43
+
44
+ def run(key, flight)
45
+ state = :aborted
46
+ begin
47
+ value = yield
48
+ state = :succeeded
49
+ value
50
+ rescue Exception => error
51
+ state = :failed
52
+ value = error
53
+ raise
54
+ ensure
55
+ @mutex.synchronize do
56
+ @flights.delete(key)
57
+ flight.value = value
58
+ flight.state = state
59
+ flight.ready.broadcast
60
+ end
61
+ end
62
+ end
63
+
64
+ def wait_for(flight, timeout)
65
+ deadline = monotonic_time + timeout if timeout
66
+ while flight.state == :pending
67
+ if deadline
68
+ remaining = deadline - monotonic_time
69
+ raise TimeoutError, "timed out waiting for the shared call" if remaining <= 0
70
+
71
+ # Ruby's native wait rejects seconds outside the platform's time range.
72
+ interval = [remaining, MAX_WAIT_INTERVAL].min
73
+ end
74
+ flight.ready.wait(@mutex, interval)
75
+ end
76
+ end
77
+
78
+ def shared_outcome(flight)
79
+ case flight.state
80
+ when :succeeded
81
+ flight.value
82
+ when :failed
83
+ raise SharedCallError, "the shared call raised an exception", cause: flight.value
84
+ when :aborted
85
+ raise FlightAbortedError, "the shared call exited before returning a result", cause: nil
86
+ end
87
+ end
88
+
89
+ def timeout_seconds(timeout)
90
+ return if timeout.nil?
91
+
92
+ if timeout.is_a?(Numeric) && timeout.real? && timeout.between?(0, Float::MAX)
93
+ seconds = timeout.to_f
94
+ return seconds if seconds.finite?
95
+ end
96
+ raise ArgumentError, "timeout must be nil or a finite nonnegative real number of seconds"
97
+ end
98
+
99
+ def monotonic_time
100
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
101
+ end
102
+ end
103
+ end
metadata ADDED
@@ -0,0 +1,41 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: keyed_coalescer
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Small Primitives
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 2026-11-27 00:00:00.000000000 Z
11
+ dependencies: []
12
+ executables: []
13
+ extensions: []
14
+ extra_rdoc_files: []
15
+ files:
16
+ - CHANGELOG.md
17
+ - LICENSE-MIT
18
+ - README.md
19
+ - lib/keyed_coalescer.rb
20
+ homepage: https://github.com/smallprimitives/keyed_coalescer
21
+ licenses:
22
+ - MIT
23
+ metadata: {}
24
+ rdoc_options: []
25
+ require_paths:
26
+ - lib
27
+ required_ruby_version: !ruby/object:Gem::Requirement
28
+ requirements:
29
+ - - ">="
30
+ - !ruby/object:Gem::Version
31
+ version: '3.4'
32
+ required_rubygems_version: !ruby/object:Gem::Requirement
33
+ requirements:
34
+ - - ">="
35
+ - !ruby/object:Gem::Version
36
+ version: '0'
37
+ requirements: []
38
+ rubygems_version: 3.6.9
39
+ specification_version: 4
40
+ summary: Share the result of overlapping Ruby calls by key
41
+ test_files: []