Class: Agent::Lock::Store::RedisStore
- Inherits:
-
Object
- Object
- Agent::Lock::Store::RedisStore
- Defined in:
- lib/agent/lock/store/redis_store.rb
Overview
The same locks in a local Redis, for the machines that already run one.
Redis buys two things the filesystem cannot: SET NX is atomic across
machines rather than only across processes on one, and a TTL can expire
an abandoned lock without anybody having to reason about whether its
holder is still alive. It costs the thing that makes the file store
pleasant, which is that you can cat a lock, so the value stored is the
same markdown document either way.
The TTL is opt-in: AGENT_LOCK_TTL_SECONDS defaults to 0, and by default
nothing expires. When it is set, #create starts it and nothing pushes
it back: #update writes with keepttl, so a note counts as a touch
for the stale window and still leaves the expiry where it was.
Picked with AGENT_LOCK_BACKEND=redis, or by default when one answers on REDIS_URL, or failing that on the local default. See Store's moduledoc for how that default is decided.
Constant Summary collapse
- LOCAL_URL =
Tried after REDIS_URL, or alone when it is unset.
"redis://127.0.0.1:6379/0"- MUTEX_LEASE_MS =
How long the store mutex outlives a holder that died holding it. A claim's critical section is a SCAN and one SET, so ten seconds is somebody gone, not somebody busy.
10_000- MUTEX_TIMEOUT =
Seconds to wait for the mutex. Longer than the lease, so that a crashed holder is waited out rather than reported.
15- LEASE_LOST =
The error raised when the mutex expired under a running claim.
"the lock store's mutex lease (#{MUTEX_LEASE_MS}ms) ran out before the claim finished, " \ "so another process may have claimed an overlapping scope: check the listing".freeze
- RELEASE =
Compare-and-delete: release the mutex only while it still holds our token, so a process whose lease ran out cannot free somebody else's.
<<~LUA if redis.call("GET", KEYS[1]) == ARGV[1] then return redis.call("DEL", KEYS[1]) end return 0 LUA
Instance Attribute Summary collapse
-
#client ⇒ Object
readonly
Returns the value of attribute client.
-
#tree ⇒ Object
readonly
Returns the value of attribute tree.
Class Method Summary collapse
-
.at(tree, url) ⇒ RedisStore
A store on one named Redis, and no other: no
REDIS_URL, no local default, no memoized client. -
.candidate_urls ⇒ Array<String>
Where to look, in order:
REDIS_URLwhen set, then the local default. -
.create_client ⇒ Array(Redis, nil), Array(nil, Exception)
Tries each candidate URL in turn and keeps the first that answers.
-
.found(tree) ⇒ RedisStore
A store on the first Redis the search finds.
-
.open(url = nil) ⇒ ::Redis
A client for a command that reads every repository in one Redis, rather than the locks of one checkout.
-
.reason(error) ⇒ String
redis-rb words its own errors without the password; anything else (a URL that does not parse) may quote the URL back.
-
.reset! ⇒ void
Drops the memoized client, so the next
create_clientprobes again. -
.safe(url) ⇒ String
A URL fit to print: an error lands in transcripts and logs, and a Redis URL may carry a password.
-
.scrub(text) ⇒ String
The same for a sentence that may quote a URL: the last net under an error somebody else worded.
-
.url ⇒ String
The URL of the Redis actually in use, once one has answered, or the first one that will be tried before then.
-
.version_tag ⇒ String
v4from4.0.3.
Instance Method Summary collapse
-
#all ⇒ Array<Record>
SCAN rather than KEYS: this runs on whatever Redis the machine already has, which may be somebody's shared development instance, and KEYS blocks the server for the length of the scan.
-
#backend ⇒ String
What the tree's backend marker says for this store.
-
#bound ⇒ Array<Record>
Only the locks taken on this host in a worktree of this checkout.
-
#create(record) ⇒ Boolean
Named to match the Store interface FileSystemStore shares: an action with a boolean outcome, not a pure predicate.
- #delete(record) ⇒ void
-
#describe ⇒ String
The store by name, its URL without any password.
- #find(scope) ⇒ Record?
-
#initialize(tree, client: nil, url: nil) ⇒ RedisStore
constructor
A new instance of RedisStore.
-
#inspect ⇒ String
The default would print
@urlas given, password and all. -
#key_for(id, lock_key = tree.lock_key) ⇒ String
The branch the id was taken on decides the key, not the branch this checkout is on now.
-
#mutex_key ⇒ String
One per repository, shared by every branch.
-
#namespace ⇒ String
Where this checkout writes.
-
#synchronize { ... } ⇒ Object
Runs the block with every other process in this store shut out, so a scan for conflicts and the write it justifies cannot be interleaved.
- #update(record) ⇒ void
Constructor Details
#initialize(tree, client: nil, url: nil) ⇒ RedisStore
Returns a new instance of RedisStore.
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
# File 'lib/agent/lock/store/redis_store.rb', line 63 def initialize(tree, client: nil, url: nil) @tree = tree @url = url if client.nil? client, error = self.class.create_client raise(error) if client.nil? && error @client = client if client else @client = client end raise "no functional Redis client could be created for #{self.class.safe(self.url)}" unless @client end |
Instance Attribute Details
#client ⇒ Object (readonly)
Returns the value of attribute client.
56 57 58 |
# File 'lib/agent/lock/store/redis_store.rb', line 56 def client @client end |
#tree ⇒ Object (readonly)
Returns the value of attribute tree.
56 57 58 |
# File 'lib/agent/lock/store/redis_store.rb', line 56 def tree @tree end |
Class Method Details
.at(tree, url) ⇒ RedisStore
A store on one named Redis, and no other: no REDIS_URL, no
local default, no memoized client.
299 300 301 302 303 304 |
# File 'lib/agent/lock/store/redis_store.rb', line 299 def at(tree, url) client, error = connect(url) raise Store::Unreachable, "cannot use Redis at #{safe(url)}: #{reason(error)}" unless client new(tree, client: client, url: url) end |
.candidate_urls ⇒ Array<String>
Where to look, in order: REDIS_URL when set, then the local
default. A REDIS_URL that nobody answers on is not the end of
the search, because the usual reason it is set is a shared
instance that is sometimes down, and a local one is still better
than falling all the way back to the filesystem.
386 387 388 389 |
# File 'lib/agent/lock/store/redis_store.rb', line 386 def candidate_urls configured = ENV["REDIS_URL"].to_s.strip [configured.empty? ? nil : configured, LOCAL_URL].compact.uniq end |
.create_client ⇒ Array(Redis, nil), Array(nil, Exception)
Tries each candidate URL in turn and keeps the first that answers.
395 396 397 398 399 400 401 402 403 404 405 406 407 408 |
# File 'lib/agent/lock/store/redis_store.rb', line 395 def create_client return [@client, nil] if @client error = nil candidate_urls.each do |candidate| client, error = connect(candidate) next unless client @url = candidate @client = client return [@client, nil] end [nil, error] end |
.found(tree) ⇒ RedisStore
A store on the first Redis the search finds.
311 312 313 314 315 316 317 |
# File 'lib/agent/lock/store/redis_store.rb', line 311 def found(tree) client, error = create_client return new(tree, client: client) if client raise Store::Unreachable, "no Redis answered on #{candidate_urls.map { |u| safe(u) }.join(" or ")}: " \ "#{reason(error)}" end |
.open(url = nil) ⇒ ::Redis
A client for a command that reads every repository in one Redis, rather than the locks of one checkout. An explicit URL is tried alone. Without one, create_client searches as usual.
326 327 328 329 330 331 332 |
# File 'lib/agent/lock/store/redis_store.rb', line 326 def open(url = nil) client, error = url ? connect(url) : create_client return client if client where = url ? safe(url) : candidate_urls.map { |candidate| safe(candidate) }.join(" or ") raise Store::Unreachable, "cannot use Redis at #{where}: #{reason(error)}" end |
.reason(error) ⇒ String
redis-rb words its own errors without the password; anything else (a URL that does not parse) may quote the URL back.
371 |
# File 'lib/agent/lock/store/redis_store.rb', line 371 def reason(error) = error.is_a?(::Redis::BaseError) ? error. : error.class.name |
.reset! ⇒ void
This method returns an undefined value.
Drops the memoized client, so the next create_client probes again.
413 414 415 416 |
# File 'lib/agent/lock/store/redis_store.rb', line 413 def reset! @client = nil @url = nil end |
.safe(url) ⇒ String
A URL fit to print: an error lands in transcripts and logs, and
a Redis URL may carry a password. Everything up to the last @
goes, because a password that was never percent-encoded may hold
a space, a / or an @ of its own. Only a scheme:// in front
is kept: a mistyped rey:secret@host has no scheme to trust, and
is the URL most likely to end up in an error.
343 344 345 346 347 348 349 |
# File 'lib/agent/lock/store/redis_store.rb', line 343 def safe(url) text = url.to_s at = text.rindex("@") return text unless at "#{text[%r{\A[a-z][a-z0-9+.-]*://}i]}***#{text[at..]}" end |
.scrub(text) ⇒ String
The same for a sentence that may quote a URL: the last net under
an error somebody else worded. A sentence does not say where an
unencoded password ends, so everything from the first :// to
the last @ goes. That can take a second URL or a few words with
it; a net that keeps the words and lets a password through is
the worse one.
360 |
# File 'lib/agent/lock/store/redis_store.rb', line 360 def scrub(text) = text.to_s.sub(%r{(?<=://).*@}m, "***@") |
.url ⇒ String
The URL of the Redis actually in use, once one has answered, or the first one that will be tried before then.
377 |
# File 'lib/agent/lock/store/redis_store.rb', line 377 def url = @url || candidate_urls.first |
Instance Method Details
#all ⇒ Array<Record>
SCAN rather than KEYS: this runs on whatever Redis the machine already has, which may be somebody's shared development instance, and KEYS blocks the server for the length of the scan.
106 107 108 109 |
# File 'lib/agent/lock/store/redis_store.rb', line 106 def all keys = client.scan_each(match: scan_match).to_a.uniq.sort keys.filter_map { |key| parse(client.get(key), key) } end |
#backend ⇒ String
Returns what the tree's backend marker says for this store.
83 |
# File 'lib/agent/lock/store/redis_store.rb', line 83 def backend = "redis" |
#bound ⇒ Array<Record>
Only the locks taken on this host in a worktree of this checkout. The label spans every clone of the repository on every machine, and each of those has a backend marker of its own, which a switch here does not touch.
91 92 93 94 |
# File 'lib/agent/lock/store/redis_store.rb', line 91 def bound roots = tree.worktree_roots all.select { |record| record.taken_in?(roots) } end |
#create(record) ⇒ Boolean
Named to match the Store interface FileSystemStore shares: an action with a boolean outcome, not a pure predicate.
rubocop:disable-next Naming/PredicateMethod
162 163 164 165 166 |
# File 'lib/agent/lock/store/redis_store.rb', line 162 def create(record) args = { nx: true } args[:ex] = ttl_seconds if ttl_seconds.positive? !!client.set(key_for(record.id, record.lock_key), record.to_markdown, **args) end |
#delete(record) ⇒ void
This method returns an undefined value.
174 |
# File 'lib/agent/lock/store/redis_store.rb', line 174 def delete(record) = client.del(key_for(record.id, record.lock_key)) |
#describe ⇒ String
Returns the store by name, its URL without any password.
80 |
# File 'lib/agent/lock/store/redis_store.rb', line 80 def describe = "redis #{self.class.safe(url)} (#{namespace})" |
#find(scope) ⇒ Record?
154 |
# File 'lib/agent/lock/store/redis_store.rb', line 154 def find(scope) = parse(client.get(key_for(Record.id_for(tree, scope))), nil) |
#inspect ⇒ String
The default would print @url as given, password and all.
99 |
# File 'lib/agent/lock/store/redis_store.rb', line 99 def inspect = "#<#{self.class.name} #{describe}>" |
#key_for(id, lock_key = tree.lock_key) ⇒ String
The branch the id was taken on decides the key, not the branch this checkout is on now. A session that switched branches after claiming still has to release the record it wrote, and that record's lock key names the branch it was taken on.
184 |
# File 'lib/agent/lock/store/redis_store.rb', line 184 def key_for(id, lock_key = tree.lock_key) = "#{namespace_for(lock_key)}:#{id}" |
#mutex_key ⇒ String
One per repository, shared by every branch. A checkout that switched
branches still writes the lock it took on the old one, and that write
has to shut out whoever is on the branch it left. all scans
<label>-<hex>*, so the mutex sits beside that pattern rather than
inside it, or every scan would read the mutex back as a lock.
150 |
# File 'lib/agent/lock/store/redis_store.rb', line 150 def mutex_key = "#{label}-mutex" |
#namespace ⇒ String
Where this checkout writes. Every branch of the repository has its own, under one readable label, and #all reads them all.
190 |
# File 'lib/agent/lock/store/redis_store.rb', line 190 def namespace = namespace_for(tree.lock_key) |
#synchronize { ... } ⇒ Object
Runs the block with every other process in this store shut out, so a
scan for conflicts and the write it justifies cannot be interleaved.
SET NX alone settles a race for one scope, but lib/** and
lib/a1.rb are two keys, and two agents that both scanned an empty
namespace before either wrote both won.
The mutex is a key set with NX to a token only this call knows, and leased rather than held: a holder that dies mid-claim cannot release it, so the lease does, within MUTEX_LEASE_MS. The wait for it is bounded, and longer than the lease, so a crashed holder costs the next agent a pause and never an error.
Not re-entrant. A nested call waits on its own mutex until the lease frees it, and the outer call then finds it gone and raises.
130 131 132 133 134 135 136 137 138 139 140 141 |
# File 'lib/agent/lock/store/redis_store.rb', line 130 def synchronize token = SecureRandom.hex(16) wait_for(token) begin outcome = yield ensure released = release(token) end raise Error, LEASE_LOST unless released outcome end |
#update(record) ⇒ void
This method returns an undefined value.
170 |
# File 'lib/agent/lock/store/redis_store.rb', line 170 def update(record) = client.set(key_for(record.id, record.lock_key), record.to_markdown, keepttl: true) |