Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions internal/gitclone/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -1268,3 +1268,13 @@ func (r *Repository) HasCommit(ctx context.Context, ref string) bool {
err := cmd.Run()
return err == nil
}

// HasAncestor reports whether ancestor is in the mirror and reachable from descendant.
func (r *Repository) HasAncestor(ctx context.Context, ancestor, descendant string) bool {
r.mu.RLock()
defer r.mu.RUnlock()

// #nosec G204 - r.path is controlled by us; callers pass commit SHAs
cmd := exec.CommandContext(ctx, "git", "-C", r.path, "merge-base", "--is-ancestor", ancestor, descendant)
return cmd.Run() == nil
}
144 changes: 143 additions & 1 deletion internal/strategy/git/bundlecoord_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -367,7 +367,7 @@ func TestBundleBuildCancellationReleasesFetchLock(t *testing.T) {
done = completed
go func() {
defer close(completed)
file, err := s.createBundle(ctx, repo, base)
file, _, err := s.createBundle(ctx, repo, base)
if file != nil {
_ = file.Close()
}
Expand Down Expand Up @@ -395,3 +395,145 @@ func TestBundleBuildCancellationReleasesFetchLock(t *testing.T) {
})
}
}

func commitToMirror(t *testing.T, repo *gitclone.Repository, message string) string {
t.Helper()
cmd := exec.CommandContext(t.Context(), "git", "-C", repo.Path(), "commit", "--allow-empty", "-m", message)
cmd.Env = append(os.Environ(), "GIT_AUTHOR_NAME=Test", "GIT_AUTHOR_EMAIL=test@example.com",
"GIT_COMMITTER_NAME=Test", "GIT_COMMITTER_EMAIL=test@example.com")
out, err := cmd.CombinedOutput()
assert.NoError(t, err, string(out))
head, err := mirrorHead(t.Context(), repo.Path())
assert.NoError(t, err)
return head
}

func TestBundleRebuiltWhenMirrorTipMoves(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
s, repo, base, gate := newBundleBuildTest(t)
close(gate.release)
oldTip := s.getMirrorHead(s.ctx, repo)
first := serveTestBundle(s.ctx, s, base)
assert.Equal(t, http.StatusOK, first.Code)
assert.Contains(t, first.Body.String(), oldTip)
synctest.Wait()

newTip := commitToMirror(t, repo, "after snapshot")
second := serveTestBundle(s.ctx, s, base)
assert.Equal(t, http.StatusOK, second.Code)
assert.Contains(t, second.Body.String(), newTip)
synctest.Wait()

third := serveTestBundle(s.ctx, s, base)
assert.Equal(t, second.Body.String(), third.Body.String())
synctest.Wait()
assert.Equal(t, int32(2), gate.creates.Load())
})
}

func TestBundleFromNewerReplicaIsKept(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
s, repo, base, gate := newBundleBuildTest(t)
close(gate.release)
key := bundleCacheKey(repo.UpstreamURL(), base)
assert.NoError(t, s.cacheBundle(s.ctx, key, strings.Repeat("ab", 20), strings.NewReader("peer bundle")))
response := serveTestBundle(s.ctx, s, base)
assert.Equal(t, http.StatusOK, response.Code)
assert.Equal(t, "peer bundle", response.Body.String())
assert.Equal(t, int32(1), gate.creates.Load())
})
}

func gitIn(t *testing.T, dir string, args ...string) string {
t.Helper()
cmd := exec.CommandContext(t.Context(), "git", append([]string{"-C", dir}, args...)...)
cmd.Env = append(os.Environ(), "GIT_AUTHOR_NAME=Test", "GIT_AUTHOR_EMAIL=test@example.com",
"GIT_COMMITTER_NAME=Test", "GIT_COMMITTER_EMAIL=test@example.com")
out, err := cmd.CombinedOutput()
assert.NoError(t, err, string(out))
return strings.TrimSpace(string(out))
}

func newBundleTipTest(t *testing.T) (s *Strategy, repo *gitclone.Repository, upstream, base string, gate *bundlePublishGate) {
t.Helper()
ctx := logging.ContextWithLogger(t.Context(), slog.Default())
t.Setenv("GIT_CONFIG_GLOBAL", os.DevNull)
t.Setenv("GIT_CONFIG_NOSYSTEM", "1")
upstream = t.TempDir()
gitIn(t, upstream, "init", "-b", "main")
gitIn(t, upstream, "commit", "--allow-empty", "-m", "base")
base = gitIn(t, upstream, "rev-parse", "HEAD")
gitIn(t, upstream, "commit", "--allow-empty", "-m", "next")
manager, err := gitclone.NewManager(ctx, gitclone.Config{MirrorRoot: t.TempDir()}, nil)
assert.NoError(t, err)
repo, err = manager.GetOrCreate(ctx, "https://example.com/org/repo")
assert.NoError(t, err)
gitIn(t, upstream, "clone", "--mirror", upstream, repo.Path())
repo.MarkReady()
mem, err := cache.NewMemory(ctx, cache.MemoryConfig{MaxTTL: time.Hour})
assert.NoError(t, err)
gate = &bundlePublishGate{Cache: mem, started: make(chan context.Context, 32), release: make(chan struct{})}
close(gate.release)
s = &Strategy{ctx: ctx, cache: gate, cloneManager: manager, metrics: newGitMetrics(), config: Config{BundleCacheTTL: time.Hour}}
return s, repo, upstream, base, gate
}

func serveTestBundleWithTip(ctx context.Context, s *Strategy, base, tip string) *httptest.ResponseRecorder {
r := httptest.NewRequestWithContext(ctx, http.MethodGet, "/git/example.com/org/repo/snapshot.bundle?base="+base+"&tip="+tip, nil)
w := httptest.NewRecorder()
s.handleBundleRequest(w, r, "example.com", "org/repo/snapshot.bundle")
return w
}

func TestBundleTipFreshensMirrorBehindClient(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
s, repo, upstream, base, gate := newBundleTipTest(t)
first := serveTestBundle(s.ctx, s, base)
assert.Equal(t, http.StatusOK, first.Code)
synctest.Wait()

gitIn(t, upstream, "commit", "--allow-empty", "-m", "pushed after this replica fetched")
tip := gitIn(t, upstream, "rev-parse", "HEAD")
assert.False(t, repo.HasCommit(s.ctx, tip))
time.Sleep(s.cloneManager.Config().RefCheckInterval)

second := serveTestBundleWithTip(s.ctx, s, base, tip)
assert.Equal(t, http.StatusOK, second.Code)
assert.Contains(t, second.Body.String(), tip)
assert.True(t, repo.HasCommit(s.ctx, tip))
synctest.Wait()
assert.Equal(t, int32(2), gate.creates.Load())

// The cached bundle now contains tip, so the same hint is served without another build.
third := serveTestBundleWithTip(s.ctx, s, base, tip)
assert.Equal(t, second.Body.String(), third.Body.String())
synctest.Wait()
assert.Equal(t, int32(2), gate.creates.Load())
})
}

func TestBundleBogusTipFetchesAtMostOncePerInterval(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
s, repo, _, base, gate := newBundleTipTest(t)
first := serveTestBundle(s.ctx, s, base)
assert.Equal(t, http.StatusOK, first.Code)
synctest.Wait()

bogus := strings.Repeat("0f", 20)
time.Sleep(s.cloneManager.Config().RefCheckInterval)
before := repo.LastFetch()
second := serveTestBundleWithTip(s.ctx, s, base, bogus)
assert.Equal(t, first.Body.String(), second.Body.String())
fetched := repo.LastFetch()
assert.True(t, fetched.After(before))

third := serveTestBundleWithTip(s.ctx, s, base, bogus)
assert.Equal(t, first.Body.String(), third.Body.String())
assert.Equal(t, fetched, repo.LastFetch())

notSHA := serveTestBundleWithTip(s.ctx, s, base, "main")
assert.Equal(t, http.StatusOK, notSHA.Code)
synctest.Wait()
assert.Equal(t, int32(1), gate.creates.Load())
})
}
2 changes: 1 addition & 1 deletion internal/strategy/git/export_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ func (s *Strategy) RunFailingCoordinatedSnapshot(ctx context.Context, repo *gitc

// CacheBundle exports cacheBundle for testing.
func (s *Strategy) CacheBundle(ctx context.Context, key cache.Key, r io.Reader) error {
return s.cacheBundle(ctx, key, r)
return s.cacheBundle(ctx, key, "", r)
}

// MirrorPreparationScheduled lets tests check for a queued or active preparation job.
Expand Down
96 changes: 81 additions & 15 deletions internal/strategy/git/snapshot.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ const lfsFetchTimeout = 25 * time.Minute

const bundleBuildTimeout = 5 * time.Minute

// bundleTipHeader records the mirror HEAD a cached bundle was built up to.
const bundleTipHeader = "X-Cachew-Bundle-Tip"

type bundleBuild struct {
done chan struct{}
verifiedEmpty bool
Expand Down Expand Up @@ -76,7 +79,7 @@ func (s *Strategy) finishBundleBuild(key cache.Key, build *bundleBuild) {
build.release()
}

func (s *Strategy) publishBundle(ctx context.Context, key cache.Key, build *bundleBuild, file *os.File) error {
func (s *Strategy) publishBundle(ctx context.Context, key cache.Key, build *bundleBuild, file *os.File, tip string) error {
info, err := file.Stat()
if err != nil {
_ = file.Close()
Expand All @@ -91,7 +94,7 @@ func (s *Strategy) publishBundle(ctx context.Context, key cache.Key, build *bund
defer s.bundleBuilds.Delete(key)
publishCtx, cancel := context.WithDeadline(s.ctx, deadline)
defer cancel()
if err := s.cacheBundle(publishCtx, key, build.reader()); err != nil {
if err := s.cacheBundle(publishCtx, key, tip, build.reader()); err != nil {
logging.FromContext(ctx).WarnContext(publishCtx, "Failed to cache bundle", "key", key, "error", err)
}
}()
Expand Down Expand Up @@ -686,6 +689,11 @@ func (s *Strategy) handleBundleRequest(w http.ResponseWriter, r *http.Request, h
return
}
span.SetAttributes(attribute.String("cachew.base_commit", base))
// The client's ensure-refs may have reached another replica; tip is the HEAD it saw there.
want := r.URL.Query().Get("tip")
if !commitSHARe.MatchString(want) {
want = ""
}

bKey := bundleCacheKey(upstreamURL, base)

Expand All @@ -710,6 +718,17 @@ func (s *Strategy) handleBundleRequest(w http.ResponseWriter, r *http.Request, h
releaseBuild := func() {}
for acquired := false; ; {
reader, headers, openErr := s.cache.Open(ctx, bKey, httputil.ConditionalOptions(r)...)
// Resumed downloads must keep reading the entry they started on, so only plain GETs re-check the tip.
if openErr == nil && r.Header.Get("Range") == "" {
stale, staleErr := s.cachedBundleStale(ctx, s.cloneManager.Get(upstreamURL), headers, want)
if staleErr != nil {
logger.WarnContext(ctx, "Failed to freshen mirror for bundle tip", "upstream", upstreamURL, "tip", want, "error", staleErr)
}
if stale {
_ = reader.Close()
openErr = os.ErrNotExist
}
}
switch {
case openErr == nil,
errors.Is(openErr, cache.ErrNotModified),
Expand Down Expand Up @@ -808,7 +827,10 @@ func (s *Strategy) handleBundleRequest(w http.ResponseWriter, r *http.Request, h
}
}

bundleFile, err := s.createBundle(ctx, repo, base)
if err := s.freshenForBundleTip(ctx, repo, want); err != nil {
logger.WarnContext(ctx, "Failed to freshen mirror for bundle tip", "upstream", upstreamURL, "tip", want, "error", err)
}
bundleFile, tip, err := s.createBundle(ctx, repo, base)
if errors.Is(err, errEmptyBundle) {
if freshenErr := s.doFetchVerified(ctx, repo); freshenErr != nil {
source = "miss_stale"
Expand All @@ -823,7 +845,7 @@ func (s *Strategy) handleBundleRequest(w http.ResponseWriter, r *http.Request, h
http.Error(w, "Bundle not available", http.StatusNotFound)
return
}
bundleFile, err = s.createBundle(ctx, repo, base)
bundleFile, tip, err = s.createBundle(ctx, repo, base)
if errors.Is(err, errEmptyBundle) {
build.verifiedEmpty = true
releaseBuild()
Expand All @@ -838,7 +860,7 @@ func (s *Strategy) handleBundleRequest(w http.ResponseWriter, r *http.Request, h
span.RecordError(err)
return
}
if err := s.publishBundle(ctx, bKey, build, bundleFile); err != nil {
if err := s.publishBundle(ctx, bKey, build, bundleFile, tip); err != nil {
logger.WarnContext(ctx, "Failed to publish bundle", "upstream", upstreamURL, "error", err)
http.Error(w, "Bundle not available", http.StatusServiceUnavailable)
span.RecordError(err)
Expand Down Expand Up @@ -928,19 +950,21 @@ func (s *Strategy) pregenerateBundle(ctx context.Context, repo *gitclone.Reposit
defer cancel()
bgCtx = logging.ContextWithLogger(bgCtx, logging.FromContext(ctx))
logger := logging.FromContext(bgCtx)
if reader, _, err := s.cache.Open(bgCtx, bKey); err == nil {
if reader, headers, err := s.cache.Open(bgCtx, bKey); err == nil {
_ = reader.Close()
return
if stale, err := s.cachedBundleStale(bgCtx, repo, headers, ""); err == nil && !stale {
return
}
}
bundleFile, err := s.createBundle(bgCtx, repo, snapshotCommit)
bundleFile, tip, err := s.createBundle(bgCtx, repo, snapshotCommit)
if err != nil {
if errors.Is(err, errEmptyBundle) {
return
}
logger.WarnContext(bgCtx, "Failed to pre-generate bundle", "upstream", upstreamURL, "error", err)
return
}
if err := s.publishBundle(bgCtx, bKey, build, bundleFile); err != nil {
if err := s.publishBundle(bgCtx, bKey, build, bundleFile, tip); err != nil {
logger.WarnContext(bgCtx, "Failed to publish bundle", "upstream", upstreamURL, "error", err)
}
}()
Expand Down Expand Up @@ -980,8 +1004,11 @@ func applySnapshotCacheHeaders(w http.ResponseWriter, headers http.Header) { //n
}
}

func (s *Strategy) cacheBundle(ctx context.Context, key cache.Key, r io.Reader) error {
func (s *Strategy) cacheBundle(ctx context.Context, key cache.Key, tip string, r io.Reader) error {
headers := http.Header{"Content-Type": {"application/x-git-bundle"}}
if tip != "" {
headers.Set(bundleTipHeader, tip)
}
wc, err := s.cache.Create(ctx, key, headers, s.config.BundleCacheTTL)
if err != nil {
return errors.Wrap(err, "create cache entry")
Expand All @@ -1006,16 +1033,55 @@ func (s *Strategy) getMirrorHead(ctx context.Context, repo *gitclone.Repository)
return head
}

// cachedBundleStale reports whether this replica's mirror HEAD has moved past the tip a cached bundle was built to.
//
// Bundles are keyed by base alone, so this stops clones getting the first one built after a snapshot. A tip this
// mirror lacks came from a newer replica and is kept; a want the bundle lacks freshens this mirror first.
func (s *Strategy) cachedBundleStale(ctx context.Context, repo *gitclone.Repository, headers http.Header, want string) (bool, error) { //nolint:privatedoc // explains why
if repo == nil || repo.State() != gitclone.StateReady {
return false, nil
}
tip := headers.Get(bundleTipHeader)
validTip := commitSHARe.MatchString(tip)
if want != "" && validTip && (tip == want || repo.HasAncestor(ctx, want, tip)) {
return false, nil
}
freshenErr := s.freshenForBundleTip(ctx, repo, want)
head := s.getMirrorHead(ctx, repo)
if head == "" || head == tip {
return false, freshenErr
}
if tip == "" {
return true, freshenErr
}
return validTip && repo.HasAncestor(ctx, tip, head), freshenErr
}

// freshenForBundleTip fetches upstream when the client saw a tip this replica's mirror lacks.
//
// freshenMirror's ref-check gate allows one fetch per interval, so a bogus or unreachable tip cannot repeat it.
func (s *Strategy) freshenForBundleTip(ctx context.Context, repo *gitclone.Repository, want string) error { //nolint:privatedoc // explains why
if want == "" || repo.HasCommit(ctx, want) {
return nil
}
if err := s.freshenMirror(ctx, repo); err != nil {
return errors.Wrap(err, "freshen mirror for bundle tip")
}
return nil
}

// createBundle writes a git bundle of the commits between baseCommit and the mirror's HEAD to a temp file.
//
// The returned file is already removed from the filesystem, so the open descriptor keeps the
// data alive. The caller must Close it.
func (s *Strategy) createBundle(ctx context.Context, repo *gitclone.Repository, baseCommit string) (*os.File, error) { //nolint:privatedoc // documents a non-obvious contract
// It also returns that HEAD. The returned file is already removed from the filesystem, so the open
// descriptor keeps the data alive. The caller must Close it.
func (s *Strategy) createBundle(ctx context.Context, repo *gitclone.Repository, baseCommit string) (*os.File, string, error) { //nolint:privatedoc // documents a non-obvious contract
ctx, cancel := context.WithTimeout(ctx, bundleBuildTimeout)
defer cancel()
var bundleFile *os.File
var head string
err := repo.WithFetchExclusion(ctx, func() error {
head, err := mirrorHead(ctx, repo.Path())
var err error
head, err = mirrorHead(ctx, repo.Path())
if err != nil {
return err
}
Expand All @@ -1025,7 +1091,7 @@ func (s *Strategy) createBundle(ctx context.Context, repo *gitclone.Repository,
bundleFile, err = createBundleFile(ctx, repo, baseCommit)
return err
})
return bundleFile, errors.WithStack(err)
return bundleFile, head, errors.WithStack(err)
}

func createBundleFile(ctx context.Context, repo *gitclone.Repository, baseCommit string) (*os.File, error) {
Expand Down