Skip to content

Commit 4b86c94

Browse files
authored
Merge pull request #706 from simonchrz/feat/git-warm-refresh
Check cached Git repositories in the background
2 parents e1ab4a6 + 7a7a072 commit 4b86c94

12 files changed

Lines changed: 615 additions & 17 deletions

File tree

‎config.example.yaml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -426,6 +426,7 @@ upstream:
426426
# max_repo_size: 5GB # refuse a repository that grows past this
427427
# refresh_wait: 5s # then serve the cached copy if the upstream check is slow
428428
# stale_max_age: 24h # never serve a copy not checked for this long
429+
# warm_max_idle: 30d # keep checking repositories used within this
429430

430431
# Gradle HttpBuildCache configuration
431432
gradle:

‎docs/configuration.md‎

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -851,6 +851,7 @@ git:
851851
max_repo_size: 5GB # refuse a repository that grows past this
852852
refresh_wait: 5s # then serve the cached copy if the upstream check is slow
853853
stale_max_age: 24h # never serve a copy not checked for this long
854+
warm_max_idle: 30d # keep checking repositories used within this
854855
```
855856

856857
Clients reach the proxy through Git's `insteadOf` setting, which rewrites the
@@ -929,6 +930,24 @@ location. A `git-upload-pack` request checks the upstream only when the last
929930
check refused the repository or the copy was last checked more than a minute
930931
past `stale_max_age` ago, so a clone checks once, at its ref listing.
931932

933+
The proxy also checks cached repositories in the background, so a copy stays
934+
servable through an outage even when nobody cloned it for a day. A repository
935+
that a client used within `warm_max_idle` (default `30d`) is checked again
936+
once half of `stale_max_age` has passed since its last successful check,
937+
and fetched if its branches or tags moved. It is checked at the URL its last
938+
successful check used, so a repository cached by an older version waits for
939+
a client to refresh it once. After a failed check it waits a quarter of that
940+
interval, at least 10 minutes, so a few retries fit before the copy goes
941+
stale. Checks run one at a time and do not count as use, so they do not keep
942+
a repository from expiring out of `warm_max_idle`. With the cache at
943+
`max_size`, a background fetch makes room as any other fetch does, by
944+
evicting the least recently used idle repositories, which can be ones used
945+
more recently than the repository being checked. Repositories the upstream
946+
refused, and those the configuration no longer serves, are skipped. `warm_max_idle: 0`, or a
947+
`stale_max_age` under `20m` (which includes `0`), turns the background
948+
checks off. They run in `proxy serve` only, each process for its own
949+
`cache_dir`.
950+
932951
The proxy runs `git` 2.31 or newer, which must be installed (the Docker image includes it).
933952
The `git` processes never reach the network themselves: their fetches go
934953
through a loopback endpoint in the proxy that forwards them with the same
@@ -1042,8 +1061,8 @@ upstream, until retention removes it or you delete it through the
10421061
Pushing, LFS uploads and locking, and the dumb HTTP protocol are not
10431062
supported. The settings
10441063
under `git` can also be set with `PROXY_GIT_CACHE_DIR`, `PROXY_GIT_MAX_SIZE`,
1045-
`PROXY_GIT_MAX_REPO_SIZE`, `PROXY_GIT_REFRESH_WAIT` and
1046-
`PROXY_GIT_STALE_MAX_AGE`.
1064+
`PROXY_GIT_MAX_REPO_SIZE`, `PROXY_GIT_REFRESH_WAIT`,
1065+
`PROXY_GIT_STALE_MAX_AGE` and `PROXY_GIT_WARM_MAX_IDLE`.
10471066

10481067
### Maven repositories
10491068

‎internal/config/config.go‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1619,6 +1619,7 @@ func (c *Config) LoadFromEnv() {
16191619
setEnvString(&c.Git.MaxRepoSize, "PROXY_GIT_MAX_REPO_SIZE")
16201620
setEnvString(&c.Git.RefreshWait, "PROXY_GIT_REFRESH_WAIT")
16211621
setEnvString(&c.Git.StaleMaxAge, "PROXY_GIT_STALE_MAX_AGE")
1622+
setEnvString(&c.Git.WarmMaxIdle, "PROXY_GIT_WARM_MAX_IDLE")
16221623
}
16231624

16241625
// validateAbsoluteURL returns an error if value is not a parseable URL with

‎internal/config/git.go‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ const (
1515
defaultGitMaxRepoSize = "5GB"
1616
defaultGitRefreshWait = "5s"
1717
defaultGitStaleMaxAge = "24h"
18+
defaultGitWarmMaxIdle = "30d"
1819
)
1920

2021
// GitUpstream is an upstream.git entry: a Git server's base URL and,
@@ -104,10 +105,17 @@ type GitConfig struct {
104105
// Default: 24h.
105106
StaleMaxAge string `json:"stale_max_age" yaml:"stale_max_age"`
106107

108+
// WarmMaxIdle is how long after a client last used a repository the
109+
// proxy keeps checking it in the background, so the cached copy stays
110+
// within StaleMaxAge through an upstream outage. Accepts a "d" suffix.
111+
// "0" turns the background checks off. Default: 30d.
112+
WarmMaxIdle string `json:"warm_max_idle" yaml:"warm_max_idle"`
113+
107114
maxSize int64
108115
maxRepoSize int64
109116
refreshWait time.Duration
110117
staleMaxAge time.Duration
118+
warmMaxIdle time.Duration
111119
}
112120

113121
// MaxSizeBytes returns the parsed MaxSize, 0 for no limit. Validate must run first.
@@ -122,6 +130,9 @@ func (g *GitConfig) RefreshWaitDuration() time.Duration { return g.refreshWait }
122130
// StaleMaxAgeDuration returns the parsed StaleMaxAge. Validate must run first.
123131
func (g *GitConfig) StaleMaxAgeDuration() time.Duration { return g.staleMaxAge }
124132

133+
// WarmMaxIdleDuration returns the parsed WarmMaxIdle, 0 for off. Validate must run first.
134+
func (g *GitConfig) WarmMaxIdleDuration() time.Duration { return g.warmMaxIdle }
135+
125136
// Validate checks the Git cache settings, applying defaults where unset.
126137
func (g *GitConfig) Validate() error {
127138
if g.CacheDir == "" {
@@ -136,6 +147,9 @@ func (g *GitConfig) Validate() error {
136147
if g.StaleMaxAge == "" {
137148
g.StaleMaxAge = defaultGitStaleMaxAge
138149
}
150+
if g.WarmMaxIdle == "" {
151+
g.WarmMaxIdle = defaultGitWarmMaxIdle
152+
}
139153

140154
var err error
141155
if g.maxSize, err = parseNonNegativeSize("git.max_size", g.MaxSize); err != nil {
@@ -150,6 +164,9 @@ func (g *GitConfig) Validate() error {
150164
if g.staleMaxAge, err = parseNonNegativeDuration("git.stale_max_age", g.StaleMaxAge); err != nil {
151165
return err
152166
}
167+
if g.warmMaxIdle, err = parseRetentionDuration("git.warm_max_idle", g.WarmMaxIdle); err != nil {
168+
return err
169+
}
153170
return nil
154171
}
155172

‎internal/config/git_test.go‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -132,11 +132,19 @@ func TestGitConfigDefaults(t *testing.T) {
132132
t.Fatalf("Validate: %v", err)
133133
}
134134
if g.CacheDir != defaultGitCacheDir || g.MaxSizeBytes() != 0 || g.MaxRepoSizeBytes() != 5<<30 ||
135-
g.RefreshWaitDuration() != 5*time.Second || g.StaleMaxAgeDuration() != 24*time.Hour {
135+
g.RefreshWaitDuration() != 5*time.Second || g.StaleMaxAgeDuration() != 24*time.Hour ||
136+
g.WarmMaxIdleDuration() != 30*24*time.Hour {
136137
t.Errorf("defaults = %+v", g)
137138
}
138139

139-
for _, bad := range []GitConfig{{MaxSize: "lots"}, {RefreshWait: "soon"}, {StaleMaxAge: "-1h"}} {
140+
for value, want := range map[string]time.Duration{"90d": 90 * 24 * time.Hour, "12h": 12 * time.Hour, "0": 0} {
141+
g := GitConfig{WarmMaxIdle: value}
142+
if err := g.Validate(); err != nil || g.WarmMaxIdleDuration() != want {
143+
t.Errorf("warm_max_idle %q = %v, %v; want %v", value, g.WarmMaxIdleDuration(), err, want)
144+
}
145+
}
146+
147+
for _, bad := range []GitConfig{{MaxSize: "lots"}, {RefreshWait: "soon"}, {StaleMaxAge: "-1h"}, {WarmMaxIdle: "-1d"}, {WarmMaxIdle: "often"}} {
140148
if err := bad.Validate(); err == nil {
141149
t.Errorf("Validate(%+v) accepted it", bad)
142150
}

‎internal/gitcache/cache.go‎

Lines changed: 42 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,9 @@ const (
4646
ecosystem = "git"
4747
upstreamHashLen = 8
4848
checkedStamp = "proxy-checked"
49+
// urlFile holds the upstream URL the last successful refresh used, for
50+
// background refreshes.
51+
urlFile = "proxy-url"
4952
usedStamp = "proxy-used"
5053
dirPermissions = 0o750
5154
lockFilePermissions = 0o600
@@ -62,17 +65,21 @@ type Options struct {
6265
// processes the cache runs. Redirects are never followed.
6366
Client *http.Client
6467
Logger *slog.Logger
68+
// WarmMaxIdle, with StaleMaxAge, lets Warm refresh the repositories
69+
// clients used within it before StaleMaxAge runs out. 0 turns that off.
70+
WarmMaxIdle time.Duration
6571
// Upstreams maps each configured upstream's name to its directory in
6672
// CacheDir, as UpstreamDir names it. Only those directories are loaded
6773
// at startup. A directory UpstreamDir would name for one of these names
6874
// at another URL, left by repointing the upstream, is removed. Nothing
6975
// else in CacheDir is touched, so it may hold other data.
7076
Upstreams map[string]string
7177

72-
// refCheckTimeout, lowSpeedTime, maxRequestBody, maxUploadPacks and
73-
// maxRefListings override their defaults in tests, and refreshWaitOver,
74-
// when set, replaces the RefreshWait timer.
78+
// refCheckTimeout, lowSpeedTime, maxRequestBody, maxUploadPacks,
79+
// maxRefListings and warmTick override their defaults in tests, and
80+
// refreshWaitOver, when set, replaces the RefreshWait timer.
7581
refCheckTimeout time.Duration
82+
warmTick time.Duration
7683
refreshWaitOver <-chan time.Time
7784
lowSpeedTime int
7885
maxRequestBody int64
@@ -158,6 +165,27 @@ type repo struct {
158165
// is current while the count is the one it was read at.
159166
state atomic.Pointer[cachedState]
160167
refsWritten atomic.Int64
168+
// url is the upstream URL the last successful refresh used.
169+
url atomic.Pointer[string]
170+
}
171+
172+
// repoURL returns the upstream URL the last successful refresh used, or ""
173+
// if none is recorded.
174+
func (rp *repo) repoURL() string {
175+
if u := rp.url.Load(); u != nil {
176+
return *u
177+
}
178+
return ""
179+
}
180+
181+
// rememberURL records repoURL as the one a refresh succeeded with, on disk
182+
// too once the repository is cached.
183+
func (rp *repo) rememberURL(repoURL string) {
184+
if rp.repoURL() == repoURL || !rp.exists() {
185+
return
186+
}
187+
rp.url.Store(&repoURL)
188+
_ = os.WriteFile(filepath.Join(rp.dir, urlFile), []byte(repoURL+"\n"), lockFilePermissions)
161189
}
162190

163191
var errLocked = errors.New("locked by another process")
@@ -323,6 +351,11 @@ func (c *Cache) load() error {
323351
rp.lastChecked.Store(stampTime(path, checkedStamp))
324352
rp.lastUsed.Store(stampTime(path, usedStamp))
325353
rp.usedWritten.Store(rp.lastUsed.Load())
354+
if data, err := os.ReadFile(filepath.Join(path, urlFile)); err == nil {
355+
if u := strings.TrimSpace(string(data)); u != "" {
356+
rp.url.Store(&u)
357+
}
358+
}
326359
c.repos[rp.key] = rp
327360
return filepath.SkipDir
328361
})
@@ -439,6 +472,7 @@ func (c *Cache) repoKey(key string) string {
439472
return key
440473
}
441474

475+
// release ends a use of the repository by a client, recording it as used.
442476
func (c *Cache) release(rp *repo) {
443477
now := time.Now()
444478
rp.lastUsed.Store(now.UnixNano())
@@ -447,7 +481,12 @@ func (c *Cache) release(rp *repo) {
447481
rp.usedWritten.Store(now.UnixNano())
448482
touch(rp.dir, usedStamp, now)
449483
}
484+
c.drop(rp, exists)
485+
}
450486

487+
// drop ends a use of the repository without recording it as used. exists
488+
// is whether the repository is cloned.
489+
func (c *Cache) drop(rp *repo, exists bool) {
451490
c.mu.Lock()
452491
rp.users--
453492
idle := rp.users == 0 && c.repos[rp.key] == rp

‎internal/gitcache/refresh.go‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,12 @@ func servesStale(err error) bool {
130130
func (c *Cache) startRefresh(rp *repo, repoURL string) *refreshCall {
131131
c.mu.Lock()
132132
defer c.mu.Unlock()
133+
return c.startRefreshLocked(rp, repoURL, false)
134+
}
135+
136+
// startRefreshLocked is startRefresh with c.mu held. A refresh started in
137+
// the background does not count as a use of the repository when it ends.
138+
func (c *Cache) startRefreshLocked(rp *repo, repoURL string, background bool) *refreshCall {
133139
if rp.refreshing != nil {
134140
return rp.refreshing
135141
}
@@ -154,6 +160,9 @@ func (c *Cache) startRefresh(rp *repo, repoURL string) *refreshCall {
154160
switch {
155161
case call.err == nil:
156162
rp.lastError.Store(nil)
163+
// The upstream answered at this URL, so background refreshes
164+
// use it.
165+
rp.rememberURL(repoURL)
157166
case c.ctx.Err() == nil:
158167
metrics.RecordUpstreamError(ecosystem, errorType(call.err), metrics.FailureDetail{URL: repoURL, Err: call.err})
159168
c.logger.Warn("git cache: refresh failed", "repository", rp.key, "error", call.err)
@@ -165,7 +174,11 @@ func (c *Cache) startRefresh(rp *repo, repoURL string) *refreshCall {
165174
rp.refused = call.err
166175
}
167176
c.mu.Unlock()
168-
c.release(rp)
177+
if background {
178+
c.drop(rp, rp.exists())
179+
} else {
180+
c.release(rp)
181+
}
169182
close(call.done)
170183
if call.err == nil {
171184
c.evict()

0 commit comments

Comments
 (0)