Skip to content
Open
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
2 changes: 1 addition & 1 deletion lib/gobuild/gobuild.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
142 changes: 142 additions & 0 deletions lib/gobuild/gobuild_test.go
Original file line number Diff line number Diff line change
@@ -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) }