From 8ff6d520312b304f80ceef09b021a695b23482cf Mon Sep 17 00:00:00 2001 From: Jeremy Schoemaker Date: Fri, 27 Nov 2026 22:24:25 -0600 Subject: [PATCH 1/2] lib/gobuild: count S3 uploads and cache hits correctly maybePutObject added to put_s3_found when it had just written the object, so put_s3_object and put_s3_found were swapped. Count a hit only when the object was already present and matching. Fixes #25 Signed-off-by: Jeremy Schoemaker --- lib/gobuild/gobuild.go | 2 +- lib/gobuild/gobuild_test.go | 142 ++++++++++++++++++++++++++++++++++++ 2 files changed, 143 insertions(+), 1 deletion(-) create mode 100644 lib/gobuild/gobuild_test.go diff --git a/lib/gobuild/gobuild.go b/lib/gobuild/gobuild.go index 5592019..2bfe5e8 100644 --- a/lib/gobuild/gobuild.go +++ b/lib/gobuild/gobuild.go @@ -230,7 +230,7 @@ func (s *S3Cache) maybePutObject(ctx context.Context, outputID, diskPath, etag s gocache.Logf(ctx, "[s3] put object %s: %v", outputID, err) return fi.ModTime(), err } - if written { + if !written { s.putS3Found.Add(1) return fi.ModTime(), nil // already present and matching } diff --git a/lib/gobuild/gobuild_test.go b/lib/gobuild/gobuild_test.go new file mode 100644 index 0000000..9819687 --- /dev/null +++ b/lib/gobuild/gobuild_test.go @@ -0,0 +1,142 @@ +// Copyright (c) Tailscale Inc & AUTHORS +// SPDX-License-Identifier: BSD-3-Clause + +package gobuild + +import ( + "context" + "crypto/md5" + "expvar" + "fmt" + "io" + "net/http" + "os" + "strings" + "testing" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/s3" + "github.com/creachadair/gocache" + "github.com/creachadair/gocache/cachedir" + "github.com/tailscale/go-cache-plugin/lib/s3util" +) + +func TestPutS3Metrics(t *testing.T) { + ctx := context.Background() + local, err := cachedir.New(t.TempDir()) + if err != nil { + t.Fatal(err) + } + + // Model S3's conditional HEAD and object PUT in memory. All requests use + // this transport, with no network access or credential discovery. + objects := make(map[string]string) + puts := make(map[string]int) + heads := 0 + client := s3.New(s3.Options{ + Region: "us-east-1", + Credentials: aws.AnonymousCredentials{}, + BaseEndpoint: aws.String("https://s3.invalid"), + UsePathStyle: true, + RetryMaxAttempts: 1, + HTTPClient: &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) { + status := http.StatusOK + switch req.Method { + case http.MethodHead: + heads++ + data, ok := objects[req.URL.Path] + if !ok { + status = http.StatusNotFound + } else if req.Header.Get("If-Match") != fmt.Sprintf("%x", md5.Sum([]byte(data))) { + status = http.StatusPreconditionFailed + } + case http.MethodPut: + data, err := io.ReadAll(req.Body) + if err != nil { + return nil, err + } + objects[req.URL.Path] = string(data) + puts[req.URL.Path]++ + default: + return nil, fmt.Errorf("unexpected S3 request: %s %s", req.Method, req.URL) + } + return &http.Response{ + StatusCode: status, + Header: make(http.Header), + Body: io.NopCloser(strings.NewReader("")), + Request: req, + }, nil + })}, + }) + cache := &S3Cache{ + Local: local, + S3Client: &s3util.Client{Client: client, Bucket: "test-bucket"}, + UploadConcurrency: 1, + } + t.Cleanup(func() { cache.Close(ctx) }) + metrics := new(expvar.Map).Init() + cache.SetMetrics(ctx, metrics) + metric := func(name string) int64 { return metrics.Get(name).(*expvar.Int).Value() } + + const outputID = "abcdef0123456789" + const body = "cached build output" + outputPath := "/test-bucket/output/ab/" + outputID + for i, step := range []struct { + name string + actionID string + object int64 + found int64 + }{ + {"new output", "0123456789abcdef", 1, 0}, + {"same output for another action", "23456789abcdef01", 0, 1}, + } { + t.Run(step.name, func(t *testing.T) { + wantDeltas := map[string]int64{ + "put_s3_object": step.object, + "put_s3_found": step.found, + "put_s3_action": 1, + "put_s3_error": 0, + } + before := make(map[string]int64) + for name := range wantDeltas { + before[name] = metric(name) + } + diskPath, err := cache.Put(ctx, gocache.Object{ + ActionID: step.actionID, + OutputID: outputID, + Size: int64(len(body)), + Body: strings.NewReader(body), + }) + if err != nil { + t.Fatal(err) + } + // Waiting for the task group also checks asynchronous upload errors + // and makes reads of the fake S3 state safe, without polling/sleeps. + if err := cache.push.Wait(); err != nil { + t.Fatalf("upload: %v", err) + } + for name, want := range wantDeltas { + if got := metric(name) - before[name]; got != want { + t.Errorf("%s increment = %d, want %d", name, got, want) + } + } + if heads != i+1 || puts[outputPath] != 1 || objects[outputPath] != body { + t.Errorf("S3 output: HEADs=%d, PUTs=%d, body=%q; want %d, 1, %q", + heads, puts[outputPath], objects[outputPath], i+1, body) + } + actionPath := "/test-bucket/action/" + step.actionID[:2] + "/" + step.actionID + if puts[actionPath] != 1 || !strings.HasPrefix(objects[actionPath], outputID+" ") { + t.Errorf("S3 action: PUTs=%d, body=%q", puts[actionPath], objects[actionPath]) + } + // Simulate local eviction so the next Put reads and hashes the body + // again instead of cachedir skipping an already-present local file. + if err := os.Remove(diskPath); err != nil { + t.Fatal(err) + } + }) + } +} + +type roundTripFunc func(*http.Request) (*http.Response, error) + +func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) { return f(req) } From 0709466b39d7880983e49f8c9f4d0de296c40ab7 Mon Sep 17 00:00:00 2001 From: Jeremy Schoemaker Date: Sun, 29 Nov 2026 13:05:02 -0600 Subject: [PATCH 2/2] lib/gobuild: drop metrics test per review --- lib/gobuild/gobuild_test.go | 142 ------------------------------------ 1 file changed, 142 deletions(-) delete mode 100644 lib/gobuild/gobuild_test.go diff --git a/lib/gobuild/gobuild_test.go b/lib/gobuild/gobuild_test.go deleted file mode 100644 index 9819687..0000000 --- a/lib/gobuild/gobuild_test.go +++ /dev/null @@ -1,142 +0,0 @@ -// Copyright (c) Tailscale Inc & AUTHORS -// SPDX-License-Identifier: BSD-3-Clause - -package gobuild - -import ( - "context" - "crypto/md5" - "expvar" - "fmt" - "io" - "net/http" - "os" - "strings" - "testing" - - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/service/s3" - "github.com/creachadair/gocache" - "github.com/creachadair/gocache/cachedir" - "github.com/tailscale/go-cache-plugin/lib/s3util" -) - -func TestPutS3Metrics(t *testing.T) { - ctx := context.Background() - local, err := cachedir.New(t.TempDir()) - if err != nil { - t.Fatal(err) - } - - // Model S3's conditional HEAD and object PUT in memory. All requests use - // this transport, with no network access or credential discovery. - objects := make(map[string]string) - puts := make(map[string]int) - heads := 0 - client := s3.New(s3.Options{ - Region: "us-east-1", - Credentials: aws.AnonymousCredentials{}, - BaseEndpoint: aws.String("https://s3.invalid"), - UsePathStyle: true, - RetryMaxAttempts: 1, - HTTPClient: &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) { - status := http.StatusOK - switch req.Method { - case http.MethodHead: - heads++ - data, ok := objects[req.URL.Path] - if !ok { - status = http.StatusNotFound - } else if req.Header.Get("If-Match") != fmt.Sprintf("%x", md5.Sum([]byte(data))) { - status = http.StatusPreconditionFailed - } - case http.MethodPut: - data, err := io.ReadAll(req.Body) - if err != nil { - return nil, err - } - objects[req.URL.Path] = string(data) - puts[req.URL.Path]++ - default: - return nil, fmt.Errorf("unexpected S3 request: %s %s", req.Method, req.URL) - } - return &http.Response{ - StatusCode: status, - Header: make(http.Header), - Body: io.NopCloser(strings.NewReader("")), - Request: req, - }, nil - })}, - }) - cache := &S3Cache{ - Local: local, - S3Client: &s3util.Client{Client: client, Bucket: "test-bucket"}, - UploadConcurrency: 1, - } - t.Cleanup(func() { cache.Close(ctx) }) - metrics := new(expvar.Map).Init() - cache.SetMetrics(ctx, metrics) - metric := func(name string) int64 { return metrics.Get(name).(*expvar.Int).Value() } - - const outputID = "abcdef0123456789" - const body = "cached build output" - outputPath := "/test-bucket/output/ab/" + outputID - for i, step := range []struct { - name string - actionID string - object int64 - found int64 - }{ - {"new output", "0123456789abcdef", 1, 0}, - {"same output for another action", "23456789abcdef01", 0, 1}, - } { - t.Run(step.name, func(t *testing.T) { - wantDeltas := map[string]int64{ - "put_s3_object": step.object, - "put_s3_found": step.found, - "put_s3_action": 1, - "put_s3_error": 0, - } - before := make(map[string]int64) - for name := range wantDeltas { - before[name] = metric(name) - } - diskPath, err := cache.Put(ctx, gocache.Object{ - ActionID: step.actionID, - OutputID: outputID, - Size: int64(len(body)), - Body: strings.NewReader(body), - }) - if err != nil { - t.Fatal(err) - } - // Waiting for the task group also checks asynchronous upload errors - // and makes reads of the fake S3 state safe, without polling/sleeps. - if err := cache.push.Wait(); err != nil { - t.Fatalf("upload: %v", err) - } - for name, want := range wantDeltas { - if got := metric(name) - before[name]; got != want { - t.Errorf("%s increment = %d, want %d", name, got, want) - } - } - if heads != i+1 || puts[outputPath] != 1 || objects[outputPath] != body { - t.Errorf("S3 output: HEADs=%d, PUTs=%d, body=%q; want %d, 1, %q", - heads, puts[outputPath], objects[outputPath], i+1, body) - } - actionPath := "/test-bucket/action/" + step.actionID[:2] + "/" + step.actionID - if puts[actionPath] != 1 || !strings.HasPrefix(objects[actionPath], outputID+" ") { - t.Errorf("S3 action: PUTs=%d, body=%q", puts[actionPath], objects[actionPath]) - } - // Simulate local eviction so the next Put reads and hashes the body - // again instead of cachedir skipping an already-present local file. - if err := os.Remove(diskPath); err != nil { - t.Fatal(err) - } - }) - } -} - -type roundTripFunc func(*http.Request) (*http.Response, error) - -func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) { return f(req) }