agent-lock 3.1.0 → 4.0.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 +4 -4
- data/.gitleaks.toml +23 -0
- data/AGENTS.md +11 -17
- data/CHANGELOG.md +124 -3
- data/README.md +496 -100
- data/Rakefile +13 -6
- data/docs/badges/coverage_badge.svg +21 -0
- data/docs/badges/yardoc.svg +1 -0
- data/docs/img/alock-sequence.avif +0 -0
- data/docs/img/alock-sequence.md +29 -0
- data/docs/img/alock-sequence.png +0 -0
- data/lefthook.yml +39 -0
- data/lib/agent/lock/cli/commands/acquire.rb +25 -19
- data/lib/agent/lock/cli/commands/base.rb +59 -23
- data/lib/agent/lock/cli/commands/break.rb +12 -7
- data/lib/agent/lock/cli/commands/check.rb +10 -9
- data/lib/agent/lock/cli/commands/completion.rb +15 -32
- data/lib/agent/lock/cli/commands/list.rb +46 -37
- data/lib/agent/lock/cli/commands/listing.rb +170 -0
- data/lib/agent/lock/cli/commands/mine.rb +7 -5
- data/lib/agent/lock/cli/commands/note.rb +13 -9
- data/lib/agent/lock/cli/commands/release.rb +10 -7
- data/lib/agent/lock/cli/commands/release_all.rb +7 -5
- data/lib/agent/lock/cli/commands/resume.rb +13 -7
- data/lib/agent/lock/cli/commands/show.rb +172 -0
- data/lib/agent/lock/cli/commands/skills.rb +28 -19
- data/lib/agent/lock/cli/commands/switch_backend.rb +205 -0
- data/lib/agent/lock/cli/commands/tree_command.rb +72 -0
- data/lib/agent/lock/cli/commands/version.rb +2 -1
- data/lib/agent/lock/cli/commands/whoami.rb +7 -3
- data/lib/agent/lock/cli.rb +63 -19
- data/lib/agent/lock/error.rb +52 -1
- data/lib/agent/lock/facade/async.rb +83 -0
- data/lib/agent/lock/facade/backend.rb +133 -0
- data/lib/agent/lock/facade/memo.rb +30 -0
- data/lib/agent/lock/facade/refusal.rb +78 -0
- data/lib/agent/lock/facade/session.rb +142 -0
- data/lib/agent/lock/facade/strategies.rb +36 -0
- data/lib/agent/lock/facade.rb +369 -0
- data/lib/agent/lock/freeze.rb +59 -5
- data/lib/agent/lock/identity.rb +63 -5
- data/lib/agent/lock/launcher.rb +17 -1
- data/lib/agent/lock/manager/enforcement.rb +98 -0
- data/lib/agent/lock/manager/switch.rb +91 -0
- data/lib/agent/lock/manager/thaw.rb +68 -0
- data/lib/agent/lock/manager.rb +176 -79
- data/lib/agent/lock/process_info/legacy_start.rb +60 -0
- data/lib/agent/lock/process_info.rb +42 -11
- data/lib/agent/lock/record.rb +124 -10
- data/lib/agent/lock/scope.rb +49 -4
- data/lib/agent/lock/skill.rb +14 -10
- data/lib/agent/lock/store/backend_name.rb +62 -0
- data/lib/agent/lock/store/file_system_store.rb +20 -1
- data/lib/agent/lock/store/redis_index.rb +179 -0
- data/lib/agent/lock/store/redis_store.rb +191 -33
- data/lib/agent/lock/store.rb +180 -19
- data/lib/agent/lock/text.rb +62 -0
- data/lib/agent/lock/tree.rb +143 -16
- data/lib/agent/lock/version.rb +2 -1
- data/lib/agent/lock.rb +3 -0
- data/skills/agent-lock/SKILL.md +75 -10
- metadata +41 -22
- data/justfile +0 -127
- data/sig/agent/lock.rbs +0 -6
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "socket"
|
|
4
|
+
require_relative "redis_store"
|
|
5
|
+
require_relative "../record"
|
|
6
|
+
|
|
7
|
+
module Agent
|
|
8
|
+
module Lock
|
|
9
|
+
module Store
|
|
10
|
+
# Every lock in one Redis, across repositories. The file store has no
|
|
11
|
+
# equivalent: its records live inside one checkout's `.git` and cannot
|
|
12
|
+
# be listed from anywhere else.
|
|
13
|
+
#
|
|
14
|
+
# Keys are the ones {RedisStore} writes, `[alock-<version>-<slug>]-<sha256>:<id>`.
|
|
15
|
+
# The mutex beside them is not a lock and is skipped. Anything still
|
|
16
|
+
# under the old `agent-lock:` prefix is counted, never read.
|
|
17
|
+
class RedisIndex
|
|
18
|
+
# What every key started with before the label named the repository.
|
|
19
|
+
# The old mutex was `agent-lock-mutex:`, so it does not match.
|
|
20
|
+
LEGACY_PREFIX = "agent-lock:"
|
|
21
|
+
|
|
22
|
+
# A lock key. The slug is everything after `alock-v<major>-`
|
|
23
|
+
# up to the closing bracket, which for GitHub is `owner/name`.
|
|
24
|
+
LOCK_KEY = /\A\[(?<label>alock-v\d+-(?<slug>[^\]]+))\]-(?<digest>[0-9a-f]{64}):(?<id>.+)\z/
|
|
25
|
+
|
|
26
|
+
# One row of `show repos`.
|
|
27
|
+
#
|
|
28
|
+
# @!attribute [r] namespace
|
|
29
|
+
# @return [String] `alock-v4-kigster/laser-cutter`, brackets aside
|
|
30
|
+
# @!attribute [r] count
|
|
31
|
+
# @return [Integer] locks under that label, every branch included
|
|
32
|
+
# @!attribute [r] bytes
|
|
33
|
+
# @return [Integer, nil] their `MEMORY USAGE` summed, nil when Redis
|
|
34
|
+
# cannot say
|
|
35
|
+
Repo = Data.define(:namespace, :count, :bytes)
|
|
36
|
+
|
|
37
|
+
# One lock, still carrying the record {RedisStore} wrote.
|
|
38
|
+
#
|
|
39
|
+
# @!attribute [r] record
|
|
40
|
+
# @return [Record]
|
|
41
|
+
# @!attribute [r] namespace
|
|
42
|
+
# @return [String] the same label as {Repo#namespace}
|
|
43
|
+
Lock = Data.define(:record, :namespace)
|
|
44
|
+
|
|
45
|
+
# @param client [::Redis]
|
|
46
|
+
def initialize(client)
|
|
47
|
+
@client = client
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
# @param url [String, nil] nil searches the way {RedisStore.open} does
|
|
51
|
+
# @return [RedisIndex]
|
|
52
|
+
# @raise [Store::Unreachable]
|
|
53
|
+
def self.open(url = nil) = new(RedisStore.open(url))
|
|
54
|
+
|
|
55
|
+
# `github.com/kigster/laser-cutter` and `kigster/laser-cutter` are the
|
|
56
|
+
# same repository. Any other forge keeps its host, the way
|
|
57
|
+
# {Tree#redis_slug} writes it: `gitlab.com/kigster/laser-cutter`. A
|
|
58
|
+
# bare name is refused; the slug is then matched whole, never as a
|
|
59
|
+
# prefix of some other one.
|
|
60
|
+
#
|
|
61
|
+
# @param text [String]
|
|
62
|
+
# @return [String]
|
|
63
|
+
# @raise [Error]
|
|
64
|
+
def self.normalize_slug(text)
|
|
65
|
+
slug = text.to_s.strip.sub(%r{\Agithub\.com/}i, "").delete_suffix("/").delete_suffix(".git")
|
|
66
|
+
return slug if slug.match?(%r{\A[^/]+(?:/[^/]+)+\z})
|
|
67
|
+
|
|
68
|
+
raise Error, "pass the repository as owner/name, for example kigster/laser-cutter, " \
|
|
69
|
+
"or host/owner/name for a forge other than GitHub"
|
|
70
|
+
end
|
|
71
|
+
|
|
72
|
+
# The repository `show repo` reads when none is named: the origin
|
|
73
|
+
# remote of the checkout `dir` is in.
|
|
74
|
+
#
|
|
75
|
+
# @param dir [String] a directory inside a checkout
|
|
76
|
+
# @return [String] `owner/name`, or `host/owner/name` off GitHub
|
|
77
|
+
# @raise [Error] when `dir` is in no checkout with an origin remote
|
|
78
|
+
def self.slug_for(dir = Dir.pwd)
|
|
79
|
+
Tree.for(dir).origin_slug ||
|
|
80
|
+
raise(Error, "no repository named, and #{dir} is not in a checkout with an origin remote. " \
|
|
81
|
+
"Pass it as owner/name")
|
|
82
|
+
end
|
|
83
|
+
|
|
84
|
+
# @param bytes [Integer, nil]
|
|
85
|
+
# @return [String]
|
|
86
|
+
def self.format_bytes(bytes)
|
|
87
|
+
return "n/a" if bytes.nil?
|
|
88
|
+
return "#{bytes} B" if bytes < 1024
|
|
89
|
+
|
|
90
|
+
value, unit = bytes < (1024 * 1024) ? [bytes / 1024.0, "KB"] : [bytes / (1024.0 * 1024), "MB"]
|
|
91
|
+
format("%<value>.1f %<unit>s", value:, unit:)
|
|
92
|
+
end
|
|
93
|
+
|
|
94
|
+
# @return [Array<Repo>] every label, fewest locks last
|
|
95
|
+
def repos
|
|
96
|
+
grouped.map { |label, entries| Repo.new(label, entries.size, bytes_of(entries)) }
|
|
97
|
+
.sort_by { |repo| [-repo.count, repo.namespace] }
|
|
98
|
+
end
|
|
99
|
+
|
|
100
|
+
# Matched whatever case the name is typed in. A label is written
|
|
101
|
+
# lower-case (see Tree.normalize_remote), so `Acme/App`, which is how
|
|
102
|
+
# the forge shows the repository, used to find nothing. The same
|
|
103
|
+
# match still reaches a label 4.0.0 wrote in the remote's own case,
|
|
104
|
+
# which no store reads any more and `show repos` goes on listing.
|
|
105
|
+
#
|
|
106
|
+
# @param slug [String] `owner/name`, a GitHub URL path, or
|
|
107
|
+
# `host/owner/name` on another forge
|
|
108
|
+
# @return [Array<Lock>]
|
|
109
|
+
# @raise [Error] when `slug` is a bare name
|
|
110
|
+
def locks(slug)
|
|
111
|
+
wanted = self.class.normalize_slug(slug)
|
|
112
|
+
pattern = /\Aalock-v\d+-#{Regexp.escape(wanted)}\z/i
|
|
113
|
+
grouped.select { |label, _entries| label.match?(pattern) }
|
|
114
|
+
.flat_map { |label, entries| entries.map { |entry| Lock.new(entry[:record], label) } }
|
|
115
|
+
.sort_by { |lock| [lock.record.scope, lock.record.created_at.to_s] }
|
|
116
|
+
end
|
|
117
|
+
|
|
118
|
+
# @return [Integer] keys an older gem wrote under {LEGACY_PREFIX}, which
|
|
119
|
+
# this version neither reads nor reaps
|
|
120
|
+
def legacy_count = client.scan_each(match: "#{LEGACY_PREFIX}*").to_a.uniq.size
|
|
121
|
+
|
|
122
|
+
# Whether the holder can be checked from this machine, and the answer.
|
|
123
|
+
#
|
|
124
|
+
# A pid on another host cannot be asked. Reporting it alive is how a
|
|
125
|
+
# dead process on a build box used to look occupied forever.
|
|
126
|
+
#
|
|
127
|
+
# @param record [Record]
|
|
128
|
+
# @return [String] "yes", "no", or "unknown"
|
|
129
|
+
def self.alive(record)
|
|
130
|
+
here = record.host.nil? || record.host == Socket.gethostname
|
|
131
|
+
return "unknown" unless here && record.pid
|
|
132
|
+
|
|
133
|
+
record.alive? ? "yes" : "no"
|
|
134
|
+
end
|
|
135
|
+
|
|
136
|
+
private
|
|
137
|
+
|
|
138
|
+
attr_reader :client
|
|
139
|
+
|
|
140
|
+
# @return [Hash{String => Array<Hash>}]
|
|
141
|
+
def grouped
|
|
142
|
+
@grouped ||= each_lock.group_by { |entry| entry[:label] }
|
|
143
|
+
end
|
|
144
|
+
|
|
145
|
+
# @return [Array<Hash>]
|
|
146
|
+
def each_lock
|
|
147
|
+
client.scan_each(match: "[[]alock-*").to_a.uniq.filter_map { |key| read(key) }
|
|
148
|
+
end
|
|
149
|
+
|
|
150
|
+
# @param key [String]
|
|
151
|
+
# @return [Hash, nil] nil for the mutex and for a value that is not a lock
|
|
152
|
+
def read(key)
|
|
153
|
+
found = LOCK_KEY.match(key)
|
|
154
|
+
return nil unless found
|
|
155
|
+
|
|
156
|
+
record = Record.parse(client.get(key))
|
|
157
|
+
return nil unless record
|
|
158
|
+
|
|
159
|
+
{ label: found[:label], key: key, record: record.with(id: found[:id]) }
|
|
160
|
+
end
|
|
161
|
+
|
|
162
|
+
# @param entries [Array<Hash>]
|
|
163
|
+
# @return [Integer, nil] nil when Redis has no MEMORY USAGE
|
|
164
|
+
def bytes_of(entries)
|
|
165
|
+
entries.sum { |entry| memory(entry[:key]) }
|
|
166
|
+
rescue Redis::CommandError
|
|
167
|
+
nil
|
|
168
|
+
end
|
|
169
|
+
|
|
170
|
+
# @param key [String]
|
|
171
|
+
# @return [Integer]
|
|
172
|
+
# @raise [Redis::CommandError] when this Redis has no MEMORY USAGE
|
|
173
|
+
def memory(key)
|
|
174
|
+
client.call("MEMORY", "USAGE", key).to_i
|
|
175
|
+
end
|
|
176
|
+
end
|
|
177
|
+
end
|
|
178
|
+
end
|
|
179
|
+
end
|
|
@@ -13,18 +13,21 @@ module Agent
|
|
|
13
13
|
# The same locks in a local Redis, for the machines that already run one.
|
|
14
14
|
#
|
|
15
15
|
# Redis buys two things the filesystem cannot: `SET NX` is atomic across
|
|
16
|
-
# machines rather than only across processes on one, and a TTL
|
|
17
|
-
# abandoned lock without anybody having to reason about whether its
|
|
18
|
-
# is still alive. It costs the thing that makes the file store
|
|
19
|
-
# which is that you can `cat` a lock, so the value stored is the
|
|
20
|
-
# markdown document either way.
|
|
16
|
+
# machines rather than only across processes on one, and a TTL can expire
|
|
17
|
+
# an abandoned lock without anybody having to reason about whether its
|
|
18
|
+
# holder is still alive. It costs the thing that makes the file store
|
|
19
|
+
# pleasant, which is that you can `cat` a lock, so the value stored is the
|
|
20
|
+
# same markdown document either way.
|
|
21
|
+
#
|
|
22
|
+
# The TTL is opt-in: AGENT_LOCK_TTL_SECONDS defaults to 0, and by default
|
|
23
|
+
# nothing expires. When it is set, {#create} starts it and nothing pushes
|
|
24
|
+
# it back: {#update} writes with `keepttl`, so a `note` counts as a touch
|
|
25
|
+
# for the stale window and still leaves the expiry where it was.
|
|
21
26
|
#
|
|
22
27
|
# Picked with AGENT_LOCK_BACKEND=redis, or by default when one answers on
|
|
23
28
|
# REDIS_URL, or failing that on the local default. See Store's moduledoc
|
|
24
29
|
# for how that default is decided.
|
|
25
30
|
class RedisStore
|
|
26
|
-
NAMESPACE = "agent-lock"
|
|
27
|
-
|
|
28
31
|
# Tried after REDIS_URL, or alone when it is unset.
|
|
29
32
|
LOCAL_URL = "redis://127.0.0.1:6379/0"
|
|
30
33
|
|
|
@@ -37,9 +40,12 @@ module Agent
|
|
|
37
40
|
# crashed holder is waited out rather than reported.
|
|
38
41
|
MUTEX_TIMEOUT = 15
|
|
39
42
|
|
|
43
|
+
# The error raised when the mutex expired under a running claim.
|
|
40
44
|
LEASE_LOST = "the lock store's mutex lease (#{MUTEX_LEASE_MS}ms) ran out before the claim finished, " \
|
|
41
45
|
"so another process may have claimed an overlapping scope: check the listing".freeze
|
|
42
46
|
|
|
47
|
+
# Compare-and-delete: release the mutex only while it still holds our
|
|
48
|
+
# token, so a process whose lease ran out cannot free somebody else's.
|
|
43
49
|
RELEASE = <<~LUA
|
|
44
50
|
if redis.call("GET", KEYS[1]) == ARGV[1] then
|
|
45
51
|
return redis.call("DEL", KEYS[1])
|
|
@@ -49,8 +55,14 @@ module Agent
|
|
|
49
55
|
|
|
50
56
|
attr_reader :tree, :client
|
|
51
57
|
|
|
52
|
-
|
|
58
|
+
# @param tree [Tree] the checkout whose repository names the namespace
|
|
59
|
+
# @param client [::Redis, nil] nil connects through {.create_client}.
|
|
60
|
+
# A facade passes its own client so two facades can use two servers.
|
|
61
|
+
# @param url [String, nil] the URL `client` speaks. Nil uses {.url}.
|
|
62
|
+
# @raise [RuntimeError] when no client can be created
|
|
63
|
+
def initialize(tree, client: nil, url: nil)
|
|
53
64
|
@tree = tree
|
|
65
|
+
@url = url
|
|
54
66
|
|
|
55
67
|
if client.nil?
|
|
56
68
|
client, error = self.class.create_client
|
|
@@ -61,11 +73,30 @@ module Agent
|
|
|
61
73
|
@client = client
|
|
62
74
|
end
|
|
63
75
|
|
|
64
|
-
raise "no functional Redis client could be created for #{self.class.url}" unless @client
|
|
76
|
+
raise "no functional Redis client could be created for #{self.class.safe(self.url)}" unless @client
|
|
65
77
|
end
|
|
66
78
|
|
|
79
|
+
# @return [String] the store by name, its URL without any password
|
|
80
|
+
def describe = "redis #{self.class.safe(url)} (#{namespace})"
|
|
81
|
+
|
|
82
|
+
# @return [String] what the tree's backend marker says for this store
|
|
83
|
+
def backend = "redis"
|
|
84
|
+
|
|
85
|
+
# Only the locks taken on this host in a worktree of this checkout.
|
|
86
|
+
# The label spans every clone of the repository on every machine, and
|
|
87
|
+
# each of those has a backend marker of its own, which a switch here
|
|
88
|
+
# does not touch.
|
|
89
|
+
#
|
|
90
|
+
# @return [Array<Record>] the locks a switch of this tree's backend strands
|
|
91
|
+
def bound
|
|
92
|
+
roots = tree.worktree_roots
|
|
93
|
+
all.select { |record| record.taken_in?(roots) }
|
|
94
|
+
end
|
|
95
|
+
|
|
96
|
+
# The default would print `@url` as given, password and all.
|
|
97
|
+
#
|
|
67
98
|
# @return [String]
|
|
68
|
-
def
|
|
99
|
+
def inspect = "#<#{self.class.name} #{describe}>"
|
|
69
100
|
|
|
70
101
|
# SCAN rather than KEYS: this runs on whatever Redis the machine
|
|
71
102
|
# already has, which may be somebody's shared development instance,
|
|
@@ -73,7 +104,7 @@ module Agent
|
|
|
73
104
|
#
|
|
74
105
|
# @return [Array<Record>]
|
|
75
106
|
def all
|
|
76
|
-
keys = client.scan_each(match:
|
|
107
|
+
keys = client.scan_each(match: scan_match).to_a.uniq.sort
|
|
77
108
|
keys.filter_map { |key| parse(client.get(key), key) }
|
|
78
109
|
end
|
|
79
110
|
|
|
@@ -109,11 +140,14 @@ module Agent
|
|
|
109
140
|
outcome
|
|
110
141
|
end
|
|
111
142
|
|
|
112
|
-
#
|
|
113
|
-
#
|
|
143
|
+
# One per repository, shared by every branch. A checkout that switched
|
|
144
|
+
# branches still writes the lock it took on the old one, and that write
|
|
145
|
+
# has to shut out whoever is on the branch it left. `all` scans
|
|
146
|
+
# `<label>-<hex>*`, so the mutex sits beside that pattern rather than
|
|
147
|
+
# inside it, or every scan would read the mutex back as a lock.
|
|
114
148
|
#
|
|
115
149
|
# @return [String]
|
|
116
|
-
def mutex_key = "#{
|
|
150
|
+
def mutex_key = "#{label}-mutex"
|
|
117
151
|
|
|
118
152
|
# @param scope [Scope]
|
|
119
153
|
# @return [Record, nil]
|
|
@@ -128,34 +162,71 @@ module Agent
|
|
|
128
162
|
def create(record)
|
|
129
163
|
args = { nx: true }
|
|
130
164
|
args[:ex] = ttl_seconds if ttl_seconds.positive?
|
|
131
|
-
!!client.set(key_for(record.id), record.to_markdown, **args)
|
|
165
|
+
!!client.set(key_for(record.id, record.lock_key), record.to_markdown, **args)
|
|
132
166
|
end
|
|
133
167
|
|
|
134
168
|
# @param record [Record]
|
|
135
169
|
# @return [void]
|
|
136
|
-
def update(record) = client.set(key_for(record.id), record.to_markdown, keepttl: true)
|
|
170
|
+
def update(record) = client.set(key_for(record.id, record.lock_key), record.to_markdown, keepttl: true)
|
|
137
171
|
|
|
138
172
|
# @param record [Record]
|
|
139
173
|
# @return [void]
|
|
140
|
-
def delete(record) = client.del(key_for(record.id))
|
|
174
|
+
def delete(record) = client.del(key_for(record.id, record.lock_key))
|
|
141
175
|
|
|
176
|
+
# The branch the id was taken on decides the key, not the branch this
|
|
177
|
+
# checkout is on now. A session that switched branches after claiming
|
|
178
|
+
# still has to release the record it wrote, and that record's lock key
|
|
179
|
+
# names the branch it was taken on.
|
|
180
|
+
#
|
|
142
181
|
# @param id [String]
|
|
182
|
+
# @param lock_key [String] {Tree#lock_key} for the checkout that owns the id
|
|
143
183
|
# @return [String]
|
|
144
|
-
def key_for(id) = "#{
|
|
184
|
+
def key_for(id, lock_key = tree.lock_key) = "#{namespace_for(lock_key)}:#{id}"
|
|
145
185
|
|
|
146
|
-
|
|
186
|
+
# Where this checkout writes. Every branch of the repository has its
|
|
187
|
+
# own, under one readable label, and {#all} reads them all.
|
|
188
|
+
#
|
|
189
|
+
# @return [String] `[alock-v<major>-<owner>/<repo>]-<sha256>`
|
|
190
|
+
def namespace = namespace_for(tree.lock_key)
|
|
147
191
|
|
|
148
|
-
|
|
149
|
-
# it, on every machine sharing this Redis, reads the same locks. It
|
|
150
|
-
# used to be the absolute path, which kept two machines apart even when
|
|
151
|
-
# they were editing the same file. Which of those locks actually
|
|
152
|
-
# collide is decided by Record#about?, not here.
|
|
153
|
-
def namespace = "#{NAMESPACE}:#{digest}"
|
|
192
|
+
private
|
|
154
193
|
|
|
194
|
+
# `[alock-v4-kigster/laser-cutter]`. The brackets are literal, so a
|
|
195
|
+
# person reading `KEYS` can see the gem and the repository. The major
|
|
196
|
+
# version only: hosts on 4.0 and 4.1 share one Redis and must go on
|
|
197
|
+
# excluding each other, so only a major release starts a new set.
|
|
198
|
+
# GitHub is `owner/repo`; any other host keeps its host, so two
|
|
199
|
+
# forges with the same owner and name do not share a label.
|
|
200
|
+
#
|
|
155
201
|
# @return [String]
|
|
156
|
-
def
|
|
202
|
+
def label = "[alock-#{self.class.version_tag}-#{tree.redis_slug}]"
|
|
203
|
+
|
|
204
|
+
# The label, then the SHA-256 of the lock key. On a branch the lock
|
|
205
|
+
# key is `repository@branch`, which every worktree and every machine
|
|
206
|
+
# on that branch computes the same way, so they share the key. The
|
|
207
|
+
# checkout's path stays out of it: hashing the path is what used to
|
|
208
|
+
# keep two machines from seeing each other. A detached HEAD has no
|
|
209
|
+
# branch, and its lock key is `host:worktree-path`, so that worktree
|
|
210
|
+
# hashes alone.
|
|
211
|
+
#
|
|
212
|
+
# @param lock_key [String]
|
|
213
|
+
# @return [String]
|
|
214
|
+
def namespace_for(lock_key) = "#{label}-#{::Digest::SHA256.hexdigest(lock_key)}"
|
|
215
|
+
|
|
216
|
+
# `all` has to see every branch, so it matches the label and any hex
|
|
217
|
+
# digest rather than this checkout's own. Redis SCAN treats `[]` as a
|
|
218
|
+
# character class. The label starts and ends with brackets, and an
|
|
219
|
+
# unescaped pattern matches one character instead of the key, which
|
|
220
|
+
# lists nothing and lets every claim through. `[[]` is one literal `[`.
|
|
221
|
+
# The mutex ends in `-mutex`, and `m` is outside `[0-9a-f]`, so the
|
|
222
|
+
# scan does not return it.
|
|
223
|
+
#
|
|
224
|
+
# @return [String]
|
|
225
|
+
def scan_match = "#{label.sub("[", "[[]")}-[0-9a-f]*"
|
|
157
226
|
|
|
158
|
-
|
|
227
|
+
# @return [String] the URL this store was given, or the one
|
|
228
|
+
# {.create_client} settled on when it was not
|
|
229
|
+
def url = @url || self.class.url
|
|
159
230
|
|
|
160
231
|
# SET NX PX until it takes, backing off with jitter so that processes
|
|
161
232
|
# which all lost the same round do not all come back for the next one
|
|
@@ -172,7 +243,8 @@ module Agent
|
|
|
172
243
|
until client.set(mutex_key, token, nx: true, px: MUTEX_LEASE_MS)
|
|
173
244
|
if Process.clock_gettime(Process::CLOCK_MONOTONIC) >= deadline
|
|
174
245
|
raise Error, format("timed out after %<timeout>gs waiting for %<key>s in %<url>s, " \
|
|
175
|
-
"which another process claiming a lock is holding",
|
|
246
|
+
"which another process claiming a lock is holding",
|
|
247
|
+
timeout:, key: mutex_key, url: self.class.safe(url))
|
|
176
248
|
end
|
|
177
249
|
|
|
178
250
|
sleep(delay * rand(0.5..1.0))
|
|
@@ -203,8 +275,12 @@ module Agent
|
|
|
203
275
|
timeout
|
|
204
276
|
end
|
|
205
277
|
|
|
278
|
+
# @return [Integer] AGENT_LOCK_TTL_SECONDS; 0 means no expiry
|
|
206
279
|
def ttl_seconds = Integer(ENV.fetch("AGENT_LOCK_TTL_SECONDS", 0))
|
|
207
280
|
|
|
281
|
+
# @param text [String, nil] the stored lock document
|
|
282
|
+
# @param key [String, nil] its Redis key, whose last segment is the id
|
|
283
|
+
# @return [Record, nil]
|
|
208
284
|
def parse(text, key)
|
|
209
285
|
return nil if text.nil?
|
|
210
286
|
|
|
@@ -213,6 +289,87 @@ module Agent
|
|
|
213
289
|
end
|
|
214
290
|
|
|
215
291
|
class << self
|
|
292
|
+
# A store on one named Redis, and no other: no `REDIS_URL`, no
|
|
293
|
+
# local default, no memoized client.
|
|
294
|
+
#
|
|
295
|
+
# @param tree [Tree]
|
|
296
|
+
# @param url [String] a Redis URL
|
|
297
|
+
# @return [RedisStore]
|
|
298
|
+
# @raise [Store::Unreachable] when nothing answers on `url`
|
|
299
|
+
def at(tree, url)
|
|
300
|
+
client, error = connect(url)
|
|
301
|
+
raise Store::Unreachable, "cannot use Redis at #{safe(url)}: #{reason(error)}" unless client
|
|
302
|
+
|
|
303
|
+
new(tree, client: client, url: url)
|
|
304
|
+
end
|
|
305
|
+
|
|
306
|
+
# A store on the first Redis the search finds.
|
|
307
|
+
#
|
|
308
|
+
# @param tree [Tree]
|
|
309
|
+
# @return [RedisStore]
|
|
310
|
+
# @raise [Store::Unreachable] when none of {.candidate_urls} answers
|
|
311
|
+
def found(tree)
|
|
312
|
+
client, error = create_client
|
|
313
|
+
return new(tree, client: client) if client
|
|
314
|
+
|
|
315
|
+
raise Store::Unreachable, "no Redis answered on #{candidate_urls.map { |u| safe(u) }.join(" or ")}: " \
|
|
316
|
+
"#{reason(error)}"
|
|
317
|
+
end
|
|
318
|
+
|
|
319
|
+
# A client for a command that reads every repository in one Redis,
|
|
320
|
+
# rather than the locks of one checkout. An explicit URL is tried
|
|
321
|
+
# alone. Without one, {.create_client} searches as usual.
|
|
322
|
+
#
|
|
323
|
+
# @param url [String, nil]
|
|
324
|
+
# @return [::Redis]
|
|
325
|
+
# @raise [Store::Unreachable] when it does not answer
|
|
326
|
+
def open(url = nil)
|
|
327
|
+
client, error = url ? connect(url) : create_client
|
|
328
|
+
return client if client
|
|
329
|
+
|
|
330
|
+
where = url ? safe(url) : candidate_urls.map { |candidate| safe(candidate) }.join(" or ")
|
|
331
|
+
raise Store::Unreachable, "cannot use Redis at #{where}: #{reason(error)}"
|
|
332
|
+
end
|
|
333
|
+
|
|
334
|
+
# A URL fit to print: an error lands in transcripts and logs, and
|
|
335
|
+
# a Redis URL may carry a password. Everything up to the last `@`
|
|
336
|
+
# goes, because a password that was never percent-encoded may hold
|
|
337
|
+
# a space, a `/` or an `@` of its own. Only a `scheme://` in front
|
|
338
|
+
# is kept: a mistyped `rey:secret@host` has no scheme to trust, and
|
|
339
|
+
# is the URL most likely to end up in an error.
|
|
340
|
+
#
|
|
341
|
+
# @param url [String] one URL, and nothing else
|
|
342
|
+
# @return [String] `url` with any userinfo replaced by `***`
|
|
343
|
+
def safe(url)
|
|
344
|
+
text = url.to_s
|
|
345
|
+
at = text.rindex("@")
|
|
346
|
+
return text unless at
|
|
347
|
+
|
|
348
|
+
"#{text[%r{\A[a-z][a-z0-9+.-]*://}i]}***#{text[at..]}"
|
|
349
|
+
end
|
|
350
|
+
|
|
351
|
+
# The same for a sentence that may quote a URL: the last net under
|
|
352
|
+
# an error somebody else worded. A sentence does not say where an
|
|
353
|
+
# unencoded password ends, so everything from the first `://` to
|
|
354
|
+
# the last `@` goes. That can take a second URL or a few words with
|
|
355
|
+
# it; a net that keeps the words and lets a password through is
|
|
356
|
+
# the worse one.
|
|
357
|
+
#
|
|
358
|
+
# @param text [String]
|
|
359
|
+
# @return [String] `text` with no userinfo left in it
|
|
360
|
+
def scrub(text) = text.to_s.sub(%r{(?<=://).*@}m, "***@")
|
|
361
|
+
|
|
362
|
+
# @return [String] `v4` from `4.0.3`. Every minor and patch of a
|
|
363
|
+
# major reads and writes one namespace; a new major starts another.
|
|
364
|
+
def version_tag = "v#{::Agent::Lock::VERSION.split(".").first}"
|
|
365
|
+
|
|
366
|
+
# redis-rb words its own errors without the password; anything
|
|
367
|
+
# else (a URL that does not parse) may quote the URL back.
|
|
368
|
+
#
|
|
369
|
+
# @param error [Exception]
|
|
370
|
+
# @return [String]
|
|
371
|
+
def reason(error) = error.is_a?(::Redis::BaseError) ? error.message : error.class.name
|
|
372
|
+
|
|
216
373
|
# The URL of the Redis actually in use, once one has answered, or
|
|
217
374
|
# the first one that will be tried before then.
|
|
218
375
|
#
|
|
@@ -233,8 +390,8 @@ module Agent
|
|
|
233
390
|
|
|
234
391
|
# Tries each candidate URL in turn and keeps the first that answers.
|
|
235
392
|
#
|
|
236
|
-
# @return Array
|
|
237
|
-
#
|
|
393
|
+
# @return [Array(Redis, nil), Array(nil, Exception)] the client and nil,
|
|
394
|
+
# or nil and the error from the last URL tried
|
|
238
395
|
def create_client
|
|
239
396
|
return [@client, nil] if @client
|
|
240
397
|
|
|
@@ -260,13 +417,14 @@ module Agent
|
|
|
260
417
|
|
|
261
418
|
private
|
|
262
419
|
|
|
263
|
-
# @param candidate [String]
|
|
264
|
-
# @return Array
|
|
420
|
+
# @param candidate [String] a Redis URL
|
|
421
|
+
# @return [Array(Redis, nil), Array(nil, Exception)] the client, or the error
|
|
265
422
|
def connect(candidate)
|
|
266
423
|
client = ::Redis.new(url: candidate)
|
|
267
424
|
client.info["redis_version"]
|
|
268
425
|
[client, nil]
|
|
269
|
-
rescue Redis::CannotConnectError, Redis::BaseError,
|
|
426
|
+
rescue Redis::CannotConnectError, Redis::BaseError, SystemCallError, SocketError, ArgumentError,
|
|
427
|
+
URI::InvalidURIError => e
|
|
270
428
|
[nil, e]
|
|
271
429
|
end
|
|
272
430
|
end
|