Skip to content
Merged
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
8 changes: 7 additions & 1 deletion internal/strategy/git/backend.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ func (b *bufferedResponseWriter) commit() {
//
// It returns true when upload-pack rejects the request with "not our ref" and it should be retried upstream.
// This typically happens when a concurrent force-push fetch orphans a previously advertised commit.
func (s *Strategy) serveFromBackend(w http.ResponseWriter, r *http.Request, repo *gitclone.Repository) bool {
func (s *Strategy) serveFromBackend(w http.ResponseWriter, r *http.Request, repo *gitclone.Repository, incremental bool) bool {
ctx := r.Context()
logger := logging.FromContext(ctx)

Expand Down Expand Up @@ -146,6 +146,12 @@ func (s *Strategy) serveFromBackend(w http.ResponseWriter, r *http.Request, repo
"PATH=" + os.Getenv("PATH"),
},
}
// Incremental fetches skip bitmaps, whose fill-in for uncovered haves walks a whole tree, seconds on a monorepo.
//
// Clones send no haves and need bitmaps to avoid walking every object.
if incremental {
handler.Env = append(handler.Env, "GIT_CONFIG_COUNT=1", "GIT_CONFIG_KEY_0=pack.useBitmaps", "GIT_CONFIG_VALUE_0=false")
}

r2 := r.Clone(r.Context())
r2.URL.Path = backendPath
Expand Down
2 changes: 1 addition & 1 deletion internal/strategy/git/bundlecoord_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -349,7 +349,7 @@ func TestBundleBuildCancellationReleasesFetchLock(t *testing.T) {
assert.NoError(t, err)
bin := t.TempDir()
started := filepath.Join(bin, "started")
script := fmt.Sprintf("#!/bin/sh\nif [ \"$3\" = bundle ]; then\n sleep 2 &\n touch %q\n wait\nfi\nexec %q \"$@\"\n", started, realGit)
script := fmt.Sprintf("#!/bin/sh\ncase \" $* \" in *\" bundle create \"*)\n sleep 2 &\n touch %q\n wait\nesac\nexec %q \"$@\"\n", started, realGit)
assert.NoError(t, os.WriteFile(filepath.Join(bin, "git"), []byte(script), 0o700))
t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
ctx, cancel := context.WithCancel(s.ctx)
Expand Down
5 changes: 3 additions & 2 deletions internal/strategy/git/git.go
Original file line number Diff line number Diff line change
Expand Up @@ -518,7 +518,8 @@ func (s *Strategy) serveReadyRepo(w http.ResponseWriter, r *http.Request, repo *
r.TransferEncoding = nil
}

if !s.serveFromBackend(w, r, repo) {
incremental := strings.HasSuffix(pathValue, "/git-upload-pack") && uploadPackBodyHasHaves(r.Header, bodyBytes)
if !s.serveFromBackend(w, r, repo, incremental) {
return nil
}
replayBody := func() {
Expand All @@ -537,7 +538,7 @@ func (s *Strategy) serveReadyRepo(w http.ResponseWriter, r *http.Request, repo *
"error", err)
} else {
replayBody()
if !s.serveFromBackend(w, r, repo) {
if !s.serveFromBackend(w, r, repo, incremental) {
logger.InfoContext(ctx, "Served from mirror after fetching object missing for 'not our ref'", "path", pathValue)
return nil
}
Expand Down
26 changes: 18 additions & 8 deletions internal/strategy/git/repocounts.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,15 +112,25 @@ func inspectUploadPackBody(r *http.Request) ([]byte, error) {
io.Closer
}{io.MultiReader(bytes.NewReader(prefix), original), original}

inspect := prefix
if strings.EqualFold(r.Header.Get("Content-Encoding"), "gzip") {
if gr, gzErr := gzip.NewReader(bytes.NewReader(prefix)); gzErr == nil {
decoded, _ := io.ReadAll(io.LimitReader(gr, uploadPackBodyInspectLimit)) //nolint:errcheck // best-effort
_ = gr.Close() //nolint:errcheck // best-effort
inspect = decoded
}
return decodeUploadPackPrefix(r.Header, prefix), nil
}

func uploadPackBodyHasHaves(header http.Header, body []byte) bool {
inspect := decodeUploadPackPrefix(header, body[:min(len(body), uploadPackBodyInspectLimit)])
return !isLsRefsBody(inspect) && bytes.Contains(inspect, haveNeedle)
}

func decodeUploadPackPrefix(header http.Header, prefix []byte) []byte {
if !strings.EqualFold(header.Get("Content-Encoding"), "gzip") {
return prefix
}
gr, err := gzip.NewReader(bytes.NewReader(prefix))
if err != nil {
return prefix
}
return inspect, nil
decoded, _ := io.ReadAll(io.LimitReader(gr, uploadPackBodyInspectLimit)) //nolint:errcheck // best-effort
_ = gr.Close() //nolint:errcheck // best-effort
return decoded
}

func isLsRefsBody(inspect []byte) bool {
Expand Down
2 changes: 1 addition & 1 deletion internal/strategy/git/snapshot.go
Original file line number Diff line number Diff line change
Expand Up @@ -1044,7 +1044,7 @@ func createBundleFile(ctx context.Context, repo *gitclone.Repository, baseCommit
return nil, errors.Wrap(err, "close bundle temp file")
}

cmd := exec.CommandContext(ctx, "git", "-C", repo.Path(), "bundle", "create", //nolint:gosec // baseCommit is a SHA string from rev-parse
cmd := exec.CommandContext(ctx, "git", "-C", repo.Path(), "-c", "pack.useBitmaps=false", "bundle", "create", //nolint:gosec // baseCommit is a SHA string from rev-parse
bundlePath, headRef, "^"+baseCommit)
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
cmd.Cancel = func() error {
Expand Down
132 changes: 132 additions & 0 deletions internal/strategy/git/upload_pack_bitmaps_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
package git_test

import (
"bytes"
"compress/gzip"
"fmt"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"

"github.com/alecthomas/assert/v2"
)

func recordBackendBitmaps(t *testing.T, upstream string) string {
t.Helper()
realGit, err := exec.LookPath("git")
assert.NoError(t, err)
dir := t.TempDir()
log := filepath.Join(dir, "backend.log")
script := fmt.Sprintf(`#!/bin/sh
if echo " $* " | grep -q ' ls-remote '; then
exec %[1]q ls-remote %[2]q
fi
if [ "$1" = http-backend ]; then
echo "bitmaps=$(%[1]q config --get pack.usebitmaps)" >> %[3]q
fi
exec %[1]q "$@"
`, realGit, upstream, log)
assert.NoError(t, os.WriteFile(filepath.Join(dir, "git"), []byte(script), 0o755))
t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))
return log
}

func TestUploadPackSkipsBitmapsOnlyForIncrementalFetches(t *testing.T) {
tests := []struct {
name string
protocol string
body func(want, have string) string
newWant bool
gzipped bool
backend []string
forwarded int32
}{
{
name: "v2 fetch with haves",
protocol: "version=2",
body: func(want, have string) string {
return pkt("command=fetch\n") + "0001" + pkt("want "+want+"\n") + pkt("have "+have+"\n") + pkt("done\n") + "0000"
},
backend: []string{"bitmaps=false"},
},
{
name: "v0 fetch with haves",
body: func(want, have string) string {
return pkt("want "+want+"\n") + "0000" + pkt("have "+have+"\n") + pkt("done\n")
},
backend: []string{"bitmaps=false"},
},
{
name: "gzipped v0 fetch with haves",
body: func(want, have string) string {
return pkt("want "+want+"\n") + "0000" + pkt("have "+have+"\n") + pkt("done\n")
},
gzipped: true,
backend: []string{"bitmaps=false"},
},
{
name: "fetch replayed after not our ref",
body: func(want, have string) string {
return pkt("want "+want+"\n") + "0000" + pkt("have "+have+"\n") + pkt("done\n")
},
newWant: true,
backend: []string{"bitmaps=false", "bitmaps=false"},
},
{
name: "v0 clone",
body: func(want, _ string) string {
return pkt("want "+want+"\n") + "0000" + pkt("done\n")
},
backend: []string{"bitmaps="},
},
{
name: "v2 ls-refs",
protocol: "version=2",
body: func(_, _ string) string { return pkt("command=ls-refs\n") + "0000" },
backend: []string{"bitmaps="},
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
fixture := newInfoRefsFixture(t)
log := recordBackendBitmaps(t, fixture.upstreamPath)
have := runInfoRefsGit(t, "-C", fixture.mirrorPath, "rev-parse", "refs/heads/main")
want := have
if test.newWant {
want = fixture.commitUpstream(t)
}
body := []byte(test.body(want, have))
if test.gzipped {
var compressed bytes.Buffer
gw := gzip.NewWriter(&compressed)
_, err := gw.Write(body)
assert.NoError(t, err)
assert.NoError(t, gw.Close())
body = compressed.Bytes()
}
req := httptest.NewRequestWithContext(fixture.ctx, http.MethodPost,
"/git/example.test/org/repo/git-upload-pack", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/x-git-upload-pack-request")
if test.gzipped {
req.Header.Set("Content-Encoding", "gzip")
}
if test.protocol != "" {
req.Header.Set("Git-Protocol", test.protocol)
}
req.SetPathValue("host", "example.test")
req.SetPathValue("path", "org/repo/git-upload-pack")
w := httptest.NewRecorder()
fixture.uploadPack.ServeHTTP(w, req)

assert.Equal(t, http.StatusOK, w.Code)
assert.Equal(t, test.forwarded, fixture.transport.hits.Load())
recorded, err := os.ReadFile(log)
assert.NoError(t, err)
assert.Equal(t, test.backend, strings.Fields(string(recorded)))
})
}
}