tests: an S3 fake that counts at the transport, its contract with the MinIO suite, fixture options and a counting app client
internal/s3fake serves a release.DirStore over the S3 REST subset release.S3Store sends (Get/Head with If-None-Match and If-Match, Put with If-Match and If-None-Match: *, Delete with If-Match, ListObjectsV2 with delimiter paging that spends max-keys on objects and prefixes alike), counts every request, delays each by SetDelay, and has an OnRequest hook that can fail a request or hold its response after the operation ran. TestS3StoreMinioContract's body is now s3StoreContract in package release_test, run against MinIO as before and against the fake in every go test (TestS3StoreFakeContract). export_test.go exposes putRaw and deleteRaw to it in test builds only. newConsoleFixtureWith takes consoleFixtureOptions; with S3 set the console runs the production NewDeploymentS3Store, timed by TimeS3Store into the server's recorder, against the fake over the seeded DirStore. perfLatency carries the 25 ms S3 and 40 ms app-host delays and the counts, and its AppClient answers the instances contract without dialing.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
8 files changed,
+1,328
−130
internal/console/perflatency_test.go+201 −0internal/console/server_test.go+81 −7internal/release/export_test.go+15 −0internal/release/s3_minio_test.go+5 −123internal/release/s3contract_test.go+139 −0internal/release/s3fake_contract_test.go+34 −0internal/s3fake/s3fake.go+613 −0internal/s3fake/s3fake_test.go+240 −0
diff --git a/internal/console/perflatency_test.go b/internal/console/perflatency_test.go| new file mode 100644 |
| index 000000000..819afd196 |
| --- /dev/null |
| +++ b/internal/console/perflatency_test.go |
| @@ -0,0 +1,201 @@ |
| +package console |
| + |
| +import ( |
| + "io" |
| + "net/http" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/s3fake" |
| +) |
| + |
| +// perfLatency is the far end of a console under a speed test: the S3 fake |
| +// its real release.S3Store talks to, and the app hosts its AppClient |
| +// reaches. Both delays start off (the fixture's own setup is free) and |
| +// Enable turns them on or off together. A fixture built with S3 set |
| +// attaches the fake; AppClient is handed to the fixture separately, as |
| +// consoleFixtureOptions.AppClient. |
| +// |
| +// The console makes no direct box HTTP call on a screen path today, so |
| +// HostDelay is applied to the app-host client alone. A box client added to |
| +// a screen path must be added here. |
| +type perfLatency struct { |
| + S3Delay, HostDelay time.Duration |
| + |
| + on atomic.Bool |
| + host atomic.Int64 |
| + fake *s3fake.Server // set by newConsoleFixtureWith |
| +} |
| + |
| +// Enable turns both delays on or off. |
| +func (l *perfLatency) Enable(on bool) { |
| + l.on.Store(on) |
| + if l.fake != nil { |
| + if on { |
| + l.fake.SetDelay(l.S3Delay) |
| + } else { |
| + l.fake.SetDelay(0) |
| + } |
| + } |
| +} |
| + |
| +// Calls is every S3 request the fake has answered and every app-host call |
| +// AppClient has made, since the fixture was built. |
| +func (l *perfLatency) Calls() (s3, host int64) { |
| + if l.fake != nil { |
| + s3 = l.fake.Requests() |
| + } |
| + return s3, l.host.Load() |
| +} |
| + |
| +// Fake is the S3 fake, nil until a fixture attaches it. |
| +func (l *perfLatency) Fake() *s3fake.Server { return l.fake } |
| + |
| +// AppClient is an app-host client that never dials: each request counts |
| +// one host call, sleeps HostDelay when enabled, and answers the instances |
| +// contract (INSTANCES.md) with one healthy instance, or 404 for any other |
| +// path. |
| +func (l *perfLatency) AppClient() *http.Client { |
| + return &http.Client{Transport: &latencyHost{l: l}} |
| +} |
| + |
| +type latencyHost struct{ l *perfLatency } |
| + |
| +func (h *latencyHost) RoundTrip(r *http.Request) (*http.Response, error) { |
| + if r.Body != nil { |
| + r.Body.Close() |
| + } |
| + h.l.host.Add(1) |
| + if h.l.on.Load() && h.l.HostDelay > 0 { |
| + t := time.NewTimer(h.l.HostDelay) |
| + select { |
| + case <-t.C: |
| + case <-r.Context().Done(): |
| + t.Stop() |
| + return nil, r.Context().Err() |
| + } |
| + } |
| + status, body := http.StatusNotFound, "404 page not found\n" |
| + if r.URL.Path == InstancesPath { |
| + status, body = http.StatusOK, `[{"slug":"web-1","status":"ok"}]` |
| + } |
| + return &http.Response{ |
| + Status: http.StatusText(status), |
| + StatusCode: status, |
| + Proto: "HTTP/1.1", |
| + ProtoMajor: 1, |
| + ProtoMinor: 1, |
| + Header: http.Header{"Content-Type": {"application/json"}}, |
| + Body: io.NopCloser(strings.NewReader(body)), |
| + ContentLength: int64(len(body)), |
| + Request: r, |
| + }, nil |
| +} |
| + |
| +func TestLatencyAppClientAnswersTheContract(t *testing.T) { |
| + l := &perfLatency{S3Delay: 25 * time.Millisecond, HostDelay: 40 * time.Millisecond} |
| + l.Enable(true) |
| + start := time.Now() |
| + resp, err := l.AppClient().Get("http://shop.example.com/.carlos/instances") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + body, _ := io.ReadAll(resp.Body) |
| + resp.Body.Close() |
| + if took := time.Since(start); took < 40*time.Millisecond { |
| + t.Errorf("an enabled host call took %v, want at least 40ms", took) |
| + } |
| + if resp.StatusCode != http.StatusOK || string(body) != `[{"slug":"web-1","status":"ok"}]` { |
| + t.Errorf("instances = %d %q, want 200 and one instance", resp.StatusCode, body) |
| + } |
| + if s3, host := l.Calls(); s3 != 0 || host != 1 { |
| + t.Errorf("Calls() = (%d, %d), want (0, 1)", s3, host) |
| + } |
| + |
| + l.Enable(false) |
| + start = time.Now() |
| + resp, err = l.AppClient().Get("http://shop.example.com/elsewhere") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + resp.Body.Close() |
| + if resp.StatusCode != http.StatusNotFound { |
| + t.Errorf("another path = %d, want 404", resp.StatusCode) |
| + } |
| + if took := time.Since(start); took >= 40*time.Millisecond { |
| + t.Errorf("a disabled host call took %v, want no delay", took) |
| + } |
| + if _, host := l.Calls(); host != 2 { |
| + t.Errorf("host calls = %d after two requests, want 2", host) |
| + } |
| +} |
| + |
| +// The fixture over the S3 fake serves a real screen, and the perf sample |
| +// for it counts exactly the S3 requests the fake answered for it. |
| +// |
| +// The first view refreshes the edge fold (server.go foldedEdgeIPs), whose |
| +// two listings run on the request's goroutine but under |
| +// context.Background(), so the recorder counts them as background, not on |
| +// the page. The cold view is held to "every request accounted for"; the |
| +// warm view, inside edgeFoldTTL, to the exact count. |
| +func TestFixtureOverTheS3FakeServesAppPage(t *testing.T) { |
| + lat := &perfLatency{S3Delay: 25 * time.Millisecond, HostDelay: 40 * time.Millisecond} |
| + fx := newConsoleFixtureWith(t, consoleFixtureOptions{WithKey: true, S3: lat, AppClient: lat.AppClient()}) |
| + c := signInPaul(t, fx) |
| + const screen = "GET /a/{sqid}/apps/{app}" |
| + pageCalls := func() int64 { |
| + if g := findGroup(fx.srv.PerfGroups(), screen); g != nil { |
| + return int64(g.Calls["s3"]) |
| + } |
| + return 0 |
| + } |
| + view := func() (fake, sample, background, host int64) { |
| + t.Helper() |
| + s0, h0 := lat.Calls() |
| + p0, b0 := pageCalls(), fx.srv.PerfBackground()["s3"] |
| + resp, body := perfGet(t, c, fx.u("/apps/kass")) |
| + if resp.StatusCode != http.StatusOK { |
| + t.Fatalf("GET app page over the S3 fake = %d:\n%s", resp.StatusCode, body) |
| + } |
| + if !strings.Contains(body, "kass") { |
| + t.Errorf("app page does not name the app:\n%s", body) |
| + } |
| + s1, h1 := lat.Calls() |
| + return s1 - s0, pageCalls() - p0, fx.srv.PerfBackground()["s3"] - b0, h1 - h0 |
| + } |
| + |
| + fake, sample, background, host := view() |
| + if fake <= 0 { |
| + t.Fatalf("the app page made %d S3 requests, want some (is the server on the fake?)", fake) |
| + } |
| + if sample+background != fake { |
| + t.Errorf("cold view: sample Calls[s3] %d + background %d, the fake answered %d", sample, background, fake) |
| + } |
| + if host != 0 { |
| + t.Errorf("the app page made %d app-host calls, want none", host) |
| + } |
| + |
| + lat.Enable(true) |
| + start := time.Now() |
| + fake, sample, background, _ = view() |
| + if fake <= 0 || sample != fake || background != 0 { |
| + t.Errorf("warm view: sample Calls[s3] = %d (background %d), the fake answered %d; want them equal", sample, background, fake) |
| + } |
| + if took, floor := time.Since(start), time.Duration(fake)*lat.S3Delay; took < floor { |
| + t.Errorf("warm view with S3 delays on took %v, under %d requests at %v", took, fake, lat.S3Delay) |
| + } |
| + if g := findGroup(fx.srv.PerfGroups(), screen); g == nil || g.Requests != 2 { |
| + t.Errorf("app page group = %+v, want two requests", g) |
| + } |
| + |
| + // The Running tab's instance report goes through Config.AppClient. |
| + _, h0 := lat.Calls() |
| + if resp, body := perfGet(t, c, fx.u("/apps/kass/instances")); resp.StatusCode != http.StatusOK { |
| + t.Fatalf("GET instances tab over the S3 fake = %d:\n%s", resp.StatusCode, body) |
| + } |
| + if _, h1 := lat.Calls(); h1-h0 != 1 { |
| + t.Errorf("the instances tab made %d app-host calls, want 1", h1-h0) |
| + } |
| +} |
diff --git a/internal/console/server_test.go b/internal/console/server_test.go| index cfad24697..f1c180a55 100644 |
| --- a/internal/console/server_test.go |
| +++ b/internal/console/server_test.go |
| @@ -19,8 +19,10 @@ import ( |
| "time" |
| "github.com/carlosframework/platform/internal/metrics" |
| + "github.com/carlosframework/platform/internal/perf" |
| "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/s3fake" |
| "github.com/carlosframework/platform/internal/status" |
| "github.com/carlosframework/platform/internal/version" |
| ) |
| @@ -53,13 +55,54 @@ func newConsoleFixtureKeyed(t *testing.T, withKey bool) *consoleFixture { |
| // newConsoleFixtureOn is newConsoleFixtureKeyed over rel, when rel is not |
| // nil, instead of the fixture's seeded DirStore. |
| func newConsoleFixtureOn(t *testing.T, withKey bool, rel release.Store) *consoleFixture { |
| + t.Helper() |
| + return newConsoleFixtureWith(t, consoleFixtureOptions{WithKey: withKey, Releases: rel}) |
| +} |
| + |
| +// consoleFixtureOptions are newConsoleFixtureWith's choices. The zero |
| +// value is newConsoleFixtureKeyed(t, false). |
| +type consoleFixtureOptions struct { |
| + // WithKey gives the console the channel signing key; false is the |
| + // read-only deployment shape. |
| + WithKey bool |
| + // Releases, when not nil, replaces the fixture's seeded DirStore. A |
| + // test that needs a real S3 store (TestDBForwardMinio) passes its own; |
| + // the fixture's seeded releases are then absent, which those tests do |
| + // not read. Not with S3. |
| + Releases release.Store |
| + // WrapReleases, when set, wraps the store NewServer is given (after S3 |
| + // is applied). fx.rel stays the unwrapped store. |
| + WrapReleases func(release.Store) release.Store |
| + // AppClient is Config.AppClient, the app-host client (nil: NewServer's). |
| + AppClient *http.Client |
| + // S3, when set, puts the console on a real release.S3Store talking to |
| + // an s3fake over the fixture's seeded DirStore, and attaches the fake |
| + // to S3. Seeding and fx.rel stay on the DirStore, so they are free and |
| + // uncounted. The store is NewDeploymentS3Store's (change index on, as |
| + // production), configured through the environment with t.Setenv, so |
| + // such a test is never parallel; its client is timed by TimeS3Store |
| + // into the server's own recorder (Config.Perf). |
| + S3 *perfLatency |
| +} |
| + |
| +// newConsoleFixtureWith builds the fixture o describes. |
| +func newConsoleFixtureWith(t *testing.T, o consoleFixtureOptions) *consoleFixture { |
| t.Helper() |
| regPath, relStore, priv, pub := buildFixtures(t) |
| - // A test that needs a real S3 store (TestDBForwardMinio) passes its own; |
| - // the fixture's seeded releases are then absent, which those tests do not |
| - // read. |
| - if rel != nil { |
| - relStore = rel |
| + if o.Releases != nil { |
| + if o.S3 != nil { |
| + t.Fatal("newConsoleFixtureWith: Releases and S3 are exclusive") |
| + } |
| + relStore = o.Releases |
| + } |
| + served := relStore |
| + var rec *perf.Recorder |
| + if o.S3 != nil { |
| + rec = new(perf.Recorder) |
| + served = fixtureS3Store(t, relStore, o.S3, rec) |
| + } |
| + if o.WrapReleases != nil { |
| + served = o.WrapReleases(served) |
| } |
| st, err := Open(filepath.Join(t.TempDir(), "console.db")) |
| if err != nil { |
| @@ -78,11 +121,13 @@ func newConsoleFixtureOn(t *testing.T, withKey bool, rel release.Store) *console |
| Origin: ts.URL, |
| Keymail: fk.srv.URL, |
| Registry: regPath, |
| - Releases: relStore, |
| + Releases: served, |
| ReleasePub: pub, |
| AppScheme: "http", // instance polls reach httptest apps, not TLS |
| + AppClient: o.AppClient, |
| + Perf: rec, |
| } |
| - if withKey { |
| + if o.WithKey { |
| cfg.Key = priv |
| } |
| srv, err = NewServer(cfg, st) |
| @@ -104,6 +149,35 @@ func newConsoleFixtureOn(t *testing.T, withKey bool, rel release.Store) *console |
| priv: priv, pub: pub, sqid: release.OpsAccount} |
| } |
| +// fixtureS3Store starts an s3fake over seeded's DirStore, attaches it to |
| +// lat, and returns the production deployment store pointed at it, timed |
| +// into rec. |
| +func fixtureS3Store(t *testing.T, seeded release.Store, lat *perfLatency, rec *perf.Recorder) release.Store { |
| + t.Helper() |
| + ds, ok := seeded.(*deletableStore) |
| + if !ok { |
| + t.Fatalf("fixture store is %T, want the seeded *deletableStore", seeded) |
| + } |
| + dir, ok := ds.Store.(*release.DirStore) |
| + if !ok { |
| + t.Fatalf("fixture store wraps %T, want *release.DirStore", ds.Store) |
| + } |
| + lat.fake = s3fake.New(dir) |
| + lat.Enable(lat.on.Load()) // apply the delay to the fake already attached |
| + fake := httptest.NewServer(lat.fake) |
| + t.Cleanup(fake.Close) |
| + t.Setenv("CARLOS_S3_ENDPOINT", fake.URL) |
| + t.Setenv("AWS_ACCESS_KEY_ID", "fixture") |
| + t.Setenv("AWS_SECRET_ACCESS_KEY", "fixture") |
| + t.Setenv("AWS_REGION", "us-east-1") |
| + t.Setenv("AWS_EC2_METADATA_DISABLED", "true") |
| + s, err := release.NewDeploymentS3Store(context.Background(), "carlos-fixture") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return TimeS3Store(s, rec) |
| +} |
| + |
| // path is a path under the fixture's account, and u is its full URL — every |
| // app page and mutation lives under /a/<sqid>/ now. |
| func (fx *consoleFixture) path(p string) string { return "/a/" + fx.sqid + p } |
diff --git a/internal/release/export_test.go b/internal/release/export_test.go| new file mode 100644 |
| index 000000000..02e1cdfba |
| --- /dev/null |
| +++ b/internal/release/export_test.go |
| @@ -0,0 +1,15 @@ |
| +package release |
| + |
| +import "context" |
| + |
| +// PutRaw and DeleteRaw expose S3Store's unhooked writes (no change-index |
| +// bump) to the external test package, which holds the S3 contract body so |
| +// it can run against internal/s3fake without an import cycle. They exist |
| +// only in test builds. |
| +func PutRaw(s *S3Store, ctx context.Context, key string, body []byte, ifMatch string) (string, error) { |
| + return s.putRaw(ctx, key, body, ifMatch) |
| +} |
| + |
| +func DeleteRaw(s *S3Store, ctx context.Context, key string) error { |
| + return s.deleteRaw(ctx, key) |
| +} |
diff --git a/internal/release/s3_minio_test.go b/internal/release/s3_minio_test.go| index 23d34442f..3fd07ca51 100644 |
| --- a/internal/release/s3_minio_test.go |
| +++ b/internal/release/s3_minio_test.go |
| @@ -1,17 +1,14 @@ |
| -package release |
| +package release_test |
| import ( |
| - "bytes" |
| - "context" |
| - "errors" |
| - "fmt" |
| "os" |
| "testing" |
| - "time" |
| "github.com/aws/aws-sdk-go-v2/aws" |
| "github.com/aws/aws-sdk-go-v2/credentials" |
| awss3 "github.com/aws/aws-sdk-go-v2/service/s3" |
| + |
| + "github.com/carlosframework/platform/internal/release" |
| ) |
| // TestS3StoreMinioContract runs release.S3Store against a real S3-compatible |
| @@ -38,124 +35,9 @@ func TestS3StoreMinioContract(t *testing.T) { |
| RequestChecksumCalculation: aws.RequestChecksumCalculationWhenRequired, |
| ResponseChecksumValidation: aws.ResponseChecksumValidationWhenRequired, |
| }) |
| - s := &S3Store{Client: client, Bucket: bucket} |
| + s := &release.S3Store{Client: client, Bucket: bucket} |
| s.EnableChangeIndex() |
| - ctx := context.Background() |
| - |
| - // One scope per run, so nothing else in the shared bucket moves its |
| - // generation. control/changes.json is the one shared key: the test |
| - // compares generations before and after and leaves it in place. |
| - app := fmt.Sprintf("mt%d", time.Now().UnixNano()) |
| - scope := "apps/" + app + "/shop" |
| - base := scope + "/" |
| - var created []string |
| - t.Cleanup(func() { |
| - for _, k := range created { |
| - _ = s.deleteRaw(context.Background(), k) // not Delete: no bump on the way out |
| - } |
| - }) |
| - keyA, keyB := base+"a.json", base+"b.json" |
| - created = append(created, keyA, keyB) |
| - |
| - gen := func() uint64 { |
| - t.Helper() |
| - idx, _, err := ReadChangeIndex(ctx, s) // an absent index reads as empty |
| - if err != nil { |
| - t.Fatalf("read change index: %v", err) |
| - } |
| - return idx.Entries[scope] |
| - } |
| - bumped := func(name string, before uint64) uint64 { |
| - t.Helper() |
| - after := gen() |
| - if after != before+1 { |
| - t.Fatalf("%s: generation %d -> %d, want exactly +1", name, before, after) |
| - } |
| - return after |
| - } |
| - |
| - t.Run("conditional get and etag listing", func(t *testing.T) { |
| - etag, err := s.putRaw(ctx, keyA, []byte("one"), "") |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - body, e, changed, err := s.GetIfChanged(ctx, keyA, "") |
| - if err != nil || !changed || string(body) != "one" || e != etag { |
| - t.Fatalf("empty etag: %q %q (put %q) %v %v", body, e, etag, changed, err) |
| - } |
| - body, e2, changed, err := s.GetIfChanged(ctx, keyA, e) |
| - if err != nil || changed || body != nil || e2 != e { |
| - t.Fatalf("current etag must be a 304: %q %q %v %v", body, e2, changed, err) |
| - } |
| - if _, err := s.putRaw(ctx, keyA, []byte("two"), e); err != nil { |
| - t.Fatal(err) |
| - } |
| - body, e3, changed, err := s.GetIfChanged(ctx, keyA, e) |
| - if err != nil || !changed || string(body) != "two" || e3 == e { |
| - t.Fatalf("after rewrite: %q %q %v %v", body, e3, changed, err) |
| - } |
| - if _, _, _, err := s.GetIfChanged(ctx, base+"absent.json", e); !errors.Is(err, os.ErrNotExist) { |
| - t.Fatalf("absent: %v", err) |
| - } |
| - if _, err := s.putRaw(ctx, keyB, []byte("b"), ""); err != nil { |
| - t.Fatal(err) |
| - } |
| - listed, err := s.ListETags(ctx, base) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - if len(listed) != 2 || listed[0].Key != keyA || listed[1].Key != keyB { |
| - t.Fatalf("listed %v, want %s and %s sorted", listed, keyA, keyB) |
| - } |
| - for _, ke := range listed { |
| - _, ge, err := s.Get(ctx, ke.Key) |
| - if err != nil || ge != ke.ETag { |
| - t.Fatalf("%s: listed etag %q, Get etag %q (%v)", ke.Key, ke.ETag, ge, err) |
| - } |
| - } |
| - for _, k := range []string{keyA, keyB} { |
| - if err := s.deleteRaw(ctx, k); err != nil { |
| - t.Fatal(err) |
| - } |
| - } |
| - }) |
| - |
| - t.Run("bump through every mutation path", func(t *testing.T) { |
| - g := gen() |
| - etag, err := s.Put(ctx, keyA, []byte("one"), "") |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - g = bumped("Put", g) |
| - |
| - // A Put whose ifMatch is stale loses and must not bump. |
| - if _, err := s.Put(ctx, keyA, []byte("stale"), `"00000000000000000000000000000000"`); !errors.Is(err, ErrCASConflict) { |
| - t.Fatalf("stale Put: %v", err) |
| - } |
| - if after := gen(); after != g { |
| - t.Fatalf("a refused Put moved the generation %d -> %d", g, after) |
| - } |
| - |
| - etag, err = s.PutFrom(ctx, keyA, bytes.NewReader([]byte("two")), 3, etag) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - g = bumped("PutFrom", g) |
| - |
| - if err := DeleteIfMatch(ctx, s, keyA, etag); err != nil { |
| - t.Fatal(err) |
| - } |
| - g = bumped("DeleteIfMatch", g) |
| - |
| - if _, err := s.Put(ctx, keyA, []byte("three"), ""); err != nil { |
| - t.Fatal(err) |
| - } |
| - g = bumped("Put again", g) |
| - if err := s.Delete(ctx, keyA); err != nil { |
| - t.Fatal(err) |
| - } |
| - bumped("Delete", g) |
| - }) |
| + s3StoreContract(t, s) |
| } |
| func minioEnv(t *testing.T, name string) string { |
diff --git a/internal/release/s3contract_test.go b/internal/release/s3contract_test.go| new file mode 100644 |
| index 000000000..188ff7a5f |
| --- /dev/null |
| +++ b/internal/release/s3contract_test.go |
| @@ -0,0 +1,139 @@ |
| +package release_test |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "errors" |
| + "fmt" |
| + "os" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// s3StoreContract is what an S3-compatible server must do for |
| +// release.S3Store, run by TestS3StoreMinioContract against a real MinIO |
| +// and by TestS3StoreFakeContract against internal/s3fake: the conditional |
| +// GET (a 304 for the current ETag), the ETag listing agreeing with Get, |
| +// and the change index bump through every S3Store mutation path. s has its |
| +// change index enabled. |
| +func s3StoreContract(t *testing.T, s *release.S3Store) { |
| + t.Helper() |
| + ctx := context.Background() |
| + |
| + // One scope per run, so nothing else in the shared bucket moves its |
| + // generation. control/changes.json is the one shared key: the test |
| + // compares generations before and after and leaves it in place. |
| + app := fmt.Sprintf("mt%d", time.Now().UnixNano()) |
| + scope := "apps/" + app + "/shop" |
| + base := scope + "/" |
| + var created []string |
| + t.Cleanup(func() { |
| + for _, k := range created { |
| + _ = release.DeleteRaw(s, context.Background(), k) // not Delete: no bump on the way out |
| + } |
| + }) |
| + keyA, keyB := base+"a.json", base+"b.json" |
| + created = append(created, keyA, keyB) |
| + |
| + gen := func() uint64 { |
| + t.Helper() |
| + idx, _, err := release.ReadChangeIndex(ctx, s) // an absent index reads as empty |
| + if err != nil { |
| + t.Fatalf("read change index: %v", err) |
| + } |
| + return idx.Entries[scope] |
| + } |
| + bumped := func(name string, before uint64) uint64 { |
| + t.Helper() |
| + after := gen() |
| + if after != before+1 { |
| + t.Fatalf("%s: generation %d -> %d, want exactly +1", name, before, after) |
| + } |
| + return after |
| + } |
| + |
| + t.Run("conditional get and etag listing", func(t *testing.T) { |
| + etag, err := release.PutRaw(s, ctx, keyA, []byte("one"), "") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + body, e, changed, err := s.GetIfChanged(ctx, keyA, "") |
| + if err != nil || !changed || string(body) != "one" || e != etag { |
| + t.Fatalf("empty etag: %q %q (put %q) %v %v", body, e, etag, changed, err) |
| + } |
| + body, e2, changed, err := s.GetIfChanged(ctx, keyA, e) |
| + if err != nil || changed || body != nil || e2 != e { |
| + t.Fatalf("current etag must be a 304: %q %q %v %v", body, e2, changed, err) |
| + } |
| + if _, err := release.PutRaw(s, ctx, keyA, []byte("two"), e); err != nil { |
| + t.Fatal(err) |
| + } |
| + body, e3, changed, err := s.GetIfChanged(ctx, keyA, e) |
| + if err != nil || !changed || string(body) != "two" || e3 == e { |
| + t.Fatalf("after rewrite: %q %q %v %v", body, e3, changed, err) |
| + } |
| + if _, _, _, err := s.GetIfChanged(ctx, base+"absent.json", e); !errors.Is(err, os.ErrNotExist) { |
| + t.Fatalf("absent: %v", err) |
| + } |
| + if _, err := release.PutRaw(s, ctx, keyB, []byte("b"), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + listed, err := s.ListETags(ctx, base) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(listed) != 2 || listed[0].Key != keyA || listed[1].Key != keyB { |
| + t.Fatalf("listed %v, want %s and %s sorted", listed, keyA, keyB) |
| + } |
| + for _, ke := range listed { |
| + _, ge, err := s.Get(ctx, ke.Key) |
| + if err != nil || ge != ke.ETag { |
| + t.Fatalf("%s: listed etag %q, Get etag %q (%v)", ke.Key, ke.ETag, ge, err) |
| + } |
| + } |
| + for _, k := range []string{keyA, keyB} { |
| + if err := release.DeleteRaw(s, ctx, k); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + }) |
| + |
| + t.Run("bump through every mutation path", func(t *testing.T) { |
| + g := gen() |
| + etag, err := s.Put(ctx, keyA, []byte("one"), "") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + g = bumped("Put", g) |
| + |
| + // A Put whose ifMatch is stale loses and must not bump. |
| + if _, err := s.Put(ctx, keyA, []byte("stale"), `"00000000000000000000000000000000"`); !errors.Is(err, release.ErrCASConflict) { |
| + t.Fatalf("stale Put: %v", err) |
| + } |
| + if after := gen(); after != g { |
| + t.Fatalf("a refused Put moved the generation %d -> %d", g, after) |
| + } |
| + |
| + etag, err = s.PutFrom(ctx, keyA, bytes.NewReader([]byte("two")), 3, etag) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + g = bumped("PutFrom", g) |
| + |
| + if err := release.DeleteIfMatch(ctx, s, keyA, etag); err != nil { |
| + t.Fatal(err) |
| + } |
| + g = bumped("DeleteIfMatch", g) |
| + |
| + if _, err := s.Put(ctx, keyA, []byte("three"), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + g = bumped("Put again", g) |
| + if err := s.Delete(ctx, keyA); err != nil { |
| + t.Fatal(err) |
| + } |
| + bumped("Delete", g) |
| + }) |
| +} |
diff --git a/internal/release/s3fake_contract_test.go b/internal/release/s3fake_contract_test.go| new file mode 100644 |
| index 000000000..d5882d8c9 |
| --- /dev/null |
| +++ b/internal/release/s3fake_contract_test.go |
| @@ -0,0 +1,34 @@ |
| +package release_test |
| + |
| +import ( |
| + "net/http/httptest" |
| + "testing" |
| + |
| + "github.com/aws/aws-sdk-go-v2/aws" |
| + "github.com/aws/aws-sdk-go-v2/credentials" |
| + awss3 "github.com/aws/aws-sdk-go-v2/service/s3" |
| + |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/s3fake" |
| +) |
| + |
| +// TestS3StoreFakeContract holds internal/s3fake to the contract the MinIO |
| +// job holds a real server to, so the console's perf tests stand on a fake |
| +// whose answers S3Store accepts. It runs in every go test. Only this |
| +// external test package imports s3fake, so the import graph stays acyclic. |
| +func TestS3StoreFakeContract(t *testing.T) { |
| + fake := s3fake.New(release.NewDirStore(t.TempDir())) |
| + ts := httptest.NewServer(fake) |
| + t.Cleanup(ts.Close) |
| + client := awss3.New(awss3.Options{ |
| + Region: "us-east-1", |
| + Credentials: credentials.NewStaticCredentialsProvider("x", "y", ""), |
| + BaseEndpoint: aws.String(ts.URL), |
| + UsePathStyle: true, |
| + RequestChecksumCalculation: aws.RequestChecksumCalculationWhenRequired, |
| + ResponseChecksumValidation: aws.ResponseChecksumValidationWhenRequired, |
| + }) |
| + s := &release.S3Store{Client: client, Bucket: "carlos-contract"} |
| + s.EnableChangeIndex() |
| + s3StoreContract(t, s) |
| +} |
diff --git a/internal/s3fake/s3fake.go b/internal/s3fake/s3fake.go| new file mode 100644 |
| index 000000000..f045bf456 |
| --- /dev/null |
| +++ b/internal/s3fake/s3fake.go |
| @@ -0,0 +1,613 @@ |
| +// Package s3fake is an in-process S3 server for tests: the REST subset |
| +// release.S3Store sends, path-style, over the objects a release.DirStore |
| +// holds. It counts every request it answers and can delay each one, so a |
| +// test that runs the production S3Store against it pays and counts what |
| +// production pays: every listing page, the change index's read and write |
| +// after a mutation, conditional requests. TestS3StoreFakeContract in |
| +// internal/release holds it to the contract the MinIO job holds a real |
| +// server to. |
| +// |
| +// It is a test helper: no production code imports it. |
| +package s3fake |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/base64" |
| + "encoding/xml" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "net/http" |
| + "os" |
| + "sort" |
| + "strconv" |
| + "strings" |
| + "sync" |
| + "sync/atomic" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// maxKeys is S3's page bound, and its default. |
| +const maxKeys = 1000 |
| + |
| +// Server is an http.Handler speaking S3 over a DirStore. Any bucket name |
| +// in the path is the same store, and authentication headers are accepted |
| +// unchecked. ETags are the DirStore's content hashes, quoted as S3 sends |
| +// them; a conditional header matches with or without the quotes. |
| +// |
| +// The store must not have its change index enabled: S3 itself never bumps |
| +// it, the client does (release.S3Store), and a store that also bumped |
| +// would count each mutation twice. |
| +type Server struct { |
| + store *release.DirStore |
| + |
| + // mu serialises the fake's own writes, so a check-then-write (an |
| + // unconditional PUT, an If-Match on a missing key) is atomic against |
| + // other requests. Writes made straight to the DirStore are outside it. |
| + mu sync.Mutex |
| + |
| + delay atomic.Int64 // nanoseconds |
| + requests atomic.Int64 |
| + |
| + hookMu sync.RWMutex |
| + hook func(r *http.Request) (status int, hold <-chan struct{}) |
| + |
| + // holding, when set (package tests only), is called as a request |
| + // starts waiting on its hold, after its operation ran. |
| + holding func(r *http.Request) |
| +} |
| + |
| +// New serves store. See Server for what store must be. |
| +func New(store *release.DirStore) *Server { return &Server{store: store} } |
| + |
| +// SetDelay makes every request wait d before it is answered; 0 is none. |
| +func (s *Server) SetDelay(d time.Duration) { s.delay.Store(int64(d)) } |
| + |
| +// Requests is every HTTP request the server has answered, failed and held |
| +// ones included. |
| +func (s *Server) Requests() int64 { return s.requests.Load() } |
| + |
| +// OnRequest installs f, called for each request after its delay and |
| +// before its operation. A non-zero status fails the request with that |
| +// status and an S3 error body, and the operation does not run. A non-nil |
| +// hold lets the operation run (the object read, or the write made) and |
| +// keeps the response until hold is closed or the client goes away. nil f |
| +// removes the hook. |
| +// |
| +// Note that the AWS SDK retries 5xx and throttling answers: a store with |
| +// default retries sends a request the hook fails more than once. |
| +func (s *Server) OnRequest(f func(r *http.Request) (status int, hold <-chan struct{})) { |
| + s.hookMu.Lock() |
| + s.hook = f |
| + s.hookMu.Unlock() |
| +} |
| + |
| +func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| + s.requests.Add(1) |
| + if d := time.Duration(s.delay.Load()); d > 0 { |
| + t := time.NewTimer(d) |
| + select { |
| + case <-t.C: |
| + case <-r.Context().Done(): |
| + t.Stop() |
| + return |
| + } |
| + } |
| + s.hookMu.RLock() |
| + hook := s.hook |
| + s.hookMu.RUnlock() |
| + var hold <-chan struct{} |
| + if hook != nil { |
| + var status int |
| + status, hold = hook(r) |
| + if status != 0 { |
| + writeError(w, r, status, codeFor(status), "failed by the test hook") |
| + return |
| + } |
| + } |
| + if hold == nil { |
| + s.serve(w, r) |
| + return |
| + } |
| + buf := &bufferedResponse{header: http.Header{}} |
| + s.serve(buf, r) |
| + if s.holding != nil { |
| + s.holding(r) |
| + } |
| + select { |
| + case <-hold: |
| + case <-r.Context().Done(): |
| + return |
| + } |
| + buf.copyTo(w) |
| +} |
| + |
| +func (s *Server) serve(w http.ResponseWriter, r *http.Request) { |
| + bucket, key, _ := strings.Cut(strings.TrimPrefix(r.URL.Path, "/"), "/") |
| + if bucket == "" { |
| + writeError(w, r, http.StatusNotImplemented, "NotImplemented", "the fake serves no service-level calls") |
| + return |
| + } |
| + q := r.URL.Query() |
| + // A sub-resource (?tagging, ?uploads, ?acl ...) is an API this fake |
| + // does not speak: say so rather than answer it as a plain object call. |
| + for name := range q { |
| + switch name { |
| + case "list-type", "prefix", "delimiter", "max-keys", "start-after", "continuation-token", "fetch-owner", "x-id": |
| + default: |
| + writeError(w, r, http.StatusNotImplemented, "NotImplemented", "the fake does not support ?"+name) |
| + return |
| + } |
| + } |
| + if key == "" { |
| + if r.Method == http.MethodGet && q.Get("list-type") == "2" { |
| + s.list(w, r, bucket) |
| + return |
| + } |
| + writeError(w, r, http.StatusNotImplemented, "NotImplemented", "the fake answers only ListObjectsV2 on a bucket") |
| + return |
| + } |
| + if r.Header.Get("Range") != "" || r.Header.Get("x-amz-copy-source") != "" { |
| + writeError(w, r, http.StatusNotImplemented, "NotImplemented", "the fake does not support ranges or copies") |
| + return |
| + } |
| + switch r.Method { |
| + case http.MethodGet, http.MethodHead: |
| + s.get(w, r, key) |
| + case http.MethodPut: |
| + s.put(w, r, key) |
| + case http.MethodDelete: |
| + s.delete(w, r, key) |
| + default: |
| + writeError(w, r, http.StatusMethodNotAllowed, "MethodNotAllowed", r.Method+" is not supported") |
| + } |
| +} |
| + |
| +func quote(etag string) string { return `"` + etag + `"` } |
| + |
| +// unquote takes an ETag as a client sent it, quoted (as AWS returns it) or |
| +// bare (the unquoted-If-Match quirk), to the DirStore's form. |
| +func unquote(etag string) string { |
| + etag = strings.TrimSpace(etag) |
| + if len(etag) >= 2 && etag[0] == '"' && etag[len(etag)-1] == '"' { |
| + return etag[1 : len(etag)-1] |
| + } |
| + return etag |
| +} |
| + |
| +// matches reports whether an If-Match or If-None-Match value names etag: |
| +// "*" or a comma-separated list of ETags. |
| +func matches(header, etag string) bool { |
| + for _, v := range strings.Split(header, ",") { |
| + v = strings.TrimSpace(v) |
| + if v == "*" || unquote(v) == etag { |
| + return true |
| + } |
| + } |
| + return false |
| +} |
| + |
| +// badKey reports a DirStore refusal of the key itself (an empty segment, |
| +// ".."), which S3 would have stored; the fake cannot, so it says so. |
| +func badKey(w http.ResponseWriter, r *http.Request, err error) bool { |
| + if err != nil && strings.Contains(err.Error(), "invalid key") { |
| + writeError(w, r, http.StatusBadRequest, "InvalidArgument", err.Error()) |
| + return true |
| + } |
| + return false |
| +} |
| + |
| +func (s *Server) get(w http.ResponseWriter, r *http.Request, key string) { |
| + ctx := r.Context() |
| + body, etag, err := s.store.Get(ctx, key) |
| + if errors.Is(err, os.ErrNotExist) || err != nil && s.isPrefix(ctx, key) { |
| + writeError(w, r, http.StatusNotFound, "NoSuchKey", "The specified key does not exist.") |
| + return |
| + } |
| + if badKey(w, r, err) { |
| + return |
| + } |
| + if err != nil { |
| + writeError(w, r, http.StatusInternalServerError, "InternalError", err.Error()) |
| + return |
| + } |
| + h := w.Header() |
| + h.Set("ETag", quote(etag)) |
| + if mod, ok := s.modTime(ctx, key); ok { |
| + h.Set("Last-Modified", mod.UTC().Format(http.TimeFormat)) |
| + } |
| + if im := r.Header.Get("If-Match"); im != "" && !matches(im, etag) { |
| + writeError(w, r, http.StatusPreconditionFailed, "PreconditionFailed", "At least one of the pre-conditions you specified did not hold") |
| + return |
| + } |
| + if inm := r.Header.Get("If-None-Match"); inm != "" && matches(inm, etag) { |
| + w.WriteHeader(http.StatusNotModified) |
| + return |
| + } |
| + h.Set("Content-Type", "application/octet-stream") |
| + h.Set("Content-Length", strconv.Itoa(len(body))) |
| + w.WriteHeader(http.StatusOK) |
| + if r.Method == http.MethodGet { |
| + _, _ = w.Write(body) |
| + } |
| +} |
| + |
| +// isPrefix reports whether objects sit under key+"/": the DirStore holds |
| +// such a key as a directory and refuses to read it, where S3 has no object |
| +// there at all. |
| +func (s *Server) isPrefix(ctx context.Context, key string) bool { |
| + keys, err := s.store.ListPage(ctx, key+"/", "", 1) |
| + return err == nil && len(keys) > 0 |
| +} |
| + |
| +// modTime is key's stamp, from the DirStore's listing of it. |
| +func (s *Server) modTime(ctx context.Context, key string) (time.Time, bool) { |
| + kms, err := s.store.ListMod(ctx, key) |
| + if err != nil { |
| + return time.Time{}, false |
| + } |
| + for _, km := range kms { |
| + if km.Key == key { |
| + return km.Mod, true |
| + } |
| + } |
| + return time.Time{}, false |
| +} |
| + |
| +func (s *Server) put(w http.ResponseWriter, r *http.Request, key string) { |
| + if strings.Contains(r.Header.Get("Content-Encoding"), "aws-chunked") || |
| + strings.HasPrefix(r.Header.Get("X-Amz-Content-Sha256"), "STREAMING-") { |
| + writeError(w, r, http.StatusNotImplemented, "NotImplemented", "the fake does not decode aws-chunked bodies") |
| + return |
| + } |
| + body, err := io.ReadAll(r.Body) |
| + if err != nil { |
| + writeError(w, r, http.StatusBadRequest, "IncompleteBody", err.Error()) |
| + return |
| + } |
| + ifMatch, ifNoneMatch := r.Header.Get("If-Match"), r.Header.Get("If-None-Match") |
| + if ifNoneMatch != "" && strings.TrimSpace(ifNoneMatch) != "*" || ifMatch != "" && ifNoneMatch != "" { |
| + writeError(w, r, http.StatusNotImplemented, "NotImplemented", "a PUT takes If-Match or If-None-Match: * alone") |
| + return |
| + } |
| + ctx := r.Context() |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + var etag string |
| + switch { |
| + case ifNoneMatch != "": |
| + etag, err = s.store.Put(ctx, key, body, "") |
| + case ifMatch != "": |
| + cur, ok, gerr := s.current(ctx, key) |
| + if badKey(w, r, gerr) { |
| + return |
| + } |
| + if gerr != nil { |
| + writeError(w, r, http.StatusInternalServerError, "InternalError", gerr.Error()) |
| + return |
| + } |
| + if !ok { |
| + // AWS answers a replace-only write on a missing key with 404. |
| + writeError(w, r, http.StatusNotFound, "NoSuchKey", "The specified key does not exist.") |
| + return |
| + } |
| + if !matches(ifMatch, cur) { |
| + err = release.ErrCASConflict |
| + break |
| + } |
| + etag, err = s.store.Put(ctx, key, body, cur) |
| + default: |
| + // Unconditional: overwrite whatever is there. |
| + cur, ok, gerr := s.current(ctx, key) |
| + if badKey(w, r, gerr) { |
| + return |
| + } |
| + if gerr != nil { |
| + writeError(w, r, http.StatusInternalServerError, "InternalError", gerr.Error()) |
| + return |
| + } |
| + if !ok { |
| + cur = "" |
| + } |
| + etag, err = s.store.Put(ctx, key, body, cur) |
| + } |
| + if errors.Is(err, release.ErrCASConflict) { |
| + writeError(w, r, http.StatusPreconditionFailed, "PreconditionFailed", "At least one of the pre-conditions you specified did not hold") |
| + return |
| + } |
| + if badKey(w, r, err) { |
| + return |
| + } |
| + if err != nil { |
| + writeError(w, r, http.StatusInternalServerError, "InternalError", err.Error()) |
| + return |
| + } |
| + w.Header().Set("ETag", quote(etag)) |
| + w.WriteHeader(http.StatusOK) |
| +} |
| + |
| +// current is key's ETag, ok=false when it is absent. |
| +func (s *Server) current(ctx context.Context, key string) (string, bool, error) { |
| + _, etag, err := s.store.Get(ctx, key) |
| + if errors.Is(err, os.ErrNotExist) { |
| + return "", false, nil |
| + } |
| + if err != nil { |
| + return "", false, err |
| + } |
| + return etag, true, nil |
| +} |
| + |
| +func (s *Server) delete(w http.ResponseWriter, r *http.Request, key string) { |
| + ctx := r.Context() |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + if ifMatch := r.Header.Get("If-Match"); ifMatch != "" { |
| + cur, ok, err := s.current(ctx, key) |
| + if badKey(w, r, err) { |
| + return |
| + } |
| + if err != nil { |
| + writeError(w, r, http.StatusInternalServerError, "InternalError", err.Error()) |
| + return |
| + } |
| + if !ok { |
| + writeError(w, r, http.StatusNotFound, "NoSuchKey", "The specified key does not exist.") |
| + return |
| + } |
| + if !matches(ifMatch, cur) { |
| + writeError(w, r, http.StatusPreconditionFailed, "PreconditionFailed", "At least one of the pre-conditions you specified did not hold") |
| + return |
| + } |
| + err = s.store.DeleteIfMatch(ctx, key, cur) |
| + if errors.Is(err, release.ErrCASConflict) { |
| + writeError(w, r, http.StatusPreconditionFailed, "PreconditionFailed", "At least one of the pre-conditions you specified did not hold") |
| + return |
| + } |
| + if err != nil { |
| + writeError(w, r, http.StatusInternalServerError, "InternalError", err.Error()) |
| + return |
| + } |
| + w.WriteHeader(http.StatusNoContent) |
| + return |
| + } |
| + err := s.store.Delete(ctx, key) |
| + if badKey(w, r, err) { |
| + return |
| + } |
| + if err != nil { |
| + writeError(w, r, http.StatusInternalServerError, "InternalError", err.Error()) |
| + return |
| + } |
| + w.WriteHeader(http.StatusNoContent) |
| +} |
| + |
| +// ---- ListObjectsV2 ---------------------------------------------------------- |
| + |
| +type listContents struct { |
| + Key string `xml:"Key"` |
| + LastModified string `xml:"LastModified"` |
| + ETag string `xml:"ETag"` |
| + Size int64 `xml:"Size"` |
| + StorageClass string `xml:"StorageClass"` |
| +} |
| + |
| +type listPrefix struct { |
| + Prefix string `xml:"Prefix"` |
| +} |
| + |
| +type listResult struct { |
| + XMLName xml.Name `xml:"http://s3.amazonaws.com/doc/2006-03-01/ ListBucketResult"` |
| + Name string `xml:"Name"` |
| + Prefix string `xml:"Prefix"` |
| + Delimiter string `xml:"Delimiter,omitempty"` |
| + StartAfter string `xml:"StartAfter,omitempty"` |
| + ContinuationToken string `xml:"ContinuationToken,omitempty"` |
| + NextContinuationToken string `xml:"NextContinuationToken,omitempty"` |
| + MaxKeys int `xml:"MaxKeys"` |
| + KeyCount int `xml:"KeyCount"` |
| + IsTruncated bool `xml:"IsTruncated"` |
| + Contents []listContents `xml:"Contents"` |
| + CommonPrefixes []listPrefix `xml:"CommonPrefixes"` |
| +} |
| + |
| +// entry is one listing slot: an object, or a common prefix standing for |
| +// every key below it. Both spend one of a page's max-keys. |
| +type entry struct { |
| + name string |
| + isPrefix bool |
| + contents listContents |
| +} |
| + |
| +func (s *Server) list(w http.ResponseWriter, r *http.Request, bucket string) { |
| + ctx := r.Context() |
| + q := r.URL.Query() |
| + prefix, delim, startAfter, token := q.Get("prefix"), q.Get("delimiter"), q.Get("start-after"), q.Get("continuation-token") |
| + limit := maxKeys |
| + if v := q.Get("max-keys"); v != "" { |
| + n, err := strconv.Atoi(v) |
| + if err != nil || n < 0 { |
| + writeError(w, r, http.StatusBadRequest, "InvalidArgument", "max-keys must be a non-negative integer") |
| + return |
| + } |
| + limit = min(n, maxKeys) |
| + } |
| + after := "" |
| + if token != "" { |
| + b, err := base64.RawURLEncoding.DecodeString(token) |
| + if err != nil { |
| + writeError(w, r, http.StatusBadRequest, "InvalidArgument", "The continuation token provided is incorrect") |
| + return |
| + } |
| + after = string(b) |
| + } |
| + |
| + // Three DirStore walks give the three columns S3 sends. A key that |
| + // appears in one walk and not another was written between them; it is |
| + // listed with what the ETag walk saw. |
| + etags, err := s.store.ListETags(ctx, prefix) |
| + if err != nil { |
| + writeError(w, r, http.StatusInternalServerError, "InternalError", err.Error()) |
| + return |
| + } |
| + mods, err := s.store.ListMod(ctx, prefix) |
| + if err != nil { |
| + writeError(w, r, http.StatusInternalServerError, "InternalError", err.Error()) |
| + return |
| + } |
| + sizes, err := s.store.ListSizes(ctx, prefix) |
| + if err != nil { |
| + writeError(w, r, http.StatusInternalServerError, "InternalError", err.Error()) |
| + return |
| + } |
| + mod := make(map[string]time.Time, len(mods)) |
| + for _, km := range mods { |
| + mod[km.Key] = km.Mod |
| + } |
| + size := make(map[string]int64, len(sizes)) |
| + for _, ks := range sizes { |
| + size[ks.Key] = ks.Size |
| + } |
| + |
| + var entries []entry |
| + for _, ke := range etags { // key-sorted |
| + if startAfter != "" && ke.Key <= startAfter { |
| + continue |
| + } |
| + if delim != "" { |
| + if i := strings.Index(ke.Key[len(prefix):], delim); i >= 0 { |
| + cp := ke.Key[:len(prefix)+i+len(delim)] |
| + if n := len(entries); n > 0 && entries[n-1].isPrefix && entries[n-1].name == cp { |
| + continue |
| + } |
| + entries = append(entries, entry{name: cp, isPrefix: true}) |
| + continue |
| + } |
| + } |
| + entries = append(entries, entry{name: ke.Key, contents: listContents{ |
| + Key: ke.Key, |
| + LastModified: mod[ke.Key].UTC().Format("2006-01-02T15:04:05.000Z"), |
| + ETag: quote(ke.ETag), |
| + Size: size[ke.Key], |
| + StorageClass: "STANDARD", |
| + }}) |
| + } |
| + // A common prefix sorts before the keys it stands for and is listed |
| + // once, so "every entry after the last one returned" resumes right. |
| + sort.SliceStable(entries, func(i, j int) bool { return entries[i].name < entries[j].name }) |
| + if after != "" { |
| + i := sort.Search(len(entries), func(i int) bool { return entries[i].name > after }) |
| + entries = entries[i:] |
| + } |
| + |
| + res := listResult{ |
| + Name: bucket, Prefix: prefix, Delimiter: delim, StartAfter: startAfter, |
| + ContinuationToken: token, MaxKeys: limit, |
| + } |
| + page := entries |
| + if limit == 0 { |
| + page = nil // max-keys=0 lists nothing and promises nothing more |
| + } else if len(page) > limit { |
| + page = page[:limit] |
| + res.IsTruncated = true |
| + res.NextContinuationToken = base64.RawURLEncoding.EncodeToString([]byte(page[len(page)-1].name)) |
| + } |
| + for _, e := range page { |
| + if e.isPrefix { |
| + res.CommonPrefixes = append(res.CommonPrefixes, listPrefix{Prefix: e.name}) |
| + } else { |
| + res.Contents = append(res.Contents, e.contents) |
| + } |
| + } |
| + res.KeyCount = len(page) |
| + writeXML(w, http.StatusOK, res) |
| +} |
| + |
| +// ---- responses -------------------------------------------------------------- |
| + |
| +type errorBody struct { |
| + XMLName xml.Name `xml:"Error"` |
| + Code string `xml:"Code"` |
| + Message string `xml:"Message"` |
| + Key string `xml:"Key,omitempty"` |
| + RequestID string `xml:"RequestId"` |
| +} |
| + |
| +var requestIDs atomic.Int64 |
| + |
| +// writeError answers an S3 error; a HEAD answer carries no body, as S3's |
| +// does not. |
| +func writeError(w http.ResponseWriter, r *http.Request, status int, code, msg string) { |
| + if r.Method == http.MethodHead { |
| + w.WriteHeader(status) |
| + return |
| + } |
| + _, key, _ := strings.Cut(strings.TrimPrefix(r.URL.Path, "/"), "/") |
| + writeXML(w, status, errorBody{Code: code, Message: msg, Key: key, |
| + RequestID: fmt.Sprintf("S3FAKE%010d", requestIDs.Add(1))}) |
| +} |
| + |
| +func writeXML(w http.ResponseWriter, status int, v any) { |
| + var b bytes.Buffer |
| + b.WriteString(xml.Header) |
| + if err := xml.NewEncoder(&b).Encode(v); err != nil { |
| + http.Error(w, err.Error(), http.StatusInternalServerError) |
| + return |
| + } |
| + w.Header().Set("Content-Type", "application/xml") |
| + w.Header().Set("Content-Length", strconv.Itoa(b.Len())) |
| + w.WriteHeader(status) |
| + _, _ = w.Write(b.Bytes()) |
| +} |
| + |
| +func codeFor(status int) string { |
| + switch status { |
| + case http.StatusInternalServerError: |
| + return "InternalError" |
| + case http.StatusServiceUnavailable: |
| + return "SlowDown" |
| + case http.StatusForbidden: |
| + return "AccessDenied" |
| + case http.StatusNotFound: |
| + return "NoSuchKey" |
| + case http.StatusPreconditionFailed: |
| + return "PreconditionFailed" |
| + case http.StatusConflict: |
| + return "ConditionalRequestConflict" |
| + } |
| + return "FakeError" |
| +} |
| + |
| +// bufferedResponse holds a response while its request waits on a hold. |
| +type bufferedResponse struct { |
| + header http.Header |
| + status int |
| + body bytes.Buffer |
| +} |
| + |
| +func (b *bufferedResponse) Header() http.Header { return b.header } |
| + |
| +func (b *bufferedResponse) WriteHeader(status int) { |
| + if b.status == 0 { |
| + b.status = status |
| + } |
| +} |
| + |
| +func (b *bufferedResponse) Write(p []byte) (int, error) { |
| + b.WriteHeader(http.StatusOK) |
| + return b.body.Write(p) |
| +} |
| + |
| +func (b *bufferedResponse) copyTo(w http.ResponseWriter) { |
| + for k, v := range b.header { |
| + w.Header()[k] = v |
| + } |
| + if b.status == 0 { |
| + b.status = http.StatusOK |
| + } |
| + w.WriteHeader(b.status) |
| + _, _ = w.Write(b.body.Bytes()) |
| +} |
diff --git a/internal/s3fake/s3fake_test.go b/internal/s3fake/s3fake_test.go| new file mode 100644 |
| index 000000000..4b9b280d6 |
| --- /dev/null |
| +++ b/internal/s3fake/s3fake_test.go |
| @@ -0,0 +1,240 @@ |
| +package s3fake |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "net/http" |
| + "net/http/httptest" |
| + "os" |
| + "path/filepath" |
| + "slices" |
| + "testing" |
| + "time" |
| + |
| + "github.com/aws/aws-sdk-go-v2/aws" |
| + "github.com/aws/aws-sdk-go-v2/credentials" |
| + awss3 "github.com/aws/aws-sdk-go-v2/service/s3" |
| + |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// fakeStore is an S3Store talking to a fresh fake over a fresh DirStore, |
| +// with the SDK's retries off so one store call is one request. |
| +func fakeStore(t *testing.T) (*release.S3Store, *Server, *release.DirStore, string) { |
| + t.Helper() |
| + root := t.TempDir() |
| + dir := release.NewDirStore(root) |
| + fake := New(dir) |
| + ts := httptest.NewServer(fake) |
| + t.Cleanup(ts.Close) |
| + client := awss3.New(awss3.Options{ |
| + Region: "us-east-1", |
| + Credentials: credentials.NewStaticCredentialsProvider("x", "y", ""), |
| + BaseEndpoint: aws.String(ts.URL), |
| + UsePathStyle: true, |
| + RequestChecksumCalculation: aws.RequestChecksumCalculationWhenRequired, |
| + ResponseChecksumValidation: aws.ResponseChecksumValidationWhenRequired, |
| + RetryMaxAttempts: 1, |
| + }) |
| + return &release.S3Store{Client: client, Bucket: "b"}, fake, dir, root |
| +} |
| + |
| +func seed(t *testing.T, d *release.DirStore, keys ...string) { |
| + t.Helper() |
| + for _, k := range keys { |
| + if _, err := d.Put(context.Background(), k, []byte("body of "+k), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| +} |
| + |
| +// seedFiles writes keys straight into the DirStore's root: the store's |
| +// own Put syncs every file, which costs seconds over thousands of keys. |
| +func seedFiles(t *testing.T, root string, keys ...string) { |
| + t.Helper() |
| + for _, k := range keys { |
| + p := filepath.Join(root, filepath.FromSlash(k)) |
| + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.WriteFile(p, []byte("body of "+k), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| +} |
| + |
| +// requestsFor is how many requests f answered while do ran. |
| +func requestsFor(t *testing.T, f *Server, do func() error) int64 { |
| + t.Helper() |
| + before := f.Requests() |
| + if err := do(); err != nil { |
| + t.Fatal(err) |
| + } |
| + return f.Requests() - before |
| +} |
| + |
| +// A listing costs what it costs on S3: a page holds 1,000 entries, and a |
| +// delimiter page spends them on objects at the level as well as on the |
| +// prefixes it returns. |
| +func TestS3FakePagesLikeS3(t *testing.T) { |
| + s, fake, _, root := fakeStore(t) |
| + ctx := context.Background() |
| + |
| + var many []string |
| + for i := range 1001 { |
| + many = append(many, fmt.Sprintf("big/k%04d", i)) |
| + } |
| + seedFiles(t, root, many...) |
| + var listed []string |
| + if n := requestsFor(t, fake, func() (err error) { listed, err = s.List(ctx, "big/"); return }); n != 2 { |
| + t.Errorf("List of 1,001 objects took %d requests, want 2", n) |
| + } |
| + if !slices.Equal(listed, many) { |
| + t.Errorf("List returned %d keys, want the 1,001 seeded in order", len(listed)) |
| + } |
| + var mods []release.KeyMod |
| + if n := requestsFor(t, fake, func() (err error) { mods, err = s.ListMod(ctx, "big/"); return }); n != 2 { |
| + t.Errorf("ListMod of 1,001 objects took %d requests, want 2", n) |
| + } |
| + if len(mods) != 1001 || mods[0].Mod.IsZero() { |
| + t.Errorf("ListMod returned %d entries (first %+v), want 1,001 with stamps", len(mods), mods[0]) |
| + } |
| + |
| + var level []string |
| + for i := range 1500 { |
| + level = append(level, fmt.Sprintf("lvl/o%04d.json", i)) |
| + } |
| + level = append(level, "lvl/a/x.json", "lvl/a/y.json", "lvl/zz/deep/z.json") |
| + seedFiles(t, root, level...) |
| + var dirs []string |
| + if n := requestsFor(t, fake, func() (err error) { dirs, err = s.ListDirs(ctx, "lvl/"); return }); n != 2 { |
| + t.Errorf("ListDirs over 1,500 objects and 2 prefixes took %d requests, want 2", n) |
| + } |
| + if want := []string{"lvl/a/", "lvl/zz/"}; !slices.Equal(dirs, want) { |
| + t.Errorf("ListDirs = %q, want %q", dirs, want) |
| + } |
| + |
| + if n := requestsFor(t, fake, func() (err error) { listed, err = s.List(ctx, "empty/"); return }); n != 1 || len(listed) != 0 { |
| + t.Errorf("List of an empty prefix took %d requests and returned %q, want 1 and nothing", n, listed) |
| + } |
| + if n := requestsFor(t, fake, func() (err error) { dirs, err = s.ListDirs(ctx, "empty/"); return }); n != 1 || len(dirs) != 0 { |
| + t.Errorf("ListDirs of an empty prefix took %d requests and returned %q, want 1 and nothing", n, dirs) |
| + } |
| + |
| + // A bounded page is one request, starting after the given key. |
| + var page []string |
| + if n := requestsFor(t, fake, func() (err error) { page, err = s.ListPage(ctx, "big/", "big/k0997", 2); return }); n != 1 { |
| + t.Errorf("ListPage took %d requests, want 1", n) |
| + } |
| + if want := []string{"big/k0998", "big/k0999"}; !slices.Equal(page, want) { |
| + t.Errorf("ListPage = %q, want %q", page, want) |
| + } |
| + // Unbounded with a start: the paginator sends start-after on every page. |
| + if n := requestsFor(t, fake, func() (err error) { page, err = s.ListPage(ctx, "big/", "big/k0000", 0); return }); n != 1 { |
| + t.Errorf("unbounded ListPage after the first key took %d requests, want 1 (1,000 keys left)", n) |
| + } |
| + if len(page) != 1000 || page[0] != "big/k0001" || page[999] != "big/k1000" { |
| + t.Errorf("unbounded ListPage returned %d keys from %q", len(page), page[0]) |
| + } |
| +} |
| + |
| +// The change index rides on every mutation of a scoped key: the write, |
| +// then the index's read and its write. The fake counts all three. |
| +func TestS3FakeCountsChangeIndexRequests(t *testing.T) { |
| + dir := release.NewDirStore(t.TempDir()) |
| + fake := New(dir) |
| + ts := httptest.NewServer(fake) |
| + t.Cleanup(ts.Close) |
| + t.Setenv("CARLOS_S3_ENDPOINT", ts.URL) |
| + t.Setenv("AWS_ACCESS_KEY_ID", "x") |
| + t.Setenv("AWS_SECRET_ACCESS_KEY", "y") |
| + t.Setenv("AWS_REGION", "us-east-1") |
| + t.Setenv("AWS_EC2_METADATA_DISABLED", "true") |
| + ctx := context.Background() |
| + s, err := release.NewDeploymentS3Store(ctx, "b") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if n := requestsFor(t, fake, func() error { |
| + _, err := s.Put(ctx, "apps/shop/web/state.json", []byte("{}"), "") |
| + return err |
| + }); n != 3 { |
| + t.Errorf("one scoped Put took %d requests, want 3 (write, index read, index write)", n) |
| + } |
| + idx, _, err := release.ReadChangeIndex(ctx, dir) |
| + if err != nil || idx.Entries["apps/shop/web"] != 1 { |
| + t.Fatalf("change index after one Put = %+v (%v), want apps/shop/web at 1", idx, err) |
| + } |
| +} |
| + |
| +func TestS3FakeDelayAndHook(t *testing.T) { |
| + s, fake, dir, _ := fakeStore(t) |
| + ctx := context.Background() |
| + seed(t, dir, "k/one", "k/broken", "k/held") |
| + |
| + // A prefix is not an object, though the DirStore holds it as a |
| + // directory. |
| + if _, _, err := s.Get(ctx, "k"); !errors.Is(err, os.ErrNotExist) { |
| + t.Errorf("Get of a prefix = %v, want not-exist", err) |
| + } |
| + |
| + fake.SetDelay(25 * time.Millisecond) |
| + start := time.Now() |
| + if _, _, err := s.Get(ctx, "k/one"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if took := time.Since(start); took < 25*time.Millisecond { |
| + t.Errorf("a Get with a 25 ms delay took %v", took) |
| + } |
| + fake.SetDelay(0) |
| + |
| + hold := make(chan struct{}) |
| + fake.OnRequest(func(r *http.Request) (int, <-chan struct{}) { |
| + switch r.URL.Path { |
| + case "/b/k/broken": |
| + return http.StatusInternalServerError, nil |
| + case "/b/k/held": |
| + return 0, hold |
| + } |
| + return 0, nil |
| + }) |
| + if _, _, err := s.Get(ctx, "k/broken"); err == nil || errors.Is(err, os.ErrNotExist) { |
| + t.Errorf("Get of the failed key = %v, want a server error", err) |
| + } |
| + if body, _, err := s.Get(ctx, "k/one"); err != nil || string(body) != "body of k/one" { |
| + t.Errorf("Get of another key = %q, %v; the hook failed it", body, err) |
| + } |
| + |
| + holding := make(chan struct{}) |
| + fake.holding = func(*http.Request) { close(holding) } |
| + type got struct { |
| + body []byte |
| + err error |
| + } |
| + done := make(chan got, 1) |
| + go func() { |
| + b, _, err := s.Get(ctx, "k/held") |
| + done <- got{b, err} |
| + }() |
| + select { |
| + case <-holding: |
| + case <-time.After(5 * time.Second): |
| + t.Fatal("the held request never reached its hold") |
| + } |
| + // The object was read before the hold: deleting it now does not |
| + // change the answer the held request gives. |
| + if err := dir.Delete(ctx, "k/held"); err != nil { |
| + t.Fatal(err) |
| + } |
| + select { |
| + case g := <-done: |
| + t.Fatalf("the held Get answered before its hold closed: %q %v", g.body, g.err) |
| + case <-time.After(50 * time.Millisecond): |
| + } |
| + close(hold) |
| + g := <-done |
| + if g.err != nil || string(g.body) != "body of k/held" { |
| + t.Errorf("held Get = %q, %v; want the body read before the hold", g.body, g.err) |
| + } |
| +} |