| new file mode 100644 |
| index 000000000..80d401d59 |
| --- /dev/null |
| +++ b/internal/edge/storedoor_stream_test.go |
| @@ -0,0 +1,388 @@ |
| +package edge |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "net/http" |
| + "net/http/httptest" |
| + "runtime" |
| + "strconv" |
| + "strings" |
| + "sync" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/aws/aws-sdk-go-v2/aws" |
| + "github.com/aws/aws-sdk-go-v2/service/s3" |
| + "github.com/carlosframework/platform/internal/fleetapi" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +type doorStreamStore struct { |
| + release.Store |
| + open func() (io.ReadCloser, string, error) |
| + opens atomic.Int32 |
| + gets atomic.Int32 |
| +} |
| + |
| +func (s *doorStreamStore) Open(context.Context, string) (io.ReadCloser, string, error) { |
| + s.opens.Add(1) |
| + return s.open() |
| +} |
| +func (s *doorStreamStore) Get(context.Context, string) ([]byte, string, error) { |
| + s.gets.Add(1) |
| + return nil, "", errors.New("unexpected buffered Get") |
| +} |
| + |
| +type doorSizedBody struct { |
| + io.Reader |
| + size int64 |
| + closed bool |
| +} |
| + |
| +func (b *doorSizedBody) Size() int64 { return b.size } |
| +func (b *doorSizedBody) Close() error { b.closed = true; return nil } |
| + |
| +type doorPatternReader struct{} |
| + |
| +func (doorPatternReader) Read(p []byte) (int, error) { |
| + for i := range p { |
| + p[i] = 'x' |
| + } |
| + return len(p), nil |
| +} |
| + |
| +type doorCountingWriter struct { |
| + header http.Header |
| + status int |
| + bytes int64 |
| + bad bool |
| +} |
| + |
| +func (w *doorCountingWriter) Header() http.Header { return w.header } |
| +func (w *doorCountingWriter) WriteHeader(code int) { w.status = code } |
| +func (w *doorCountingWriter) Write(p []byte) (int, error) { |
| + if w.status == 0 { |
| + w.status = http.StatusOK |
| + } |
| + w.bytes += int64(len(p)) |
| + for _, b := range p { |
| + if b != 'x' { |
| + w.bad = true |
| + } |
| + } |
| + return len(p), nil |
| +} |
| + |
| +func TestStoreDoorStreamsLargeObject(t *testing.T) { |
| + d, base := newTestDoor(t) |
| + const size = 64 << 20 |
| + body := &doorSizedBody{Reader: io.LimitReader(doorPatternReader{}, size), size: size} |
| + s := &doorStreamStore{Store: base, open: func() (io.ReadCloser, string, error) { return body, `"opaque"`, nil }} |
| + d.store = s |
| + w := &doorCountingWriter{header: make(http.Header)} |
| + req := doorReq("GET", storeObjectPrefix+ownKey, testChannel, testToken, "") |
| + runtime.GC() |
| + var before, after runtime.MemStats |
| + runtime.ReadMemStats(&before) |
| + d.ServeHTTP(w, req) |
| + runtime.ReadMemStats(&after) |
| + if allocated := after.TotalAlloc - before.TotalAlloc; allocated >= 8<<20 { |
| + t.Fatalf("allocated %d bytes for a %d-byte stream", allocated, size) |
| + } else { |
| + t.Logf("64 MiB stream allocated %d bytes", allocated) |
| + } |
| + if s.gets.Load() != 0 || s.opens.Load() != 1 || !body.closed { |
| + t.Fatalf("gets=%d opens=%d closed=%v", s.gets.Load(), s.opens.Load(), body.closed) |
| + } |
| + if w.status != 200 || w.bytes != size || w.bad { |
| + t.Fatalf("status=%d bytes=%d bad=%v", w.status, w.bytes, w.bad) |
| + } |
| + for k, v := range map[string]string{"ETag": `"opaque"`, "Content-Type": "application/octet-stream", "Content-Length": strconv.Itoa(size)} { |
| + if got := w.header.Get(k); got != v { |
| + t.Errorf("%s=%q want %q", k, got, v) |
| + } |
| + } |
| +} |
| + |
| +func TestStoreDoorStreamMissingAndDirMetadata(t *testing.T) { |
| + d, s := newTestDoor(t) |
| + for _, key := range []string{ownKey, release.AppPolicyKey(testSqid, "web")} { |
| + w := doorDo(d, "GET", storeObjectPrefix+key, "", nil) |
| + absent := "" |
| + if key != ownKey { |
| + absent = "1" |
| + } |
| + if w.Code != 404 || w.Body.String() != "404 page not found\n" || w.Header().Get(storeAbsentHeader) != absent { |
| + t.Fatalf("missing %s: %d %q %v", key, w.Code, w.Body.String(), w.Header()) |
| + } |
| + } |
| + etag := seedObject(t, s, ownKey, "body") |
| + w := doorDo(d, "GET", storeObjectPrefix+ownKey, "", nil) |
| + if w.Code != 200 || w.Body.String() != "body" || w.Header().Get("ETag") != etag || w.Header().Get("Content-Length") != "4" { |
| + t.Fatalf("GET: %d %q %v", w.Code, w.Body.String(), w.Header()) |
| + } |
| +} |
| + |
| +type doorGetOnly struct { |
| + release.Store |
| + body []byte |
| + gets int |
| +} |
| + |
| +func (s *doorGetOnly) Get(context.Context, string) ([]byte, string, error) { |
| + s.gets++ |
| + return s.body, "legacy", nil |
| +} |
| + |
| +func TestStoreDoorStreamFallback(t *testing.T) { |
| + for _, size := range []int{3, release.PutFromFallbackMax, release.PutFromFallbackMax + 1} { |
| + t.Run(strconv.Itoa(size), func(t *testing.T) { |
| + d, base := newTestDoor(t) |
| + s := &doorGetOnly{Store: base, body: make([]byte, size)} |
| + d.store = s |
| + w := httptest.NewRecorder() |
| + w.Body = nil |
| + d.ServeHTTP(w, doorReq("GET", storeObjectPrefix+ownKey, testChannel, testToken, "")) |
| + want := 200 |
| + if size > release.PutFromFallbackMax { |
| + want = 502 |
| + } |
| + if w.Code != want || s.gets != 1 { |
| + t.Fatalf("status=%d gets=%d", w.Code, s.gets) |
| + } |
| + if want == 200 && (w.Header().Get("Content-Length") != strconv.Itoa(size) || w.Header().Get("ETag") != "legacy") { |
| + t.Fatal(w.Header()) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +type doorBlockingReader struct { |
| + release <-chan struct{} |
| + started chan<- struct{} |
| + done bool |
| +} |
| + |
| +func (r *doorBlockingReader) Read(p []byte) (int, error) { |
| + if r.done { |
| + return 0, io.EOF |
| + } |
| + r.started <- struct{}{} |
| + <-r.release |
| + r.done = true |
| + return copy(p, "x"), nil |
| +} |
| + |
| +func TestStoreDoorStreamCaps(t *testing.T) { |
| + d, base := newTestDoor(t) |
| + releaseBodies := make(chan struct{}) |
| + started := make(chan struct{}, 8) |
| + var workers sync.WaitGroup |
| + s := &doorStreamStore{Store: base, open: func() (io.ReadCloser, string, error) { |
| + return io.NopCloser(&doorBlockingReader{release: releaseBodies, started: started}), "", nil |
| + }} |
| + d.store = s |
| + auth := map[string]string{} |
| + for i := 0; i < 5; i++ { |
| + auth[fmt.Sprintf("%s/box-%d", testFleet, i)] = sha256Hex(testToken) |
| + } |
| + d.hub.SetDynamicAuth(auth) |
| + defer func() { |
| + close(releaseBodies) |
| + workers.Wait() |
| + if d.getTotal != 0 || len(d.gets) != 0 { |
| + t.Errorf("leaked slots: total=%d boxes=%v", d.getTotal, d.gets) |
| + } |
| + }() |
| + request := func(box int) *http.Request { |
| + return doorReq("GET", storeObjectPrefix+ownKey, fmt.Sprintf("%s/box-%d", testFleet, box), testToken, "") |
| + } |
| + start := func(box int) { |
| + workers.Add(1) |
| + go func() { defer workers.Done(); d.ServeHTTP(httptest.NewRecorder(), request(box)) }() |
| + select { |
| + case <-started: |
| + case <-time.After(5 * time.Second): |
| + t.Fatal("GET did not start") |
| + } |
| + } |
| + reject := func(box int) { |
| + before := s.opens.Load() |
| + w := httptest.NewRecorder() |
| + done := make(chan struct{}) |
| + workers.Add(1) |
| + go func() { defer workers.Done(); d.ServeHTTP(w, request(box)); close(done) }() |
| + select { |
| + case <-done: |
| + case <-time.After(5 * time.Second): |
| + t.Fatal("capped GET blocked instead of returning 429") |
| + } |
| + if w.Code != 429 || w.Header().Get("Retry-After") != "5" || s.opens.Load() != before { |
| + t.Fatalf("cap: %d %v opens %d -> %d", w.Code, w.Header(), before, s.opens.Load()) |
| + } |
| + } |
| + start(0) |
| + start(0) |
| + reject(0) |
| + for box := 1; box < 4; box++ { |
| + start(box) |
| + start(box) |
| + } |
| + reject(4) |
| + // Auth and ACL refusals must still be indistinguishable at capacity. |
| + r := request(0) |
| + r.URL.Path = storeObjectPrefix + otherAccountKey |
| + w := httptest.NewRecorder() |
| + d.ServeHTTP(w, r) |
| + if w.Code != 404 || w.Body.String() != "404 page not found\n" { |
| + t.Fatal(w.Code, w.Body) |
| + } |
| + // Claim reads and PUTs do not consume object GET slots. |
| + w = httptest.NewRecorder() |
| + r = request(0) |
| + r.URL.Path = storeObjectPrefix + "domains/missing.example.json" |
| + d.ServeHTTP(w, r) |
| + if w.Code != 502 { |
| + t.Fatalf("claim must reach Get (tripwire), got %d", w.Code) |
| + } |
| + r = request(0) |
| + r.Method = "PUT" |
| + r.URL.Path = storeObjectPrefix + ownFleetKey |
| + r.Body = io.NopCloser(strings.NewReader("ok")) |
| + r.Header.Set("If-None-Match", "*") |
| + w = httptest.NewRecorder() |
| + d.ServeHTTP(w, r) |
| + if w.Code != 200 { |
| + t.Fatalf("PUT: %d", w.Code) |
| + } |
| +} |
| + |
| +func TestStoreDoorStreamUnknownLengthClient(t *testing.T) { |
| + d, base := newTestDoor(t) |
| + s := &doorStreamStore{Store: base, open: func() (io.ReadCloser, string, error) { |
| + return io.NopCloser(io.LimitReader(doorPatternReader{}, 128<<10)), "", nil |
| + }} |
| + d.store = s |
| + server := httptest.NewServer(d) |
| + defer server.Close() |
| + client, err := fleetapi.New(server.URL, testChannel, testToken) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + body, tag, err := release.OpenObjectStreaming(t.Context(), client, ownKey) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer body.Close() |
| + n, err := io.Copy(io.Discard, body) |
| + if err != nil || n != 128<<10 || tag != "" || s.gets.Load() != 0 { |
| + t.Fatalf("bytes=%d tag=%q err=%v gets=%d", n, tag, err, s.gets.Load()) |
| + } |
| + w := doorDo(d, "GET", storeObjectPrefix+ownKey, "", nil) |
| + if w.Header().Get("Content-Length") != "" || w.Header().Get("ETag") != "" { |
| + t.Fatal(w.Header()) |
| + } |
| +} |
| + |
| +func TestStoreDoorStreamS3MetadataAndMissing(t *testing.T) { |
| + for _, known := range []bool{true, false} { |
| + t.Run(strconv.FormatBool(known), func(t *testing.T) { |
| + backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if strings.HasSuffix(r.URL.Path, "/missing") || strings.Contains(r.URL.Path, release.AppPolicyPrefix) { |
| + w.Header().Set("Content-Type", "application/xml") |
| + w.WriteHeader(404) |
| + io.WriteString(w, "<Error><Code>NoSuchKey</Code></Error>") |
| + return |
| + } |
| + w.Header().Set("ETag", `"s3-tag"`) |
| + if known { |
| + w.Header().Set("Content-Length", "7") |
| + } else { |
| + w.(http.Flusher).Flush() |
| + } |
| + io.WriteString(w, "s3 body") |
| + })) |
| + defer backend.Close() |
| + d, _ := newTestDoor(t) |
| + d.store = &release.S3Store{Bucket: "bucket", Client: s3.New(s3.Options{Region: "us-east-1", Credentials: aws.AnonymousCredentials{}, BaseEndpoint: aws.String(backend.URL), UsePathStyle: true})} |
| + w := doorDo(d, "GET", storeObjectPrefix+ownKey, "", nil) |
| + length := "" |
| + if known { |
| + length = "7" |
| + } |
| + if w.Code != 200 || w.Body.String() != "s3 body" || w.Header().Get("ETag") != `"s3-tag"` || w.Header().Get("Content-Length") != length || w.Header().Get("Content-Type") != "application/octet-stream" { |
| + t.Fatalf("%d %q %v", w.Code, w.Body.String(), w.Header()) |
| + } |
| + for _, key := range []string{"apps/" + testSqid + "/missing", release.AppPolicyKey(testSqid, "web")} { |
| + w = doorDo(d, "GET", storeObjectPrefix+key, "", nil) |
| + absent := "" |
| + if strings.HasPrefix(key, release.AppPolicyPrefix) { |
| + absent = "1" |
| + } |
| + if w.Code != 404 || w.Body.String() != "404 page not found\n" || w.Header().Get(storeAbsentHeader) != absent { |
| + t.Fatalf("%s: %d %q %v", key, w.Code, w.Body.String(), w.Header()) |
| + } |
| + } |
| + }) |
| + } |
| +} |
| + |
| +type doorErrorReader struct{} |
| + |
| +func (doorErrorReader) Read([]byte) (int, error) { return 0, io.ErrUnexpectedEOF } |
| + |
| +func TestStoreDoorStreamReleasesOnFailure(t *testing.T) { |
| + for _, mode := range []string{"open", "copy", "write"} { |
| + t.Run(mode, func(t *testing.T) { |
| + d, base := newTestDoor(t) |
| + var body *doorSizedBody |
| + s := &doorStreamStore{Store: base, open: func() (io.ReadCloser, string, error) { |
| + if mode == "open" { |
| + return nil, "", io.ErrUnexpectedEOF |
| + } |
| + reader := io.Reader(doorErrorReader{}) |
| + if mode == "write" { |
| + reader = strings.NewReader("body") |
| + } |
| + body = &doorSizedBody{Reader: reader, size: -1} |
| + return body, "", nil |
| + }} |
| + d.store = s |
| + for i := 0; i < 3; i++ { |
| + func() { |
| + defer func() { |
| + if got := recover(); got != nil && got != http.ErrAbortHandler { |
| + panic(got) |
| + } else if mode != "open" && got != http.ErrAbortHandler { |
| + t.Error("incomplete response was not aborted") |
| + } |
| + }() |
| + w := http.ResponseWriter(httptest.NewRecorder()) |
| + if mode == "write" { |
| + w = &doorErrorWriter{header: make(http.Header)} |
| + } |
| + d.ServeHTTP(w, doorReq("GET", storeObjectPrefix+ownKey, testChannel, testToken, "")) |
| + }() |
| + if d.getTotal != 0 || len(d.gets) != 0 { |
| + t.Fatalf("leaked slots: total=%d boxes=%v", d.getTotal, d.gets) |
| + } |
| + if body != nil && !body.closed { |
| + t.Fatal("body not closed") |
| + } |
| + } |
| + if s.opens.Load() != 3 || s.gets.Load() != 0 { |
| + t.Fatalf("opens=%d gets=%d", s.opens.Load(), s.gets.Load()) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +type doorErrorWriter struct{ header http.Header } |
| + |
| +func (w *doorErrorWriter) Header() http.Header { return w.header } |
| +func (w *doorErrorWriter) WriteHeader(int) {} |
| +func (w *doorErrorWriter) Write([]byte) (int, error) { return 0, io.ErrClosedPipe } |