From 045040e2ed1370904536edfb28189a1d1fa28bba Mon Sep 17 00:00:00 2001 From: "yunlu.wen" Date: Thu, 5 Nov 2026 13:23:24 +0800 Subject: [PATCH 01/13] feat(oss): add optional streaming and range reads --- README.md | 96 +++++ oss/aliyun/aliyun.go | 49 ++- oss/aliyun/aliyun_stream_test.go | 496 +++++++++++++++++++++ oss/azureblob/blob.go | 69 ++- oss/azureblob/blob_stream_test.go | 664 +++++++++++++++++++++++++++++ oss/local/localfile.go | 74 +++- oss/local/localfile_stream_test.go | 240 +++++++++++ oss/s3/s3.go | 54 ++- oss/s3/s3_stream_test.go | 518 ++++++++++++++++++++++ oss/stream.go | 222 ++++++++++ oss/stream_test.go | 175 ++++++++ 11 files changed, 2638 insertions(+), 19 deletions(-) create mode 100644 oss/aliyun/aliyun_stream_test.go create mode 100644 oss/azureblob/blob_stream_test.go create mode 100644 oss/local/localfile_stream_test.go create mode 100644 oss/s3/s3_stream_test.go create mode 100644 oss/stream.go create mode 100644 oss/stream_test.go diff --git a/README.md b/README.md index ff9c6e8..cd0e1e6 100644 --- a/README.md +++ b/README.md @@ -66,6 +66,102 @@ store, err := factory.Load("s3", oss.OSSArgs{ }) ``` +## ๐ŸŒŠ Streaming Reads (Range Support) + +`oss.OSS.Load` always buffers the entire object in memory. For large objects or +partial reads, providers can implement the optional `oss.StreamingOSS` +interface, which streams object content through an `io.ReadCloser` without +buffering. + +```go +type StreamingOSS interface { + OSS + Open(ctx context.Context, key string, byteRange *ByteRange) (io.ReadCloser, error) +} + +type ByteRange struct { + Offset int64 // >= 0 + Length int64 // > 0 bounded, -1 = from Offset to EOF +} +``` + +Semantics: + +- `byteRange == nil` streams the whole object. +- `Length == -1` streams from `Offset` to end of object. +- `Length == 0` or `< -1` fails with `oss.ErrInvalidRange` before any I/O. +- A range outside the object fails with `oss.ErrRangeNotSatisfiable` (HTTP 416 + is mapped to this sentinel for remote providers). +- There is **no suffix-range parser**: resolve `bytes=-N` yourself using the + object size from `State`. +- Cancelling `ctx` aborts the request and subsequent `Read` calls. Always + `defer rc.Close()`. +- **No automatic fallback**: backends without `Open` fail the type assertion; + the library never secretly buffers a ranged request via `Load`. +- Ranged `Open` calls verify the server actually honored the `Range` header + (via `Content-Range`); a server that ignores it causes an error instead of a + silent full download. + +### Supported streaming providers + +| Provider | `Open` support | Notes | +|------------|----------------|-------------------------------------------| +| Local | โœ… | `os.File` + `io.SectionReader`, end clamped to file size | +| AWS S3 | โœ… | `GetObjectInput.Range`, body streamed | +| Aliyun OSS | โœ… | `NormalizedRange` + `RangeBehavior("standard")` | +| Azure Blob | โœ… | `DownloadStreamOptions.Range`, `NewRetryReader` resumes interrupted reads | +| Others | โŒ | type assertion fails | + +### Capability detection + +Callers can check support explicitly instead of relying on a raw type +assertion: + +```go +if !oss.SupportsStreaming(store) { + // backend cannot stream; no fallback buffering is performed +} +``` + +`oss.OpenStream` performs the assertion and delegates to `Open`, returning an +error wrapping `oss.ErrStreamingNotSupported` for unsupported (or nil) +backends: + +```go +rc, err := oss.OpenStream(ctx, store, key, &oss.ByteRange{Offset: 0, Length: -1}) +if errors.Is(err, oss.ErrStreamingNotSupported) { + // handle non-streaming backend +} +if err != nil { + return err +} +defer rc.Close() +``` + +### Example + +```go +streamer, ok := store.(oss.StreamingOSS) +if !ok { + return errors.New("backend does not support streaming") +} + +ctx := request.Context() // tie the read to the request lifecycle +rc, err := streamer.Open(ctx, "big-file.bin", &oss.ByteRange{Offset: 0, Length: -1}) +if err != nil { + return err +} +defer rc.Close() + +// streams without loading the whole object into memory +if _, err := io.Copy(w, rc); err != nil { + return err +} +``` + +Note: enterprise-side caller integration (e.g. wiring `StreamingOSS` into +dify-enterprise) is handled separately and is out of scope for this library. + ## ๐Ÿงช Testing Unit tests are located in `tests/oss/oss_test.go`. diff --git a/oss/aliyun/aliyun.go b/oss/aliyun/aliyun.go index a9d837f..c16ba36 100644 --- a/oss/aliyun/aliyun.go +++ b/oss/aliyun/aliyun.go @@ -2,8 +2,11 @@ package aliyun import ( "bytes" + "context" + "errors" "fmt" "io" + "net/http" "path" "strings" "time" @@ -12,6 +15,8 @@ import ( difyoss "github.com/langgenius/dify-cloud-kit/oss" ) +var _ difyoss.StreamingOSS = (*AliyunOSSStorage)(nil) + type AliyunOSSStorage struct { client *oss.Client bucket *oss.Bucket @@ -99,19 +104,51 @@ func (s *AliyunOSSStorage) Save(key string, data []byte) error { } func (s *AliyunOSSStorage) Load(key string) ([]byte, error) { - fullPath := s.fullPath(key) - object, err := s.bucket.GetObject(fullPath) + reader, err := s.Open(context.Background(), key, nil) if err != nil { return nil, err } - // Ensure object is closed after reading - defer object.Close() + defer reader.Close() + + return io.ReadAll(reader) +} + +func (s *AliyunOSSStorage) Open(ctx context.Context, key string, byteRange *difyoss.ByteRange) (io.ReadCloser, error) { + options := []oss.Option{oss.WithContext(ctx)} + if byteRange != nil { + rangeHeader, err := byteRange.HTTPRange() + if err != nil { + return nil, err + } + options = append(options, + oss.NormalizedRange(strings.TrimPrefix(rangeHeader, "bytes=")), + // "standard" makes OSS return 416 for out-of-range offsets + // instead of silently serving the whole object. + oss.RangeBehavior("standard"), + ) + } + if err := ctx.Err(); err != nil { + return nil, err + } - data, err := io.ReadAll(object) + fullPath := s.fullPath(key) + result, err := s.bucket.DoGetObject(&oss.GetObjectRequest{ObjectKey: fullPath}, options) if err != nil { + var svcErr oss.ServiceError + if errors.As(err, &svcErr) && svcErr.StatusCode == http.StatusRequestedRangeNotSatisfiable { + return nil, difyoss.ErrRangeNotSatisfiable + } return nil, err } - return data, nil + + if byteRange != nil { + if err := difyoss.VerifyContentRange(result.Response.Headers.Get("Content-Range"), byteRange); err != nil { + result.Response.Close() + return nil, err + } + } + + return result.Response, nil } func (s *AliyunOSSStorage) Exists(key string) (bool, error) { diff --git a/oss/aliyun/aliyun_stream_test.go b/oss/aliyun/aliyun_stream_test.go new file mode 100644 index 0000000..b5df1cf --- /dev/null +++ b/oss/aliyun/aliyun_stream_test.go @@ -0,0 +1,496 @@ +package aliyun + +import ( + "context" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/aliyun/aliyun-oss-go-sdk/oss" + difyoss "github.com/langgenius/dify-cloud-kit/oss" +) + +func newTestStorage(t *testing.T, handler http.Handler, prefix string) *AliyunOSSStorage { + t.Helper() + srv := httptest.NewServer(handler) + t.Cleanup(srv.Close) + + endpoint := strings.TrimPrefix(srv.URL, "http://") + client, err := oss.New(endpoint, "ak", "sk", oss.AuthVersion(oss.AuthV1)) + if err != nil { + t.Fatalf("oss.New: %v", err) + } + bucket, err := client.Bucket("bkt") + if err != nil { + t.Fatalf("client.Bucket: %v", err) + } + return &AliyunOSSStorage{client: client, bucket: bucket, path: prefix} +} + +// objectHandler serves a fixed body, honoring Range the way OSS does in +// "standard" range behavior, and records headers + request count. +type objectHandler struct { + body []byte + rangeHdr *string + behavior *string + path *string + requests *int32 + ignore bool + statusCode int + errCode string +} + +func (h *objectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + if h.requests != nil { + atomic.AddInt32(h.requests, 1) + } + if h.path != nil { + *h.path = r.URL.Path + } + if h.statusCode > 0 { + w.Header().Set("Content-Type", "application/xml") + w.WriteHeader(h.statusCode) + fmt.Fprintf(w, `%serr`, h.errCode) + return + } + rangeHdr := r.Header.Get("Range") + if h.rangeHdr != nil { + *h.rangeHdr = rangeHdr + } + if h.behavior != nil { + *h.behavior = r.Header.Get("x-oss-range-behavior") + } + if rangeHdr == "" || h.ignore { + w.Header().Set("Content-Length", fmt.Sprint(len(h.body))) + w.WriteHeader(http.StatusOK) + w.Write(h.body) + return + } + var start, end int64 + spec := strings.TrimPrefix(rangeHdr, "bytes=") + if dash := strings.Index(spec, "-"); dash >= 0 { + fmt.Sscan(spec[:dash], &start) + if spec[dash+1:] == "" { + end = int64(len(h.body)) - 1 + } else { + fmt.Sscan(spec[dash+1:], &end) + } + } + if start >= int64(len(h.body)) { + w.WriteHeader(http.StatusRequestedRangeNotSatisfiable) + fmt.Fprint(w, `InvalidRangebad range`) + return + } + // clamp like a real OSS backend does for ranges extending past EOF + if end >= int64(len(h.body)) { + end = int64(len(h.body)) - 1 + } + part := h.body[start : end+1] + w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", start, end, len(h.body))) + w.Header().Set("Content-Length", fmt.Sprint(len(part))) + w.WriteHeader(http.StatusPartialContent) + w.Write(part) +} + +func TestAliyunOpenFull(t *testing.T) { + var rangeHdr string + st := newTestStorage(t, &objectHandler{body: []byte("hello world"), rangeHdr: &rangeHdr}, "") + + rc, err := st.Open(context.Background(), "key", nil) + if err != nil { + t.Fatalf("Open: %v", err) + } + defer rc.Close() + data, err := io.ReadAll(rc) + if err != nil { + t.Fatalf("ReadAll: %v", err) + } + if string(data) != "hello world" { + t.Fatalf("got %q", data) + } + if rangeHdr != "" { + t.Fatalf("unexpected Range header %q", rangeHdr) + } +} + +func TestAliyunOpenBounded(t *testing.T) { + var rangeHdr, behavior string + st := newTestStorage(t, &objectHandler{body: []byte("0123456789"), rangeHdr: &rangeHdr, behavior: &behavior}, "") + + rc, err := st.Open(context.Background(), "key", &difyoss.ByteRange{Offset: 2, Length: 4}) + if err != nil { + t.Fatalf("Open: %v", err) + } + defer rc.Close() + data, err := io.ReadAll(rc) + if err != nil { + t.Fatalf("ReadAll: %v", err) + } + if rangeHdr != "bytes=2-5" { + t.Fatalf("Range header %q", rangeHdr) + } + if behavior != "standard" { + t.Fatalf("x-oss-range-behavior %q", behavior) + } + if string(data) != "2345" { + t.Fatalf("got %q", data) + } +} + +func TestAliyunOpenOpenEnded(t *testing.T) { + var rangeHdr string + st := newTestStorage(t, &objectHandler{body: []byte("0123456789"), rangeHdr: &rangeHdr}, "") + + rc, err := st.Open(context.Background(), "key", &difyoss.ByteRange{Offset: 4, Length: -1}) + if err != nil { + t.Fatalf("Open: %v", err) + } + defer rc.Close() + data, err := io.ReadAll(rc) + if err != nil { + t.Fatalf("ReadAll: %v", err) + } + if rangeHdr != "bytes=4-" { + t.Fatalf("Range header %q", rangeHdr) + } + if string(data) != "456789" { + t.Fatalf("got %q", data) + } +} + +func TestAliyunOpenHonorsConfiguredPrefix(t *testing.T) { + var reqPath string + st := newTestStorage(t, &objectHandler{body: []byte("x"), path: &reqPath}, "prefix/") + + rc, err := st.Open(context.Background(), "dir/key", nil) + if err != nil { + t.Fatalf("Open: %v", err) + } + rc.Close() + if !strings.HasSuffix(reqPath, "/prefix/dir/key") { + t.Fatalf("request path %q does not include configured prefix", reqPath) + } +} + +func TestAliyunOpenInvalidRangeNoRequest(t *testing.T) { + var requests int32 + st := newTestStorage(t, &objectHandler{body: []byte("x"), requests: &requests}, "") + + for _, r := range []difyoss.ByteRange{ + {Offset: -1, Length: 1}, + {Offset: 0, Length: 0}, + {Offset: 0, Length: -2}, + } { + if _, err := st.Open(context.Background(), "key", &r); !errors.Is(err, difyoss.ErrInvalidRange) { + t.Fatalf("range=%+v: expected ErrInvalidRange, got %v", r, err) + } + } + if n := atomic.LoadInt32(&requests); n != 0 { + t.Fatalf("expected no requests, got %d", n) + } +} + +func TestAliyunOpenCanceledBeforeRequest(t *testing.T) { + var requests int32 + st := newTestStorage(t, &objectHandler{body: []byte("x"), requests: &requests}, "") + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if _, err := st.Open(ctx, "key", nil); err == nil { + t.Fatal("expected error") + } + if n := atomic.LoadInt32(&requests); n != 0 { + t.Fatalf("expected no requests, got %d", n) + } +} + +func TestAliyunOpenCanceledInflight(t *testing.T) { + entered := make(chan struct{}) + release := make(chan struct{}) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + close(entered) + select { + case <-r.Context().Done(): + case <-release: + } + })) + t.Cleanup(srv.Close) + t.Cleanup(func() { close(release) }) + endpoint := strings.TrimPrefix(srv.URL, "http://") + client, err := oss.New(endpoint, "ak", "sk", oss.AuthVersion(oss.AuthV1)) + if err != nil { + t.Fatalf("oss.New: %v", err) + } + bucket, err := client.Bucket("bkt") + if err != nil { + t.Fatalf("client.Bucket: %v", err) + } + st := &AliyunOSSStorage{client: client, bucket: bucket} + + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan error, 1) + go func() { + _, err := st.Open(ctx, "key", nil) + done <- err + }() + select { + case <-entered: + case <-time.After(5 * time.Second): + t.Fatal("handler never received request") + } + cancel() + select { + case err := <-done: + if err == nil { + t.Fatal("expected error after cancel") + } + case <-time.After(5 * time.Second): + t.Fatal("Open did not return after cancel") + } +} + +// TestAliyunOpenCanceledDuringBodyRead cancels the context after Open +// succeeded while a Read is blocked on an in-flight body. +func TestAliyunOpenCanceledDuringBodyRead(t *testing.T) { + release := make(chan struct{}) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Length", "10") + w.WriteHeader(http.StatusOK) + w.Write([]byte("abc")) + w.(http.Flusher).Flush() + select { + case <-r.Context().Done(): + case <-release: + } + })) + t.Cleanup(srv.Close) + t.Cleanup(func() { close(release) }) + endpoint := strings.TrimPrefix(srv.URL, "http://") + client, err := oss.New(endpoint, "ak", "sk", oss.AuthVersion(oss.AuthV1)) + if err != nil { + t.Fatalf("oss.New: %v", err) + } + bucket, err := client.Bucket("bkt") + if err != nil { + t.Fatalf("client.Bucket: %v", err) + } + st := &AliyunOSSStorage{client: client, bucket: bucket} + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + rc, err := st.Open(ctx, "key", nil) + if err != nil { + t.Fatalf("Open: %v", err) + } + defer rc.Close() + + readDone := make(chan error, 1) + go func() { + _, err := io.ReadFull(rc, make([]byte, 10)) + readDone <- err + }() + time.Sleep(50 * time.Millisecond) + cancel() + select { + case err := <-readDone: + if err == nil { + t.Fatal("expected read error after cancel") + } + case <-time.After(5 * time.Second): + t.Fatal("Read did not return after cancel") + } +} + +func TestAliyunOpenMissing(t *testing.T) { + st := newTestStorage(t, &objectHandler{statusCode: http.StatusNotFound, errCode: "NoSuchKey"}, "") + if _, err := st.Open(context.Background(), "missing", nil); err == nil { + t.Fatal("expected error") + } +} + +func TestAliyunOpenRangeNotSatisfiable(t *testing.T) { + st := newTestStorage(t, &objectHandler{statusCode: http.StatusRequestedRangeNotSatisfiable, errCode: "InvalidRange"}, "") + _, err := st.Open(context.Background(), "key", &difyoss.ByteRange{Offset: 100, Length: 1}) + if !errors.Is(err, difyoss.ErrRangeNotSatisfiable) { + t.Fatalf("expected ErrRangeNotSatisfiable, got %v", err) + } +} + +func TestAliyunOpenServerIgnoresRange(t *testing.T) { + st := newTestStorage(t, &objectHandler{body: []byte("0123456789"), ignore: true}, "") + rc, err := st.Open(context.Background(), "key", &difyoss.ByteRange{Offset: 2, Length: 4}) + if err == nil { + rc.Close() + t.Fatal("expected error when server ignores Range") + } +} + +// TestAliyunOpenRejectedRangeClosesBody ensures the response body is closed +// when a ranged response is rejected for missing Content-Range. +func TestAliyunOpenRejectedRangeClosesBody(t *testing.T) { + var closed int32 + rt := roundTripFunc(func(r *http.Request) (*http.Response, error) { + return &http.Response{ + StatusCode: http.StatusOK, + Status: "200 OK", + Header: http.Header{"Content-Length": []string{"10"}}, + Body: trackingBody{strings.NewReader("0123456789"), &closed}, + ContentLength: 10, + Request: r, + }, nil + }) + client, err := oss.New("oss.invalid", "ak", "sk", + oss.AuthVersion(oss.AuthV1), oss.HTTPClient(&http.Client{Transport: rt})) + if err != nil { + t.Fatalf("oss.New: %v", err) + } + bucket, err := client.Bucket("bkt") + if err != nil { + t.Fatalf("client.Bucket: %v", err) + } + st := &AliyunOSSStorage{client: client, bucket: bucket} + + _, err = st.Open(context.Background(), "key", &difyoss.ByteRange{Offset: 2, Length: 4}) + if err == nil { + t.Fatal("expected rejection of range-ignoring response") + } + if atomic.LoadInt32(&closed) != 1 { + t.Fatal("response body was not closed on rejection") + } +} + +// TestAliyunOpenOversizedEndClamped verifies a bounded range extending past +// EOF is accepted when the server clamps the end to the last byte. +func TestAliyunOpenOversizedEndClamped(t *testing.T) { + var rangeHdr string + st := newTestStorage(t, &objectHandler{body: []byte("0123456789"), rangeHdr: &rangeHdr}, "") + + rc, err := st.Open(context.Background(), "key", &difyoss.ByteRange{Offset: 8, Length: 100}) + if err != nil { + t.Fatalf("Open: %v", err) + } + defer rc.Close() + data, err := io.ReadAll(rc) + if err != nil { + t.Fatalf("ReadAll: %v", err) + } + if rangeHdr != "bytes=8-107" { + t.Fatalf("Range header %q", rangeHdr) + } + if string(data) != "89" { + t.Fatalf("got %q", data) + } +} + +func TestAliyunOpenEmptyObject(t *testing.T) { + st := newTestStorage(t, &objectHandler{body: nil}, "") + rc, err := st.Open(context.Background(), "key", nil) + if err != nil { + t.Fatalf("Open: %v", err) + } + defer rc.Close() + data, err := io.ReadAll(rc) + if err != nil { + t.Fatalf("ReadAll: %v", err) + } + if len(data) != 0 { + t.Fatalf("expected empty body, got %q", data) + } +} + +// trackingBody records whether it was closed. +type trackingBody struct { + *strings.Reader + closed *int32 +} + +func (b trackingBody) Close() error { + atomic.StoreInt32(b.closed, 1) + return nil +} + +type roundTripFunc func(*http.Request) (*http.Response, error) + +func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { + return f(r) +} + +// TestAliyunOpenStreamsBeforeFullDownload proves Open returns after headers +// and first bytes are readable while the rest is still in flight. +func TestAliyunOpenStreamsBeforeFullDownload(t *testing.T) { + release := make(chan struct{}) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Range", "bytes 0-9/10") + w.Header().Set("Content-Length", "10") + w.WriteHeader(http.StatusPartialContent) + w.Write([]byte("abc")) + w.(http.Flusher).Flush() + select { + case <-r.Context().Done(): + case <-release: + } + })) + t.Cleanup(srv.Close) + t.Cleanup(func() { close(release) }) + + endpoint := strings.TrimPrefix(srv.URL, "http://") + client, err := oss.New(endpoint, "ak", "sk", oss.AuthVersion(oss.AuthV1)) + if err != nil { + t.Fatalf("oss.New: %v", err) + } + bucket, err := client.Bucket("bkt") + if err != nil { + t.Fatalf("client.Bucket: %v", err) + } + st := &AliyunOSSStorage{client: client, bucket: bucket} + + type res struct { + rc io.ReadCloser + err error + } + opened := make(chan res, 1) + go func() { + rc, err := st.Open(context.Background(), "key", &difyoss.ByteRange{Offset: 0, Length: -1}) + opened <- res{rc, err} + }() + + var rc io.ReadCloser + select { + case r := <-opened: + if r.err != nil { + t.Fatalf("Open: %v", r.err) + } + rc = r.rc + case <-time.After(5 * time.Second): + t.Fatal("Open blocked until full body downloaded") + } + defer rc.Close() + + buf := make([]byte, 3) + if _, err := io.ReadFull(rc, buf); err != nil { + t.Fatalf("Read: %v", err) + } + if string(buf) != "abc" { + t.Fatalf("got %q", buf) + } + + if err := rc.Close(); err != nil { + t.Fatalf("Close: %v", err) + } + serverDone := make(chan struct{}) + go func() { + srv.Close() + close(serverDone) + }() + select { + case <-serverDone: + case <-time.After(5 * time.Second): + t.Fatal("server handler still blocked after Close") + } +} diff --git a/oss/azureblob/blob.go b/oss/azureblob/blob.go index 9c49145..a0e56c9 100644 --- a/oss/azureblob/blob.go +++ b/oss/azureblob/blob.go @@ -1,15 +1,22 @@ package azureblob import ( - "bytes" "context" + "errors" + "fmt" + "io" + "math" + "net/http" "strings" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" "github.com/Azure/azure-sdk-for-go/sdk/azidentity" "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob" "github.com/langgenius/dify-cloud-kit/oss" ) +var _ oss.StreamingOSS = (*AzureBlobStorage)(nil) + type AzureBlobStorage struct { client *azblob.Client containerName string @@ -56,24 +63,70 @@ func (a *AzureBlobStorage) Save(key string, data []byte) error { } func (a *AzureBlobStorage) Load(key string) ([]byte, error) { - get, err := a.client.DownloadStream(context.TODO(), a.containerName, key, nil) + reader, err := a.Open(context.Background(), key, nil) if err != nil { return nil, err } + defer reader.Close() - downloadedData := bytes.Buffer{} - retryReader := get.NewRetryReader(context.TODO(), &azblob.RetryReaderOptions{}) - _, err = downloadedData.ReadFrom(retryReader) - if err != nil { + return io.ReadAll(reader) +} + +func (a *AzureBlobStorage) Open(ctx context.Context, key string, byteRange *oss.ByteRange) (io.ReadCloser, error) { + options := &azblob.DownloadStreamOptions{} + if byteRange != nil { + if _, err := byteRange.HTTPRange(); err != nil { + return nil, err + } + options.Range = azblob.HTTPRange{Offset: byteRange.Offset} + switch { + case byteRange.Length > 0: + options.Range.Count = byteRange.Length + case byteRange.Offset == 0 && byteRange.Length == -1: + // HTTPRange{Offset:0, Count:0} makes the SDK omit the Range + // header entirely, which would skip Content-Range verification + // and turn an unsatisfiable range (e.g. empty object) into a + // silent full download. Request the largest signed range + // instead; the service clamps the end to the object size and + // still returns 416 when offset >= size. The header must go + // through the SDK's signed Range option โ€” injecting x-ms-range + // via WithHTTPHeader after signing breaks SharedKey auth. + options.Range.Count = math.MaxInt64 + } + } + if err := ctx.Err(); err != nil { return nil, err } - err = retryReader.Close() + resp, err := a.client.DownloadStream(ctx, a.containerName, key, options) if err != nil { + var respErr *azcore.ResponseError + if errors.As(err, &respErr) && respErr.StatusCode == http.StatusRequestedRangeNotSatisfiable { + return nil, oss.ErrRangeNotSatisfiable + } return nil, err } - return downloadedData.Bytes(), nil + if byteRange != nil { + contentRange := "" + if resp.ContentRange != nil { + contentRange = *resp.ContentRange + } + if err := oss.VerifyContentRange(contentRange, byteRange); err != nil { + resp.Body.Close() + // Azurite signals an unsatisfiable range with a degenerate + // "bytes -/" Content-Range (end before + // start) instead of 416; an empty range at the requested + // offset is unambiguously unsatisfiable. + if strings.HasPrefix(contentRange, + fmt.Sprintf("bytes %d-%d/", byteRange.Offset, byteRange.Offset-1)) { + return nil, oss.ErrRangeNotSatisfiable + } + return nil, err + } + } + + return resp.NewRetryReader(ctx, &azblob.RetryReaderOptions{EarlyCloseAsError: true}), nil } func (a *AzureBlobStorage) Exists(key string) (bool, error) { diff --git a/oss/azureblob/blob_stream_test.go b/oss/azureblob/blob_stream_test.go new file mode 100644 index 0000000..eb237c9 --- /dev/null +++ b/oss/azureblob/blob_stream_test.go @@ -0,0 +1,664 @@ +package azureblob + +import ( + "context" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob" + "github.com/langgenius/dify-cloud-kit/oss" +) + +func newTestStorage(t *testing.T, handler http.Handler) (*AzureBlobStorage, *httptest.Server) { + t.Helper() + srv := httptest.NewServer(handler) + t.Cleanup(srv.Close) + + client, err := azblob.NewClientWithNoCredential(srv.URL, nil) + if err != nil { + t.Fatalf("NewClientWithNoCredential: %v", err) + } + return &AzureBlobStorage{client: client, containerName: "cont"}, srv +} + +// objectHandler serves a fixed body, honoring x-ms-range the way Azure Blob +// does, and records headers + request count. +type objectHandler struct { + body []byte + rangeHdr *string + requests *int32 + ignore bool + statusCode int + errCode string +} + +func (h *objectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + if h.requests != nil { + atomic.AddInt32(h.requests, 1) + } + if h.statusCode > 0 { + w.WriteHeader(h.statusCode) + fmt.Fprintf(w, `%serr`, h.errCode) + return + } + rangeHdr := r.Header.Get("x-ms-range") + if h.rangeHdr != nil { + *h.rangeHdr = rangeHdr + } + w.Header().Set("ETag", `"etag1"`) + if rangeHdr == "" || h.ignore { + w.Header().Set("Content-Length", fmt.Sprint(len(h.body))) + w.WriteHeader(http.StatusOK) + w.Write(h.body) + return + } + var start, end int64 + spec := strings.TrimPrefix(rangeHdr, "bytes=") + if dash := strings.Index(spec, "-"); dash >= 0 { + fmt.Sscan(spec[:dash], &start) + if spec[dash+1:] == "" { + end = int64(len(h.body)) - 1 + } else { + fmt.Sscan(spec[dash+1:], &end) + } + } + if start >= int64(len(h.body)) { + w.WriteHeader(http.StatusRequestedRangeNotSatisfiable) + fmt.Fprint(w, `InvalidRangebad range`) + return + } + if end >= int64(len(h.body)) { + end = int64(len(h.body)) - 1 + } + part := h.body[start : end+1] + w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", start, end, len(h.body))) + w.Header().Set("Content-Length", fmt.Sprint(len(part))) + w.WriteHeader(http.StatusPartialContent) + w.Write(part) +} + +func TestAzureOpenFull(t *testing.T) { + var rangeHdr string + st, _ := newTestStorage(t, &objectHandler{body: []byte("hello world"), rangeHdr: &rangeHdr}) + + rc, err := st.Open(context.Background(), "key", nil) + if err != nil { + t.Fatalf("Open: %v", err) + } + defer rc.Close() + data, err := io.ReadAll(rc) + if err != nil { + t.Fatalf("ReadAll: %v", err) + } + if string(data) != "hello world" { + t.Fatalf("got %q", data) + } + if rangeHdr != "" { + t.Fatalf("unexpected x-ms-range header %q", rangeHdr) + } +} + +func TestAzureOpenEmptyObject(t *testing.T) { + st, _ := newTestStorage(t, &objectHandler{body: nil}) + rc, err := st.Open(context.Background(), "key", nil) + if err != nil { + t.Fatalf("Open: %v", err) + } + defer rc.Close() + data, err := io.ReadAll(rc) + if err != nil { + t.Fatalf("ReadAll: %v", err) + } + if len(data) != 0 { + t.Fatalf("expected empty body, got %q", data) + } +} + +func TestAzureOpenBounded(t *testing.T) { + var rangeHdr string + st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789"), rangeHdr: &rangeHdr}) + + rc, err := st.Open(context.Background(), "key", &oss.ByteRange{Offset: 2, Length: 4}) + if err != nil { + t.Fatalf("Open: %v", err) + } + defer rc.Close() + data, err := io.ReadAll(rc) + if err != nil { + t.Fatalf("ReadAll: %v", err) + } + if rangeHdr != "bytes=2-5" { + t.Fatalf("x-ms-range header %q", rangeHdr) + } + if string(data) != "2345" { + t.Fatalf("got %q", data) + } +} + +func TestAzureOpenToEOF(t *testing.T) { + var rangeHdr string + st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789"), rangeHdr: &rangeHdr}) + + rc, err := st.Open(context.Background(), "key", &oss.ByteRange{Offset: 4, Length: -1}) + if err != nil { + t.Fatalf("Open: %v", err) + } + defer rc.Close() + data, err := io.ReadAll(rc) + if err != nil { + t.Fatalf("ReadAll: %v", err) + } + if rangeHdr != "bytes=4-" { + t.Fatalf("x-ms-range header %q", rangeHdr) + } + if string(data) != "456789" { + t.Fatalf("got %q", data) + } +} + +// TestAzureOpenZeroToEOF verifies ByteRange{0,-1} sends an explicit signed +// range header even though the SDK's HTTPRange{0,0} would omit it, and that +// the same range on an empty object yields 416 -> ErrRangeNotSatisfiable. +func TestAzureOpenZeroToEOF(t *testing.T) { + var rangeHdr string + st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789"), rangeHdr: &rangeHdr}) + + rc, err := st.Open(context.Background(), "key", &oss.ByteRange{Offset: 0, Length: -1}) + if err != nil { + t.Fatalf("Open: %v", err) + } + defer rc.Close() + data, err := io.ReadAll(rc) + if err != nil { + t.Fatalf("ReadAll: %v", err) + } + if rangeHdr != "bytes=0-9223372036854775806" { + t.Fatalf("x-ms-range header %q, want bytes=0-9223372036854775806", rangeHdr) + } + if string(data) != "0123456789" { + t.Fatalf("got %q", data) + } + + // empty object + bytes=0- must surface ErrRangeNotSatisfiable + st2, _ := newTestStorage(t, &objectHandler{body: nil}) + _, err = st2.Open(context.Background(), "key", &oss.ByteRange{Offset: 0, Length: -1}) + if !errors.Is(err, oss.ErrRangeNotSatisfiable) { + t.Fatalf("expected ErrRangeNotSatisfiable, got %v", err) + } +} + +func TestAzureOpenOversizedEndClamped(t *testing.T) { + var rangeHdr string + st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789"), rangeHdr: &rangeHdr}) + + rc, err := st.Open(context.Background(), "key", &oss.ByteRange{Offset: 8, Length: 100}) + if err != nil { + t.Fatalf("Open: %v", err) + } + defer rc.Close() + data, err := io.ReadAll(rc) + if err != nil { + t.Fatalf("ReadAll: %v", err) + } + if rangeHdr != "bytes=8-107" { + t.Fatalf("x-ms-range header %q", rangeHdr) + } + if string(data) != "89" { + t.Fatalf("got %q", data) + } +} + +func TestAzureOpenInvalidRangeNoRequest(t *testing.T) { + var requests int32 + st, _ := newTestStorage(t, &objectHandler{body: []byte("x"), requests: &requests}) + + for _, r := range []oss.ByteRange{ + {Offset: -1, Length: 1}, + {Offset: 0, Length: 0}, + {Offset: 0, Length: -2}, + {Offset: 1<<62 + 1, Length: 1 << 62}, // overflowing end + } { + if _, err := st.Open(context.Background(), "key", &r); !errors.Is(err, oss.ErrInvalidRange) { + t.Fatalf("range=%+v: expected ErrInvalidRange, got %v", r, err) + } + } + if n := atomic.LoadInt32(&requests); n != 0 { + t.Fatalf("expected no requests, got %d", n) + } +} + +func TestAzureOpenMissing(t *testing.T) { + st, _ := newTestStorage(t, &objectHandler{statusCode: http.StatusNotFound, errCode: "BlobNotFound"}) + if _, err := st.Open(context.Background(), "missing", nil); err == nil { + t.Fatal("expected error") + } +} + +func TestAzureOpenRangeNotSatisfiable(t *testing.T) { + st, _ := newTestStorage(t, &objectHandler{statusCode: http.StatusRequestedRangeNotSatisfiable, errCode: "InvalidRange"}) + _, err := st.Open(context.Background(), "key", &oss.ByteRange{Offset: 100, Length: 1}) + if !errors.Is(err, oss.ErrRangeNotSatisfiable) { + t.Fatalf("expected ErrRangeNotSatisfiable, got %v", err) + } +} + +// TestAzureOpenPlain416 verifies HTTP 416 maps to ErrRangeNotSatisfiable even +// without an XML error body. +func TestAzureOpenPlain416(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusRequestedRangeNotSatisfiable) + w.Write([]byte("not xml")) + })) + t.Cleanup(srv.Close) + client, err := azblob.NewClientWithNoCredential(srv.URL, nil) + if err != nil { + t.Fatalf("NewClientWithNoCredential: %v", err) + } + st := &AzureBlobStorage{client: client, containerName: "cont"} + + _, err = st.Open(context.Background(), "key", &oss.ByteRange{Offset: 100, Length: 1}) + if !errors.Is(err, oss.ErrRangeNotSatisfiable) { + t.Fatalf("expected ErrRangeNotSatisfiable, got %v", err) + } +} + +// trackingBody records whether it was closed. +type trackingBody struct { + *strings.Reader + closed *int32 +} + +func (b trackingBody) Close() error { + atomic.StoreInt32(b.closed, 1) + return nil +} + +type roundTripFunc func(*http.Request) (*http.Response, error) + +func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { + return f(r) +} + +func newTrackingStorage(t *testing.T, rt http.RoundTripper) *AzureBlobStorage { + t.Helper() + client, err := azblob.NewClientWithNoCredential("http://blob.invalid", &azblob.ClientOptions{ + ClientOptions: azcore.ClientOptions{Transport: &http.Client{Transport: rt}}, + }) + if err != nil { + t.Fatalf("NewClientWithNoCredential: %v", err) + } + return &AzureBlobStorage{client: client, containerName: "cont"} +} + +// TestAzureOpenRejectedRangeClosesBody ensures the response body is closed +// when a ranged response is rejected for a missing or mismatched +// Content-Range. +func TestAzureOpenRejectedRangeClosesBody(t *testing.T) { + for _, tc := range []struct { + name string + contentRange string + }{ + {"missing", ""}, + {"malformed", "garbage"}, + {"wrong start", "bytes 0-3/10"}, + } { + t.Run(tc.name, func(t *testing.T) { + var closed int32 + rt := roundTripFunc(func(r *http.Request) (*http.Response, error) { + hdr := http.Header{"Content-Length": []string{"10"}} + if tc.contentRange != "" { + hdr.Set("Content-Range", tc.contentRange) + } + return &http.Response{ + StatusCode: http.StatusOK, + Status: "200 OK", + Header: hdr, + Body: trackingBody{strings.NewReader("0123456789"), &closed}, + ContentLength: 10, + Request: r, + }, nil + }) + st := newTrackingStorage(t, rt) + + _, err := st.Open(context.Background(), "key", &oss.ByteRange{Offset: 2, Length: 4}) + if err == nil { + t.Fatal("expected rejection") + } + if atomic.LoadInt32(&closed) != 1 { + t.Fatal("response body was not closed on rejection") + } + }) + } +} + +func TestAzureOpenCanceledBeforeRequest(t *testing.T) { + var requests int32 + st, _ := newTestStorage(t, &objectHandler{body: []byte("x"), requests: &requests}) + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if _, err := st.Open(ctx, "key", nil); err == nil { + t.Fatal("expected error") + } + if n := atomic.LoadInt32(&requests); n != 0 { + t.Fatalf("expected no requests, got %d", n) + } +} + +func TestAzureOpenCanceledInflight(t *testing.T) { + entered := make(chan struct{}) + release := make(chan struct{}) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + close(entered) + select { + case <-r.Context().Done(): + case <-release: + } + })) + t.Cleanup(srv.Close) + t.Cleanup(func() { close(release) }) + client, err := azblob.NewClientWithNoCredential(srv.URL, nil) + if err != nil { + t.Fatalf("NewClientWithNoCredential: %v", err) + } + st := &AzureBlobStorage{client: client, containerName: "cont"} + + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan error, 1) + go func() { + _, err := st.Open(ctx, "key", nil) + done <- err + }() + select { + case <-entered: + case <-time.After(5 * time.Second): + t.Fatal("handler never received request") + } + cancel() + select { + case err := <-done: + if err == nil { + t.Fatal("expected error after cancel") + } + case <-time.After(5 * time.Second): + t.Fatal("Open did not return after cancel") + } +} + +// TestAzureOpenCanceledDuringBodyRead cancels the context after Open +// succeeded while a Read is blocked on an in-flight body. +func TestAzureOpenCanceledDuringBodyRead(t *testing.T) { + release := make(chan struct{}) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Length", "10") + w.WriteHeader(http.StatusOK) + w.Write([]byte("abc")) + w.(http.Flusher).Flush() + select { + case <-r.Context().Done(): + case <-release: + } + })) + t.Cleanup(srv.Close) + t.Cleanup(func() { close(release) }) + client, err := azblob.NewClientWithNoCredential(srv.URL, nil) + if err != nil { + t.Fatalf("NewClientWithNoCredential: %v", err) + } + st := &AzureBlobStorage{client: client, containerName: "cont"} + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + rc, err := st.Open(ctx, "key", nil) + if err != nil { + t.Fatalf("Open: %v", err) + } + defer rc.Close() + + readDone := make(chan error, 1) + go func() { + _, err := io.ReadFull(rc, make([]byte, 10)) + readDone <- err + }() + time.Sleep(50 * time.Millisecond) + cancel() + select { + case err := <-readDone: + if err == nil { + t.Fatal("expected read error after cancel") + } + case <-time.After(5 * time.Second): + t.Fatal("Read did not return after cancel") + } +} + +// TestAzureOpenStreamsBeforeFullDownload proves Open returns after headers +// and first bytes are readable while the rest is still in flight, and that +// Close releases the blocked handler. +func TestAzureOpenStreamsBeforeFullDownload(t *testing.T) { + release := make(chan struct{}) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Range", "bytes 0-9/10") + w.Header().Set("Content-Length", "10") + w.WriteHeader(http.StatusPartialContent) + w.Write([]byte("abc")) + w.(http.Flusher).Flush() + select { + case <-r.Context().Done(): + case <-release: + } + })) + t.Cleanup(srv.Close) + t.Cleanup(func() { close(release) }) + client, err := azblob.NewClientWithNoCredential(srv.URL, nil) + if err != nil { + t.Fatalf("NewClientWithNoCredential: %v", err) + } + st := &AzureBlobStorage{client: client, containerName: "cont"} + + type res struct { + rc io.ReadCloser + err error + } + opened := make(chan res, 1) + go func() { + rc, err := st.Open(context.Background(), "key", &oss.ByteRange{Offset: 0, Length: -1}) + opened <- res{rc, err} + }() + + var rc io.ReadCloser + select { + case r := <-opened: + if r.err != nil { + t.Fatalf("Open: %v", r.err) + } + rc = r.rc + case <-time.After(5 * time.Second): + t.Fatal("Open blocked until full body downloaded") + } + defer rc.Close() + + buf := make([]byte, 3) + if _, err := io.ReadFull(rc, buf); err != nil { + t.Fatalf("Read: %v", err) + } + if string(buf) != "abc" { + t.Fatalf("got %q", buf) + } + + if err := rc.Close(); err != nil { + t.Fatalf("Close: %v", err) + } + serverDone := make(chan struct{}) + go func() { + srv.Close() + close(serverDone) + }() + select { + case <-serverDone: + case <-time.After(5 * time.Second): + t.Fatal("server handler still blocked after Close") + } +} + +// retryHandler serves a truncated first response (declares Content-Length +// for the whole object but closes early), then asserts the retry carries an +// advanced x-ms-range and If-Match ETag, and completes the remaining bytes. +type retryHandler struct { + full string // full object content + served int // bytes served on the first response + retried chan struct{} + gotRange string + gotIfMatch string + t *testing.T +} + +func (h *retryHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + rangeHdr := r.Header.Get("x-ms-range") + if strings.HasPrefix(rangeHdr, "bytes=0-") || rangeHdr == "" { + w.Header().Set("ETag", `"etag1"`) + w.Header().Set("Content-Range", fmt.Sprintf("bytes 0-%d/%d", len(h.full)-1, len(h.full))) + w.Header().Set("Content-Length", fmt.Sprint(len(h.full))) + w.WriteHeader(http.StatusPartialContent) + w.Write([]byte(h.full[:h.served])) // truncated: unexpected EOF for the client + return + } + // retry request + h.gotRange = rangeHdr + h.gotIfMatch = r.Header.Get("If-Match") + var start int64 + fmt.Sscan(strings.TrimSuffix(strings.TrimPrefix(rangeHdr, "bytes="), "-"), &start) + part := h.full[start:] + w.Header().Set("ETag", `"etag1"`) + w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", start, len(h.full)-1, len(h.full))) + w.Header().Set("Content-Length", fmt.Sprint(len(part))) + w.WriteHeader(http.StatusPartialContent) + w.Write([]byte(part)) + close(h.retried) +} + +func runRetryTest(t *testing.T, byteRange *oss.ByteRange, body string, served int, wantRetryRange string) string { + t.Helper() + h := &retryHandler{full: body, served: served, retried: make(chan struct{}), t: t} + st, _ := newTestStorage(t, h) + + rc, err := st.Open(context.Background(), "key", byteRange) + if err != nil { + t.Fatalf("Open: %v", err) + } + defer rc.Close() + + readDone := make(chan struct { + data []byte + err error + }, 1) + go func() { + data, err := io.ReadAll(rc) + readDone <- struct { + data []byte + err error + }{data, err} + }() + + select { + case <-h.retried: + case <-time.After(10 * time.Second): + t.Fatal("retry never issued") + } + res := <-readDone + if res.err != nil { + t.Fatalf("ReadAll: %v", res.err) + } + if h.gotIfMatch != `"etag1"` { + t.Fatalf("retry If-Match %q", h.gotIfMatch) + } + if h.gotRange != wantRetryRange { + t.Fatalf("retry x-ms-range %q, want %q", h.gotRange, wantRetryRange) + } + return string(res.data) +} + +func TestAzureRetryReaderAdvancesRange(t *testing.T) { + // bounded range 0-9 of a 10-byte object; first response truncates at 3 + // bytes, retry must advance the offset while keeping the requested end. + got := runRetryTest(t, &oss.ByteRange{Offset: 0, Length: 10}, "0123456789", 3, "bytes=3-9") + if got != "0123456789" { + t.Fatalf("got %q", got) + } +} + +// TestAzureRetryAfterZeroToEOF proves retries after a {0,-1} request advance +// the range correctly instead of re-requesting from 0. +func TestAzureRetryAfterZeroToEOF(t *testing.T) { + got := runRetryTest(t, &oss.ByteRange{Offset: 0, Length: -1}, "0123456789", 3, "bytes=3-9223372036854775806") + if got != "0123456789" { + t.Fatalf("got %q", got) + } +} + +func TestAzureLoadStillWorks(t *testing.T) { + st, _ := newTestStorage(t, &objectHandler{body: []byte("payload")}) + data, err := st.Load("key") + if err != nil { + t.Fatalf("Load: %v", err) + } + if string(data) != "payload" { + t.Fatalf("got %q", data) + } +} + +// TestAzureLoadClosesBodyOnReadError ensures a failed read still closes the +// body through Load's deferred Close. +func TestAzureLoadClosesBodyOnReadError(t *testing.T) { + var closed int32 + rt := roundTripFunc(func(r *http.Request) (*http.Response, error) { + return &http.Response{ + StatusCode: http.StatusOK, + Status: "200 OK", + Header: http.Header{"Content-Length": []string{"10"}}, + Body: failingBody{Reader: strings.NewReader(""), failAfter: 0, closed: &closed}, + ContentLength: 10, + Request: r, + }, nil + }) + st := newTrackingStorage(t, rt) + + // Reads fail immediately; the retry reader must close each failed body + // before retrying, and Load returns the error. + _, err := st.Load("key") + if err == nil { + t.Fatal("expected Load to fail") + } + if atomic.LoadInt32(&closed) == 0 { + t.Fatal("response body was not closed on read failure") + } +} + +// failingBody errors after failAfter successful reads. +type failingBody struct { + *strings.Reader + failAfter int + reads int + closed *int32 +} + +func (b failingBody) Read(p []byte) (int, error) { + b.reads++ + if b.reads > b.failAfter { + return 0, fmt.Errorf("simulated read failure") + } + return b.Reader.Read(p) +} + +func (b failingBody) Close() error { + atomic.AddInt32(b.closed, 1) + return nil +} diff --git a/oss/local/localfile.go b/oss/local/localfile.go index aebe0fb..1013418 100644 --- a/oss/local/localfile.go +++ b/oss/local/localfile.go @@ -1,6 +1,8 @@ package local import ( + "context" + "io" "io/fs" "os" "path/filepath" @@ -9,6 +11,8 @@ import ( "github.com/langgenius/dify-cloud-kit/oss" ) +var _ oss.StreamingOSS = (*LocalStorage)(nil) + type LocalStorage struct { root string } @@ -40,9 +44,77 @@ func (l *LocalStorage) Save(key string, data []byte) error { } func (l *LocalStorage) Load(key string) ([]byte, error) { + reader, err := l.Open(context.Background(), key, nil) + if err != nil { + return nil, err + } + defer reader.Close() + + return io.ReadAll(reader) +} + +// ctxFileReader reads from a file section through an open *os.File, checking +// the context on every Read so a cancelled read returns promptly. +type ctxFileReader struct { + ctx context.Context + file *os.File + section *io.SectionReader +} + +func (r *ctxFileReader) Read(p []byte) (int, error) { + if err := r.ctx.Err(); err != nil { + return 0, err + } + return r.section.Read(p) +} + +func (r *ctxFileReader) Close() error { + return r.file.Close() +} + +func (l *LocalStorage) Open(ctx context.Context, key string, byteRange *oss.ByteRange) (io.ReadCloser, error) { + if byteRange != nil { + if _, err := byteRange.HTTPRange(); err != nil { + return nil, err + } + } + if err := ctx.Err(); err != nil { + return nil, err + } + path := filepath.Join(l.root, key) + file, err := os.Open(path) + if err != nil { + return nil, err + } + info, err := file.Stat() + if err != nil { + file.Close() + return nil, err + } + size := info.Size() + + var offset, length int64 + if byteRange != nil { + offset = byteRange.Offset + if offset >= size { + file.Close() + return nil, oss.ErrRangeNotSatisfiable + } + if byteRange.Length == -1 || byteRange.Length > size-offset { + length = size - offset + } else { + length = byteRange.Length + } + } else { + length = size + } - return os.ReadFile(path) + return &ctxFileReader{ + ctx: ctx, + file: file, + section: io.NewSectionReader(file, offset, length), + }, nil } func (l *LocalStorage) Exists(key string) (bool, error) { diff --git a/oss/local/localfile_stream_test.go b/oss/local/localfile_stream_test.go new file mode 100644 index 0000000..95294aa --- /dev/null +++ b/oss/local/localfile_stream_test.go @@ -0,0 +1,240 @@ +package local + +import ( + "context" + "errors" + "io" + "math" + "os" + "path/filepath" + "testing" + "time" + + "github.com/langgenius/dify-cloud-kit/oss" +) + +func newTestStorage(t *testing.T) *LocalStorage { + t.Helper() + st, err := NewLocalStorage(oss.OSSArgs{Local: &oss.Local{Path: t.TempDir()}}) + if err != nil { + t.Fatalf("NewLocalStorage: %v", err) + } + return st.(*LocalStorage) +} + +func writeFile(t *testing.T, st *LocalStorage, key string, data []byte) { + t.Helper() + if err := st.Save(key, data); err != nil { + t.Fatalf("Save: %v", err) + } +} + +func openRange(t *testing.T, st *LocalStorage, key string, r *oss.ByteRange) io.ReadCloser { + t.Helper() + rc, err := st.Open(context.Background(), key, r) + if err != nil { + t.Fatalf("Open: %v", err) + } + t.Cleanup(func() { rc.Close() }) + return rc +} + +func TestLocalOpenFull(t *testing.T) { + st := newTestStorage(t) + writeFile(t, st, "a/b.bin", []byte("hello world")) + + rc := openRange(t, st, "a/b.bin", nil) + data, err := io.ReadAll(rc) + if err != nil { + t.Fatalf("ReadAll: %v", err) + } + if string(data) != "hello world" { + t.Fatalf("got %q", data) + } +} + +func TestLocalOpenFullEmptyFile(t *testing.T) { + st := newTestStorage(t) + writeFile(t, st, "empty", nil) + + rc := openRange(t, st, "empty", nil) + data, err := io.ReadAll(rc) + if err != nil { + t.Fatalf("ReadAll: %v", err) + } + if len(data) != 0 { + t.Fatalf("expected empty, got %q", data) + } +} + +func TestLocalOpenBounded(t *testing.T) { + st := newTestStorage(t) + writeFile(t, st, "f", []byte("0123456789")) + + rc := openRange(t, st, "f", &oss.ByteRange{Offset: 2, Length: 4}) + data, err := io.ReadAll(rc) + if err != nil { + t.Fatalf("ReadAll: %v", err) + } + if string(data) != "2345" { + t.Fatalf("got %q", data) + } +} + +func TestLocalOpenToEOF(t *testing.T) { + st := newTestStorage(t) + writeFile(t, st, "f", []byte("0123456789")) + + rc := openRange(t, st, "f", &oss.ByteRange{Offset: 7, Length: -1}) + data, err := io.ReadAll(rc) + if err != nil { + t.Fatalf("ReadAll: %v", err) + } + if string(data) != "789" { + t.Fatalf("got %q", data) + } +} + +func TestLocalOpenClampedEnd(t *testing.T) { + st := newTestStorage(t) + writeFile(t, st, "f", []byte("0123456789")) + + // Length extends past end of file; only remaining bytes come back. + rc := openRange(t, st, "f", &oss.ByteRange{Offset: 8, Length: 100}) + data, err := io.ReadAll(rc) + if err != nil { + t.Fatalf("ReadAll: %v", err) + } + if string(data) != "89" { + t.Fatalf("got %q", data) + } +} + +func TestLocalOpenHugeLengthClamped(t *testing.T) { + st := newTestStorage(t) + writeFile(t, st, "f", []byte("0123456789")) + + // Length is a valid inclusive HTTP range (end = MaxInt64); the local + // clamp must not overflow computing offset+length. + rc := openRange(t, st, "f", &oss.ByteRange{Offset: 1, Length: math.MaxInt64}) + data, err := io.ReadAll(rc) + if err != nil { + t.Fatalf("ReadAll: %v", err) + } + if string(data) != "123456789" { + t.Fatalf("got %q", data) + } +} + +func TestLocalOpenMissing(t *testing.T) { + st := newTestStorage(t) + if _, err := st.Open(context.Background(), "nope", nil); err == nil { + t.Fatal("expected error for missing key") + } +} + +func TestLocalOpenUnsatisfiable(t *testing.T) { + st := newTestStorage(t) + writeFile(t, st, "f", []byte("0123456789")) + writeFile(t, st, "empty", nil) + + for _, c := range []struct { + key string + r oss.ByteRange + }{ + {"f", oss.ByteRange{Offset: 10, Length: 1}}, // offset == size + {"f", oss.ByteRange{Offset: 10, Length: -1}}, // offset == size to EOF + {"f", oss.ByteRange{Offset: 11, Length: 1}}, // offset > size + {"empty", oss.ByteRange{Offset: 0, Length: 1}}, // empty file + {"empty", oss.ByteRange{Offset: 0, Length: -1}}, + } { + if _, err := st.Open(context.Background(), c.key, &c.r); !errors.Is(err, oss.ErrRangeNotSatisfiable) { + t.Fatalf("key=%s range=%+v: expected ErrRangeNotSatisfiable, got %v", c.key, c.r, err) + } + } +} + +func TestLocalOpenInvalidRange(t *testing.T) { + st := newTestStorage(t) + writeFile(t, st, "f", []byte("0123456789")) + + for _, r := range []oss.ByteRange{ + {Offset: -1, Length: 1}, + {Offset: 0, Length: 0}, + {Offset: 0, Length: -2}, + } { + if _, err := st.Open(context.Background(), "f", &r); !errors.Is(err, oss.ErrInvalidRange) { + t.Fatalf("range=%+v: expected ErrInvalidRange, got %v", r, err) + } + } +} + +func TestLocalOpenCanceledBefore(t *testing.T) { + st := newTestStorage(t) + writeFile(t, st, "f", []byte("0123456789")) + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if _, err := st.Open(ctx, "f", nil); err == nil { + t.Fatal("expected context error") + } +} + +func TestLocalOpenCanceledDuringRead(t *testing.T) { + st := newTestStorage(t) + writeFile(t, st, "f", []byte("0123456789")) + + ctx, cancel := context.WithCancel(context.Background()) + rc, err := st.Open(ctx, "f", nil) + if err != nil { + t.Fatalf("Open: %v", err) + } + defer rc.Close() + + cancel() + buf := make([]byte, 4) + done := make(chan error, 1) + go func() { + _, err := rc.Read(buf) + done <- err + }() + select { + case err := <-done: + if err == nil || !errors.Is(err, context.Canceled) { + t.Fatalf("expected context.Canceled, got %v", err) + } + case <-time.After(5 * time.Second): + t.Fatal("Read did not return after cancel") + } +} + +func TestLocalOpenClosedResource(t *testing.T) { + st := newTestStorage(t) + writeFile(t, st, "f", []byte("0123456789")) + + rc, err := st.Open(context.Background(), "f", nil) + if err != nil { + t.Fatalf("Open: %v", err) + } + if err := rc.Close(); err != nil { + t.Fatalf("Close: %v", err) + } + if _, err := rc.Read(make([]byte, 1)); err == nil { + t.Fatal("expected error reading closed resource") + } +} + +func TestLocalOpenLoadStillWorks(t *testing.T) { + st := newTestStorage(t) + writeFile(t, st, "f", []byte("payload")) + data, err := st.Load("f") + if err != nil { + t.Fatalf("Load: %v", err) + } + if string(data) != "payload" { + t.Fatalf("got %q", data) + } + if _, err := os.Stat(filepath.Join(st.root, "f")); err != nil { + t.Fatal(err) + } +} diff --git a/oss/s3/s3.go b/oss/s3/s3.go index 408e7f0..f860c68 100644 --- a/oss/s3/s3.go +++ b/oss/s3/s3.go @@ -5,10 +5,12 @@ import ( "context" "errors" "io" + "net/http" "strings" "time" "github.com/aws/aws-sdk-go-v2/aws" + awshttp "github.com/aws/aws-sdk-go-v2/aws/transport/http" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/credentials" "github.com/aws/aws-sdk-go-v2/service/s3" @@ -16,6 +18,8 @@ import ( "github.com/langgenius/dify-cloud-kit/oss" ) +var _ oss.StreamingOSS = (*S3Storage)(nil) + type S3Storage struct { bucket string client *s3.Client @@ -128,7 +132,7 @@ func normalizeSignatureVersion(version string) string { case "unsigned": return "" case "": - return "v4" // ้ป˜่ฎคไฝฟ็”จ v4 + return "v4" // ้ป˜่ฎคไฝฟ็”จ v4 default: return version } @@ -144,15 +148,57 @@ func (s *S3Storage) Save(key string, data []byte) error { } func (s *S3Storage) Load(key string) ([]byte, error) { - resp, err := s.client.GetObject(context.TODO(), &s3.GetObjectInput{ + reader, err := s.Open(context.Background(), key, nil) + if err != nil { + return nil, err + } + defer reader.Close() + + return io.ReadAll(reader) +} + +func (s *S3Storage) Open(ctx context.Context, key string, byteRange *oss.ByteRange) (io.ReadCloser, error) { + input := &s3.GetObjectInput{ Bucket: aws.String(s.bucket), Key: aws.String(key), - }) + } + if byteRange != nil { + rangeHeader, err := byteRange.HTTPRange() + if err != nil { + return nil, err + } + input.Range = aws.String(rangeHeader) + } + if err := ctx.Err(); err != nil { + return nil, err + } + + resp, err := s.client.GetObject(ctx, input) if err != nil { + var apiErr smithy.APIError + if errors.As(err, &apiErr) && + (apiErr.ErrorCode() == "InvalidRange" || apiErr.ErrorCode() == "RequestedRangeNotSatisfiable") { + return nil, oss.ErrRangeNotSatisfiable + } + var respErr *awshttp.ResponseError + if errors.As(err, &respErr) && respErr.HTTPStatusCode() == http.StatusRequestedRangeNotSatisfiable { + return nil, oss.ErrRangeNotSatisfiable + } return nil, err } - return io.ReadAll(resp.Body) + if byteRange != nil { + contentRange := "" + if resp.ContentRange != nil { + contentRange = *resp.ContentRange + } + if err := oss.VerifyContentRange(contentRange, byteRange); err != nil { + resp.Body.Close() + return nil, err + } + } + + return resp.Body, nil } func (s *S3Storage) Exists(key string) (bool, error) { diff --git a/oss/s3/s3_stream_test.go b/oss/s3/s3_stream_test.go new file mode 100644 index 0000000..c12c662 --- /dev/null +++ b/oss/s3/s3_stream_test.go @@ -0,0 +1,518 @@ +package s3 + +import ( + "context" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/s3" + "github.com/langgenius/dify-cloud-kit/oss" +) + +func newTestStorage(t *testing.T, handler http.Handler) (*S3Storage, *httptest.Server) { + t.Helper() + srv := httptest.NewServer(handler) + t.Cleanup(srv.Close) + + client := s3.New(s3.Options{ + Region: "us-east-1", + Credentials: aws.AnonymousCredentials{}, + BaseEndpoint: aws.String(srv.URL), + UsePathStyle: true, + }) + return &S3Storage{bucket: "bkt", client: client}, srv +} + +// objectHandler serves a fixed body, honoring Range the way S3 does, and +// records the received Range header and request count. +type objectHandler struct { + body []byte + rangeHdr *string + requests *int32 + ignore bool // respond 200 with full body regardless of Range + statusCode int // if >0, respond with this status + XML error instead + errCode string +} + +func (h *objectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + if h.requests != nil { + atomic.AddInt32(h.requests, 1) + } + if h.statusCode > 0 { + w.Header().Set("Content-Type", "application/xml") + w.WriteHeader(h.statusCode) + fmt.Fprintf(w, `%serr`, h.errCode) + return + } + rangeHdr := r.Header.Get("Range") + if h.rangeHdr != nil { + *h.rangeHdr = rangeHdr + } + if rangeHdr == "" || h.ignore { + w.Header().Set("Content-Length", fmt.Sprint(len(h.body))) + w.WriteHeader(http.StatusOK) + w.Write(h.body) + return + } + // parse "bytes=start-end" / "bytes=start-" + var start, end int64 + spec := strings.TrimPrefix(rangeHdr, "bytes=") + if dash := strings.Index(spec, "-"); dash >= 0 { + fmt.Sscan(spec[:dash], &start) + if spec[dash+1:] == "" { + end = int64(len(h.body)) - 1 + } else { + fmt.Sscan(spec[dash+1:], &end) + } + } + if start >= int64(len(h.body)) { + w.WriteHeader(http.StatusRequestedRangeNotSatisfiable) + fmt.Fprint(w, `InvalidRangebad range`) + return + } + // clamp like a real S3 backend does for ranges extending past EOF + if end >= int64(len(h.body)) { + end = int64(len(h.body)) - 1 + } + part := h.body[start : end+1] + w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", start, end, len(h.body))) + w.Header().Set("Content-Length", fmt.Sprint(len(part))) + w.WriteHeader(http.StatusPartialContent) + w.Write(part) +} + +func TestS3OpenFull(t *testing.T) { + var rangeHdr string + st, _ := newTestStorage(t, &objectHandler{body: []byte("hello world"), rangeHdr: &rangeHdr}) + + rc, err := st.Open(context.Background(), "key", nil) + if err != nil { + t.Fatalf("Open: %v", err) + } + defer rc.Close() + data, err := io.ReadAll(rc) + if err != nil { + t.Fatalf("ReadAll: %v", err) + } + if string(data) != "hello world" { + t.Fatalf("got %q", data) + } + if rangeHdr != "" { + t.Fatalf("unexpected Range header %q", rangeHdr) + } +} + +func TestS3OpenBounded(t *testing.T) { + var rangeHdr string + st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789"), rangeHdr: &rangeHdr}) + + rc, err := st.Open(context.Background(), "key", &oss.ByteRange{Offset: 2, Length: 4}) + if err != nil { + t.Fatalf("Open: %v", err) + } + defer rc.Close() + data, err := io.ReadAll(rc) + if err != nil { + t.Fatalf("ReadAll: %v", err) + } + if rangeHdr != "bytes=2-5" { + t.Fatalf("Range header %q", rangeHdr) + } + if string(data) != "2345" { + t.Fatalf("got %q", data) + } +} + +func TestS3OpenOpenEnded(t *testing.T) { + var rangeHdr string + st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789"), rangeHdr: &rangeHdr}) + + rc, err := st.Open(context.Background(), "key", &oss.ByteRange{Offset: 4, Length: -1}) + if err != nil { + t.Fatalf("Open: %v", err) + } + defer rc.Close() + data, err := io.ReadAll(rc) + if err != nil { + t.Fatalf("ReadAll: %v", err) + } + if rangeHdr != "bytes=4-" { + t.Fatalf("Range header %q", rangeHdr) + } + if string(data) != "456789" { + t.Fatalf("got %q", data) + } +} + +func TestS3OpenInvalidRangeNoRequest(t *testing.T) { + var requests int32 + st, _ := newTestStorage(t, &objectHandler{body: []byte("x"), requests: &requests}) + + for _, r := range []oss.ByteRange{ + {Offset: -1, Length: 1}, + {Offset: 0, Length: 0}, + {Offset: 0, Length: -2}, + } { + if _, err := st.Open(context.Background(), "key", &r); !errors.Is(err, oss.ErrInvalidRange) { + t.Fatalf("range=%+v: expected ErrInvalidRange, got %v", r, err) + } + } + if n := atomic.LoadInt32(&requests); n != 0 { + t.Fatalf("expected no requests, got %d", n) + } +} + +func TestS3OpenCanceledBeforeRequest(t *testing.T) { + var requests int32 + st, _ := newTestStorage(t, &objectHandler{body: []byte("x"), requests: &requests}) + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if _, err := st.Open(ctx, "key", nil); err == nil { + t.Fatal("expected error") + } + if n := atomic.LoadInt32(&requests); n != 0 { + t.Fatalf("expected no requests, got %d", n) + } +} + +func TestS3OpenCanceledInflight(t *testing.T) { + entered := make(chan struct{}) + release := make(chan struct{}) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + close(entered) + select { + case <-r.Context().Done(): + case <-release: + } + })) + t.Cleanup(srv.Close) + t.Cleanup(func() { close(release) }) + client := s3.New(s3.Options{ + Region: "us-east-1", + Credentials: aws.AnonymousCredentials{}, + BaseEndpoint: aws.String(srv.URL), + UsePathStyle: true, + }) + st := &S3Storage{bucket: "bkt", client: client} + + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan error, 1) + go func() { + _, err := st.Open(ctx, "key", nil) + done <- err + }() + select { + case <-entered: + case <-time.After(5 * time.Second): + t.Fatal("handler never received request") + } + cancel() + select { + case err := <-done: + if !errors.Is(err, context.Canceled) { + t.Fatalf("expected context.Canceled, got %v", err) + } + case <-time.After(5 * time.Second): + t.Fatal("Open did not return after cancel") + } +} + +// TestS3OpenCanceledDuringBodyRead cancels the context after Open succeeded +// while a Read is blocked on an in-flight body. +func TestS3OpenCanceledDuringBodyRead(t *testing.T) { + release := make(chan struct{}) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Length", "10") + w.WriteHeader(http.StatusOK) + w.Write([]byte("abc")) + w.(http.Flusher).Flush() + select { + case <-r.Context().Done(): + case <-release: + } + })) + t.Cleanup(srv.Close) + t.Cleanup(func() { close(release) }) + client := s3.New(s3.Options{ + Region: "us-east-1", + Credentials: aws.AnonymousCredentials{}, + BaseEndpoint: aws.String(srv.URL), + UsePathStyle: true, + }) + st := &S3Storage{bucket: "bkt", client: client} + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + rc, err := st.Open(ctx, "key", nil) + if err != nil { + t.Fatalf("Open: %v", err) + } + defer rc.Close() + + readDone := make(chan error, 1) + go func() { + _, err := io.ReadFull(rc, make([]byte, 10)) + readDone <- err + }() + time.Sleep(50 * time.Millisecond) + cancel() + select { + case err := <-readDone: + if err == nil { + t.Fatal("expected read error after cancel") + } + case <-time.After(5 * time.Second): + t.Fatal("Read did not return after cancel") + } +} + +func TestS3OpenMissing(t *testing.T) { + st, _ := newTestStorage(t, &objectHandler{statusCode: http.StatusNotFound, errCode: "NoSuchKey"}) + if _, err := st.Open(context.Background(), "missing", nil); err == nil { + t.Fatal("expected error") + } +} + +func TestS3OpenRangeNotSatisfiable(t *testing.T) { + st, _ := newTestStorage(t, &objectHandler{statusCode: http.StatusRequestedRangeNotSatisfiable, errCode: "InvalidRange"}) + _, err := st.Open(context.Background(), "key", &oss.ByteRange{Offset: 100, Length: 1}) + if !errors.Is(err, oss.ErrRangeNotSatisfiable) { + t.Fatalf("expected ErrRangeNotSatisfiable, got %v", err) + } +} + +// TestS3OpenPlain416 verifies HTTP 416 maps to ErrRangeNotSatisfiable even +// when the error body carries no InvalidRange code. +func TestS3OpenPlain416(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusRequestedRangeNotSatisfiable) + w.Write([]byte("not xml")) + })) + t.Cleanup(srv.Close) + client := s3.New(s3.Options{ + Region: "us-east-1", + Credentials: aws.AnonymousCredentials{}, + BaseEndpoint: aws.String(srv.URL), + UsePathStyle: true, + }) + st := &S3Storage{bucket: "bkt", client: client} + + _, err := st.Open(context.Background(), "key", &oss.ByteRange{Offset: 100, Length: 1}) + if !errors.Is(err, oss.ErrRangeNotSatisfiable) { + t.Fatalf("expected ErrRangeNotSatisfiable, got %v", err) + } +} + +// TestS3OpenOversizedEndClamped verifies a bounded range extending past EOF +// is accepted when the server clamps the end to the last byte. +func TestS3OpenOversizedEndClamped(t *testing.T) { + var rangeHdr string + st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789"), rangeHdr: &rangeHdr}) + + rc, err := st.Open(context.Background(), "key", &oss.ByteRange{Offset: 8, Length: 100}) + if err != nil { + t.Fatalf("Open: %v", err) + } + defer rc.Close() + data, err := io.ReadAll(rc) + if err != nil { + t.Fatalf("ReadAll: %v", err) + } + if rangeHdr != "bytes=8-107" { + t.Fatalf("Range header %q", rangeHdr) + } + if string(data) != "89" { + t.Fatalf("got %q", data) + } +} + +func TestS3OpenEmptyObject(t *testing.T) { + st, _ := newTestStorage(t, &objectHandler{body: nil}) + rc, err := st.Open(context.Background(), "key", nil) + if err != nil { + t.Fatalf("Open: %v", err) + } + defer rc.Close() + data, err := io.ReadAll(rc) + if err != nil { + t.Fatalf("ReadAll: %v", err) + } + if len(data) != 0 { + t.Fatalf("expected empty body, got %q", data) + } +} + +// TestS3OpenRejectedRangeClosesBody ensures the response body is closed when +// a ranged response is rejected for missing Content-Range. +func TestS3OpenRejectedRangeClosesBody(t *testing.T) { + var closed int32 + rt := roundTripFunc(func(r *http.Request) (*http.Response, error) { + return &http.Response{ + StatusCode: http.StatusOK, + Status: "200 OK", + Header: http.Header{"Content-Length": []string{"10"}}, + Body: trackingBody{strings.NewReader("0123456789"), &closed}, + ContentLength: 10, + Request: r, + }, nil + }) + client := s3.New(s3.Options{ + Region: "us-east-1", + Credentials: aws.AnonymousCredentials{}, + HTTPClient: &http.Client{Transport: rt}, + EndpointResolver: s3.EndpointResolverFunc(func(region string, o s3.EndpointResolverOptions) (aws.Endpoint, error) { + return aws.Endpoint{URL: "http://s3.invalid"}, nil + }), + }) + st := &S3Storage{bucket: "bkt", client: client} + + _, err := st.Open(context.Background(), "key", &oss.ByteRange{Offset: 2, Length: 4}) + if err == nil { + t.Fatal("expected rejection of range-ignoring response") + } + if atomic.LoadInt32(&closed) != 1 { + t.Fatal("response body was not closed on rejection") + } +} + +func TestS3OpenServerIgnoresRange(t *testing.T) { + st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789"), ignore: true}) + rc, err := st.Open(context.Background(), "key", &oss.ByteRange{Offset: 2, Length: 4}) + if err == nil { + rc.Close() + t.Fatal("expected error when server ignores Range") + } +} + +// TestS3OpenStreamsBeforeFullDownload proves Open returns after headers and +// the first bytes are readable while the rest of the body is still in flight. +func TestS3OpenStreamsBeforeFullDownload(t *testing.T) { + release := make(chan struct{}) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Range", "bytes 0-9/10") + w.Header().Set("Content-Length", "10") + w.WriteHeader(http.StatusPartialContent) + w.Write([]byte("abc")) + w.(http.Flusher).Flush() + select { + case <-r.Context().Done(): + case <-release: + } + })) + t.Cleanup(srv.Close) + t.Cleanup(func() { close(release) }) + + client := s3.New(s3.Options{ + Region: "us-east-1", + Credentials: aws.AnonymousCredentials{}, + BaseEndpoint: aws.String(srv.URL), + UsePathStyle: true, + }) + st := &S3Storage{bucket: "bkt", client: client} + + type res struct { + rc io.ReadCloser + err error + } + opened := make(chan res, 1) + go func() { + rc, err := st.Open(context.Background(), "key", &oss.ByteRange{Offset: 0, Length: -1}) + opened <- res{rc, err} + }() + + var rc io.ReadCloser + select { + case r := <-opened: + if r.err != nil { + t.Fatalf("Open: %v", r.err) + } + rc = r.rc + case <-time.After(5 * time.Second): + t.Fatal("Open blocked until full body downloaded") + } + defer rc.Close() + + buf := make([]byte, 3) + if _, err := io.ReadFull(rc, buf); err != nil { + t.Fatalf("Read: %v", err) + } + if string(buf) != "abc" { + t.Fatalf("got %q", buf) + } + + // Closing the reader must release the in-flight server handler. + if err := rc.Close(); err != nil { + t.Fatalf("Close: %v", err) + } + serverDone := make(chan struct{}) + go func() { + srv.Close() // waits for handlers to return + close(serverDone) + }() + select { + case <-serverDone: + case <-time.After(5 * time.Second): + t.Fatal("server handler still blocked after Close") + } +} + +// trackingBody records whether it was closed. +type trackingBody struct { + *strings.Reader + closed *int32 +} + +func (b trackingBody) Close() error { + atomic.StoreInt32(b.closed, 1) + return nil +} + +type roundTripFunc func(*http.Request) (*http.Response, error) + +func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { + return f(r) +} + +// TestS3LoadClosesBody proves the legacy Load no longer leaks the HTTP body. +func TestS3LoadClosesBody(t *testing.T) { + var closed int32 + rt := roundTripFunc(func(r *http.Request) (*http.Response, error) { + return &http.Response{ + StatusCode: http.StatusOK, + Status: "200 OK", + Header: http.Header{"Content-Length": []string{"7"}}, + Body: trackingBody{strings.NewReader("payload"), &closed}, + ContentLength: 7, + Request: r, + }, nil + }) + client := s3.New(s3.Options{ + Region: "us-east-1", + Credentials: aws.AnonymousCredentials{}, + HTTPClient: &http.Client{Transport: rt}, + EndpointResolver: s3.EndpointResolverFunc(func(region string, o s3.EndpointResolverOptions) (aws.Endpoint, error) { + return aws.Endpoint{URL: "http://s3.invalid"}, nil + }), + }) + st := &S3Storage{bucket: "bkt", client: client} + + data, err := st.Load("key") + if err != nil { + t.Fatalf("Load: %v", err) + } + if string(data) != "payload" { + t.Fatalf("got %q", data) + } + if atomic.LoadInt32(&closed) != 1 { + t.Fatal("response body was not closed") + } +} diff --git a/oss/stream.go b/oss/stream.go new file mode 100644 index 0000000..9fa0014 --- /dev/null +++ b/oss/stream.go @@ -0,0 +1,222 @@ +package oss + +import ( + "context" + "errors" + "fmt" + "io" + "math" + "reflect" + "strconv" + "strings" +) + +var ( + // ErrInvalidRange is returned when a ByteRange is malformed + // (negative offset, zero or less-than-minus-one length, or overflowing end). + ErrInvalidRange = errors.New("invalid byte range") + // ErrRangeNotSatisfiable is returned when a range cannot be satisfied, + // either because it is outside the local object size or because the + // remote service answered 416 Requested Range Not Satisfiable. + ErrRangeNotSatisfiable = errors.New("byte range not satisfiable") + // ErrStreamingNotSupported is returned by OpenStream when the given OSS + // implementation does not implement StreamingOSS. + ErrStreamingNotSupported = errors.New("streaming reads are not supported") +) + +// ByteRange describes a byte range of an object starting at Offset. A nil +// *ByteRange means the whole object. +// +// Offset must be >= 0. Length > 0 requests up to Length bytes (the result may +// be shorter when clamped to the end of the object); Length == -1 reads from +// Offset to the end of the object. Length == 0 or < -1 is invalid. +type ByteRange struct { + Offset int64 + Length int64 +} + +// HTTPRange validates the range and returns the HTTP Range header value, +// "bytes=N-M" for bounded ranges or "bytes=N-" for offset-to-EOF ranges. +func (r ByteRange) HTTPRange() (string, error) { + if r.Offset < 0 { + return "", fmt.Errorf("%w: offset %d is negative", ErrInvalidRange, r.Offset) + } + if r.Length == 0 || r.Length < -1 { + return "", fmt.Errorf("%w: length %d", ErrInvalidRange, r.Length) + } + if r.Length == -1 { + return fmt.Sprintf("bytes=%d-", r.Offset), nil + } + if r.Length-1 > math.MaxInt64-r.Offset { + return "", fmt.Errorf("%w: end of range overflows", ErrInvalidRange) + } + return fmt.Sprintf("bytes=%d-%d", r.Offset, r.Offset+(r.Length-1)), nil +} + +// StreamingOSS is an optional extension of OSS for providers that can stream +// an object (or a byte range of it) without buffering the whole object in +// memory. Callers must type-assert OSS implementations to StreamingOSS; there +// is intentionally no fallback that silently buffers via Load. +// +// The caller must Close the returned reader. The read is governed by ctx: +// cancelling ctx aborts the request and subsequent reads. +type StreamingOSS interface { + OSS + // Open returns a reader over the object stored at key. byteRange may be + // nil to request the whole object. An invalid range fails with + // ErrInvalidRange before any I/O; a range outside the object fails with + // ErrRangeNotSatisfiable. + Open(ctx context.Context, key string, byteRange *ByteRange) (io.ReadCloser, error) +} + +// isNilOSS reports whether store is nil, including a nil pointer inside a +// non-nil interface, so callers never invoke methods on it. +func isNilOSS(store OSS) bool { + if store == nil { + return true + } + v := reflect.ValueOf(store) + switch v.Kind() { + case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: + return v.IsNil() + } + return false +} + +// SupportsStreaming reports whether store implements StreamingOSS, i.e. +// supports both full-object and ranged streaming reads via Open. A nil store +// reports false. +func SupportsStreaming(store OSS) bool { + if isNilOSS(store) { + return false + } + _, ok := store.(StreamingOSS) + return ok +} + +// OpenStream opens a streaming read on store when it implements StreamingOSS. +// byteRange may be nil for the whole object. A store without streaming +// support fails with ErrStreamingNotSupported; there is no fallback to Load, +// which would silently buffer the whole object in memory. +func OpenStream(ctx context.Context, store OSS, key string, byteRange *ByteRange) (io.ReadCloser, error) { + if isNilOSS(store) { + return nil, fmt.Errorf("%w: ", ErrStreamingNotSupported) + } + streamer, ok := store.(StreamingOSS) + if !ok { + return nil, fmt.Errorf("%w: %T", ErrStreamingNotSupported, store) + } + return streamer.Open(ctx, key, byteRange) +} + +// contentRange is a strictly parsed HTTP Content-Range value +// "bytes -/". +type contentRange struct { + start int64 + end int64 // inclusive + total int64 // -1 when the server reported "*" +} + +func parseDigits(s string) (int64, bool) { + if s == "" { + return 0, false + } + for i := 0; i < len(s); i++ { + if s[i] < '0' || s[i] > '9' { + return 0, false + } + } + n, err := strconv.ParseInt(s, 10, 64) + if err != nil { + return 0, false + } + return n, true +} + +// parseContentRange parses a Content-Range header strictly: digits only, no +// signs or spaces inside fields, start >= 0, end >= start, and a numeric +// total must be > end. +func parseContentRange(h string) (contentRange, error) { + var cr contentRange + rest, ok := strings.CutPrefix(h, "bytes ") + if !ok { + return cr, fmt.Errorf("malformed Content-Range %q", h) + } + span, total, ok := strings.Cut(rest, "/") + if !ok { + return cr, fmt.Errorf("malformed Content-Range %q", h) + } + startStr, endStr, ok := strings.Cut(span, "-") + if !ok { + return cr, fmt.Errorf("malformed Content-Range %q", h) + } + start, ok := parseDigits(startStr) + if !ok { + return cr, fmt.Errorf("malformed Content-Range %q", h) + } + end, ok := parseDigits(endStr) + if !ok { + return cr, fmt.Errorf("malformed Content-Range %q", h) + } + if end < start { + return cr, fmt.Errorf("malformed Content-Range %q: end before start", h) + } + cr.start, cr.end, cr.total = start, end, -1 + if total == "*" { + return cr, nil + } + t, ok := parseDigits(total) + if !ok { + return cr, fmt.Errorf("malformed Content-Range %q", h) + } + if t <= end { + return cr, fmt.Errorf("malformed Content-Range %q: total not greater than end", h) + } + cr.total = t + return cr, nil +} + +// VerifyContentRange checks that a ranged GET was honored by the server: the +// Content-Range header must be present, well-formed, start at the requested +// offset, and its end must be consistent with the requested length and the +// reported total size. +func VerifyContentRange(contentRange string, r *ByteRange) error { + if r == nil { + return nil + } + if _, err := r.HTTPRange(); err != nil { + return err + } + cr, err := parseContentRange(contentRange) + if err != nil { + return fmt.Errorf("server did not honor requested range %v: %w", *r, err) + } + if cr.start != r.Offset { + return fmt.Errorf("server did not honor requested range %v: Content-Range starts at %d", *r, cr.start) + } + if r.Length == -1 { + // Open-ended request: with a known total the response must run to + // the last byte; with "*" any end is accepted (it may be EOF). + if cr.total >= 0 && cr.end != cr.total-1 { + return fmt.Errorf("server did not honor requested range %v: Content-Range ends at %d of %d", *r, cr.end, cr.total) + } + return nil + } + requestedEnd := r.Offset + (r.Length - 1) + if cr.total >= 0 { + // The server must return exactly the requested end, clamped to the + // last available byte when the range extends past EOF. + expected := requestedEnd + if expected > cr.total-1 { + expected = cr.total - 1 + } + if cr.end != expected { + return fmt.Errorf("server did not honor requested range %v: Content-Range ends at %d, expected %d", *r, cr.end, expected) + } + return nil + } + if cr.end > requestedEnd { + return fmt.Errorf("server did not honor requested range %v: Content-Range ends at %d, requested %d", *r, cr.end, requestedEnd) + } + return nil +} diff --git a/oss/stream_test.go b/oss/stream_test.go new file mode 100644 index 0000000..04441fd --- /dev/null +++ b/oss/stream_test.go @@ -0,0 +1,175 @@ +package oss + +import ( + "context" + "errors" + "io" + "math" + "strings" + "testing" +) + +func TestByteRangeHTTPRange(t *testing.T) { + cases := []struct { + name string + r ByteRange + want string + wantErr bool + }{ + {"bounded", ByteRange{Offset: 0, Length: 10}, "bytes=0-9", false}, + {"bounded mid", ByteRange{Offset: 5, Length: 4}, "bytes=5-8", false}, + {"to EOF", ByteRange{Offset: 3, Length: -1}, "bytes=3-", false}, + {"to EOF at zero", ByteRange{Offset: 0, Length: -1}, "bytes=0-", false}, + {"single byte at maxint", ByteRange{Offset: math.MaxInt64, Length: 1}, "bytes=9223372036854775807-9223372036854775807", false}, + {"max length from zero", ByteRange{Offset: 0, Length: math.MaxInt64}, "bytes=0-9223372036854775806", false}, + {"overflow end", ByteRange{Offset: math.MaxInt64, Length: 2}, "", true}, + {"overflow end mid", ByteRange{Offset: math.MaxInt64 - 5, Length: 7}, "", true}, + {"negative offset", ByteRange{Offset: -1, Length: 10}, "", true}, + {"negative offset to EOF", ByteRange{Offset: -1, Length: -1}, "", true}, + {"zero length", ByteRange{Offset: 0, Length: 0}, "", true}, + {"length below -1", ByteRange{Offset: 0, Length: -2}, "", true}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + got, err := c.r.HTTPRange() + if c.wantErr { + if err == nil { + t.Fatalf("expected error, got %q", got) + } + if !errors.Is(err, ErrInvalidRange) { + t.Fatalf("expected ErrInvalidRange, got %v", err) + } + return + } + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if got != c.want { + t.Fatalf("got %q, want %q", got, c.want) + } + }) + } +} + +func TestVerifyContentRange(t *testing.T) { + bounded := &ByteRange{Offset: 5, Length: 4} // requested end 8 + openEnded := &ByteRange{Offset: 4, Length: -1} // requested 4-EOF + clamped := &ByteRange{Offset: 8, Length: 100} // requested end 107 + + cases := []struct { + name string + header string + r *ByteRange + wantErr bool + }{ + {"bounded ok", "bytes 5-8/100", bounded, false}, + {"bounded unknown total ok", "bytes 5-8/*", bounded, false}, + {"bounded clamped to EOF ok", "bytes 8-9/10", clamped, false}, + {"bounded short of requested end", "bytes 8-8/10", clamped, true}, + {"open ended ok", "bytes 4-9/10", openEnded, false}, + {"open ended unknown total ok", "bytes 4-9/*", openEnded, false}, + {"open ended stops before EOF", "bytes 4-8/10", openEnded, true}, + {"missing header", "", bounded, true}, + {"garbage", "garbage", bounded, true}, + {"malformed end", "bytes 5-garbage/100", bounded, true}, + {"malformed total", "bytes 5-8/x", bounded, true}, + {"trailing junk on total", "bytes 5-8/100x", bounded, true}, + {"sign on start", "bytes +5-8/100", bounded, true}, + {"sign on end", "bytes 5-+8/100", bounded, true}, + {"negative start rejected by digits", "bytes -1-8/100", bounded, true}, + {"inverted range", "bytes 8-5/100", bounded, true}, + {"missing dash", "bytes 5/100", bounded, true}, + {"missing total part", "bytes 5-8", bounded, true}, + {"wrong start", "bytes 0-8/100", bounded, true}, + {"wrong end", "bytes 5-9/100", bounded, true}, + {"server returned whole object", "bytes 0-99/100", &ByteRange{Offset: 0, Length: 10}, true}, + {"total not greater than end", "bytes 5-8/8", bounded, true}, + {"total equal to end+1 ok", "bytes 5-8/9", bounded, false}, + {"unknown total end beyond request", "bytes 5-99/*", bounded, true}, + {"nil request range ignores header", "", nil, false}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + err := VerifyContentRange(c.header, c.r) + if c.wantErr && err == nil { + t.Fatalf("expected error for %q", c.header) + } + if !c.wantErr && err != nil { + t.Fatalf("unexpected error for %q: %v", c.header, err) + } + }) + } +} + +// fakeOSS satisfies OSS only via the embedded interface; calling any method +// on it panics because the embedded value is nil. +type fakeOSS struct { + OSS +} + +type fakeStreamingOSS struct { + OSS + opened bool + gotCtx context.Context + gotKey string + gotRange *ByteRange + reader io.ReadCloser + err error +} + +func (f *fakeStreamingOSS) Open(ctx context.Context, key string, byteRange *ByteRange) (io.ReadCloser, error) { + f.opened = true + f.gotCtx = ctx + f.gotKey = key + f.gotRange = byteRange + return f.reader, f.err +} + +func TestSupportsStreaming(t *testing.T) { + if !SupportsStreaming(&fakeStreamingOSS{}) { + t.Fatal("expected true for StreamingOSS implementation") + } + if SupportsStreaming(&fakeOSS{}) { + t.Fatal("expected false for OSS-only implementation") + } + if SupportsStreaming(nil) { + t.Fatal("expected false for nil") + } + if SupportsStreaming((*fakeStreamingOSS)(nil)) { + t.Fatal("expected false for typed nil") + } +} + +func TestOpenStreamUnsupported(t *testing.T) { + for _, store := range []OSS{nil, &fakeOSS{}, (*fakeStreamingOSS)(nil)} { + _, err := OpenStream(context.Background(), store, "key", nil) + if !errors.Is(err, ErrStreamingNotSupported) { + t.Fatalf("expected ErrStreamingNotSupported, got %v", err) + } + } +} + +func TestOpenStreamDelegates(t *testing.T) { + reader := io.NopCloser(strings.NewReader("data")) + fake := &fakeStreamingOSS{reader: reader} + r := &ByteRange{Offset: 2, Length: 4} + type ctxKey struct{} + ctx := context.WithValue(context.Background(), ctxKey{}, "v") + + rc, err := OpenStream(ctx, fake, "key", r) + if err != nil { + t.Fatalf("OpenStream: %v", err) + } + if rc != reader { + t.Fatal("expected the same reader back") + } + if !fake.opened || fake.gotKey != "key" || fake.gotRange != r || fake.gotCtx.Value(ctxKey{}) != "v" { + t.Fatalf("Open not called with same ctx/key/range: %+v", fake) + } + + fakeErr := errors.New("boom") + fake2 := &fakeStreamingOSS{err: fakeErr} + if _, err := OpenStream(context.Background(), fake2, "key", nil); !errors.Is(err, fakeErr) { + t.Fatalf("expected provider error, got %v", err) + } +} From 1239ec7b67aac3761568a0ee6293d15503193ba5 Mon Sep 17 00:00:00 2001 From: "yunlu.wen" Date: Thu, 5 Nov 2026 13:23:37 +0800 Subject: [PATCH 02/13] test(oss): add emulator integration checks for pull requests --- .github/workflows/integration.yml | 49 +++++++++ Makefile | 17 +++ README.md | 41 +++++++ compose.integration.yaml | 30 +++++ oss/azureblob/blob_live_test.go | 177 ++++++++++++++++++++++++++++++ tests/integration/azure_test.go | 94 ++++++++++++++++ tests/integration/common_test.go | 142 ++++++++++++++++++++++++ tests/integration/fixture_test.go | 75 +++++++++++++ tests/integration/s3_test.go | 110 +++++++++++++++++++ 9 files changed, 735 insertions(+) create mode 100644 .github/workflows/integration.yml create mode 100644 Makefile create mode 100644 compose.integration.yaml create mode 100644 oss/azureblob/blob_live_test.go create mode 100644 tests/integration/azure_test.go create mode 100644 tests/integration/common_test.go create mode 100644 tests/integration/fixture_test.go create mode 100644 tests/integration/s3_test.go diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml new file mode 100644 index 0000000..4e79f42 --- /dev/null +++ b/.github/workflows/integration.yml @@ -0,0 +1,49 @@ +name: Integration Tests + +on: + pull_request: + push: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: integration-${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + integration: + name: Storage Integration + runs-on: ubuntu-24.04 + timeout-minutes: 15 + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-go@v5 + with: + go-version-file: go.mod + cache: true + + - name: Run integration tests + run: make test-integration + + - name: Collect container diagnostics + if: always() + run: | + docker compose -f compose.integration.yaml ps + docker compose -f compose.integration.yaml logs --no-color > integration-containers.log 2>&1 + + - name: Upload container logs + if: failure() + uses: actions/upload-artifact@v4 + with: + name: integration-container-logs + path: integration-containers.log + retention-days: 7 + if-no-files-found: warn + + - name: Stop integration services + if: always() + run: make integration-down diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..272f11d --- /dev/null +++ b/Makefile @@ -0,0 +1,17 @@ +COMPOSE_INTEGRATION := docker compose -f compose.integration.yaml + +# Start the ephemeral emulator stack (LocalStack S3 + Azurite Blob) and wait +# for healthchecks. Services are left running until `make integration-down`. +integration-up: + $(COMPOSE_INTEGRATION) up -d --wait --wait-timeout 120 + +# Run the emulator-backed integration suite. Services stay up afterwards so +# repeated runs are fast; use `make integration-down` to stop them. +test-integration: integration-up + CLOUDKIT_INTEGRATION=1 go test -race -count=1 -timeout=5m -v ./tests/integration + +# Stop and remove the integration compose project (containers only). +integration-down: + $(COMPOSE_INTEGRATION) down + +.PHONY: integration-up test-integration integration-down diff --git a/README.md b/README.md index cd0e1e6..09a09bb 100644 --- a/README.md +++ b/README.md @@ -205,3 +205,44 @@ Some parts of the code in this project originate from [dify-plugin-daemon](https | AWS S3 |[Yeuoly](https://github.com/Yeuoly)|https://github.com/langgenius/dify-plugin-daemon/commit/9ad9d7d4de1d123956ab07955e541bc4053e5170| | Tencent COS |[quicksand](https://github.com/quicksandznzn)|https://github.com/langgenius/dify-plugin-daemon/pull/97| | Volcengine TOS |[quicksand](https://github.com/quicksandznzn)|https://github.com/langgenius/dify-cloud-kit/pull/2| + +## ๐Ÿงฉ Integration Tests (Emulators) + +Hermetic integration tests run the streaming `OpenStream` API against local +emulators โ€” **no real cloud credentials or accounts required**: + +| Emulator | Image | Endpoint | +|-----------|------------------------------------------------|-----------------------------| +| LocalStack| `localstack/localstack:4.0.3` (S3 only) | `http://127.0.0.1:14566` | +| Azurite | `mcr.microsoft.com/azure-storage/azurite:3.35.0` (blob) | `http://127.0.0.1:11000` | + +### Make targets + +```bash +make integration-up # start the ephemeral compose project and wait for health +make test-integration # up + CLOUDKIT_INTEGRATION=1 go test -race ./tests/integration +make integration-down # stop and remove the compose project +``` + +`test-integration` leaves services running for fast reruns; use +`integration-down` when finished. Tests create uniquely named +buckets/containers and delete only resources they created. The suite is +gated on `CLOUDKIT_INTEGRATION=1` โ€” a plain `go test ./...` skips it. + +### CI + +`.github/workflows/integration.yml` runs `make test-integration` on every +pull request, push to `main`, and manual dispatch ("Storage Integration" +check). No secrets are needed; emulator container logs are uploaded as a +workflow artifact on failure and services are always torn down at the end. + +### Scope + +- Offline unit tests live under `./oss/...` and run with a plain `go test`. +- `tests/oss/` is the legacy real-cloud suite (requires credentials) and is + not part of the hermetic integration gate. +- A true-cloud opt-in test (`oss/azureblob/blob_live_test.go`, requires + `CLOUDKIT_AZURE_LIVE_*` env vars and an existing blob) is separate. + +Note: this suite depends on the streaming `OpenStream`/`StreamingOSS` API and +must rebase onto the streaming feature branch once it lands. diff --git a/compose.integration.yaml b/compose.integration.yaml new file mode 100644 index 0000000..895edef --- /dev/null +++ b/compose.integration.yaml @@ -0,0 +1,30 @@ +name: cloudkit-integration + +# Ephemeral object-storage emulators for `make test-integration`. +# Loopback-only ports, no volumes, no credentials, no cloud access. + +services: + localstack: + image: localstack/localstack:4.0.3 + environment: + SERVICES: s3 + ports: + - "127.0.0.1:14566:4566" + healthcheck: + test: ["CMD-SHELL", "curl -sf http://127.0.0.1:4566/_localstack/health >/dev/null"] + interval: 2s + timeout: 5s + retries: 30 + + azurite: + image: mcr.microsoft.com/azure-storage/azurite:3.35.0 + command: azurite-blob --blobHost 0.0.0.0 --skipApiVersionCheck + ports: + - "127.0.0.1:11000:10000" + healthcheck: + # Azurite answers an anonymous root request with 400/403 once the + # blob service is up; only a connection failure means "not ready". + test: ["CMD", "node", "-e", "require('http').get('http://127.0.0.1:10000/',r=>process.exit([400,403].includes(r.statusCode)?0:1)).on('error',()=>process.exit(1))"] + interval: 2s + timeout: 5s + retries: 30 diff --git a/oss/azureblob/blob_live_test.go b/oss/azureblob/blob_live_test.go new file mode 100644 index 0000000..859359a --- /dev/null +++ b/oss/azureblob/blob_live_test.go @@ -0,0 +1,177 @@ +package azureblob + +import ( + "context" + "errors" + "fmt" + "io" + "math" + "os" + "testing" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob" + "github.com/langgenius/dify-cloud-kit/oss" +) + +// TestAzureLiveStreaming is an OPT-IN real-Azure integration test. It only +// READS an existing blob; it performs no cloud writes or deletes. +// +// Required env vars (test skips unless all are set): +// +// CLOUDKIT_AZURE_LIVE_ACCOUNT storage account name +// CLOUDKIT_AZURE_LIVE_CONTAINER container name +// CLOUDKIT_AZURE_LIVE_KEY blob key (16MiB fixture: byte i = i % 251) +func TestAzureLiveStreaming(t *testing.T) { + account := os.Getenv("CLOUDKIT_AZURE_LIVE_ACCOUNT") + container := os.Getenv("CLOUDKIT_AZURE_LIVE_CONTAINER") + key := os.Getenv("CLOUDKIT_AZURE_LIVE_KEY") + if account == "" || container == "" || key == "" { + t.Skip("set CLOUDKIT_AZURE_LIVE_ACCOUNT, CLOUDKIT_AZURE_LIVE_CONTAINER, CLOUDKIT_AZURE_LIVE_KEY to run") + } + + cred, err := azidentity.NewAzureCLICredential(nil) + if err != nil { + t.Fatalf("NewAzureCLICredential: %v", err) + } + client, err := azblob.NewClient("https://"+account+".blob.core.windows.net", cred, nil) + if err != nil { + t.Fatalf("azblob.NewClient: %v", err) + } + store := &AzureBlobStorage{client: client, containerName: container} + + const size = 16 * 1024 * 1024 + expected := func(pos int64) byte { return byte(pos % 251) } + + if !oss.SupportsStreaming(store) { + t.Fatal("AzureBlobStorage does not report streaming support") + } + + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + + // Use the SDK directly so the size check is bounded by ctx (store.State + // has no context parameter). + props, err := client.ServiceClient().NewContainerClient(container). + NewBlobClient(key).GetProperties(ctx, nil) + if err != nil { + t.Fatalf("GetProperties: %v", err) + } + if props.ContentLength == nil || *props.ContentLength != size { + t.Fatalf("ContentLength %v, want %d", props.ContentLength, size) + } + t.Logf("blob %s/%s/%s size=%d", account, container, key, *props.ContentLength) + + // readBounded streams rc through a 32KiB buffer, validating every byte + // against expected(globalOffset+i) starting at startOff. Returns bytes read. + readBounded := func(rc io.Reader, startOff int64) (int64, error) { + buf := make([]byte, 32*1024) + var total int64 + for { + n, err := rc.Read(buf) + for i := 0; i < n; i++ { + pos := startOff + total + int64(i) + if buf[i] != expected(pos) { + return total, fmt.Errorf("content mismatch at offset %d: got %d, want %d", pos, buf[i], expected(pos)) + } + } + total += int64(n) + if err == io.EOF { + return total, nil + } + if err != nil { + return total, err + } + } + } + + // verify opens, reads through a bounded buffer, and closes the reader + // before returning; t.Cleanup is only a backup for early failures. + verify := func(name string, r *oss.ByteRange, startOff, want int64) { + t.Helper() + c, cancel := context.WithTimeout(context.Background(), 60*time.Second) + rc, err := oss.OpenStream(c, store, key, r) + if err != nil { + cancel() + t.Fatalf("%s: OpenStream(%+v): %v", name, r, err) + } + t.Cleanup(func() { + rc.Close() + cancel() + }) + got, err := readBounded(rc, startOff) + rc.Close() + cancel() + if err != nil { + t.Fatalf("%s: %v", name, err) + } + if got != want { + t.Fatalf("%s: read %d bytes, want %d", name, got, want) + } + t.Logf("%s: verified %d bytes from offset %d", name, want, startOff) + } + + verify("full", nil, 0, size) + verify("bounded early", &oss.ByteRange{Offset: 2, Length: 4096}, 2, 4096) + verify("bounded mid", &oss.ByteRange{Offset: 1<<20 + 17, Length: 65536}, 1<<20+17, 65536) + verify("tail to EOF", &oss.ByteRange{Offset: size - 123, Length: -1}, size-123, 123) + verify("zero to EOF", &oss.ByteRange{Offset: 0, Length: -1}, 0, size) + verify("clamped end", &oss.ByteRange{Offset: size - 8, Length: 100}, size-8, 8) + + // offset == size is unsatisfiable + _, err = oss.OpenStream(ctx, store, key, &oss.ByteRange{Offset: size, Length: 1}) + if !errors.Is(err, oss.ErrRangeNotSatisfiable) { + t.Fatalf("offset==size: expected ErrRangeNotSatisfiable, got %v", err) + } + + // invalid ranges fail before any I/O + for _, r := range []oss.ByteRange{ + {Offset: -1, Length: 1}, + {Offset: 0, Length: 0}, + {Offset: 0, Length: -2}, + {Offset: math.MaxInt64, Length: 2}, // overflowing end + } { + if _, err := oss.OpenStream(ctx, store, key, &r); !errors.Is(err, oss.ErrInvalidRange) { + t.Fatalf("range=%+v: expected ErrInvalidRange, got %v", r, err) + } + } + + // pre-canceled context + canceled, cancelNow := context.WithCancel(context.Background()) + cancelNow() + if _, err := oss.OpenStream(canceled, store, key, nil); !errors.Is(err, context.Canceled) { + t.Fatalf("expected context.Canceled, got %v", err) + } + + // mid-read cancel: read 1KiB then cancel; a subsequent read must produce + // a non-EOF error before the whole object is consumed. The context + // timeout bounds a blocked Read. + midCtx, midCancel := context.WithTimeout(context.Background(), 60*time.Second) + defer midCancel() + rc, err := oss.OpenStream(midCtx, store, key, nil) + if err != nil { + t.Fatalf("OpenStream (midread): %v", err) + } + defer rc.Close() + + buf := make([]byte, 32*1024) + if _, err := io.ReadFull(rc, buf[:1024]); err != nil { + t.Fatalf("initial read: %v", err) + } + midCancel() + var consumed int64 = 1024 + var readErr error + for consumed < size { + n, err := rc.Read(buf) + consumed += int64(n) + if err != nil { + readErr = err + break + } + } + if readErr == nil || errors.Is(readErr, io.EOF) || consumed >= size { + t.Fatalf("expected non-EOF error before consuming the whole object; consumed %d bytes, err %v", consumed, readErr) + } + t.Logf("mid-read cancel: consumed %d bytes then error %v", consumed, readErr) +} diff --git a/tests/integration/azure_test.go b/tests/integration/azure_test.go new file mode 100644 index 0000000..2d9acfe --- /dev/null +++ b/tests/integration/azure_test.go @@ -0,0 +1,94 @@ +package integration + +import ( + "context" + "fmt" + "io" + "os" + "testing" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob" + "github.com/google/uuid" + "github.com/langgenius/dify-cloud-kit/oss" + "github.com/langgenius/dify-cloud-kit/oss/factory" +) + +// Azurite's well-known development account and key (public, documented by +// Microsoft; not a real credential). +const ( + azuriteEndpoint = "http://127.0.0.1:11000/devstoreaccount1" + azuriteConnStr = "DefaultEndpointsProtocol=http;" + + "AccountName=devstoreaccount1;" + + "AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;" + + "BlobEndpoint=" + azuriteEndpoint + ";" +) + +func TestAzureIntegrationStreaming(t *testing.T) { + requireIntegration(t) + + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + + container := fmt.Sprintf("cloudkit-it-%s", uuid.NewString()) + objKey := "fixture.bin" + emptyKey := "empty.bin" + containerCreated := false + + client, err := azblob.NewClientFromConnectionString(azuriteConnStr, nil) + if err != nil { + t.Fatalf("NewClientFromConnectionString: %v", err) + } + + t.Cleanup(func() { + if !containerCreated { + return + } + c, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + for _, k := range []string{objKey, emptyKey} { + if _, err := client.DeleteBlob(c, container, k, nil); err != nil { + t.Logf("cleanup DeleteBlob %s: %v", k, err) + } + } + if _, err := client.DeleteContainer(c, container, nil); err != nil { + t.Logf("cleanup DeleteContainer: %v", err) + } + }) + + if _, err := client.CreateContainer(ctx, container, nil); err != nil { + t.Fatalf("CreateContainer: %v", err) + } + containerCreated = true + t.Logf("created container %s on %s", container, azuriteEndpoint) + + fixture := writeFixture(t, objectSize) + f, err := os.Open(fixture) + if err != nil { + t.Fatalf("open fixture: %v", err) + } + defer f.Close() + if _, err := client.UploadStream(ctx, container, objKey, f, nil); err != nil { + t.Fatalf("UploadStream: %v", err) + } + if _, err := client.UploadStream(ctx, container, emptyKey, emptyReader{}, nil); err != nil { + t.Fatalf("UploadStream empty: %v", err) + } + + store, err := factory.Load("azure_blob", oss.OSSArgs{ + AzureBlob: &oss.AzureBlob{ + ConnectionString: azuriteConnStr, + ContainerName: container, + }, + }) + if err != nil { + t.Fatalf("factory.Load azure_blob: %v", err) + } + + runStreamingChecks(t, store, objKey, emptyKey) +} + +// emptyReader is a zero-length io.Reader. +type emptyReader struct{} + +func (emptyReader) Read([]byte) (int, error) { return 0, io.EOF } diff --git a/tests/integration/common_test.go b/tests/integration/common_test.go new file mode 100644 index 0000000..d9c020b --- /dev/null +++ b/tests/integration/common_test.go @@ -0,0 +1,142 @@ +package integration + +import ( + "context" + "errors" + "io" + "math" + "testing" + "time" + + "github.com/langgenius/dify-cloud-kit/oss" +) + +// runStreamingChecks runs the shared streaming-range assertion suite against +// a cloudkit store backed by an emulator. objKey must hold the deterministic +// 16MiB fixture; emptyKey must exist as a zero-byte object. +func runStreamingChecks(t *testing.T, store oss.OSS, objKey, emptyKey string) { + t.Helper() + + if !oss.SupportsStreaming(store) { + t.Fatalf("%T does not report streaming support", store) + } + + // verify opens, streams through a bounded buffer, and closes before + // returning. It takes the subtest's *testing.T explicitly so a failure + // reports on the subtest, not the parent. + verify := func(t *testing.T, key string, r *oss.ByteRange, startOff, want int64) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + rc, err := oss.OpenStream(ctx, store, key, r) + if err != nil { + t.Fatalf("OpenStream(%+v): %v", r, err) + } + defer rc.Close() + got, err := readBounded(rc, startOff) + if err != nil { + t.Fatalf("%v", err) + } + if got != want { + t.Fatalf("read %d bytes, want %d", got, want) + } + t.Logf("verified %d bytes from offset %d", want, startOff) + } + + t.Run("full", func(t *testing.T) { verify(t, objKey, nil, 0, objectSize) }) + t.Run("zero to EOF", func(t *testing.T) { + verify(t, objKey, &oss.ByteRange{Offset: 0, Length: -1}, 0, objectSize) + }) + t.Run("bounded early", func(t *testing.T) { + verify(t, objKey, &oss.ByteRange{Offset: 2, Length: 4096}, 2, 4096) + }) + t.Run("bounded mid", func(t *testing.T) { + verify(t, objKey, &oss.ByteRange{Offset: 1<<20 + 17, Length: 65536}, 1<<20+17, 65536) + }) + t.Run("tail to EOF", func(t *testing.T) { + verify(t, objKey, &oss.ByteRange{Offset: objectSize - 123, Length: -1}, objectSize-123, 123) + }) + t.Run("clamped end", func(t *testing.T) { + verify(t, objKey, &oss.ByteRange{Offset: objectSize - 8, Length: 100}, objectSize-8, 8) + }) + t.Run("empty object", func(t *testing.T) { verify(t, emptyKey, nil, 0, 0) }) + + t.Run("empty object ranged unsatisfiable", func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + _, err := oss.OpenStream(ctx, store, emptyKey, &oss.ByteRange{Offset: 0, Length: 1}) + if !errors.Is(err, oss.ErrRangeNotSatisfiable) { + t.Fatalf("expected ErrRangeNotSatisfiable, got %v", err) + } + }) + + t.Run("offset equals size unsatisfiable", func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + _, err := oss.OpenStream(ctx, store, objKey, &oss.ByteRange{Offset: objectSize, Length: 1}) + if !errors.Is(err, oss.ErrRangeNotSatisfiable) { + t.Fatalf("expected ErrRangeNotSatisfiable, got %v", err) + } + }) + + t.Run("missing key", func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + if _, err := oss.OpenStream(ctx, store, "no-such-key", nil); err == nil { + t.Fatal("expected error for missing key") + } + }) + + t.Run("invalid ranges", func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + for _, r := range []oss.ByteRange{ + {Offset: -1, Length: 1}, + {Offset: 0, Length: 0}, + {Offset: 0, Length: -2}, + {Offset: math.MaxInt64, Length: 2}, // overflowing end + } { + if _, err := oss.OpenStream(ctx, store, objKey, &r); !errors.Is(err, oss.ErrInvalidRange) { + t.Fatalf("range=%+v: expected ErrInvalidRange, got %v", r, err) + } + } + }) + + t.Run("pre-canceled context", func(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if _, err := oss.OpenStream(ctx, store, objKey, nil); !errors.Is(err, context.Canceled) { + t.Fatalf("expected context.Canceled, got %v", err) + } + }) + + t.Run("cancel during read", func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + rc, err := oss.OpenStream(ctx, store, objKey, nil) + if err != nil { + t.Fatalf("OpenStream: %v", err) + } + defer rc.Close() + + buf := make([]byte, 32*1024) + if _, err := io.ReadFull(rc, buf[:1024]); err != nil { + t.Fatalf("initial read: %v", err) + } + cancel() + var consumed int64 = 1024 + var readErr error + for consumed < objectSize { + n, err := rc.Read(buf) + consumed += int64(n) + if err != nil { + readErr = err + break + } + } + if readErr == nil || errors.Is(readErr, io.EOF) || consumed >= objectSize { + t.Fatalf("expected non-EOF error before consuming the whole object; consumed %d bytes, err %v", consumed, readErr) + } + t.Logf("cancel during read: consumed %d bytes then error %v", consumed, readErr) + }) +} diff --git a/tests/integration/fixture_test.go b/tests/integration/fixture_test.go new file mode 100644 index 0000000..274f576 --- /dev/null +++ b/tests/integration/fixture_test.go @@ -0,0 +1,75 @@ +package integration + +import ( + "fmt" + "io" + "os" + "path/filepath" + "testing" +) + +// objectSize is the shared fixture size: byte at offset i equals i % 251. +const objectSize = 16 * 1024 * 1024 + +func expectedByte(pos int64) byte { return byte(pos % 251) } + +// requireIntegration skips unless the emulator gate is enabled; ordinary +// `go test` never contacts emulators from this package. +func requireIntegration(t *testing.T) { + t.Helper() + if os.Getenv("CLOUDKIT_INTEGRATION") != "1" { + t.Skip("set CLOUDKIT_INTEGRATION=1 (via make test-integration) to run emulator integration tests") + } +} + +// writeFixture writes the deterministic object to a temp file in <=32KiB +// chunks (no full-object allocation) and returns its path. +func writeFixture(t *testing.T, size int64) string { + t.Helper() + path := filepath.Join(t.TempDir(), "fixture.bin") + f, err := os.Create(path) + if err != nil { + t.Fatalf("create fixture: %v", err) + } + defer f.Close() + + buf := make([]byte, 32*1024) + var off int64 + for off < size { + n := int64(len(buf)) + if size-off < n { + n = size - off + } + for i := int64(0); i < n; i++ { + buf[i] = expectedByte(off + i) + } + if _, err := f.Write(buf[:n]); err != nil { + t.Fatalf("write fixture: %v", err) + } + off += n + } + return path +} + +// readBounded streams rc through a 32KiB buffer, validating every byte +// against expectedByte(startOff+i). Returns total bytes read. +func readBounded(rc io.Reader, startOff int64) (int64, error) { + buf := make([]byte, 32*1024) + var total int64 + for { + n, err := rc.Read(buf) + for i := 0; i < n; i++ { + pos := startOff + total + int64(i) + if buf[i] != expectedByte(pos) { + return total, fmt.Errorf("content mismatch at offset %d: got %d, want %d", pos, buf[i], expectedByte(pos)) + } + } + total += int64(n) + if err == io.EOF { + return total, nil + } + if err != nil { + return total, err + } + } +} diff --git a/tests/integration/s3_test.go b/tests/integration/s3_test.go new file mode 100644 index 0000000..9da0f2c --- /dev/null +++ b/tests/integration/s3_test.go @@ -0,0 +1,110 @@ +package integration + +import ( + "bytes" + "context" + "fmt" + "os" + "testing" + "time" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/credentials" + "github.com/aws/aws-sdk-go-v2/service/s3" + "github.com/google/uuid" + "github.com/langgenius/dify-cloud-kit/oss" + "github.com/langgenius/dify-cloud-kit/oss/factory" +) + +const localstackEndpoint = "http://127.0.0.1:14566" + +func newLocalstackS3Client() *s3.Client { + return s3.New(s3.Options{ + Region: "us-east-1", + Credentials: credentials.NewStaticCredentialsProvider("test", "test", ""), + BaseEndpoint: aws.String(localstackEndpoint), + UsePathStyle: true, + }) +} + +func TestS3IntegrationStreaming(t *testing.T) { + requireIntegration(t) + + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + + bucket := fmt.Sprintf("cloudkit-it-%s", uuid.NewString()) + objKey := "fixture.bin" + emptyKey := "empty.bin" + bucketCreated := false + client := newLocalstackS3Client() + + t.Cleanup(func() { + if !bucketCreated { + return + } + c, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + for _, k := range []string{objKey, emptyKey} { + if _, err := client.DeleteObject(c, &s3.DeleteObjectInput{ + Bucket: aws.String(bucket), Key: aws.String(k), + }); err != nil { + t.Logf("cleanup DeleteObject %s: %v", k, err) + } + } + if _, err := client.DeleteBucket(c, &s3.DeleteBucketInput{ + Bucket: aws.String(bucket), + }); err != nil { + t.Logf("cleanup DeleteBucket: %v", err) + } + }) + + if _, err := client.CreateBucket(ctx, &s3.CreateBucketInput{ + Bucket: aws.String(bucket), + }); err != nil { + t.Fatalf("CreateBucket: %v", err) + } + bucketCreated = true + t.Logf("created bucket %s on %s", bucket, localstackEndpoint) + + fixture := writeFixture(t, objectSize) + f, err := os.Open(fixture) + if err != nil { + t.Fatalf("open fixture: %v", err) + } + defer f.Close() + if _, err := client.PutObject(ctx, &s3.PutObjectInput{ + Bucket: aws.String(bucket), + Key: aws.String(objKey), + Body: f, + ContentLength: aws.Int64(objectSize), + }); err != nil { + t.Fatalf("PutObject: %v", err) + } + if _, err := client.PutObject(ctx, &s3.PutObjectInput{ + Bucket: aws.String(bucket), + Key: aws.String(emptyKey), + Body: bytes.NewReader(nil), + ContentLength: aws.Int64(0), + }); err != nil { + t.Fatalf("PutObject empty: %v", err) + } + + store, err := factory.Load("s3", oss.OSSArgs{ + S3: &oss.S3{ + UseAws: false, + Endpoint: localstackEndpoint, + UsePathStyle: true, + AccessKey: "test", + SecretKey: "test", + Bucket: bucket, + Region: "us-east-1", + SignatureVersion: "v4", + }, + }) + if err != nil { + t.Fatalf("factory.Load s3: %v", err) + } + + runStreamingChecks(t, store, objKey, emptyKey) +} From 786f3628569845fa0bc5f56e163f4700957379f9 Mon Sep 17 00:00:00 2001 From: "yunlu.wen" Date: Thu, 5 Nov 2026 21:06:01 +0800 Subject: [PATCH 03/13] ci: gate streaming feature on unit and integration tests --- .github/workflows/integration.yml | 3 +++ README.md | 13 +++++++------ 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml index 4e79f42..81884fa 100644 --- a/.github/workflows/integration.yml +++ b/.github/workflows/integration.yml @@ -26,6 +26,9 @@ jobs: go-version-file: go.mod cache: true + - name: Run unit tests + run: go test -race -count=1 -timeout=5m ./oss/... + - name: Run integration tests run: make test-integration diff --git a/README.md b/README.md index 09a09bb..47b1d41 100644 --- a/README.md +++ b/README.md @@ -231,10 +231,11 @@ gated on `CLOUDKIT_INTEGRATION=1` โ€” a plain `go test ./...` skips it. ### CI -`.github/workflows/integration.yml` runs `make test-integration` on every -pull request, push to `main`, and manual dispatch ("Storage Integration" -check). No secrets are needed; emulator container logs are uploaded as a -workflow artifact on failure and services are always torn down at the end. +`.github/workflows/integration.yml` runs the unit tests (`./oss/...`) first, +then `make test-integration`, on every pull request, push to `main`, and +manual dispatch ("Storage Integration" check). No secrets are needed; +emulator container logs are uploaded as a workflow artifact on failure and +services are always torn down at the end. ### Scope @@ -244,5 +245,5 @@ workflow artifact on failure and services are always torn down at the end. - A true-cloud opt-in test (`oss/azureblob/blob_live_test.go`, requires `CLOUDKIT_AZURE_LIVE_*` env vars and an existing blob) is separate. -Note: this suite depends on the streaming `OpenStream`/`StreamingOSS` API and -must rebase onto the streaming feature branch once it lands. +The streaming feature and these emulator/CI tests ship together in the same +PR โ€” there is no stacked-branch dependency. From acde563b261727f5bd4d831d6b48feca5bb681a9 Mon Sep 17 00:00:00 2001 From: "yunlu.wen" Date: Thu, 5 Nov 2026 21:10:07 +0800 Subject: [PATCH 04/13] refactor(oss): rename streaming Open method to Range --- README.md | 12 ++-- oss/aliyun/aliyun.go | 4 +- oss/aliyun/aliyun_stream_test.go | 88 +++++++++++++-------------- oss/azureblob/blob.go | 4 +- oss/azureblob/blob_stream_test.go | 96 +++++++++++++++--------------- oss/local/localfile.go | 4 +- oss/local/localfile_stream_test.go | 60 +++++++++---------- oss/s3/s3.go | 4 +- oss/s3/s3_stream_test.go | 88 +++++++++++++-------------- oss/stream.go | 8 +-- oss/stream_test.go | 4 +- 11 files changed, 186 insertions(+), 186 deletions(-) diff --git a/README.md b/README.md index 47b1d41..78a530a 100644 --- a/README.md +++ b/README.md @@ -76,7 +76,7 @@ buffering. ```go type StreamingOSS interface { OSS - Open(ctx context.Context, key string, byteRange *ByteRange) (io.ReadCloser, error) + Range(ctx context.Context, key string, byteRange *ByteRange) (io.ReadCloser, error) } type ByteRange struct { @@ -96,15 +96,15 @@ Semantics: object size from `State`. - Cancelling `ctx` aborts the request and subsequent `Read` calls. Always `defer rc.Close()`. -- **No automatic fallback**: backends without `Open` fail the type assertion; +- **No automatic fallback**: backends without `Range` fail the type assertion; the library never secretly buffers a ranged request via `Load`. -- Ranged `Open` calls verify the server actually honored the `Range` header +- Partial `Range` calls verify the server actually honored the `Range` header (via `Content-Range`); a server that ignores it causes an error instead of a silent full download. ### Supported streaming providers -| Provider | `Open` support | Notes | +| Provider | `Range` support | Notes | |------------|----------------|-------------------------------------------| | Local | โœ… | `os.File` + `io.SectionReader`, end clamped to file size | | AWS S3 | โœ… | `GetObjectInput.Range`, body streamed | @@ -123,7 +123,7 @@ if !oss.SupportsStreaming(store) { } ``` -`oss.OpenStream` performs the assertion and delegates to `Open`, returning an +`oss.OpenStream` performs the assertion and delegates to `Range`, returning an error wrapping `oss.ErrStreamingNotSupported` for unsupported (or nil) backends: @@ -147,7 +147,7 @@ if !ok { } ctx := request.Context() // tie the read to the request lifecycle -rc, err := streamer.Open(ctx, "big-file.bin", &oss.ByteRange{Offset: 0, Length: -1}) +rc, err := streamer.Range(ctx, "big-file.bin", &oss.ByteRange{Offset: 0, Length: -1}) if err != nil { return err } diff --git a/oss/aliyun/aliyun.go b/oss/aliyun/aliyun.go index c16ba36..a8a74bf 100644 --- a/oss/aliyun/aliyun.go +++ b/oss/aliyun/aliyun.go @@ -104,7 +104,7 @@ func (s *AliyunOSSStorage) Save(key string, data []byte) error { } func (s *AliyunOSSStorage) Load(key string) ([]byte, error) { - reader, err := s.Open(context.Background(), key, nil) + reader, err := s.Range(context.Background(), key, nil) if err != nil { return nil, err } @@ -113,7 +113,7 @@ func (s *AliyunOSSStorage) Load(key string) ([]byte, error) { return io.ReadAll(reader) } -func (s *AliyunOSSStorage) Open(ctx context.Context, key string, byteRange *difyoss.ByteRange) (io.ReadCloser, error) { +func (s *AliyunOSSStorage) Range(ctx context.Context, key string, byteRange *difyoss.ByteRange) (io.ReadCloser, error) { options := []oss.Option{oss.WithContext(ctx)} if byteRange != nil { rangeHeader, err := byteRange.HTTPRange() diff --git a/oss/aliyun/aliyun_stream_test.go b/oss/aliyun/aliyun_stream_test.go index b5df1cf..ffff057 100644 --- a/oss/aliyun/aliyun_stream_test.go +++ b/oss/aliyun/aliyun_stream_test.go @@ -98,13 +98,13 @@ func (h *objectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.Write(part) } -func TestAliyunOpenFull(t *testing.T) { +func TestAliyunRangeFull(t *testing.T) { var rangeHdr string st := newTestStorage(t, &objectHandler{body: []byte("hello world"), rangeHdr: &rangeHdr}, "") - rc, err := st.Open(context.Background(), "key", nil) + rc, err := st.Range(context.Background(), "key", nil) if err != nil { - t.Fatalf("Open: %v", err) + t.Fatalf("Range: %v", err) } defer rc.Close() data, err := io.ReadAll(rc) @@ -119,13 +119,13 @@ func TestAliyunOpenFull(t *testing.T) { } } -func TestAliyunOpenBounded(t *testing.T) { +func TestAliyunRangeBounded(t *testing.T) { var rangeHdr, behavior string st := newTestStorage(t, &objectHandler{body: []byte("0123456789"), rangeHdr: &rangeHdr, behavior: &behavior}, "") - rc, err := st.Open(context.Background(), "key", &difyoss.ByteRange{Offset: 2, Length: 4}) + rc, err := st.Range(context.Background(), "key", &difyoss.ByteRange{Offset: 2, Length: 4}) if err != nil { - t.Fatalf("Open: %v", err) + t.Fatalf("Range: %v", err) } defer rc.Close() data, err := io.ReadAll(rc) @@ -143,13 +143,13 @@ func TestAliyunOpenBounded(t *testing.T) { } } -func TestAliyunOpenOpenEnded(t *testing.T) { +func TestAliyunRangeOpenEnded(t *testing.T) { var rangeHdr string st := newTestStorage(t, &objectHandler{body: []byte("0123456789"), rangeHdr: &rangeHdr}, "") - rc, err := st.Open(context.Background(), "key", &difyoss.ByteRange{Offset: 4, Length: -1}) + rc, err := st.Range(context.Background(), "key", &difyoss.ByteRange{Offset: 4, Length: -1}) if err != nil { - t.Fatalf("Open: %v", err) + t.Fatalf("Range: %v", err) } defer rc.Close() data, err := io.ReadAll(rc) @@ -164,13 +164,13 @@ func TestAliyunOpenOpenEnded(t *testing.T) { } } -func TestAliyunOpenHonorsConfiguredPrefix(t *testing.T) { +func TestAliyunRangeHonorsConfiguredPrefix(t *testing.T) { var reqPath string st := newTestStorage(t, &objectHandler{body: []byte("x"), path: &reqPath}, "prefix/") - rc, err := st.Open(context.Background(), "dir/key", nil) + rc, err := st.Range(context.Background(), "dir/key", nil) if err != nil { - t.Fatalf("Open: %v", err) + t.Fatalf("Range: %v", err) } rc.Close() if !strings.HasSuffix(reqPath, "/prefix/dir/key") { @@ -178,7 +178,7 @@ func TestAliyunOpenHonorsConfiguredPrefix(t *testing.T) { } } -func TestAliyunOpenInvalidRangeNoRequest(t *testing.T) { +func TestAliyunRangeInvalidRangeNoRequest(t *testing.T) { var requests int32 st := newTestStorage(t, &objectHandler{body: []byte("x"), requests: &requests}, "") @@ -187,7 +187,7 @@ func TestAliyunOpenInvalidRangeNoRequest(t *testing.T) { {Offset: 0, Length: 0}, {Offset: 0, Length: -2}, } { - if _, err := st.Open(context.Background(), "key", &r); !errors.Is(err, difyoss.ErrInvalidRange) { + if _, err := st.Range(context.Background(), "key", &r); !errors.Is(err, difyoss.ErrInvalidRange) { t.Fatalf("range=%+v: expected ErrInvalidRange, got %v", r, err) } } @@ -196,13 +196,13 @@ func TestAliyunOpenInvalidRangeNoRequest(t *testing.T) { } } -func TestAliyunOpenCanceledBeforeRequest(t *testing.T) { +func TestAliyunRangeCanceledBeforeRequest(t *testing.T) { var requests int32 st := newTestStorage(t, &objectHandler{body: []byte("x"), requests: &requests}, "") ctx, cancel := context.WithCancel(context.Background()) cancel() - if _, err := st.Open(ctx, "key", nil); err == nil { + if _, err := st.Range(ctx, "key", nil); err == nil { t.Fatal("expected error") } if n := atomic.LoadInt32(&requests); n != 0 { @@ -210,7 +210,7 @@ func TestAliyunOpenCanceledBeforeRequest(t *testing.T) { } } -func TestAliyunOpenCanceledInflight(t *testing.T) { +func TestAliyunRangeCanceledInflight(t *testing.T) { entered := make(chan struct{}) release := make(chan struct{}) srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -236,7 +236,7 @@ func TestAliyunOpenCanceledInflight(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) done := make(chan error, 1) go func() { - _, err := st.Open(ctx, "key", nil) + _, err := st.Range(ctx, "key", nil) done <- err }() select { @@ -251,13 +251,13 @@ func TestAliyunOpenCanceledInflight(t *testing.T) { t.Fatal("expected error after cancel") } case <-time.After(5 * time.Second): - t.Fatal("Open did not return after cancel") + t.Fatal("Range did not return after cancel") } } -// TestAliyunOpenCanceledDuringBodyRead cancels the context after Open +// TestAliyunRangeCanceledDuringBodyRead cancels the context after Range // succeeded while a Read is blocked on an in-flight body. -func TestAliyunOpenCanceledDuringBodyRead(t *testing.T) { +func TestAliyunRangeCanceledDuringBodyRead(t *testing.T) { release := make(chan struct{}) srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Length", "10") @@ -284,9 +284,9 @@ func TestAliyunOpenCanceledDuringBodyRead(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() - rc, err := st.Open(ctx, "key", nil) + rc, err := st.Range(ctx, "key", nil) if err != nil { - t.Fatalf("Open: %v", err) + t.Fatalf("Range: %v", err) } defer rc.Close() @@ -307,33 +307,33 @@ func TestAliyunOpenCanceledDuringBodyRead(t *testing.T) { } } -func TestAliyunOpenMissing(t *testing.T) { +func TestAliyunRangeMissing(t *testing.T) { st := newTestStorage(t, &objectHandler{statusCode: http.StatusNotFound, errCode: "NoSuchKey"}, "") - if _, err := st.Open(context.Background(), "missing", nil); err == nil { + if _, err := st.Range(context.Background(), "missing", nil); err == nil { t.Fatal("expected error") } } -func TestAliyunOpenRangeNotSatisfiable(t *testing.T) { +func TestAliyunRangeRangeNotSatisfiable(t *testing.T) { st := newTestStorage(t, &objectHandler{statusCode: http.StatusRequestedRangeNotSatisfiable, errCode: "InvalidRange"}, "") - _, err := st.Open(context.Background(), "key", &difyoss.ByteRange{Offset: 100, Length: 1}) + _, err := st.Range(context.Background(), "key", &difyoss.ByteRange{Offset: 100, Length: 1}) if !errors.Is(err, difyoss.ErrRangeNotSatisfiable) { t.Fatalf("expected ErrRangeNotSatisfiable, got %v", err) } } -func TestAliyunOpenServerIgnoresRange(t *testing.T) { +func TestAliyunRangeServerIgnoresRange(t *testing.T) { st := newTestStorage(t, &objectHandler{body: []byte("0123456789"), ignore: true}, "") - rc, err := st.Open(context.Background(), "key", &difyoss.ByteRange{Offset: 2, Length: 4}) + rc, err := st.Range(context.Background(), "key", &difyoss.ByteRange{Offset: 2, Length: 4}) if err == nil { rc.Close() t.Fatal("expected error when server ignores Range") } } -// TestAliyunOpenRejectedRangeClosesBody ensures the response body is closed +// TestAliyunRangeRejectedRangeClosesBody ensures the response body is closed // when a ranged response is rejected for missing Content-Range. -func TestAliyunOpenRejectedRangeClosesBody(t *testing.T) { +func TestAliyunRangeRejectedRangeClosesBody(t *testing.T) { var closed int32 rt := roundTripFunc(func(r *http.Request) (*http.Response, error) { return &http.Response{ @@ -356,7 +356,7 @@ func TestAliyunOpenRejectedRangeClosesBody(t *testing.T) { } st := &AliyunOSSStorage{client: client, bucket: bucket} - _, err = st.Open(context.Background(), "key", &difyoss.ByteRange{Offset: 2, Length: 4}) + _, err = st.Range(context.Background(), "key", &difyoss.ByteRange{Offset: 2, Length: 4}) if err == nil { t.Fatal("expected rejection of range-ignoring response") } @@ -365,15 +365,15 @@ func TestAliyunOpenRejectedRangeClosesBody(t *testing.T) { } } -// TestAliyunOpenOversizedEndClamped verifies a bounded range extending past +// TestAliyunRangeOversizedEndClamped verifies a bounded range extending past // EOF is accepted when the server clamps the end to the last byte. -func TestAliyunOpenOversizedEndClamped(t *testing.T) { +func TestAliyunRangeOversizedEndClamped(t *testing.T) { var rangeHdr string st := newTestStorage(t, &objectHandler{body: []byte("0123456789"), rangeHdr: &rangeHdr}, "") - rc, err := st.Open(context.Background(), "key", &difyoss.ByteRange{Offset: 8, Length: 100}) + rc, err := st.Range(context.Background(), "key", &difyoss.ByteRange{Offset: 8, Length: 100}) if err != nil { - t.Fatalf("Open: %v", err) + t.Fatalf("Range: %v", err) } defer rc.Close() data, err := io.ReadAll(rc) @@ -388,11 +388,11 @@ func TestAliyunOpenOversizedEndClamped(t *testing.T) { } } -func TestAliyunOpenEmptyObject(t *testing.T) { +func TestAliyunRangeEmptyObject(t *testing.T) { st := newTestStorage(t, &objectHandler{body: nil}, "") - rc, err := st.Open(context.Background(), "key", nil) + rc, err := st.Range(context.Background(), "key", nil) if err != nil { - t.Fatalf("Open: %v", err) + t.Fatalf("Range: %v", err) } defer rc.Close() data, err := io.ReadAll(rc) @@ -421,9 +421,9 @@ func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } -// TestAliyunOpenStreamsBeforeFullDownload proves Open returns after headers +// TestAliyunRangeStreamsBeforeFullDownload proves Range returns after headers // and first bytes are readable while the rest is still in flight. -func TestAliyunOpenStreamsBeforeFullDownload(t *testing.T) { +func TestAliyunRangeStreamsBeforeFullDownload(t *testing.T) { release := make(chan struct{}) srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Range", "bytes 0-9/10") @@ -456,7 +456,7 @@ func TestAliyunOpenStreamsBeforeFullDownload(t *testing.T) { } opened := make(chan res, 1) go func() { - rc, err := st.Open(context.Background(), "key", &difyoss.ByteRange{Offset: 0, Length: -1}) + rc, err := st.Range(context.Background(), "key", &difyoss.ByteRange{Offset: 0, Length: -1}) opened <- res{rc, err} }() @@ -464,11 +464,11 @@ func TestAliyunOpenStreamsBeforeFullDownload(t *testing.T) { select { case r := <-opened: if r.err != nil { - t.Fatalf("Open: %v", r.err) + t.Fatalf("Range: %v", r.err) } rc = r.rc case <-time.After(5 * time.Second): - t.Fatal("Open blocked until full body downloaded") + t.Fatal("Range blocked until full body downloaded") } defer rc.Close() diff --git a/oss/azureblob/blob.go b/oss/azureblob/blob.go index a0e56c9..f1f97cc 100644 --- a/oss/azureblob/blob.go +++ b/oss/azureblob/blob.go @@ -63,7 +63,7 @@ func (a *AzureBlobStorage) Save(key string, data []byte) error { } func (a *AzureBlobStorage) Load(key string) ([]byte, error) { - reader, err := a.Open(context.Background(), key, nil) + reader, err := a.Range(context.Background(), key, nil) if err != nil { return nil, err } @@ -72,7 +72,7 @@ func (a *AzureBlobStorage) Load(key string) ([]byte, error) { return io.ReadAll(reader) } -func (a *AzureBlobStorage) Open(ctx context.Context, key string, byteRange *oss.ByteRange) (io.ReadCloser, error) { +func (a *AzureBlobStorage) Range(ctx context.Context, key string, byteRange *oss.ByteRange) (io.ReadCloser, error) { options := &azblob.DownloadStreamOptions{} if byteRange != nil { if _, err := byteRange.HTTPRange(); err != nil { diff --git a/oss/azureblob/blob_stream_test.go b/oss/azureblob/blob_stream_test.go index eb237c9..b54a4a5 100644 --- a/oss/azureblob/blob_stream_test.go +++ b/oss/azureblob/blob_stream_test.go @@ -85,13 +85,13 @@ func (h *objectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.Write(part) } -func TestAzureOpenFull(t *testing.T) { +func TestAzureRangeFull(t *testing.T) { var rangeHdr string st, _ := newTestStorage(t, &objectHandler{body: []byte("hello world"), rangeHdr: &rangeHdr}) - rc, err := st.Open(context.Background(), "key", nil) + rc, err := st.Range(context.Background(), "key", nil) if err != nil { - t.Fatalf("Open: %v", err) + t.Fatalf("Range: %v", err) } defer rc.Close() data, err := io.ReadAll(rc) @@ -106,11 +106,11 @@ func TestAzureOpenFull(t *testing.T) { } } -func TestAzureOpenEmptyObject(t *testing.T) { +func TestAzureRangeEmptyObject(t *testing.T) { st, _ := newTestStorage(t, &objectHandler{body: nil}) - rc, err := st.Open(context.Background(), "key", nil) + rc, err := st.Range(context.Background(), "key", nil) if err != nil { - t.Fatalf("Open: %v", err) + t.Fatalf("Range: %v", err) } defer rc.Close() data, err := io.ReadAll(rc) @@ -122,13 +122,13 @@ func TestAzureOpenEmptyObject(t *testing.T) { } } -func TestAzureOpenBounded(t *testing.T) { +func TestAzureRangeBounded(t *testing.T) { var rangeHdr string st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789"), rangeHdr: &rangeHdr}) - rc, err := st.Open(context.Background(), "key", &oss.ByteRange{Offset: 2, Length: 4}) + rc, err := st.Range(context.Background(), "key", &oss.ByteRange{Offset: 2, Length: 4}) if err != nil { - t.Fatalf("Open: %v", err) + t.Fatalf("Range: %v", err) } defer rc.Close() data, err := io.ReadAll(rc) @@ -143,13 +143,13 @@ func TestAzureOpenBounded(t *testing.T) { } } -func TestAzureOpenToEOF(t *testing.T) { +func TestAzureRangeToEOF(t *testing.T) { var rangeHdr string st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789"), rangeHdr: &rangeHdr}) - rc, err := st.Open(context.Background(), "key", &oss.ByteRange{Offset: 4, Length: -1}) + rc, err := st.Range(context.Background(), "key", &oss.ByteRange{Offset: 4, Length: -1}) if err != nil { - t.Fatalf("Open: %v", err) + t.Fatalf("Range: %v", err) } defer rc.Close() data, err := io.ReadAll(rc) @@ -164,16 +164,16 @@ func TestAzureOpenToEOF(t *testing.T) { } } -// TestAzureOpenZeroToEOF verifies ByteRange{0,-1} sends an explicit signed +// TestAzureRangeZeroToEOF verifies ByteRange{0,-1} sends an explicit signed // range header even though the SDK's HTTPRange{0,0} would omit it, and that // the same range on an empty object yields 416 -> ErrRangeNotSatisfiable. -func TestAzureOpenZeroToEOF(t *testing.T) { +func TestAzureRangeZeroToEOF(t *testing.T) { var rangeHdr string st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789"), rangeHdr: &rangeHdr}) - rc, err := st.Open(context.Background(), "key", &oss.ByteRange{Offset: 0, Length: -1}) + rc, err := st.Range(context.Background(), "key", &oss.ByteRange{Offset: 0, Length: -1}) if err != nil { - t.Fatalf("Open: %v", err) + t.Fatalf("Range: %v", err) } defer rc.Close() data, err := io.ReadAll(rc) @@ -189,19 +189,19 @@ func TestAzureOpenZeroToEOF(t *testing.T) { // empty object + bytes=0- must surface ErrRangeNotSatisfiable st2, _ := newTestStorage(t, &objectHandler{body: nil}) - _, err = st2.Open(context.Background(), "key", &oss.ByteRange{Offset: 0, Length: -1}) + _, err = st2.Range(context.Background(), "key", &oss.ByteRange{Offset: 0, Length: -1}) if !errors.Is(err, oss.ErrRangeNotSatisfiable) { t.Fatalf("expected ErrRangeNotSatisfiable, got %v", err) } } -func TestAzureOpenOversizedEndClamped(t *testing.T) { +func TestAzureRangeOversizedEndClamped(t *testing.T) { var rangeHdr string st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789"), rangeHdr: &rangeHdr}) - rc, err := st.Open(context.Background(), "key", &oss.ByteRange{Offset: 8, Length: 100}) + rc, err := st.Range(context.Background(), "key", &oss.ByteRange{Offset: 8, Length: 100}) if err != nil { - t.Fatalf("Open: %v", err) + t.Fatalf("Range: %v", err) } defer rc.Close() data, err := io.ReadAll(rc) @@ -216,7 +216,7 @@ func TestAzureOpenOversizedEndClamped(t *testing.T) { } } -func TestAzureOpenInvalidRangeNoRequest(t *testing.T) { +func TestAzureRangeInvalidRangeNoRequest(t *testing.T) { var requests int32 st, _ := newTestStorage(t, &objectHandler{body: []byte("x"), requests: &requests}) @@ -226,7 +226,7 @@ func TestAzureOpenInvalidRangeNoRequest(t *testing.T) { {Offset: 0, Length: -2}, {Offset: 1<<62 + 1, Length: 1 << 62}, // overflowing end } { - if _, err := st.Open(context.Background(), "key", &r); !errors.Is(err, oss.ErrInvalidRange) { + if _, err := st.Range(context.Background(), "key", &r); !errors.Is(err, oss.ErrInvalidRange) { t.Fatalf("range=%+v: expected ErrInvalidRange, got %v", r, err) } } @@ -235,24 +235,24 @@ func TestAzureOpenInvalidRangeNoRequest(t *testing.T) { } } -func TestAzureOpenMissing(t *testing.T) { +func TestAzureRangeMissing(t *testing.T) { st, _ := newTestStorage(t, &objectHandler{statusCode: http.StatusNotFound, errCode: "BlobNotFound"}) - if _, err := st.Open(context.Background(), "missing", nil); err == nil { + if _, err := st.Range(context.Background(), "missing", nil); err == nil { t.Fatal("expected error") } } -func TestAzureOpenRangeNotSatisfiable(t *testing.T) { +func TestAzureRangeRangeNotSatisfiable(t *testing.T) { st, _ := newTestStorage(t, &objectHandler{statusCode: http.StatusRequestedRangeNotSatisfiable, errCode: "InvalidRange"}) - _, err := st.Open(context.Background(), "key", &oss.ByteRange{Offset: 100, Length: 1}) + _, err := st.Range(context.Background(), "key", &oss.ByteRange{Offset: 100, Length: 1}) if !errors.Is(err, oss.ErrRangeNotSatisfiable) { t.Fatalf("expected ErrRangeNotSatisfiable, got %v", err) } } -// TestAzureOpenPlain416 verifies HTTP 416 maps to ErrRangeNotSatisfiable even +// TestAzureRangePlain416 verifies HTTP 416 maps to ErrRangeNotSatisfiable even // without an XML error body. -func TestAzureOpenPlain416(t *testing.T) { +func TestAzureRangePlain416(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusRequestedRangeNotSatisfiable) w.Write([]byte("not xml")) @@ -264,7 +264,7 @@ func TestAzureOpenPlain416(t *testing.T) { } st := &AzureBlobStorage{client: client, containerName: "cont"} - _, err = st.Open(context.Background(), "key", &oss.ByteRange{Offset: 100, Length: 1}) + _, err = st.Range(context.Background(), "key", &oss.ByteRange{Offset: 100, Length: 1}) if !errors.Is(err, oss.ErrRangeNotSatisfiable) { t.Fatalf("expected ErrRangeNotSatisfiable, got %v", err) } @@ -298,10 +298,10 @@ func newTrackingStorage(t *testing.T, rt http.RoundTripper) *AzureBlobStorage { return &AzureBlobStorage{client: client, containerName: "cont"} } -// TestAzureOpenRejectedRangeClosesBody ensures the response body is closed +// TestAzureRangeRejectedRangeClosesBody ensures the response body is closed // when a ranged response is rejected for a missing or mismatched // Content-Range. -func TestAzureOpenRejectedRangeClosesBody(t *testing.T) { +func TestAzureRangeRejectedRangeClosesBody(t *testing.T) { for _, tc := range []struct { name string contentRange string @@ -328,7 +328,7 @@ func TestAzureOpenRejectedRangeClosesBody(t *testing.T) { }) st := newTrackingStorage(t, rt) - _, err := st.Open(context.Background(), "key", &oss.ByteRange{Offset: 2, Length: 4}) + _, err := st.Range(context.Background(), "key", &oss.ByteRange{Offset: 2, Length: 4}) if err == nil { t.Fatal("expected rejection") } @@ -339,13 +339,13 @@ func TestAzureOpenRejectedRangeClosesBody(t *testing.T) { } } -func TestAzureOpenCanceledBeforeRequest(t *testing.T) { +func TestAzureRangeCanceledBeforeRequest(t *testing.T) { var requests int32 st, _ := newTestStorage(t, &objectHandler{body: []byte("x"), requests: &requests}) ctx, cancel := context.WithCancel(context.Background()) cancel() - if _, err := st.Open(ctx, "key", nil); err == nil { + if _, err := st.Range(ctx, "key", nil); err == nil { t.Fatal("expected error") } if n := atomic.LoadInt32(&requests); n != 0 { @@ -353,7 +353,7 @@ func TestAzureOpenCanceledBeforeRequest(t *testing.T) { } } -func TestAzureOpenCanceledInflight(t *testing.T) { +func TestAzureRangeCanceledInflight(t *testing.T) { entered := make(chan struct{}) release := make(chan struct{}) srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -374,7 +374,7 @@ func TestAzureOpenCanceledInflight(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) done := make(chan error, 1) go func() { - _, err := st.Open(ctx, "key", nil) + _, err := st.Range(ctx, "key", nil) done <- err }() select { @@ -389,13 +389,13 @@ func TestAzureOpenCanceledInflight(t *testing.T) { t.Fatal("expected error after cancel") } case <-time.After(5 * time.Second): - t.Fatal("Open did not return after cancel") + t.Fatal("Range did not return after cancel") } } -// TestAzureOpenCanceledDuringBodyRead cancels the context after Open +// TestAzureRangeCanceledDuringBodyRead cancels the context after Range // succeeded while a Read is blocked on an in-flight body. -func TestAzureOpenCanceledDuringBodyRead(t *testing.T) { +func TestAzureRangeCanceledDuringBodyRead(t *testing.T) { release := make(chan struct{}) srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Length", "10") @@ -417,9 +417,9 @@ func TestAzureOpenCanceledDuringBodyRead(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() - rc, err := st.Open(ctx, "key", nil) + rc, err := st.Range(ctx, "key", nil) if err != nil { - t.Fatalf("Open: %v", err) + t.Fatalf("Range: %v", err) } defer rc.Close() @@ -440,10 +440,10 @@ func TestAzureOpenCanceledDuringBodyRead(t *testing.T) { } } -// TestAzureOpenStreamsBeforeFullDownload proves Open returns after headers +// TestAzureRangeStreamsBeforeFullDownload proves Range returns after headers // and first bytes are readable while the rest is still in flight, and that // Close releases the blocked handler. -func TestAzureOpenStreamsBeforeFullDownload(t *testing.T) { +func TestAzureRangeStreamsBeforeFullDownload(t *testing.T) { release := make(chan struct{}) srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Range", "bytes 0-9/10") @@ -470,7 +470,7 @@ func TestAzureOpenStreamsBeforeFullDownload(t *testing.T) { } opened := make(chan res, 1) go func() { - rc, err := st.Open(context.Background(), "key", &oss.ByteRange{Offset: 0, Length: -1}) + rc, err := st.Range(context.Background(), "key", &oss.ByteRange{Offset: 0, Length: -1}) opened <- res{rc, err} }() @@ -478,11 +478,11 @@ func TestAzureOpenStreamsBeforeFullDownload(t *testing.T) { select { case r := <-opened: if r.err != nil { - t.Fatalf("Open: %v", r.err) + t.Fatalf("Range: %v", r.err) } rc = r.rc case <-time.After(5 * time.Second): - t.Fatal("Open blocked until full body downloaded") + t.Fatal("Range blocked until full body downloaded") } defer rc.Close() @@ -550,9 +550,9 @@ func runRetryTest(t *testing.T, byteRange *oss.ByteRange, body string, served in h := &retryHandler{full: body, served: served, retried: make(chan struct{}), t: t} st, _ := newTestStorage(t, h) - rc, err := st.Open(context.Background(), "key", byteRange) + rc, err := st.Range(context.Background(), "key", byteRange) if err != nil { - t.Fatalf("Open: %v", err) + t.Fatalf("Range: %v", err) } defer rc.Close() diff --git a/oss/local/localfile.go b/oss/local/localfile.go index 1013418..be22f94 100644 --- a/oss/local/localfile.go +++ b/oss/local/localfile.go @@ -44,7 +44,7 @@ func (l *LocalStorage) Save(key string, data []byte) error { } func (l *LocalStorage) Load(key string) ([]byte, error) { - reader, err := l.Open(context.Background(), key, nil) + reader, err := l.Range(context.Background(), key, nil) if err != nil { return nil, err } @@ -72,7 +72,7 @@ func (r *ctxFileReader) Close() error { return r.file.Close() } -func (l *LocalStorage) Open(ctx context.Context, key string, byteRange *oss.ByteRange) (io.ReadCloser, error) { +func (l *LocalStorage) Range(ctx context.Context, key string, byteRange *oss.ByteRange) (io.ReadCloser, error) { if byteRange != nil { if _, err := byteRange.HTTPRange(); err != nil { return nil, err diff --git a/oss/local/localfile_stream_test.go b/oss/local/localfile_stream_test.go index 95294aa..2b92e10 100644 --- a/oss/local/localfile_stream_test.go +++ b/oss/local/localfile_stream_test.go @@ -29,21 +29,21 @@ func writeFile(t *testing.T, st *LocalStorage, key string, data []byte) { } } -func openRange(t *testing.T, st *LocalStorage, key string, r *oss.ByteRange) io.ReadCloser { +func rangeReader(t *testing.T, st *LocalStorage, key string, r *oss.ByteRange) io.ReadCloser { t.Helper() - rc, err := st.Open(context.Background(), key, r) + rc, err := st.Range(context.Background(), key, r) if err != nil { - t.Fatalf("Open: %v", err) + t.Fatalf("Range: %v", err) } t.Cleanup(func() { rc.Close() }) return rc } -func TestLocalOpenFull(t *testing.T) { +func TestLocalRangeFull(t *testing.T) { st := newTestStorage(t) writeFile(t, st, "a/b.bin", []byte("hello world")) - rc := openRange(t, st, "a/b.bin", nil) + rc := rangeReader(t, st, "a/b.bin", nil) data, err := io.ReadAll(rc) if err != nil { t.Fatalf("ReadAll: %v", err) @@ -53,11 +53,11 @@ func TestLocalOpenFull(t *testing.T) { } } -func TestLocalOpenFullEmptyFile(t *testing.T) { +func TestLocalRangeFullEmptyFile(t *testing.T) { st := newTestStorage(t) writeFile(t, st, "empty", nil) - rc := openRange(t, st, "empty", nil) + rc := rangeReader(t, st, "empty", nil) data, err := io.ReadAll(rc) if err != nil { t.Fatalf("ReadAll: %v", err) @@ -67,11 +67,11 @@ func TestLocalOpenFullEmptyFile(t *testing.T) { } } -func TestLocalOpenBounded(t *testing.T) { +func TestLocalRangeBounded(t *testing.T) { st := newTestStorage(t) writeFile(t, st, "f", []byte("0123456789")) - rc := openRange(t, st, "f", &oss.ByteRange{Offset: 2, Length: 4}) + rc := rangeReader(t, st, "f", &oss.ByteRange{Offset: 2, Length: 4}) data, err := io.ReadAll(rc) if err != nil { t.Fatalf("ReadAll: %v", err) @@ -81,11 +81,11 @@ func TestLocalOpenBounded(t *testing.T) { } } -func TestLocalOpenToEOF(t *testing.T) { +func TestLocalRangeToEOF(t *testing.T) { st := newTestStorage(t) writeFile(t, st, "f", []byte("0123456789")) - rc := openRange(t, st, "f", &oss.ByteRange{Offset: 7, Length: -1}) + rc := rangeReader(t, st, "f", &oss.ByteRange{Offset: 7, Length: -1}) data, err := io.ReadAll(rc) if err != nil { t.Fatalf("ReadAll: %v", err) @@ -95,12 +95,12 @@ func TestLocalOpenToEOF(t *testing.T) { } } -func TestLocalOpenClampedEnd(t *testing.T) { +func TestLocalRangeClampedEnd(t *testing.T) { st := newTestStorage(t) writeFile(t, st, "f", []byte("0123456789")) // Length extends past end of file; only remaining bytes come back. - rc := openRange(t, st, "f", &oss.ByteRange{Offset: 8, Length: 100}) + rc := rangeReader(t, st, "f", &oss.ByteRange{Offset: 8, Length: 100}) data, err := io.ReadAll(rc) if err != nil { t.Fatalf("ReadAll: %v", err) @@ -110,13 +110,13 @@ func TestLocalOpenClampedEnd(t *testing.T) { } } -func TestLocalOpenHugeLengthClamped(t *testing.T) { +func TestLocalRangeHugeLengthClamped(t *testing.T) { st := newTestStorage(t) writeFile(t, st, "f", []byte("0123456789")) // Length is a valid inclusive HTTP range (end = MaxInt64); the local // clamp must not overflow computing offset+length. - rc := openRange(t, st, "f", &oss.ByteRange{Offset: 1, Length: math.MaxInt64}) + rc := rangeReader(t, st, "f", &oss.ByteRange{Offset: 1, Length: math.MaxInt64}) data, err := io.ReadAll(rc) if err != nil { t.Fatalf("ReadAll: %v", err) @@ -126,14 +126,14 @@ func TestLocalOpenHugeLengthClamped(t *testing.T) { } } -func TestLocalOpenMissing(t *testing.T) { +func TestLocalRangeMissing(t *testing.T) { st := newTestStorage(t) - if _, err := st.Open(context.Background(), "nope", nil); err == nil { + if _, err := st.Range(context.Background(), "nope", nil); err == nil { t.Fatal("expected error for missing key") } } -func TestLocalOpenUnsatisfiable(t *testing.T) { +func TestLocalRangeUnsatisfiable(t *testing.T) { st := newTestStorage(t) writeFile(t, st, "f", []byte("0123456789")) writeFile(t, st, "empty", nil) @@ -148,13 +148,13 @@ func TestLocalOpenUnsatisfiable(t *testing.T) { {"empty", oss.ByteRange{Offset: 0, Length: 1}}, // empty file {"empty", oss.ByteRange{Offset: 0, Length: -1}}, } { - if _, err := st.Open(context.Background(), c.key, &c.r); !errors.Is(err, oss.ErrRangeNotSatisfiable) { + if _, err := st.Range(context.Background(), c.key, &c.r); !errors.Is(err, oss.ErrRangeNotSatisfiable) { t.Fatalf("key=%s range=%+v: expected ErrRangeNotSatisfiable, got %v", c.key, c.r, err) } } } -func TestLocalOpenInvalidRange(t *testing.T) { +func TestLocalRangeInvalidRange(t *testing.T) { st := newTestStorage(t) writeFile(t, st, "f", []byte("0123456789")) @@ -163,31 +163,31 @@ func TestLocalOpenInvalidRange(t *testing.T) { {Offset: 0, Length: 0}, {Offset: 0, Length: -2}, } { - if _, err := st.Open(context.Background(), "f", &r); !errors.Is(err, oss.ErrInvalidRange) { + if _, err := st.Range(context.Background(), "f", &r); !errors.Is(err, oss.ErrInvalidRange) { t.Fatalf("range=%+v: expected ErrInvalidRange, got %v", r, err) } } } -func TestLocalOpenCanceledBefore(t *testing.T) { +func TestLocalRangeCanceledBefore(t *testing.T) { st := newTestStorage(t) writeFile(t, st, "f", []byte("0123456789")) ctx, cancel := context.WithCancel(context.Background()) cancel() - if _, err := st.Open(ctx, "f", nil); err == nil { + if _, err := st.Range(ctx, "f", nil); err == nil { t.Fatal("expected context error") } } -func TestLocalOpenCanceledDuringRead(t *testing.T) { +func TestLocalRangeCanceledDuringRead(t *testing.T) { st := newTestStorage(t) writeFile(t, st, "f", []byte("0123456789")) ctx, cancel := context.WithCancel(context.Background()) - rc, err := st.Open(ctx, "f", nil) + rc, err := st.Range(ctx, "f", nil) if err != nil { - t.Fatalf("Open: %v", err) + t.Fatalf("Range: %v", err) } defer rc.Close() @@ -208,13 +208,13 @@ func TestLocalOpenCanceledDuringRead(t *testing.T) { } } -func TestLocalOpenClosedResource(t *testing.T) { +func TestLocalRangeClosedResource(t *testing.T) { st := newTestStorage(t) writeFile(t, st, "f", []byte("0123456789")) - rc, err := st.Open(context.Background(), "f", nil) + rc, err := st.Range(context.Background(), "f", nil) if err != nil { - t.Fatalf("Open: %v", err) + t.Fatalf("Range: %v", err) } if err := rc.Close(); err != nil { t.Fatalf("Close: %v", err) @@ -224,7 +224,7 @@ func TestLocalOpenClosedResource(t *testing.T) { } } -func TestLocalOpenLoadStillWorks(t *testing.T) { +func TestLocalRangeLoadStillWorks(t *testing.T) { st := newTestStorage(t) writeFile(t, st, "f", []byte("payload")) data, err := st.Load("f") diff --git a/oss/s3/s3.go b/oss/s3/s3.go index f860c68..978166a 100644 --- a/oss/s3/s3.go +++ b/oss/s3/s3.go @@ -148,7 +148,7 @@ func (s *S3Storage) Save(key string, data []byte) error { } func (s *S3Storage) Load(key string) ([]byte, error) { - reader, err := s.Open(context.Background(), key, nil) + reader, err := s.Range(context.Background(), key, nil) if err != nil { return nil, err } @@ -157,7 +157,7 @@ func (s *S3Storage) Load(key string) ([]byte, error) { return io.ReadAll(reader) } -func (s *S3Storage) Open(ctx context.Context, key string, byteRange *oss.ByteRange) (io.ReadCloser, error) { +func (s *S3Storage) Range(ctx context.Context, key string, byteRange *oss.ByteRange) (io.ReadCloser, error) { input := &s3.GetObjectInput{ Bucket: aws.String(s.bucket), Key: aws.String(key), diff --git a/oss/s3/s3_stream_test.go b/oss/s3/s3_stream_test.go index c12c662..7e1f1e5 100644 --- a/oss/s3/s3_stream_test.go +++ b/oss/s3/s3_stream_test.go @@ -89,13 +89,13 @@ func (h *objectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.Write(part) } -func TestS3OpenFull(t *testing.T) { +func TestS3RangeFull(t *testing.T) { var rangeHdr string st, _ := newTestStorage(t, &objectHandler{body: []byte("hello world"), rangeHdr: &rangeHdr}) - rc, err := st.Open(context.Background(), "key", nil) + rc, err := st.Range(context.Background(), "key", nil) if err != nil { - t.Fatalf("Open: %v", err) + t.Fatalf("Range: %v", err) } defer rc.Close() data, err := io.ReadAll(rc) @@ -110,13 +110,13 @@ func TestS3OpenFull(t *testing.T) { } } -func TestS3OpenBounded(t *testing.T) { +func TestS3RangeBounded(t *testing.T) { var rangeHdr string st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789"), rangeHdr: &rangeHdr}) - rc, err := st.Open(context.Background(), "key", &oss.ByteRange{Offset: 2, Length: 4}) + rc, err := st.Range(context.Background(), "key", &oss.ByteRange{Offset: 2, Length: 4}) if err != nil { - t.Fatalf("Open: %v", err) + t.Fatalf("Range: %v", err) } defer rc.Close() data, err := io.ReadAll(rc) @@ -131,13 +131,13 @@ func TestS3OpenBounded(t *testing.T) { } } -func TestS3OpenOpenEnded(t *testing.T) { +func TestS3RangeOpenEnded(t *testing.T) { var rangeHdr string st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789"), rangeHdr: &rangeHdr}) - rc, err := st.Open(context.Background(), "key", &oss.ByteRange{Offset: 4, Length: -1}) + rc, err := st.Range(context.Background(), "key", &oss.ByteRange{Offset: 4, Length: -1}) if err != nil { - t.Fatalf("Open: %v", err) + t.Fatalf("Range: %v", err) } defer rc.Close() data, err := io.ReadAll(rc) @@ -152,7 +152,7 @@ func TestS3OpenOpenEnded(t *testing.T) { } } -func TestS3OpenInvalidRangeNoRequest(t *testing.T) { +func TestS3RangeInvalidRangeNoRequest(t *testing.T) { var requests int32 st, _ := newTestStorage(t, &objectHandler{body: []byte("x"), requests: &requests}) @@ -161,7 +161,7 @@ func TestS3OpenInvalidRangeNoRequest(t *testing.T) { {Offset: 0, Length: 0}, {Offset: 0, Length: -2}, } { - if _, err := st.Open(context.Background(), "key", &r); !errors.Is(err, oss.ErrInvalidRange) { + if _, err := st.Range(context.Background(), "key", &r); !errors.Is(err, oss.ErrInvalidRange) { t.Fatalf("range=%+v: expected ErrInvalidRange, got %v", r, err) } } @@ -170,13 +170,13 @@ func TestS3OpenInvalidRangeNoRequest(t *testing.T) { } } -func TestS3OpenCanceledBeforeRequest(t *testing.T) { +func TestS3RangeCanceledBeforeRequest(t *testing.T) { var requests int32 st, _ := newTestStorage(t, &objectHandler{body: []byte("x"), requests: &requests}) ctx, cancel := context.WithCancel(context.Background()) cancel() - if _, err := st.Open(ctx, "key", nil); err == nil { + if _, err := st.Range(ctx, "key", nil); err == nil { t.Fatal("expected error") } if n := atomic.LoadInt32(&requests); n != 0 { @@ -184,7 +184,7 @@ func TestS3OpenCanceledBeforeRequest(t *testing.T) { } } -func TestS3OpenCanceledInflight(t *testing.T) { +func TestS3RangeCanceledInflight(t *testing.T) { entered := make(chan struct{}) release := make(chan struct{}) srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -207,7 +207,7 @@ func TestS3OpenCanceledInflight(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) done := make(chan error, 1) go func() { - _, err := st.Open(ctx, "key", nil) + _, err := st.Range(ctx, "key", nil) done <- err }() select { @@ -222,13 +222,13 @@ func TestS3OpenCanceledInflight(t *testing.T) { t.Fatalf("expected context.Canceled, got %v", err) } case <-time.After(5 * time.Second): - t.Fatal("Open did not return after cancel") + t.Fatal("Range did not return after cancel") } } -// TestS3OpenCanceledDuringBodyRead cancels the context after Open succeeded +// TestS3RangeCanceledDuringBodyRead cancels the context after Range succeeded // while a Read is blocked on an in-flight body. -func TestS3OpenCanceledDuringBodyRead(t *testing.T) { +func TestS3RangeCanceledDuringBodyRead(t *testing.T) { release := make(chan struct{}) srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Length", "10") @@ -252,9 +252,9 @@ func TestS3OpenCanceledDuringBodyRead(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() - rc, err := st.Open(ctx, "key", nil) + rc, err := st.Range(ctx, "key", nil) if err != nil { - t.Fatalf("Open: %v", err) + t.Fatalf("Range: %v", err) } defer rc.Close() @@ -275,24 +275,24 @@ func TestS3OpenCanceledDuringBodyRead(t *testing.T) { } } -func TestS3OpenMissing(t *testing.T) { +func TestS3RangeMissing(t *testing.T) { st, _ := newTestStorage(t, &objectHandler{statusCode: http.StatusNotFound, errCode: "NoSuchKey"}) - if _, err := st.Open(context.Background(), "missing", nil); err == nil { + if _, err := st.Range(context.Background(), "missing", nil); err == nil { t.Fatal("expected error") } } -func TestS3OpenRangeNotSatisfiable(t *testing.T) { +func TestS3RangeRangeNotSatisfiable(t *testing.T) { st, _ := newTestStorage(t, &objectHandler{statusCode: http.StatusRequestedRangeNotSatisfiable, errCode: "InvalidRange"}) - _, err := st.Open(context.Background(), "key", &oss.ByteRange{Offset: 100, Length: 1}) + _, err := st.Range(context.Background(), "key", &oss.ByteRange{Offset: 100, Length: 1}) if !errors.Is(err, oss.ErrRangeNotSatisfiable) { t.Fatalf("expected ErrRangeNotSatisfiable, got %v", err) } } -// TestS3OpenPlain416 verifies HTTP 416 maps to ErrRangeNotSatisfiable even +// TestS3RangePlain416 verifies HTTP 416 maps to ErrRangeNotSatisfiable even // when the error body carries no InvalidRange code. -func TestS3OpenPlain416(t *testing.T) { +func TestS3RangePlain416(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusRequestedRangeNotSatisfiable) w.Write([]byte("not xml")) @@ -306,21 +306,21 @@ func TestS3OpenPlain416(t *testing.T) { }) st := &S3Storage{bucket: "bkt", client: client} - _, err := st.Open(context.Background(), "key", &oss.ByteRange{Offset: 100, Length: 1}) + _, err := st.Range(context.Background(), "key", &oss.ByteRange{Offset: 100, Length: 1}) if !errors.Is(err, oss.ErrRangeNotSatisfiable) { t.Fatalf("expected ErrRangeNotSatisfiable, got %v", err) } } -// TestS3OpenOversizedEndClamped verifies a bounded range extending past EOF +// TestS3RangeOversizedEndClamped verifies a bounded range extending past EOF // is accepted when the server clamps the end to the last byte. -func TestS3OpenOversizedEndClamped(t *testing.T) { +func TestS3RangeOversizedEndClamped(t *testing.T) { var rangeHdr string st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789"), rangeHdr: &rangeHdr}) - rc, err := st.Open(context.Background(), "key", &oss.ByteRange{Offset: 8, Length: 100}) + rc, err := st.Range(context.Background(), "key", &oss.ByteRange{Offset: 8, Length: 100}) if err != nil { - t.Fatalf("Open: %v", err) + t.Fatalf("Range: %v", err) } defer rc.Close() data, err := io.ReadAll(rc) @@ -335,11 +335,11 @@ func TestS3OpenOversizedEndClamped(t *testing.T) { } } -func TestS3OpenEmptyObject(t *testing.T) { +func TestS3RangeEmptyObject(t *testing.T) { st, _ := newTestStorage(t, &objectHandler{body: nil}) - rc, err := st.Open(context.Background(), "key", nil) + rc, err := st.Range(context.Background(), "key", nil) if err != nil { - t.Fatalf("Open: %v", err) + t.Fatalf("Range: %v", err) } defer rc.Close() data, err := io.ReadAll(rc) @@ -351,9 +351,9 @@ func TestS3OpenEmptyObject(t *testing.T) { } } -// TestS3OpenRejectedRangeClosesBody ensures the response body is closed when +// TestS3RangeRejectedRangeClosesBody ensures the response body is closed when // a ranged response is rejected for missing Content-Range. -func TestS3OpenRejectedRangeClosesBody(t *testing.T) { +func TestS3RangeRejectedRangeClosesBody(t *testing.T) { var closed int32 rt := roundTripFunc(func(r *http.Request) (*http.Response, error) { return &http.Response{ @@ -375,7 +375,7 @@ func TestS3OpenRejectedRangeClosesBody(t *testing.T) { }) st := &S3Storage{bucket: "bkt", client: client} - _, err := st.Open(context.Background(), "key", &oss.ByteRange{Offset: 2, Length: 4}) + _, err := st.Range(context.Background(), "key", &oss.ByteRange{Offset: 2, Length: 4}) if err == nil { t.Fatal("expected rejection of range-ignoring response") } @@ -384,18 +384,18 @@ func TestS3OpenRejectedRangeClosesBody(t *testing.T) { } } -func TestS3OpenServerIgnoresRange(t *testing.T) { +func TestS3RangeServerIgnoresRange(t *testing.T) { st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789"), ignore: true}) - rc, err := st.Open(context.Background(), "key", &oss.ByteRange{Offset: 2, Length: 4}) + rc, err := st.Range(context.Background(), "key", &oss.ByteRange{Offset: 2, Length: 4}) if err == nil { rc.Close() t.Fatal("expected error when server ignores Range") } } -// TestS3OpenStreamsBeforeFullDownload proves Open returns after headers and +// TestS3RangeStreamsBeforeFullDownload proves Range returns after headers and // the first bytes are readable while the rest of the body is still in flight. -func TestS3OpenStreamsBeforeFullDownload(t *testing.T) { +func TestS3RangeStreamsBeforeFullDownload(t *testing.T) { release := make(chan struct{}) srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Range", "bytes 0-9/10") @@ -425,7 +425,7 @@ func TestS3OpenStreamsBeforeFullDownload(t *testing.T) { } opened := make(chan res, 1) go func() { - rc, err := st.Open(context.Background(), "key", &oss.ByteRange{Offset: 0, Length: -1}) + rc, err := st.Range(context.Background(), "key", &oss.ByteRange{Offset: 0, Length: -1}) opened <- res{rc, err} }() @@ -433,11 +433,11 @@ func TestS3OpenStreamsBeforeFullDownload(t *testing.T) { select { case r := <-opened: if r.err != nil { - t.Fatalf("Open: %v", r.err) + t.Fatalf("Range: %v", r.err) } rc = r.rc case <-time.After(5 * time.Second): - t.Fatal("Open blocked until full body downloaded") + t.Fatal("Range blocked until full body downloaded") } defer rc.Close() diff --git a/oss/stream.go b/oss/stream.go index 9fa0014..0e4d0ef 100644 --- a/oss/stream.go +++ b/oss/stream.go @@ -62,11 +62,11 @@ func (r ByteRange) HTTPRange() (string, error) { // cancelling ctx aborts the request and subsequent reads. type StreamingOSS interface { OSS - // Open returns a reader over the object stored at key. byteRange may be + // Range returns a reader over the object stored at key. byteRange may be // nil to request the whole object. An invalid range fails with // ErrInvalidRange before any I/O; a range outside the object fails with // ErrRangeNotSatisfiable. - Open(ctx context.Context, key string, byteRange *ByteRange) (io.ReadCloser, error) + Range(ctx context.Context, key string, byteRange *ByteRange) (io.ReadCloser, error) } // isNilOSS reports whether store is nil, including a nil pointer inside a @@ -84,7 +84,7 @@ func isNilOSS(store OSS) bool { } // SupportsStreaming reports whether store implements StreamingOSS, i.e. -// supports both full-object and ranged streaming reads via Open. A nil store +// supports both full-object and ranged streaming reads via Range. A nil store // reports false. func SupportsStreaming(store OSS) bool { if isNilOSS(store) { @@ -106,7 +106,7 @@ func OpenStream(ctx context.Context, store OSS, key string, byteRange *ByteRange if !ok { return nil, fmt.Errorf("%w: %T", ErrStreamingNotSupported, store) } - return streamer.Open(ctx, key, byteRange) + return streamer.Range(ctx, key, byteRange) } // contentRange is a strictly parsed HTTP Content-Range value diff --git a/oss/stream_test.go b/oss/stream_test.go index 04441fd..2b687d9 100644 --- a/oss/stream_test.go +++ b/oss/stream_test.go @@ -117,7 +117,7 @@ type fakeStreamingOSS struct { err error } -func (f *fakeStreamingOSS) Open(ctx context.Context, key string, byteRange *ByteRange) (io.ReadCloser, error) { +func (f *fakeStreamingOSS) Range(ctx context.Context, key string, byteRange *ByteRange) (io.ReadCloser, error) { f.opened = true f.gotCtx = ctx f.gotKey = key @@ -164,7 +164,7 @@ func TestOpenStreamDelegates(t *testing.T) { t.Fatal("expected the same reader back") } if !fake.opened || fake.gotKey != "key" || fake.gotRange != r || fake.gotCtx.Value(ctxKey{}) != "v" { - t.Fatalf("Open not called with same ctx/key/range: %+v", fake) + t.Fatalf("Range not called with same ctx/key/range: %+v", fake) } fakeErr := errors.New("boom") From 9c952635d3c7902b19bb15a0f5cdfb5e3a1dac9d Mon Sep 17 00:00:00 2001 From: "yunlu.wen" Date: Thu, 5 Nov 2026 22:30:48 +0800 Subject: [PATCH 05/13] feat(oss): add explicit preparation capability for Azure containers --- README.md | 32 ++++ oss/azureblob/blob.go | 23 ++- oss/azureblob/blob_prepare_test.go | 248 +++++++++++++++++++++++++++++ oss/prepare.go | 46 ++++++ oss/prepare_test.go | 65 ++++++++ tests/integration/azure_test.go | 52 ++++-- 6 files changed, 452 insertions(+), 14 deletions(-) create mode 100644 oss/azureblob/blob_prepare_test.go create mode 100644 oss/prepare.go create mode 100644 oss/prepare_test.go diff --git a/README.md b/README.md index 78a530a..6df32fb 100644 --- a/README.md +++ b/README.md @@ -206,6 +206,38 @@ Some parts of the code in this project originate from [dify-plugin-daemon](https | Tencent COS |[quicksand](https://github.com/quicksandznzn)|https://github.com/langgenius/dify-plugin-daemon/pull/97| | Volcengine TOS |[quicksand](https://github.com/quicksandznzn)|https://github.com/langgenius/dify-cloud-kit/pull/2| +## ๐Ÿ› ๏ธ Explicit Preparation + +Some backends can create their configured storage resource on demand via the +optional `oss.Preparer` capability interface: + +```go +type Preparer interface { + Prepare(ctx context.Context) error +} +``` + +`Prepare` is **idempotent** and is only ever invoked explicitly โ€” never by +constructors or read/write methods, so read-only clients can simply opt out. +Check support and call it at deployment/startup time: + +```go +if !oss.SupportsPrepare(store) { + // backend does not (yet) implement Preparer +} +err := oss.Prepare(ctx, store) +if errors.Is(err, oss.ErrPrepareNotSupported) { + // unsupported backend +} +``` + +Currently only **Azure Blob** implements `Preparer`: it creates the +configured container in the existing storage account (requires create +permission). `ContainerAlreadyExists` is treated as success; every other +error โ€” 403, other 409 codes, 5xx, network, cancellation โ€” is returned to the +caller. Other providers do not implement `Preparer` yet (the legacy S3 +constructor's ensure-bucket behavior is unchanged and unrelated). + ## ๐Ÿงฉ Integration Tests (Emulators) Hermetic integration tests run the streaming `OpenStream` API against local diff --git a/oss/azureblob/blob.go b/oss/azureblob/blob.go index f1f97cc..c0c42f7 100644 --- a/oss/azureblob/blob.go +++ b/oss/azureblob/blob.go @@ -12,10 +12,14 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/azcore" "github.com/Azure/azure-sdk-for-go/sdk/azidentity" "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob" + "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/bloberror" "github.com/langgenius/dify-cloud-kit/oss" ) -var _ oss.StreamingOSS = (*AzureBlobStorage)(nil) +var ( + _ oss.StreamingOSS = (*AzureBlobStorage)(nil) + _ oss.Preparer = (*AzureBlobStorage)(nil) +) type AzureBlobStorage struct { client *azblob.Client @@ -57,6 +61,23 @@ func NewAzureBlobStorage(args oss.OSSArgs) (oss.OSS, error) { }, nil } +// Prepare creates the configured container in the storage account if it does +// not exist. It is idempotent: ContainerAlreadyExists is a success, and every +// other error is returned to the caller. It is never called implicitly. +func (a *AzureBlobStorage) Prepare(ctx context.Context) error { + if err := ctx.Err(); err != nil { + return err + } + _, err := a.client.CreateContainer(ctx, a.containerName, nil) + if err == nil { + return nil + } + if bloberror.HasCode(err, bloberror.ContainerAlreadyExists) { + return nil + } + return fmt.Errorf("failed to prepare container %q: %w", a.containerName, err) +} + func (a *AzureBlobStorage) Save(key string, data []byte) error { _, err := a.client.UploadBuffer(context.TODO(), a.containerName, key, data, nil) return err diff --git a/oss/azureblob/blob_prepare_test.go b/oss/azureblob/blob_prepare_test.go new file mode 100644 index 0000000..907d13d --- /dev/null +++ b/oss/azureblob/blob_prepare_test.go @@ -0,0 +1,248 @@ +package azureblob + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob" + "github.com/langgenius/dify-cloud-kit/oss" +) + +// newPrepareStorage builds a client pointed at the httptest server with SDK +// retries disabled so error-status tests return promptly. +func newPrepareStorage(t *testing.T, handler http.Handler) *AzureBlobStorage { + t.Helper() + srv := httptest.NewServer(handler) + t.Cleanup(srv.Close) + client, err := azblob.NewClientWithNoCredential(srv.URL, &azblob.ClientOptions{ + ClientOptions: azcore.ClientOptions{ + Retry: policy.RetryOptions{MaxRetries: -1}, + }, + }) + if err != nil { + t.Fatalf("NewClientWithNoCredential: %v", err) + } + return &AzureBlobStorage{client: client, containerName: "cont"} +} + +// containerHandler emulates PUT /?restype=container. +type containerHandler struct { + statuses []int // statuses to serve in order; last one repeats + codes []string + requests *int32 + gotMethod *string + gotQuery *string + call int32 // incremented per request + failStatus int // if >0, always serve this status+errCode + errCode string +} + +func (h *containerHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + if h.requests != nil { + atomic.AddInt32(h.requests, 1) + } + if h.gotMethod != nil { + *h.gotMethod = r.Method + } + if h.gotQuery != nil { + *h.gotQuery = r.URL.RawQuery + } + status := h.failStatus + code := h.errCode + if len(h.statuses) > 0 { + i := int(atomic.AddInt32(&h.call, 1)) - 1 + if i >= len(h.statuses) { + i = len(h.statuses) - 1 + } + status = h.statuses[i] + if i < len(h.codes) { + code = h.codes[i] + } + } + if status >= 400 { + w.Header().Set("Content-Type", "application/xml") + w.WriteHeader(status) + fmt.Fprintf(w, `%serr`, code) + return + } + w.WriteHeader(status) +} + +func TestAzurePrepareCreatesContainer(t *testing.T) { + var requests int32 + var method, query string + st := newPrepareStorage(t, &containerHandler{ + statuses: []int{http.StatusCreated}, + requests: &requests, gotMethod: &method, gotQuery: &query, + }) + + if err := st.Prepare(context.Background()); err != nil { + t.Fatalf("Prepare: %v", err) + } + if method != http.MethodPut || !strings.Contains(query, "restype=container") { + t.Fatalf("unexpected request %s ?%s", method, query) + } + if n := atomic.LoadInt32(&requests); n != 1 { + t.Fatalf("expected 1 request, got %d", n) + } +} + +func TestAzurePrepareAlreadyExistsIdempotent(t *testing.T) { + st := newPrepareStorage(t, &containerHandler{ + statuses: []int{http.StatusCreated, http.StatusConflict}, + codes: []string{"", "ContainerAlreadyExists"}, + }) + if err := st.Prepare(context.Background()); err != nil { + t.Fatalf("first Prepare: %v", err) + } + if err := st.Prepare(context.Background()); err != nil { + t.Fatalf("second Prepare (ContainerAlreadyExists): %v", err) + } +} + +func TestAzurePrepareErrorPropagation(t *testing.T) { + for _, tc := range []struct { + name string + status int + code string + }{ + {"conflict being deleted", http.StatusConflict, "ContainerBeingDeleted"}, + {"forbidden", http.StatusForbidden, "AuthorizationFailure"}, + {"server error", http.StatusInternalServerError, "InternalError"}, + } { + t.Run(tc.name, func(t *testing.T) { + st := newPrepareStorage(t, &containerHandler{failStatus: tc.status, errCode: tc.code}) + err := st.Prepare(context.Background()) + if err == nil { + t.Fatal("expected error") + } + var respErr *azcore.ResponseError + if !errors.As(err, &respErr) { + t.Fatalf("expected *azcore.ResponseError, got %v", err) + } + if respErr.StatusCode != tc.status || respErr.ErrorCode != tc.code { + t.Fatalf("got %d/%s, want %d/%s", respErr.StatusCode, respErr.ErrorCode, tc.status, tc.code) + } + }) + } +} + +func TestAzurePrepareCanceledBeforeRequest(t *testing.T) { + var requests int32 + st := newPrepareStorage(t, &containerHandler{statuses: []int{http.StatusCreated}, requests: &requests}) + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if err := st.Prepare(ctx); err == nil { + t.Fatal("expected error") + } + if n := atomic.LoadInt32(&requests); n != 0 { + t.Fatalf("expected no requests, got %d", n) + } +} + +func TestAzurePrepareCanceledInflight(t *testing.T) { + entered := make(chan struct{}) + release := make(chan struct{}) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + close(entered) + select { + case <-r.Context().Done(): + case <-release: + } + })) + t.Cleanup(srv.Close) + t.Cleanup(func() { close(release) }) + client, err := azblob.NewClientWithNoCredential(srv.URL, &azblob.ClientOptions{ + ClientOptions: azcore.ClientOptions{Retry: policy.RetryOptions{MaxRetries: -1}}, + }) + if err != nil { + t.Fatalf("NewClientWithNoCredential: %v", err) + } + st := &AzureBlobStorage{client: client, containerName: "cont"} + + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan error, 1) + go func() { + done <- st.Prepare(ctx) + }() + select { + case <-entered: + case <-time.After(5 * time.Second): + t.Fatal("handler never received request") + } + cancel() + select { + case err := <-done: + if err == nil { + t.Fatal("expected error after cancel") + } + case <-time.After(5 * time.Second): + t.Fatal("Prepare did not return after cancel") + } +} + +func TestAzurePrepareConcurrentIdempotent(t *testing.T) { + var requests int32 + st := newPrepareStorage(t, &containerHandler{ + statuses: []int{http.StatusCreated, http.StatusConflict}, + codes: []string{"", "ContainerAlreadyExists"}, + requests: &requests, + }) + + var wg sync.WaitGroup + errs := make(chan error, 4) + for i := 0; i < 4; i++ { + wg.Add(1) + go func() { + defer wg.Done() + errs <- st.Prepare(context.Background()) + }() + } + wg.Wait() + close(errs) + for err := range errs { + if err != nil { + t.Fatalf("concurrent Prepare: %v", err) + } + } + if n := atomic.LoadInt32(&requests); n != 4 { + t.Fatalf("expected 4 requests, got %d", n) + } +} + +func TestFactoryDoesNotPrepare(t *testing.T) { + var requests int32 + srv := httptest.NewServer(&containerHandler{requests: &requests}) + t.Cleanup(srv.Close) + + connStr := "DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;" + + "AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;" + + "BlobEndpoint=" + srv.URL + "/devstoreaccount1;" + + store, err := NewAzureBlobStorage(oss.OSSArgs{ + AzureBlob: &oss.AzureBlob{ + ConnectionString: connStr, + ContainerName: "cont", + }, + }) + if err != nil { + t.Fatalf("NewAzureBlobStorage: %v", err) + } + if !oss.SupportsPrepare(store) { + t.Fatal("expected SupportsPrepare true") + } + if n := atomic.LoadInt32(&requests); n != 0 { + t.Fatalf("constructor made %d requests", n) + } +} diff --git a/oss/prepare.go b/oss/prepare.go new file mode 100644 index 0000000..52fa0b5 --- /dev/null +++ b/oss/prepare.go @@ -0,0 +1,46 @@ +package oss + +import ( + "context" + "errors" + "fmt" +) + +// ErrPrepareNotSupported is returned by Prepare when the given OSS +// implementation does not implement Preparer. +var ErrPrepareNotSupported = errors.New("storage preparation is not supported") + +// Preparer is an optional capability interface for providers that can +// perform idempotent, provider-specific resource preparation (for example, +// creating the configured container or bucket). It is an explicit, +// potentially resource-creating operation โ€” it is never invoked implicitly +// by constructors or other methods. +type Preparer interface { + // Prepare performs idempotent resource preparation. Calling it more + // than once must be safe. It returns an error when preparation fails. + Prepare(ctx context.Context) error +} + +// SupportsPrepare reports whether store implements Preparer. A nil store +// reports false. +func SupportsPrepare(store OSS) bool { + if isNilOSS(store) { + return false + } + _, ok := store.(Preparer) + return ok +} + +// Prepare delegates to store's Preparer implementation when present. A store +// without preparation support fails with ErrPrepareNotSupported; there is no +// silent no-op fallback. +func Prepare(ctx context.Context, store OSS) error { + if isNilOSS(store) { + return fmt.Errorf("%w: ", ErrPrepareNotSupported) + } + preparer, ok := store.(Preparer) + if !ok { + return fmt.Errorf("%w: %T", ErrPrepareNotSupported, store) + } + return preparer.Prepare(ctx) +} diff --git a/oss/prepare_test.go b/oss/prepare_test.go new file mode 100644 index 0000000..0223136 --- /dev/null +++ b/oss/prepare_test.go @@ -0,0 +1,65 @@ +package oss + +import ( + "context" + "errors" + "testing" +) + +// fakePreparer satisfies OSS via the embedded interface (any method call +// other than Prepare would panic on the nil embedded value). +type fakePreparer struct { + OSS + prepared bool + gotCtx context.Context + err error +} + +func (f *fakePreparer) Prepare(ctx context.Context) error { + f.prepared = true + f.gotCtx = ctx + return f.err +} + +func TestSupportsPrepare(t *testing.T) { + if !SupportsPrepare(&fakePreparer{}) { + t.Fatal("expected true for Preparer implementation") + } + if SupportsPrepare(&fakeOSS{}) { + t.Fatal("expected false for OSS-only implementation") + } + if SupportsPrepare(nil) { + t.Fatal("expected false for nil") + } + if SupportsPrepare((*fakePreparer)(nil)) { + t.Fatal("expected false for typed nil") + } +} + +func TestPrepareUnsupported(t *testing.T) { + for _, store := range []OSS{nil, &fakeOSS{}, (*fakePreparer)(nil)} { + err := Prepare(context.Background(), store) + if !errors.Is(err, ErrPrepareNotSupported) { + t.Fatalf("expected ErrPrepareNotSupported, got %v", err) + } + } +} + +func TestPrepareDelegates(t *testing.T) { + type ctxKey struct{} + ctx := context.WithValue(context.Background(), ctxKey{}, "v") + + fake := &fakePreparer{} + if err := Prepare(ctx, fake); err != nil { + t.Fatalf("Prepare: %v", err) + } + if !fake.prepared || fake.gotCtx.Value(ctxKey{}) != "v" { + t.Fatalf("Prepare not called with same ctx: %+v", fake) + } + + fakeErr := errors.New("boom") + fake2 := &fakePreparer{err: fakeErr} + if err := Prepare(ctx, fake2); !errors.Is(err, fakeErr) { + t.Fatalf("expected provider error, got %v", err) + } +} diff --git a/tests/integration/azure_test.go b/tests/integration/azure_test.go index 2d9acfe..b62934b 100644 --- a/tests/integration/azure_test.go +++ b/tests/integration/azure_test.go @@ -35,6 +35,21 @@ func TestAzureIntegrationStreaming(t *testing.T) { emptyKey := "empty.bin" containerCreated := false + // Build the store before the container exists: the constructor must not + // require or create it. + store, err := factory.Load("azure_blob", oss.OSSArgs{ + AzureBlob: &oss.AzureBlob{ + ConnectionString: azuriteConnStr, + ContainerName: container, + }, + }) + if err != nil { + t.Fatalf("factory.Load azure_blob: %v", err) + } + if !oss.SupportsPrepare(store) { + t.Fatal("azure_blob does not report preparation support") + } + client, err := azblob.NewClientFromConnectionString(azuriteConnStr, nil) if err != nil { t.Fatalf("NewClientFromConnectionString: %v", err) @@ -56,11 +71,32 @@ func TestAzureIntegrationStreaming(t *testing.T) { } }) - if _, err := client.CreateContainer(ctx, container, nil); err != nil { - t.Fatalf("CreateContainer: %v", err) + // Prepare is the production entry point for resource creation and must + // be idempotent. + if err := oss.Prepare(ctx, store); err != nil { + t.Fatalf("Prepare: %v", err) } containerCreated = true - t.Logf("created container %s on %s", container, azuriteEndpoint) + t.Logf("prepared container %s on %s", container, azuriteEndpoint) + + // A second call and concurrent calls must all succeed on the already + // existing container. + if err := oss.Prepare(ctx, store); err != nil { + t.Fatalf("second Prepare: %v", err) + } + prepareErrs := make(chan error, 4) + for i := 0; i < 4; i++ { + go func() { + c, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + prepareErrs <- oss.Prepare(c, store) + }() + } + for i := 0; i < 4; i++ { + if err := <-prepareErrs; err != nil { + t.Fatalf("concurrent Prepare: %v", err) + } + } fixture := writeFixture(t, objectSize) f, err := os.Open(fixture) @@ -75,16 +111,6 @@ func TestAzureIntegrationStreaming(t *testing.T) { t.Fatalf("UploadStream empty: %v", err) } - store, err := factory.Load("azure_blob", oss.OSSArgs{ - AzureBlob: &oss.AzureBlob{ - ConnectionString: azuriteConnStr, - ContainerName: container, - }, - }) - if err != nil { - t.Fatalf("factory.Load azure_blob: %v", err) - } - runStreamingChecks(t, store, objKey, emptyKey) } From 6f6a264230bb5c738c394191fdec3e47433f1674 Mon Sep 17 00:00:00 2001 From: "yunlu.wen" Date: Mon, 9 Nov 2026 16:32:10 +0800 Subject: [PATCH 06/13] feat(oss): complete streaming range support and interface-driven integration tests Add Range (streaming byte-range reads) to Google GCS, Tencent COS, Huawei OBS, and Volcengine TOS, closing the gap with the existing Local/S3/Aliyun/Azure implementations. 416 responses map to ErrRangeNotSatisfiable and ranged reads verify the server honored the Range header via Content-Range. Huawei OBS resolves open-ended and single-byte ranges with a HEAD first because its SDK cannot emit "bytes=N-" or "bytes=N-N". Add explicit, idempotent Prepare (bucket creation) to S3 and GCS alongside the existing Azure implementation, so provisioning also goes through the library interface. Rewrite the emulator integration tests to exercise only the library's own interface (factory.Load, Prepare, Save, Range/OpenStream, Load, Exists, State, Delete) instead of raw cloud SDK clients, and add a fake-gcs-server emulator to the compose stack. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- .github/workflows/integration.yml | 2 +- Makefile | 5 +- README.md | 50 ++++- compose.integration.yaml | 14 ++ oss/gcsblob/gcs.go | 84 +++++++- oss/gcsblob/gcs_prepare_test.go | 85 ++++++++ oss/gcsblob/gcs_stream_test.go | 248 +++++++++++++++++++++++ oss/huaweiobs/obs.go | 85 +++++++- oss/huaweiobs/obs_stream_test.go | 293 +++++++++++++++++++++++++++ oss/oss.go | 3 + oss/s3/s3.go | 35 ++++ oss/s3/s3_prepare_test.go | 115 +++++++++++ oss/tencentcos/cos.go | 40 +++- oss/tencentcos/cos_stream_test.go | 245 ++++++++++++++++++++++ oss/volcenginetos/tos.go | 42 +++- oss/volcenginetos/tos_stream_test.go | 246 ++++++++++++++++++++++ tests/integration/azure_test.go | 44 +--- tests/integration/common_test.go | 76 +++++++ tests/integration/gcs_test.go | 66 ++++++ tests/integration/s3_test.go | 94 +++------ 20 files changed, 1740 insertions(+), 132 deletions(-) create mode 100644 oss/gcsblob/gcs_prepare_test.go create mode 100644 oss/gcsblob/gcs_stream_test.go create mode 100644 oss/huaweiobs/obs_stream_test.go create mode 100644 oss/s3/s3_prepare_test.go create mode 100644 oss/tencentcos/cos_stream_test.go create mode 100644 oss/volcenginetos/tos_stream_test.go create mode 100644 tests/integration/gcs_test.go diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml index 81884fa..658b91f 100644 --- a/.github/workflows/integration.yml +++ b/.github/workflows/integration.yml @@ -17,7 +17,7 @@ jobs: integration: name: Storage Integration runs-on: ubuntu-24.04 - timeout-minutes: 15 + timeout-minutes: 20 steps: - uses: actions/checkout@v4 diff --git a/Makefile b/Makefile index 272f11d..9b0f551 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,8 @@ COMPOSE_INTEGRATION := docker compose -f compose.integration.yaml -# Start the ephemeral emulator stack (LocalStack S3 + Azurite Blob) and wait -# for healthchecks. Services are left running until `make integration-down`. +# Start the ephemeral emulator stack (LocalStack S3 + Azurite Blob + +# fake-gcs-server) and wait for healthchecks. Services are left running until +# `make integration-down`. integration-up: $(COMPOSE_INTEGRATION) up -d --wait --wait-timeout 120 diff --git a/README.md b/README.md index 6df32fb..deb49e0 100644 --- a/README.md +++ b/README.md @@ -110,7 +110,16 @@ Semantics: | AWS S3 | โœ… | `GetObjectInput.Range`, body streamed | | Aliyun OSS | โœ… | `NormalizedRange` + `RangeBehavior("standard")` | | Azure Blob | โœ… | `DownloadStreamOptions.Range`, `NewRetryReader` resumes interrupted reads | -| Others | โŒ | type assertion fails | +| Google GCS | โœ… | `NewRangeReader`, 416 mapped to `ErrRangeNotSatisfiable` | +| Tencent COS| โœ… | `ObjectGetOptions.Range`, body streamed | +| Huawei OBS | โœ… | `GetObjectInput.RangeStart/RangeEnd`; `Length == -1` resolves the size with a HEAD first (the SDK cannot emit `bytes=N-`) | +| Volcengine TOS| โœ… | `GetObjectV2Input.Range`, body streamed | + +Huawei OBS caveat: the SDK only emits `bytes=start-end` when `end > start`, +so a single-byte range (`Length == 1`) cannot be expressed. Such requests +still fail loudly (Content-Range verification) instead of returning wrong +data, and an unsatisfiable single-byte range still maps to +`ErrRangeNotSatisfiable` via a size check. ### Capability detection @@ -231,22 +240,37 @@ if errors.Is(err, oss.ErrPrepareNotSupported) { } ``` -Currently only **Azure Blob** implements `Preparer`: it creates the -configured container in the existing storage account (requires create -permission). `ContainerAlreadyExists` is treated as success; every other -error โ€” 403, other 409 codes, 5xx, network, cancellation โ€” is returned to the -caller. Other providers do not implement `Preparer` yet (the legacy S3 -constructor's ensure-bucket behavior is unchanged and unrelated). +`Preparer` is currently implemented by: + +- **Azure Blob** โ€” creates the configured container in the existing storage + account (requires create permission). `ContainerAlreadyExists` is treated + as success. +- **Google GCS** โ€” creates the configured bucket, requiring + `GoogleCloudStorage.Project`. A 409 Conflict (bucket already exists) is + treated as success. +- **AWS S3** โ€” creates the configured bucket when missing. `NotFound` / + `NoSuchBucket` on the bucket probe triggers creation; + `BucketAlreadyOwnedByYou` / `BucketAlreadyExists` are treated as success. + (The legacy constructor's ensure-bucket behavior is unchanged and + unrelated.) + +Every other error โ€” 403, other 409 codes, 5xx, network, cancellation โ€” is +returned to the caller. Remaining providers (Aliyun, Tencent COS, Huawei +OBS, Volcengine TOS) do not implement `Preparer` yet. ## ๐Ÿงฉ Integration Tests (Emulators) -Hermetic integration tests run the streaming `OpenStream` API against local -emulators โ€” **no real cloud credentials or accounts required**: +Hermetic integration tests exercise the **library's own interface** โ€” +`factory.Load`, `oss.Prepare`, `Save`, `Range`/`OpenStream`, `Load`, +`Exists`, `State`, `Delete` โ€” end to end against local emulators. No raw +cloud SDK clients are used in the tests and **no real cloud credentials or +accounts are required**: | Emulator | Image | Endpoint | |-----------|------------------------------------------------|-----------------------------| | LocalStack| `localstack/localstack:4.0.3` (S3 only) | `http://127.0.0.1:14566` | | Azurite | `mcr.microsoft.com/azure-storage/azurite:3.35.0` (blob) | `http://127.0.0.1:11000` | +| fake-gcs | `fsouza/fake-gcs-server:1.56.1` (memory) | `http://127.0.0.1:14443` | ### Make targets @@ -271,7 +295,13 @@ services are always torn down at the end. ### Scope -- Offline unit tests live under `./oss/...` and run with a plain `go test`. +- Offline unit tests live under `./oss/...` and run with a plain `go test` + (every provider that implements `Range` โ€” Local, S3, Aliyun, Azure, GCS, + Tencent COS, Huawei OBS, Volcengine TOS โ€” has mock-server coverage). +- Emulator-backed integration tests cover S3 (LocalStack), Azure Blob + (Azurite) and GCS (fake-gcs-server). Tencent COS, Huawei OBS and + Volcengine TOS have no official emulator, so they are covered by the + offline mock-server suite only. - `tests/oss/` is the legacy real-cloud suite (requires credentials) and is not part of the hermetic integration gate. - A true-cloud opt-in test (`oss/azureblob/blob_live_test.go`, requires diff --git a/compose.integration.yaml b/compose.integration.yaml index 895edef..933b28b 100644 --- a/compose.integration.yaml +++ b/compose.integration.yaml @@ -28,3 +28,17 @@ services: interval: 2s timeout: 5s retries: 30 + + fake-gcs: + image: fsouza/fake-gcs-server:1.56.1 + # -public-host must equal the host:port the SDK's XML API reads use, + # otherwise the emulator only answers the JSON API. + command: ["-scheme", "http", "-backend", "memory", "-public-host", "127.0.0.1:14443"] + ports: + - "127.0.0.1:14443:4443" + healthcheck: + # The JSON API answers /storage/v1/b as soon as the server is up. + test: ["CMD-SHELL", "wget -q -O /dev/null http://127.0.0.1:4443/storage/v1/b || exit 1"] + interval: 2s + timeout: 5s + retries: 30 diff --git a/oss/gcsblob/gcs.go b/oss/gcsblob/gcs.go index 0d8a531..4fcb9a7 100644 --- a/oss/gcsblob/gcs.go +++ b/oss/gcsblob/gcs.go @@ -4,18 +4,22 @@ import ( "context" "encoding/base64" "errors" + "fmt" "io" + "net/http" "strings" "cloud.google.com/go/storage" "github.com/langgenius/dify-cloud-kit/oss" + "google.golang.org/api/googleapi" "google.golang.org/api/iterator" "google.golang.org/api/option" ) type GoogleCloudStorage struct { - bucket string - client *storage.Client + bucket string + project string + client *storage.Client } func NewGoogleCloudStorage(args oss.OSSArgs) (oss.OSS, error) { @@ -47,11 +51,33 @@ func NewGoogleCloudStorage(args oss.OSSArgs) (oss.OSS, error) { } } return &GoogleCloudStorage{ - bucket: bucket, - client: client, + bucket: bucket, + project: args.GoogleCloudStorage.Project, + client: client, }, nil } +// Prepare creates the configured bucket if it does not exist. It is +// idempotent: a 409 Conflict (bucket already exists) is a success, and every +// other error is returned to the caller. It is never called implicitly. +func (g *GoogleCloudStorage) Prepare(ctx context.Context) error { + if err := ctx.Err(); err != nil { + return err + } + if g.project == "" { + return fmt.Errorf("gcs: cannot prepare bucket %q without a project ID (set GoogleCloudStorage.Project)", g.bucket) + } + err := g.client.Bucket(g.bucket).Create(ctx, g.project, nil) + if err == nil { + return nil + } + var apiErr *googleapi.Error + if errors.As(err, &apiErr) && apiErr.Code == http.StatusConflict { + return nil + } + return fmt.Errorf("failed to prepare bucket %q: %w", g.bucket, err) +} + func (g *GoogleCloudStorage) Save(key string, data []byte) error { ctx := context.Background() obj := g.client.Bucket(g.bucket).Object(key) @@ -64,17 +90,59 @@ func (g *GoogleCloudStorage) Save(key string, data []byte) error { } func (g *GoogleCloudStorage) Load(key string) ([]byte, error) { - rc, err := g.client.Bucket(g.bucket).Object(key).NewReader(context.Background()) + reader, err := g.Range(context.Background(), key, nil) if err != nil { return nil, err } - defer rc.Close() + defer reader.Close() - data, err := io.ReadAll(rc) + return io.ReadAll(reader) +} + +func (g *GoogleCloudStorage) Range(ctx context.Context, key string, byteRange *oss.ByteRange) (io.ReadCloser, error) { + if byteRange != nil { + if _, err := byteRange.HTTPRange(); err != nil { + return nil, err + } + } + if err := ctx.Err(); err != nil { + return nil, err + } + + obj := g.client.Bucket(g.bucket).Object(key) + + offset, length := int64(0), int64(-1) + if byteRange != nil { + offset, length = byteRange.Offset, byteRange.Length + } + + // NewRangeReader reads at most length bytes starting at offset; a + // negative length reads to the end of the object. Offsets beyond the + // end of the object fail with a 416 error. + rc, err := obj.NewRangeReader(ctx, offset, length) if err != nil { + var apiErr *googleapi.Error + if errors.As(err, &apiErr) && apiErr.Code == http.StatusRequestedRangeNotSatisfiable { + return nil, oss.ErrRangeNotSatisfiable + } return nil, err } - return data, nil + + if byteRange != nil { + // The GCS SDK enforces that a range starting at a non-zero offset + // returns 206; reconstruct the Content-Range from the reader + // attributes and verify it the same way as other providers so a + // server that ignores the range (e.g. decompressive transcoding) + // fails loudly instead of streaming the whole object. + contentRange := fmt.Sprintf("bytes %d-%d/%d", + rc.Attrs.StartOffset, rc.Attrs.StartOffset+rc.Remain()-1, rc.Attrs.Size) + if err := oss.VerifyContentRange(contentRange, byteRange); err != nil { + rc.Close() + return nil, err + } + } + + return rc, nil } func (g *GoogleCloudStorage) Exists(key string) (bool, error) { diff --git a/oss/gcsblob/gcs_prepare_test.go b/oss/gcsblob/gcs_prepare_test.go new file mode 100644 index 0000000..1e003cd --- /dev/null +++ b/oss/gcsblob/gcs_prepare_test.go @@ -0,0 +1,85 @@ +package gcsblob + +import ( + "context" + "errors" + "fmt" + "net/http" + "strings" + "sync/atomic" + "testing" +) + +// bucketHandler answers the JSON API bucket-create endpoint: the first POST +// creates the bucket, subsequent ones conflict. +type bucketHandler struct { + creates *int32 +} + +func (h *bucketHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodPost && strings.HasPrefix(r.URL.Path, "/storage/v1/b") { + if h.creates != nil { + atomic.AddInt32(h.creates, 1) + } + w.WriteHeader(http.StatusOK) + fmt.Fprint(w, `{"kind":"storage#bucket","name":"bkt"}`) + return + } + w.WriteHeader(http.StatusNotFound) +} + +func TestGCSPrepareCreatesBucket(t *testing.T) { + var creates int32 + handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodPost && strings.HasPrefix(r.URL.Path, "/storage/v1/b") { + if atomic.AddInt32(&creates, 1) == 1 { + w.WriteHeader(http.StatusOK) + fmt.Fprint(w, `{"kind":"storage#bucket","name":"bkt"}`) + return + } + w.WriteHeader(http.StatusConflict) + fmt.Fprint(w, `{"error":{"code":409,"message":"conflict"}}`) + return + } + w.WriteHeader(http.StatusNotFound) + }) + st, _ := newTestStorage(t, handler) + st.project = "test-project" + + if err := st.Prepare(context.Background()); err != nil { + t.Fatalf("Prepare: %v", err) + } + if err := st.Prepare(context.Background()); err != nil { + t.Fatalf("second Prepare (409): %v", err) + } + if creates != 2 { + t.Fatalf("expected 2 create calls, got %d", creates) + } +} + +func TestGCSPrepareRequiresProject(t *testing.T) { + var requests int32 + st, _ := newTestStorage(t, &bucketHandler{creates: &requests}) + + if err := st.Prepare(context.Background()); err == nil { + t.Fatal("expected error when project is empty") + } + if requests != 0 { + t.Fatalf("expected no request, got %d", requests) + } +} + +func TestGCSPrepareCanceled(t *testing.T) { + var requests int32 + st, _ := newTestStorage(t, &bucketHandler{creates: &requests}) + st.project = "test-project" + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if err := st.Prepare(ctx); !errors.Is(err, context.Canceled) { + t.Fatalf("expected context.Canceled, got %v", err) + } + if requests != 0 { + t.Fatalf("expected no request, got %d", requests) + } +} diff --git a/oss/gcsblob/gcs_stream_test.go b/oss/gcsblob/gcs_stream_test.go new file mode 100644 index 0000000..4f64a00 --- /dev/null +++ b/oss/gcsblob/gcs_stream_test.go @@ -0,0 +1,248 @@ +package gcsblob + +import ( + "context" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + + "cloud.google.com/go/storage" + "github.com/langgenius/dify-cloud-kit/oss" +) + +// newTestStorage points a GCS client at a mock server via the +// STORAGE_EMULATOR_HOST convention (the SDK routes both XML reads and JSON +// API calls there and disables authentication). +func newTestStorage(t *testing.T, handler http.Handler) (*GoogleCloudStorage, *httptest.Server) { + t.Helper() + srv := httptest.NewServer(handler) + t.Cleanup(srv.Close) + + t.Setenv("STORAGE_EMULATOR_HOST", srv.URL) + client, err := storage.NewClient(context.Background()) + if err != nil { + t.Fatalf("storage.NewClient: %v", err) + } + t.Cleanup(func() { client.Close() }) + return &GoogleCloudStorage{bucket: "bkt", client: client}, srv +} + +// objectHandler serves a fixed body, honoring Range the way GCS does, and +// records the received Range header and request count. +type objectHandler struct { + body []byte + rangeHdr *string + requests *int32 + ignore bool // respond 200 with full body regardless of Range + statusCode int // if >0, respond with this status + XML error instead +} + +func (h *objectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + if h.requests != nil { + atomic.AddInt32(h.requests, 1) + } + if h.statusCode > 0 { + w.WriteHeader(h.statusCode) + fmt.Fprint(w, `InvalidRangebad range`) + return + } + rangeHdr := r.Header.Get("Range") + if h.rangeHdr != nil { + *h.rangeHdr = rangeHdr + } + if rangeHdr == "" || h.ignore { + w.Header().Set("Content-Length", fmt.Sprint(len(h.body))) + w.WriteHeader(http.StatusOK) + w.Write(h.body) + return + } + // parse "bytes=start-end" / "bytes=start-" + var start, end int64 + spec := strings.TrimPrefix(rangeHdr, "bytes=") + if dash := strings.Index(spec, "-"); dash >= 0 { + fmt.Sscan(spec[:dash], &start) + if spec[dash+1:] == "" { + end = int64(len(h.body)) - 1 + } else { + fmt.Sscan(spec[dash+1:], &end) + } + } + if start >= int64(len(h.body)) { + w.WriteHeader(http.StatusRequestedRangeNotSatisfiable) + fmt.Fprint(w, `InvalidRangebad range`) + return + } + // clamp like a real GCS backend does for ranges extending past EOF + if end >= int64(len(h.body)) { + end = int64(len(h.body)) - 1 + } + part := h.body[start : end+1] + w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", start, end, len(h.body))) + w.Header().Set("Content-Length", fmt.Sprint(len(part))) + w.WriteHeader(http.StatusPartialContent) + w.Write(part) +} + +func TestGCSRangeFull(t *testing.T) { + var rangeHdr string + st, _ := newTestStorage(t, &objectHandler{body: []byte("hello world"), rangeHdr: &rangeHdr}) + + rc, err := st.Range(context.Background(), "key", nil) + if err != nil { + t.Fatalf("Range: %v", err) + } + defer rc.Close() + data, err := io.ReadAll(rc) + if err != nil { + t.Fatalf("ReadAll: %v", err) + } + if string(data) != "hello world" { + t.Fatalf("got %q", data) + } + if rangeHdr != "" { + t.Fatalf("unexpected Range header %q", rangeHdr) + } +} + +func TestGCSRangeBounded(t *testing.T) { + var rangeHdr string + st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789"), rangeHdr: &rangeHdr}) + + rc, err := st.Range(context.Background(), "key", &oss.ByteRange{Offset: 2, Length: 4}) + if err != nil { + t.Fatalf("Range: %v", err) + } + defer rc.Close() + data, err := io.ReadAll(rc) + if err != nil { + t.Fatalf("ReadAll: %v", err) + } + if string(data) != "2345" { + t.Fatalf("got %q", data) + } + if rangeHdr != "bytes=2-5" { + t.Fatalf("got Range header %q", rangeHdr) + } +} + +func TestGCSRangeOpenEnded(t *testing.T) { + var rangeHdr string + st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789"), rangeHdr: &rangeHdr}) + + rc, err := st.Range(context.Background(), "key", &oss.ByteRange{Offset: 4, Length: -1}) + if err != nil { + t.Fatalf("Range: %v", err) + } + defer rc.Close() + data, err := io.ReadAll(rc) + if err != nil { + t.Fatalf("ReadAll: %v", err) + } + if string(data) != "456789" { + t.Fatalf("got %q", data) + } + if rangeHdr != "bytes=4-" { + t.Fatalf("got Range header %q", rangeHdr) + } +} + +func TestGCSRangeOversizedEndClamped(t *testing.T) { + st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789")}) + + rc, err := st.Range(context.Background(), "key", &oss.ByteRange{Offset: 8, Length: 100}) + if err != nil { + t.Fatalf("Range: %v", err) + } + defer rc.Close() + data, err := io.ReadAll(rc) + if err != nil { + t.Fatalf("ReadAll: %v", err) + } + if string(data) != "89" { + t.Fatalf("got %q", data) + } +} + +func TestGCSRangeInvalidRangeNoRequest(t *testing.T) { + var requests int32 + st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789"), requests: &requests}) + + for _, r := range []oss.ByteRange{ + {Offset: -1, Length: 1}, + {Offset: 0, Length: 0}, + {Offset: 0, Length: -2}, + } { + if _, err := st.Range(context.Background(), "key", &r); !errors.Is(err, oss.ErrInvalidRange) { + t.Fatalf("range=%+v: expected ErrInvalidRange, got %v", r, err) + } + } + if requests != 0 { + t.Fatalf("expected no request, got %d", requests) + } +} + +func TestGCSRangeCanceledBeforeRequest(t *testing.T) { + var requests int32 + st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789"), requests: &requests}) + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if _, err := st.Range(ctx, "key", nil); !errors.Is(err, context.Canceled) { + t.Fatalf("expected context.Canceled, got %v", err) + } + if requests != 0 { + t.Fatalf("expected no request, got %d", requests) + } +} + +func TestGCSRangeRangeNotSatisfiable(t *testing.T) { + st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789")}) + + _, err := st.Range(context.Background(), "key", &oss.ByteRange{Offset: 100, Length: 1}) + if !errors.Is(err, oss.ErrRangeNotSatisfiable) { + t.Fatalf("expected ErrRangeNotSatisfiable, got %v", err) + } +} + +func TestGCSRangeEmptyObject(t *testing.T) { + st, _ := newTestStorage(t, &objectHandler{body: nil}) + + rc, err := st.Range(context.Background(), "key", nil) + if err != nil { + t.Fatalf("Range: %v", err) + } + defer rc.Close() + data, err := io.ReadAll(rc) + if err != nil { + t.Fatalf("ReadAll: %v", err) + } + if len(data) != 0 { + t.Fatalf("expected empty body, got %q", data) + } +} + +func TestGCSRangeServerIgnoresRange(t *testing.T) { + st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789"), ignore: true}) + + _, err := st.Range(context.Background(), "key", &oss.ByteRange{Offset: 2, Length: 4}) + if err == nil { + t.Fatal("expected error when server ignores the range") + } +} + +func TestGCSLoadStillWorks(t *testing.T) { + st, _ := newTestStorage(t, &objectHandler{body: []byte("hello world")}) + + data, err := st.Load("key") + if err != nil { + t.Fatalf("Load: %v", err) + } + if string(data) != "hello world" { + t.Fatalf("got %q", data) + } +} diff --git a/oss/huaweiobs/obs.go b/oss/huaweiobs/obs.go index c0de121..5b3b428 100644 --- a/oss/huaweiobs/obs.go +++ b/oss/huaweiobs/obs.go @@ -1,7 +1,10 @@ package huaweiobs import ( + "context" + "errors" "io" + "net/http" "os" "strings" "time" @@ -68,18 +71,92 @@ func (h *HuaweiOBSStorage) Save(key string, data []byte) error { } func (h *HuaweiOBSStorage) Load(key string) ([]byte, error) { - output, err := h.client.GetObject(&obs.GetObjectInput{ + reader, err := h.Range(context.Background(), key, nil) + if err != nil { + return nil, err + } + defer reader.Close() + + return io.ReadAll(reader) +} + +func (h *HuaweiOBSStorage) Range(ctx context.Context, key string, byteRange *oss.ByteRange) (io.ReadCloser, error) { + if byteRange != nil { + if _, err := byteRange.HTTPRange(); err != nil { + return nil, err + } + } + if err := ctx.Err(); err != nil { + return nil, err + } + + input := &obs.GetObjectInput{ GetObjectMetadataInput: obs.GetObjectMetadataInput{ Bucket: h.bucket, Key: key, }, - }) + } + if byteRange != nil { + input.RangeStart = byteRange.Offset + // The OBS SDK only emits "bytes=start-end" when end > start; it can + // neither express "bytes=start-" nor a single-byte range. Both cases + // resolve the object size first so an unsatisfiable range maps to + // ErrRangeNotSatisfiable instead of a silent full download. + if byteRange.Length == -1 || byteRange.Length == 1 { + size, err := h.objectSize(key) + if err != nil { + return nil, err + } + if byteRange.Offset >= size { + return nil, oss.ErrRangeNotSatisfiable + } + if byteRange.Length == -1 { + input.RangeEnd = size - 1 + } + // Length == 1 keeps RangeEnd == RangeStart, so the SDK sends no + // Range header; the GET below then fails Content-Range + // verification loudly instead of returning wrong data. + } else { + input.RangeEnd = byteRange.Offset + byteRange.Length - 1 + } + } + + output, err := h.client.GetObject(input) if err != nil { + var apiErr obs.ObsError + if errors.As(err, &apiErr) && apiErr.StatusCode == http.StatusRequestedRangeNotSatisfiable { + return nil, oss.ErrRangeNotSatisfiable + } return nil, err } - defer output.Body.Close() - return io.ReadAll(output.Body) + if byteRange != nil { + contentRange := "" + // The OBS SDK lower-cases response header keys. + if values := output.ResponseHeaders["content-range"]; len(values) > 0 { + contentRange = values[0] + } + if err := oss.VerifyContentRange(contentRange, byteRange); err != nil { + output.Body.Close() + return nil, err + } + } + + return output.Body, nil +} + +// objectSize resolves the object's content length via a HEAD request. +func (h *HuaweiOBSStorage) objectSize(key string) (int64, error) { + attrs, err := h.client.GetAttribute(&obs.GetAttributeInput{ + GetObjectMetadataInput: obs.GetObjectMetadataInput{ + Bucket: h.bucket, + Key: key, + }, + }) + if err != nil { + return 0, err + } + return attrs.ContentLength, nil } func (h *HuaweiOBSStorage) Exists(key string) (bool, error) { diff --git a/oss/huaweiobs/obs_stream_test.go b/oss/huaweiobs/obs_stream_test.go new file mode 100644 index 0000000..e2e7221 --- /dev/null +++ b/oss/huaweiobs/obs_stream_test.go @@ -0,0 +1,293 @@ +package huaweiobs + +import ( + "context" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + + "github.com/huaweicloud/huaweicloud-sdk-go-obs/obs" + "github.com/langgenius/dify-cloud-kit/oss" +) + +// newTestStorage points an OBS client at a mock server using path-style +// addressing (http://host/bucket/key). +func newTestStorage(t *testing.T, handler http.Handler) (*HuaweiOBSStorage, *httptest.Server) { + t.Helper() + srv := httptest.NewServer(handler) + t.Cleanup(srv.Close) + + client, err := obs.New("ak", "sk", srv.URL, obs.WithPathStyle(true)) + if err != nil { + t.Fatalf("obs.New: %v", err) + } + return &HuaweiOBSStorage{bucket: "bkt", client: client}, srv +} + +// objectHandler serves a fixed body, honoring Range the way OBS does, and +// records the received Range header and request count. HEAD requests answer +// with Content-Length like OBS's GetObjectMetadata. +type objectHandler struct { + body []byte + rangeHdr *string + requests *int32 + ignore bool + statusCode int +} + +func (h *objectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + if h.requests != nil { + atomic.AddInt32(h.requests, 1) + } + if r.Method == http.MethodHead { + w.Header().Set("Content-Length", fmt.Sprint(len(h.body))) + w.WriteHeader(http.StatusOK) + return + } + if h.statusCode > 0 { + w.WriteHeader(h.statusCode) + fmt.Fprintf(w, `%serr`, "InvalidRange") + return + } + rangeHdr := r.Header.Get("Range") + if h.rangeHdr != nil { + *h.rangeHdr = rangeHdr + } + if rangeHdr == "" || h.ignore { + w.Header().Set("Content-Length", fmt.Sprint(len(h.body))) + w.WriteHeader(http.StatusOK) + w.Write(h.body) + return + } + var start, end int64 + spec := strings.TrimPrefix(rangeHdr, "bytes=") + if dash := strings.Index(spec, "-"); dash >= 0 { + fmt.Sscan(spec[:dash], &start) + if spec[dash+1:] == "" { + end = int64(len(h.body)) - 1 + } else { + fmt.Sscan(spec[dash+1:], &end) + } + } + if start >= int64(len(h.body)) { + w.WriteHeader(http.StatusRequestedRangeNotSatisfiable) + fmt.Fprintf(w, `%sbad range`, "InvalidRange") + return + } + if end >= int64(len(h.body)) { + end = int64(len(h.body)) - 1 + } + part := h.body[start : end+1] + w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", start, end, len(h.body))) + w.Header().Set("Content-Length", fmt.Sprint(len(part))) + w.WriteHeader(http.StatusPartialContent) + w.Write(part) +} + +func TestOBSRangeFull(t *testing.T) { + var rangeHdr string + st, _ := newTestStorage(t, &objectHandler{body: []byte("hello world"), rangeHdr: &rangeHdr}) + + rc, err := st.Range(context.Background(), "key", nil) + if err != nil { + t.Fatalf("Range: %v", err) + } + defer rc.Close() + data, err := io.ReadAll(rc) + if err != nil { + t.Fatalf("ReadAll: %v", err) + } + if string(data) != "hello world" { + t.Fatalf("got %q", data) + } + if rangeHdr != "" { + t.Fatalf("unexpected Range header %q", rangeHdr) + } +} + +func TestOBSRangeBounded(t *testing.T) { + var rangeHdr string + st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789"), rangeHdr: &rangeHdr}) + + rc, err := st.Range(context.Background(), "key", &oss.ByteRange{Offset: 2, Length: 4}) + if err != nil { + t.Fatalf("Range: %v", err) + } + defer rc.Close() + data, err := io.ReadAll(rc) + if err != nil { + t.Fatalf("ReadAll: %v", err) + } + if string(data) != "2345" { + t.Fatalf("got %q", data) + } + if rangeHdr != "bytes=2-5" { + t.Fatalf("got Range header %q", rangeHdr) + } +} + +func TestOBSRangeOpenEnded(t *testing.T) { + var rangeHdr string + st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789"), rangeHdr: &rangeHdr}) + + rc, err := st.Range(context.Background(), "key", &oss.ByteRange{Offset: 4, Length: -1}) + if err != nil { + t.Fatalf("Range: %v", err) + } + defer rc.Close() + data, err := io.ReadAll(rc) + if err != nil { + t.Fatalf("ReadAll: %v", err) + } + if string(data) != "456789" { + t.Fatalf("got %q", data) + } + // OBS can only express bounded ranges; open-ended is resolved via a HEAD + // first, so the GET must carry the computed last byte. + if rangeHdr != "bytes=4-9" { + t.Fatalf("got Range header %q", rangeHdr) + } +} + +func TestOBSRangeOpenEndedUnsatisfiable(t *testing.T) { + var requests int32 + st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789"), requests: &requests}) + + // offset == size: detected locally after the HEAD, no GET is issued. + _, err := st.Range(context.Background(), "key", &oss.ByteRange{Offset: 10, Length: -1}) + if !errors.Is(err, oss.ErrRangeNotSatisfiable) { + t.Fatalf("expected ErrRangeNotSatisfiable, got %v", err) + } + if requests != 1 { + t.Fatalf("expected a single HEAD request, got %d", requests) + } +} + +func TestOBSRangeSingleByteUnsatisfiable(t *testing.T) { + var requests int32 + st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789"), requests: &requests}) + + // A single-byte range cannot be expressed by the SDK (it only sends + // "bytes=start-end" when end > start); the size check must still map + // offset >= size to ErrRangeNotSatisfiable. + _, err := st.Range(context.Background(), "key", &oss.ByteRange{Offset: 10, Length: 1}) + if !errors.Is(err, oss.ErrRangeNotSatisfiable) { + t.Fatalf("expected ErrRangeNotSatisfiable, got %v", err) + } + if requests != 1 { + t.Fatalf("expected a single HEAD request, got %d", requests) + } +} + +func TestOBSRangeSingleByteSatisfiableFailsLoudly(t *testing.T) { + st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789")}) + + // Satisfiable single-byte ranges are not expressible via the OBS SDK: + // the GET is issued without a Range header and the full object comes + // back, which fails Content-Range verification instead of returning + // wrong data. + if _, err := st.Range(context.Background(), "key", &oss.ByteRange{Offset: 2, Length: 1}); err == nil { + t.Fatal("expected an error for a single-byte range") + } +} + +func TestOBSRangeOversizedEndClamped(t *testing.T) { + st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789")}) + + rc, err := st.Range(context.Background(), "key", &oss.ByteRange{Offset: 8, Length: 100}) + if err != nil { + t.Fatalf("Range: %v", err) + } + defer rc.Close() + data, err := io.ReadAll(rc) + if err != nil { + t.Fatalf("ReadAll: %v", err) + } + if string(data) != "89" { + t.Fatalf("got %q", data) + } +} + +func TestOBSRangeInvalidRangeNoRequest(t *testing.T) { + var requests int32 + st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789"), requests: &requests}) + + for _, r := range []oss.ByteRange{ + {Offset: -1, Length: 1}, + {Offset: 0, Length: 0}, + {Offset: 0, Length: -2}, + } { + if _, err := st.Range(context.Background(), "key", &r); !errors.Is(err, oss.ErrInvalidRange) { + t.Fatalf("range=%+v: expected ErrInvalidRange, got %v", r, err) + } + } + if requests != 0 { + t.Fatalf("expected no request, got %d", requests) + } +} + +func TestOBSRangeCanceledBeforeRequest(t *testing.T) { + var requests int32 + st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789"), requests: &requests}) + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if _, err := st.Range(ctx, "key", nil); !errors.Is(err, context.Canceled) { + t.Fatalf("expected context.Canceled, got %v", err) + } + if requests != 0 { + t.Fatalf("expected no request, got %d", requests) + } +} + +func TestOBSRangeRangeNotSatisfiable(t *testing.T) { + st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789")}) + + _, err := st.Range(context.Background(), "key", &oss.ByteRange{Offset: 100, Length: 1}) + if !errors.Is(err, oss.ErrRangeNotSatisfiable) { + t.Fatalf("expected ErrRangeNotSatisfiable, got %v", err) + } +} + +func TestOBSRangeEmptyObject(t *testing.T) { + st, _ := newTestStorage(t, &objectHandler{body: nil}) + + rc, err := st.Range(context.Background(), "key", nil) + if err != nil { + t.Fatalf("Range: %v", err) + } + defer rc.Close() + data, err := io.ReadAll(rc) + if err != nil { + t.Fatalf("ReadAll: %v", err) + } + if len(data) != 0 { + t.Fatalf("expected empty body, got %q", data) + } +} + +func TestOBSRangeServerIgnoresRange(t *testing.T) { + st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789"), ignore: true}) + + _, err := st.Range(context.Background(), "key", &oss.ByteRange{Offset: 2, Length: 4}) + if err == nil { + t.Fatal("expected error when server ignores the range") + } +} + +func TestOBSLoadStillWorks(t *testing.T) { + st, _ := newTestStorage(t, &objectHandler{body: []byte("hello world")}) + + data, err := st.Load("key") + if err != nil { + t.Fatalf("Load: %v", err) + } + if string(data) != "hello world" { + t.Fatalf("got %q", data) + } +} diff --git a/oss/oss.go b/oss/oss.go index be6640d..20cec6a 100644 --- a/oss/oss.go +++ b/oss/oss.go @@ -153,6 +153,9 @@ func (t *TencentCOS) Validate() error { type GoogleCloudStorage struct { Bucket string CredentialsB64 string + // Project is required only for Prepare (bucket creation); reads and + // writes work without it. + Project string } func (g *GoogleCloudStorage) Validate() error { diff --git a/oss/s3/s3.go b/oss/s3/s3.go index 978166a..96474f4 100644 --- a/oss/s3/s3.go +++ b/oss/s3/s3.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "errors" + "fmt" "io" "net/http" "strings" @@ -276,6 +277,40 @@ func (s *S3Storage) Type() string { return oss.OSS_TYPE_S3 } +// Prepare creates the configured bucket if it does not exist. It is +// idempotent: an already-existing bucket is a success, and every other error +// is returned to the caller. It is never called implicitly. (The legacy +// constructor additionally ensures the bucket at load time; Prepare is the +// explicit capability for callers that want to control this.) +func (s *S3Storage) Prepare(ctx context.Context) error { + if err := ctx.Err(); err != nil { + return err + } + _, err := s.client.HeadBucket(ctx, &s3.HeadBucketInput{ + Bucket: aws.String(s.bucket), + }) + if err == nil { + return nil + } + var apiErr smithy.APIError + if !errors.As(err, &apiErr) || + (apiErr.ErrorCode() != "NotFound" && apiErr.ErrorCode() != "NoSuchBucket") { + return fmt.Errorf("failed to prepare bucket %q: %w", s.bucket, err) + } + _, err = s.client.CreateBucket(ctx, &s3.CreateBucketInput{ + Bucket: aws.String(s.bucket), + }) + if err == nil { + return nil + } + var createErr smithy.APIError + if errors.As(err, &createErr) && + (createErr.ErrorCode() == "BucketAlreadyOwnedByYou" || createErr.ErrorCode() == "BucketAlreadyExists") { + return nil + } + return fmt.Errorf("failed to prepare bucket %q: %w", s.bucket, err) +} + func ToPtr[T any](value T) *T { return &value } diff --git a/oss/s3/s3_prepare_test.go b/oss/s3/s3_prepare_test.go new file mode 100644 index 0000000..fedc637 --- /dev/null +++ b/oss/s3/s3_prepare_test.go @@ -0,0 +1,115 @@ +package s3 + +import ( + "context" + "errors" + "fmt" + "net/http" + "sync/atomic" + "testing" +) + +// bucketHandler simulates S3 bucket-level operations: HEAD /bucket returns +// 404 until the bucket is created, then 200; PUT /bucket creates it. +type bucketHandler struct { + heads *int32 + creates *int32 + headCode int // if >0, always respond HEAD with this status +} + +func (h *bucketHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodHead: + if h.heads != nil { + atomic.AddInt32(h.heads, 1) + } + if h.headCode > 0 { + w.WriteHeader(h.headCode) + return + } + w.WriteHeader(http.StatusOK) + case http.MethodPut: + if h.creates != nil { + atomic.AddInt32(h.creates, 1) + } + w.WriteHeader(http.StatusOK) + default: + w.WriteHeader(http.StatusBadRequest) + } +} + +func TestS3PrepareCreatesBucket(t *testing.T) { + var heads, creates int32 + handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodHead: + if atomic.AddInt32(&heads, 1) == 1 { + w.WriteHeader(http.StatusNotFound) + fmt.Fprint(w, `NotFoundnot found`) + return + } + w.WriteHeader(http.StatusOK) + case http.MethodPut: + atomic.AddInt32(&creates, 1) + w.WriteHeader(http.StatusOK) + default: + w.WriteHeader(http.StatusBadRequest) + } + }) + st, _ := newTestStorage(t, handler) + + if err := st.Prepare(context.Background()); err != nil { + t.Fatalf("Prepare: %v", err) + } + if err := st.Prepare(context.Background()); err != nil { + t.Fatalf("second Prepare: %v", err) + } + if heads != 2 || creates != 1 { + t.Fatalf("expected 2 HEADs and 1 create, got %d HEADs and %d creates", heads, creates) + } +} + +func TestS3PrepareCreateRaceTolerated(t *testing.T) { + var heads, creates int32 + handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodHead: + atomic.AddInt32(&heads, 1) + w.WriteHeader(http.StatusNotFound) + fmt.Fprint(w, `NotFoundnot found`) + case http.MethodPut: + atomic.AddInt32(&creates, 1) + w.WriteHeader(http.StatusConflict) + fmt.Fprint(w, `BucketAlreadyOwnedByYouexists`) + default: + w.WriteHeader(http.StatusBadRequest) + } + }) + st, _ := newTestStorage(t, handler) + + if err := st.Prepare(context.Background()); err != nil { + t.Fatalf("Prepare with BucketAlreadyOwnedByYou: %v", err) + } +} + +func TestS3PrepareHeadFails(t *testing.T) { + st, _ := newTestStorage(t, &bucketHandler{headCode: http.StatusForbidden}) + + if err := st.Prepare(context.Background()); err == nil { + t.Fatal("expected error when HEAD is forbidden") + } +} + +func TestS3PrepareCanceled(t *testing.T) { + var requests int32 + st, _ := newTestStorage(t, &bucketHandler{heads: &requests}) + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if err := st.Prepare(ctx); !errors.Is(err, context.Canceled) { + t.Fatalf("expected context.Canceled, got %v", err) + } + if requests != 0 { + t.Fatalf("expected no request, got %d", requests) + } +} diff --git a/oss/tencentcos/cos.go b/oss/tencentcos/cos.go index a261075..f30cd52 100644 --- a/oss/tencentcos/cos.go +++ b/oss/tencentcos/cos.go @@ -3,6 +3,7 @@ package tencentcos import ( "bytes" "context" + "errors" "io" "net/http" "net/url" @@ -68,12 +69,47 @@ func (s *TencentCOSStorage) Save(key string, data []byte) error { } func (s *TencentCOSStorage) Load(key string) ([]byte, error) { - resp, err := s.client.Object.Get(context.Background(), key, nil) + reader, err := s.Range(context.Background(), key, nil) if err != nil { return nil, err } + defer reader.Close() - return io.ReadAll(resp.Body) + return io.ReadAll(reader) +} + +func (s *TencentCOSStorage) Range(ctx context.Context, key string, byteRange *oss.ByteRange) (io.ReadCloser, error) { + opt := &cos.ObjectGetOptions{} + if byteRange != nil { + rangeHeader, err := byteRange.HTTPRange() + if err != nil { + return nil, err + } + opt.Range = rangeHeader + } + if err := ctx.Err(); err != nil { + return nil, err + } + + resp, err := s.client.Object.Get(ctx, key, opt) + if err != nil { + var apiErr *cos.ErrorResponse + if errors.As(err, &apiErr) && apiErr.Response != nil && + apiErr.Response.StatusCode == http.StatusRequestedRangeNotSatisfiable { + return nil, oss.ErrRangeNotSatisfiable + } + return nil, err + } + + if byteRange != nil { + contentRange := resp.Header.Get("Content-Range") + if err := oss.VerifyContentRange(contentRange, byteRange); err != nil { + resp.Body.Close() + return nil, err + } + } + + return resp.Body, nil } func (s *TencentCOSStorage) Exists(key string) (bool, error) { diff --git a/oss/tencentcos/cos_stream_test.go b/oss/tencentcos/cos_stream_test.go new file mode 100644 index 0000000..b0ccdb3 --- /dev/null +++ b/oss/tencentcos/cos_stream_test.go @@ -0,0 +1,245 @@ +package tencentcos + +import ( + "context" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync/atomic" + "testing" + + "github.com/langgenius/dify-cloud-kit/oss" + "github.com/tencentyun/cos-go-sdk-v5" +) + +// newTestStorage points a COS client at a mock server. The bucket lives in +// the endpoint host, so the object path is "/key". +func newTestStorage(t *testing.T, handler http.Handler) (*TencentCOSStorage, *httptest.Server) { + t.Helper() + srv := httptest.NewServer(handler) + t.Cleanup(srv.Close) + + u, err := url.Parse(srv.URL) + if err != nil { + t.Fatalf("url.Parse: %v", err) + } + client := cos.NewClient(&cos.BaseURL{BucketURL: u}, &http.Client{}) + return &TencentCOSStorage{bucket: "bkt", client: client}, srv +} + +// objectHandler serves a fixed body, honoring Range the way COS does, and +// records the received Range header and request count. +type objectHandler struct { + body []byte + rangeHdr *string + requests *int32 + ignore bool + statusCode int +} + +func (h *objectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + if h.requests != nil { + atomic.AddInt32(h.requests, 1) + } + if h.statusCode > 0 { + w.WriteHeader(h.statusCode) + fmt.Fprintf(w, `%serr`, "InvalidRange") + return + } + rangeHdr := r.Header.Get("Range") + if h.rangeHdr != nil { + *h.rangeHdr = rangeHdr + } + if rangeHdr == "" || h.ignore { + w.Header().Set("Content-Length", fmt.Sprint(len(h.body))) + w.WriteHeader(http.StatusOK) + w.Write(h.body) + return + } + var start, end int64 + spec := strings.TrimPrefix(rangeHdr, "bytes=") + if dash := strings.Index(spec, "-"); dash >= 0 { + fmt.Sscan(spec[:dash], &start) + if spec[dash+1:] == "" { + end = int64(len(h.body)) - 1 + } else { + fmt.Sscan(spec[dash+1:], &end) + } + } + if start >= int64(len(h.body)) { + w.WriteHeader(http.StatusRequestedRangeNotSatisfiable) + fmt.Fprintf(w, `%sbad range`, "InvalidRange") + return + } + if end >= int64(len(h.body)) { + end = int64(len(h.body)) - 1 + } + part := h.body[start : end+1] + w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", start, end, len(h.body))) + w.Header().Set("Content-Length", fmt.Sprint(len(part))) + w.WriteHeader(http.StatusPartialContent) + w.Write(part) +} + +func TestCOSRangeFull(t *testing.T) { + var rangeHdr string + st, _ := newTestStorage(t, &objectHandler{body: []byte("hello world"), rangeHdr: &rangeHdr}) + + rc, err := st.Range(context.Background(), "key", nil) + if err != nil { + t.Fatalf("Range: %v", err) + } + defer rc.Close() + data, err := io.ReadAll(rc) + if err != nil { + t.Fatalf("ReadAll: %v", err) + } + if string(data) != "hello world" { + t.Fatalf("got %q", data) + } + if rangeHdr != "" { + t.Fatalf("unexpected Range header %q", rangeHdr) + } +} + +func TestCOSRangeBounded(t *testing.T) { + var rangeHdr string + st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789"), rangeHdr: &rangeHdr}) + + rc, err := st.Range(context.Background(), "key", &oss.ByteRange{Offset: 2, Length: 4}) + if err != nil { + t.Fatalf("Range: %v", err) + } + defer rc.Close() + data, err := io.ReadAll(rc) + if err != nil { + t.Fatalf("ReadAll: %v", err) + } + if string(data) != "2345" { + t.Fatalf("got %q", data) + } + if rangeHdr != "bytes=2-5" { + t.Fatalf("got Range header %q", rangeHdr) + } +} + +func TestCOSRangeOpenEnded(t *testing.T) { + var rangeHdr string + st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789"), rangeHdr: &rangeHdr}) + + rc, err := st.Range(context.Background(), "key", &oss.ByteRange{Offset: 4, Length: -1}) + if err != nil { + t.Fatalf("Range: %v", err) + } + defer rc.Close() + data, err := io.ReadAll(rc) + if err != nil { + t.Fatalf("ReadAll: %v", err) + } + if string(data) != "456789" { + t.Fatalf("got %q", data) + } + if rangeHdr != "bytes=4-" { + t.Fatalf("got Range header %q", rangeHdr) + } +} + +func TestCOSRangeOversizedEndClamped(t *testing.T) { + st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789")}) + + rc, err := st.Range(context.Background(), "key", &oss.ByteRange{Offset: 8, Length: 100}) + if err != nil { + t.Fatalf("Range: %v", err) + } + defer rc.Close() + data, err := io.ReadAll(rc) + if err != nil { + t.Fatalf("ReadAll: %v", err) + } + if string(data) != "89" { + t.Fatalf("got %q", data) + } +} + +func TestCOSRangeInvalidRangeNoRequest(t *testing.T) { + var requests int32 + st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789"), requests: &requests}) + + for _, r := range []oss.ByteRange{ + {Offset: -1, Length: 1}, + {Offset: 0, Length: 0}, + {Offset: 0, Length: -2}, + } { + if _, err := st.Range(context.Background(), "key", &r); !errors.Is(err, oss.ErrInvalidRange) { + t.Fatalf("range=%+v: expected ErrInvalidRange, got %v", r, err) + } + } + if requests != 0 { + t.Fatalf("expected no request, got %d", requests) + } +} + +func TestCOSRangeCanceledBeforeRequest(t *testing.T) { + var requests int32 + st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789"), requests: &requests}) + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if _, err := st.Range(ctx, "key", nil); !errors.Is(err, context.Canceled) { + t.Fatalf("expected context.Canceled, got %v", err) + } + if requests != 0 { + t.Fatalf("expected no request, got %d", requests) + } +} + +func TestCOSRangeRangeNotSatisfiable(t *testing.T) { + st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789")}) + + _, err := st.Range(context.Background(), "key", &oss.ByteRange{Offset: 100, Length: 1}) + if !errors.Is(err, oss.ErrRangeNotSatisfiable) { + t.Fatalf("expected ErrRangeNotSatisfiable, got %v", err) + } +} + +func TestCOSRangeEmptyObject(t *testing.T) { + st, _ := newTestStorage(t, &objectHandler{body: nil}) + + rc, err := st.Range(context.Background(), "key", nil) + if err != nil { + t.Fatalf("Range: %v", err) + } + defer rc.Close() + data, err := io.ReadAll(rc) + if err != nil { + t.Fatalf("ReadAll: %v", err) + } + if len(data) != 0 { + t.Fatalf("expected empty body, got %q", data) + } +} + +func TestCOSRangeServerIgnoresRange(t *testing.T) { + st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789"), ignore: true}) + + _, err := st.Range(context.Background(), "key", &oss.ByteRange{Offset: 2, Length: 4}) + if err == nil { + t.Fatal("expected error when server ignores the range") + } +} + +func TestCOSLoadStillWorks(t *testing.T) { + st, _ := newTestStorage(t, &objectHandler{body: []byte("hello world")}) + + data, err := st.Load("key") + if err != nil { + t.Fatalf("Load: %v", err) + } + if string(data) != "hello world" { + t.Fatalf("got %q", data) + } +} diff --git a/oss/volcenginetos/tos.go b/oss/volcenginetos/tos.go index 3db4a4d..ddf1b39 100644 --- a/oss/volcenginetos/tos.go +++ b/oss/volcenginetos/tos.go @@ -3,9 +3,11 @@ package volcenginetos import ( "bytes" "context" + "errors" "github.com/langgenius/dify-cloud-kit/oss" "github.com/volcengine/ve-tos-golang-sdk/v2/tos" "io" + "net/http" "strings" ) @@ -55,14 +57,48 @@ func (s *VolcengineTOSStorage) Save(key string, data []byte) error { } func (s *VolcengineTOSStorage) Load(key string) ([]byte, error) { - resp, err := s.client.GetObjectV2(context.Background(), &tos.GetObjectV2Input{ + reader, err := s.Range(context.Background(), key, nil) + if err != nil { + return nil, err + } + defer reader.Close() + + return io.ReadAll(reader) +} + +func (s *VolcengineTOSStorage) Range(ctx context.Context, key string, byteRange *oss.ByteRange) (io.ReadCloser, error) { + input := &tos.GetObjectV2Input{ Bucket: s.bucket, Key: key, - }) + } + if byteRange != nil { + rangeHeader, err := byteRange.HTTPRange() + if err != nil { + return nil, err + } + input.Range = rangeHeader + } + if err := ctx.Err(); err != nil { + return nil, err + } + + resp, err := s.client.GetObjectV2(ctx, input) if err != nil { + var apiErr *tos.TosServerError + if errors.As(err, &apiErr) && apiErr.StatusCode == http.StatusRequestedRangeNotSatisfiable { + return nil, oss.ErrRangeNotSatisfiable + } return nil, err } - return io.ReadAll(resp.Content) + + if byteRange != nil { + if err := oss.VerifyContentRange(resp.ContentRange, byteRange); err != nil { + resp.Content.Close() + return nil, err + } + } + + return resp.Content, nil } func (s *VolcengineTOSStorage) Exists(key string) (bool, error) { diff --git a/oss/volcenginetos/tos_stream_test.go b/oss/volcenginetos/tos_stream_test.go new file mode 100644 index 0000000..6a2a260 --- /dev/null +++ b/oss/volcenginetos/tos_stream_test.go @@ -0,0 +1,246 @@ +package volcenginetos + +import ( + "context" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + + "github.com/langgenius/dify-cloud-kit/oss" + "github.com/volcengine/ve-tos-golang-sdk/v2/tos" +) + +// newTestStorage points a TOS client at a mock server. IP endpoints switch +// the SDK to path-style addressing (http://host/bucket/key). +func newTestStorage(t *testing.T, handler http.Handler) (*VolcengineTOSStorage, *httptest.Server) { + t.Helper() + srv := httptest.NewServer(handler) + t.Cleanup(srv.Close) + + client, err := tos.NewClientV2(srv.URL, + tos.WithRegion("cn-beijing"), + tos.WithCredentials(tos.NewStaticCredentials("ak", "sk")), + ) + if err != nil { + t.Fatalf("tos.NewClientV2: %v", err) + } + return &VolcengineTOSStorage{bucket: "bkt", client: client}, srv +} + +// objectHandler serves a fixed body, honoring Range the way TOS does, and +// records the received Range header and request count. +type objectHandler struct { + body []byte + rangeHdr *string + requests *int32 + ignore bool + statusCode int +} + +func (h *objectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + if h.requests != nil { + atomic.AddInt32(h.requests, 1) + } + if h.statusCode > 0 { + w.WriteHeader(h.statusCode) + fmt.Fprintf(w, `%serr`, "InvalidRange") + return + } + rangeHdr := r.Header.Get("Range") + if h.rangeHdr != nil { + *h.rangeHdr = rangeHdr + } + if rangeHdr == "" || h.ignore { + w.Header().Set("Content-Length", fmt.Sprint(len(h.body))) + w.WriteHeader(http.StatusOK) + w.Write(h.body) + return + } + var start, end int64 + spec := strings.TrimPrefix(rangeHdr, "bytes=") + if dash := strings.Index(spec, "-"); dash >= 0 { + fmt.Sscan(spec[:dash], &start) + if spec[dash+1:] == "" { + end = int64(len(h.body)) - 1 + } else { + fmt.Sscan(spec[dash+1:], &end) + } + } + if start >= int64(len(h.body)) { + w.WriteHeader(http.StatusRequestedRangeNotSatisfiable) + fmt.Fprintf(w, `%sbad range`, "InvalidRange") + return + } + if end >= int64(len(h.body)) { + end = int64(len(h.body)) - 1 + } + part := h.body[start : end+1] + w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", start, end, len(h.body))) + w.Header().Set("Content-Length", fmt.Sprint(len(part))) + w.WriteHeader(http.StatusPartialContent) + w.Write(part) +} + +func TestTOSRangeFull(t *testing.T) { + var rangeHdr string + st, _ := newTestStorage(t, &objectHandler{body: []byte("hello world"), rangeHdr: &rangeHdr}) + + rc, err := st.Range(context.Background(), "key", nil) + if err != nil { + t.Fatalf("Range: %v", err) + } + defer rc.Close() + data, err := io.ReadAll(rc) + if err != nil { + t.Fatalf("ReadAll: %v", err) + } + if string(data) != "hello world" { + t.Fatalf("got %q", data) + } + if rangeHdr != "" { + t.Fatalf("unexpected Range header %q", rangeHdr) + } +} + +func TestTOSRangeBounded(t *testing.T) { + var rangeHdr string + st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789"), rangeHdr: &rangeHdr}) + + rc, err := st.Range(context.Background(), "key", &oss.ByteRange{Offset: 2, Length: 4}) + if err != nil { + t.Fatalf("Range: %v", err) + } + defer rc.Close() + data, err := io.ReadAll(rc) + if err != nil { + t.Fatalf("ReadAll: %v", err) + } + if string(data) != "2345" { + t.Fatalf("got %q", data) + } + if rangeHdr != "bytes=2-5" { + t.Fatalf("got Range header %q", rangeHdr) + } +} + +func TestTOSRangeOpenEnded(t *testing.T) { + var rangeHdr string + st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789"), rangeHdr: &rangeHdr}) + + rc, err := st.Range(context.Background(), "key", &oss.ByteRange{Offset: 4, Length: -1}) + if err != nil { + t.Fatalf("Range: %v", err) + } + defer rc.Close() + data, err := io.ReadAll(rc) + if err != nil { + t.Fatalf("ReadAll: %v", err) + } + if string(data) != "456789" { + t.Fatalf("got %q", data) + } + if rangeHdr != "bytes=4-" { + t.Fatalf("got Range header %q", rangeHdr) + } +} + +func TestTOSRangeOversizedEndClamped(t *testing.T) { + st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789")}) + + rc, err := st.Range(context.Background(), "key", &oss.ByteRange{Offset: 8, Length: 100}) + if err != nil { + t.Fatalf("Range: %v", err) + } + defer rc.Close() + data, err := io.ReadAll(rc) + if err != nil { + t.Fatalf("ReadAll: %v", err) + } + if string(data) != "89" { + t.Fatalf("got %q", data) + } +} + +func TestTOSRangeInvalidRangeNoRequest(t *testing.T) { + var requests int32 + st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789"), requests: &requests}) + + for _, r := range []oss.ByteRange{ + {Offset: -1, Length: 1}, + {Offset: 0, Length: 0}, + {Offset: 0, Length: -2}, + } { + if _, err := st.Range(context.Background(), "key", &r); !errors.Is(err, oss.ErrInvalidRange) { + t.Fatalf("range=%+v: expected ErrInvalidRange, got %v", r, err) + } + } + if requests != 0 { + t.Fatalf("expected no request, got %d", requests) + } +} + +func TestTOSRangeCanceledBeforeRequest(t *testing.T) { + var requests int32 + st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789"), requests: &requests}) + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if _, err := st.Range(ctx, "key", nil); !errors.Is(err, context.Canceled) { + t.Fatalf("expected context.Canceled, got %v", err) + } + if requests != 0 { + t.Fatalf("expected no request, got %d", requests) + } +} + +func TestTOSRangeRangeNotSatisfiable(t *testing.T) { + st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789")}) + + _, err := st.Range(context.Background(), "key", &oss.ByteRange{Offset: 100, Length: 1}) + if !errors.Is(err, oss.ErrRangeNotSatisfiable) { + t.Fatalf("expected ErrRangeNotSatisfiable, got %v", err) + } +} + +func TestTOSRangeEmptyObject(t *testing.T) { + st, _ := newTestStorage(t, &objectHandler{body: nil}) + + rc, err := st.Range(context.Background(), "key", nil) + if err != nil { + t.Fatalf("Range: %v", err) + } + defer rc.Close() + data, err := io.ReadAll(rc) + if err != nil { + t.Fatalf("ReadAll: %v", err) + } + if len(data) != 0 { + t.Fatalf("expected empty body, got %q", data) + } +} + +func TestTOSRangeServerIgnoresRange(t *testing.T) { + st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789"), ignore: true}) + + _, err := st.Range(context.Background(), "key", &oss.ByteRange{Offset: 2, Length: 4}) + if err == nil { + t.Fatal("expected error when server ignores the range") + } +} + +func TestTOSLoadStillWorks(t *testing.T) { + st, _ := newTestStorage(t, &objectHandler{body: []byte("hello world")}) + + data, err := st.Load("key") + if err != nil { + t.Fatalf("Load: %v", err) + } + if string(data) != "hello world" { + t.Fatalf("got %q", data) + } +} diff --git a/tests/integration/azure_test.go b/tests/integration/azure_test.go index b62934b..186cef2 100644 --- a/tests/integration/azure_test.go +++ b/tests/integration/azure_test.go @@ -3,12 +3,9 @@ package integration import ( "context" "fmt" - "io" - "os" "testing" "time" - "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob" "github.com/google/uuid" "github.com/langgenius/dify-cloud-kit/oss" "github.com/langgenius/dify-cloud-kit/oss/factory" @@ -33,7 +30,6 @@ func TestAzureIntegrationStreaming(t *testing.T) { container := fmt.Sprintf("cloudkit-it-%s", uuid.NewString()) objKey := "fixture.bin" emptyKey := "empty.bin" - containerCreated := false // Build the store before the container exists: the constructor must not // require or create it. @@ -50,25 +46,12 @@ func TestAzureIntegrationStreaming(t *testing.T) { t.Fatal("azure_blob does not report preparation support") } - client, err := azblob.NewClientFromConnectionString(azuriteConnStr, nil) - if err != nil { - t.Fatalf("NewClientFromConnectionString: %v", err) - } - t.Cleanup(func() { - if !containerCreated { - return - } - c, cancel := context.WithTimeout(context.Background(), 60*time.Second) - defer cancel() for _, k := range []string{objKey, emptyKey} { - if _, err := client.DeleteBlob(c, container, k, nil); err != nil { - t.Logf("cleanup DeleteBlob %s: %v", k, err) + if err := store.Delete(k); err != nil { + t.Logf("cleanup Delete %s: %v", k, err) } } - if _, err := client.DeleteContainer(c, container, nil); err != nil { - t.Logf("cleanup DeleteContainer: %v", err) - } }) // Prepare is the production entry point for resource creation and must @@ -76,7 +59,6 @@ func TestAzureIntegrationStreaming(t *testing.T) { if err := oss.Prepare(ctx, store); err != nil { t.Fatalf("Prepare: %v", err) } - containerCreated = true t.Logf("prepared container %s on %s", container, azuriteEndpoint) // A second call and concurrent calls must all succeed on the already @@ -98,23 +80,15 @@ func TestAzureIntegrationStreaming(t *testing.T) { } } - fixture := writeFixture(t, objectSize) - f, err := os.Open(fixture) - if err != nil { - t.Fatalf("open fixture: %v", err) - } - defer f.Close() - if _, err := client.UploadStream(ctx, container, objKey, f, nil); err != nil { - t.Fatalf("UploadStream: %v", err) + // Upload the fixtures through the library's own Save, then exercise the + // streaming and plain-object interfaces end to end. + if err := store.Save(objKey, fixtureBytes(objectSize)); err != nil { + t.Fatalf("Save fixture: %v", err) } - if _, err := client.UploadStream(ctx, container, emptyKey, emptyReader{}, nil); err != nil { - t.Fatalf("UploadStream empty: %v", err) + if err := store.Save(emptyKey, nil); err != nil { + t.Fatalf("Save empty: %v", err) } runStreamingChecks(t, store, objKey, emptyKey) + runInterfaceChecks(t, store, objKey, emptyKey) } - -// emptyReader is a zero-length io.Reader. -type emptyReader struct{} - -func (emptyReader) Read([]byte) (int, error) { return 0, io.EOF } diff --git a/tests/integration/common_test.go b/tests/integration/common_test.go index d9c020b..839ab29 100644 --- a/tests/integration/common_test.go +++ b/tests/integration/common_test.go @@ -11,6 +11,82 @@ import ( "github.com/langgenius/dify-cloud-kit/oss" ) +// fixtureBytes returns the deterministic object as an in-memory slice. +func fixtureBytes(size int64) []byte { + data := make([]byte, size) + for i := int64(0); i < size; i++ { + data[i] = expectedByte(i) + } + return data +} + +// runInterfaceChecks drives the store's own plain-object API โ€” Save, +// Exists, State, Load, Delete โ€” against the emulator, complementing the +// streaming suite. It uses its own scratch key for the delete round-trip so +// the shared fixture keys stay intact for the test's cleanup. +func runInterfaceChecks(t *testing.T, store oss.OSS, objKey, emptyKey string) { + t.Helper() + + if ok, err := store.Exists(objKey); err != nil || !ok { + t.Fatalf("Exists(%q) = %v, %v; want true", objKey, ok, err) + } + st, err := store.State(objKey) + if err != nil { + t.Fatalf("State(%q): %v", objKey, err) + } + if st.Size != objectSize { + t.Fatalf("State(%q).Size = %d, want %d", objKey, st.Size, objectSize) + } + data, err := store.Load(objKey) + if err != nil { + t.Fatalf("Load(%q): %v", objKey, err) + } + if int64(len(data)) != objectSize { + t.Fatalf("Load(%q) returned %d bytes, want %d", objKey, len(data), objectSize) + } + for _, off := range []int64{0, 1, 4096, 1 << 20, objectSize - 1} { + if data[off] != expectedByte(off) { + t.Fatalf("Load(%q) mismatch at offset %d: got %d, want %d", objKey, off, data[off], expectedByte(off)) + } + } + + if ok, err := store.Exists(emptyKey); err != nil || !ok { + t.Fatalf("Exists(%q) = %v, %v; want true", emptyKey, ok, err) + } + st, err = store.State(emptyKey) + if err != nil { + t.Fatalf("State(%q): %v", emptyKey, err) + } + if st.Size != 0 { + t.Fatalf("State(%q).Size = %d, want 0", emptyKey, st.Size) + } + empty, err := store.Load(emptyKey) + if err != nil { + t.Fatalf("Load(%q): %v", emptyKey, err) + } + if len(empty) != 0 { + t.Fatalf("Load(%q) returned %d bytes, want 0", emptyKey, len(empty)) + } + + // Save/Delete round-trip on a dedicated key. + scratchKey := "scratch.bin" + if err := store.Save(scratchKey, []byte("scratch")); err != nil { + t.Fatalf("Save(%q): %v", scratchKey, err) + } + if ok, err := store.Exists(scratchKey); err != nil || !ok { + t.Fatalf("Exists(%q) = %v, %v; want true", scratchKey, ok, err) + } + if err := store.Delete(scratchKey); err != nil { + t.Fatalf("Delete(%q): %v", scratchKey, err) + } + if ok, err := store.Exists(scratchKey); err != nil || ok { + t.Fatalf("Exists(%q) after Delete = %v, %v; want false", scratchKey, ok, err) + } + if _, err := store.Load(scratchKey); err == nil { + t.Fatalf("Load(%q) after Delete: expected error", scratchKey) + } +} + // runStreamingChecks runs the shared streaming-range assertion suite against // a cloudkit store backed by an emulator. objKey must hold the deterministic // 16MiB fixture; emptyKey must exist as a zero-byte object. diff --git a/tests/integration/gcs_test.go b/tests/integration/gcs_test.go new file mode 100644 index 0000000..36525f9 --- /dev/null +++ b/tests/integration/gcs_test.go @@ -0,0 +1,66 @@ +package integration + +import ( + "context" + "fmt" + "testing" + "time" + + "github.com/google/uuid" + "github.com/langgenius/dify-cloud-kit/oss" + "github.com/langgenius/dify-cloud-kit/oss/factory" +) + +const gcsEmulatorEndpoint = "http://127.0.0.1:14443" + +func TestGCSIntegrationStreaming(t *testing.T) { + requireIntegration(t) + + // The GCS SDK routes every client created while STORAGE_EMULATOR_HOST + // is set to the emulator and disables authentication. + t.Setenv("STORAGE_EMULATOR_HOST", gcsEmulatorEndpoint) + + ctx, cancel := context.WithTimeout(context.Background(), 120*time.Second) + defer cancel() + + bucket := fmt.Sprintf("cloudkit-it-%s", uuid.NewString()) + objKey := "fixture.bin" + emptyKey := "empty.bin" + + store, err := factory.Load("gcs", oss.OSSArgs{ + GoogleCloudStorage: &oss.GoogleCloudStorage{ + Bucket: bucket, + Project: "test-project", + }, + }) + if err != nil { + t.Fatalf("factory.Load gcs: %v", err) + } + if !oss.SupportsPrepare(store) { + t.Fatal("gcs does not report preparation support") + } + if err := oss.Prepare(ctx, store); err != nil { + t.Fatalf("Prepare: %v", err) + } + t.Logf("prepared bucket %s on %s", bucket, gcsEmulatorEndpoint) + + t.Cleanup(func() { + for _, k := range []string{objKey, emptyKey} { + if err := store.Delete(k); err != nil { + t.Logf("cleanup Delete %s: %v", k, err) + } + } + }) + + // Upload the fixtures through the library's own Save, then exercise the + // streaming and plain-object interfaces end to end. + if err := store.Save(objKey, fixtureBytes(objectSize)); err != nil { + t.Fatalf("Save fixture: %v", err) + } + if err := store.Save(emptyKey, nil); err != nil { + t.Fatalf("Save empty: %v", err) + } + + runStreamingChecks(t, store, objKey, emptyKey) + runInterfaceChecks(t, store, objKey, emptyKey) +} diff --git a/tests/integration/s3_test.go b/tests/integration/s3_test.go index 9da0f2c..076f7ed 100644 --- a/tests/integration/s3_test.go +++ b/tests/integration/s3_test.go @@ -1,16 +1,11 @@ package integration import ( - "bytes" "context" "fmt" - "os" "testing" "time" - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/credentials" - "github.com/aws/aws-sdk-go-v2/service/s3" "github.com/google/uuid" "github.com/langgenius/dify-cloud-kit/oss" "github.com/langgenius/dify-cloud-kit/oss/factory" @@ -18,15 +13,6 @@ import ( const localstackEndpoint = "http://127.0.0.1:14566" -func newLocalstackS3Client() *s3.Client { - return s3.New(s3.Options{ - Region: "us-east-1", - Credentials: credentials.NewStaticCredentialsProvider("test", "test", ""), - BaseEndpoint: aws.String(localstackEndpoint), - UsePathStyle: true, - }) -} - func TestS3IntegrationStreaming(t *testing.T) { requireIntegration(t) @@ -36,60 +22,9 @@ func TestS3IntegrationStreaming(t *testing.T) { bucket := fmt.Sprintf("cloudkit-it-%s", uuid.NewString()) objKey := "fixture.bin" emptyKey := "empty.bin" - bucketCreated := false - client := newLocalstackS3Client() - - t.Cleanup(func() { - if !bucketCreated { - return - } - c, cancel := context.WithTimeout(context.Background(), 60*time.Second) - defer cancel() - for _, k := range []string{objKey, emptyKey} { - if _, err := client.DeleteObject(c, &s3.DeleteObjectInput{ - Bucket: aws.String(bucket), Key: aws.String(k), - }); err != nil { - t.Logf("cleanup DeleteObject %s: %v", k, err) - } - } - if _, err := client.DeleteBucket(c, &s3.DeleteBucketInput{ - Bucket: aws.String(bucket), - }); err != nil { - t.Logf("cleanup DeleteBucket: %v", err) - } - }) - - if _, err := client.CreateBucket(ctx, &s3.CreateBucketInput{ - Bucket: aws.String(bucket), - }); err != nil { - t.Fatalf("CreateBucket: %v", err) - } - bucketCreated = true - t.Logf("created bucket %s on %s", bucket, localstackEndpoint) - - fixture := writeFixture(t, objectSize) - f, err := os.Open(fixture) - if err != nil { - t.Fatalf("open fixture: %v", err) - } - defer f.Close() - if _, err := client.PutObject(ctx, &s3.PutObjectInput{ - Bucket: aws.String(bucket), - Key: aws.String(objKey), - Body: f, - ContentLength: aws.Int64(objectSize), - }); err != nil { - t.Fatalf("PutObject: %v", err) - } - if _, err := client.PutObject(ctx, &s3.PutObjectInput{ - Bucket: aws.String(bucket), - Key: aws.String(emptyKey), - Body: bytes.NewReader(nil), - ContentLength: aws.Int64(0), - }); err != nil { - t.Fatalf("PutObject empty: %v", err) - } + // The legacy constructor ensures the bucket at load time; Prepare then + // reports it idempotently through the explicit capability. store, err := factory.Load("s3", oss.OSSArgs{ S3: &oss.S3{ UseAws: false, @@ -105,6 +40,31 @@ func TestS3IntegrationStreaming(t *testing.T) { if err != nil { t.Fatalf("factory.Load s3: %v", err) } + if !oss.SupportsPrepare(store) { + t.Fatal("s3 does not report preparation support") + } + if err := oss.Prepare(ctx, store); err != nil { + t.Fatalf("Prepare: %v", err) + } + t.Logf("prepared bucket %s on %s", bucket, localstackEndpoint) + + t.Cleanup(func() { + for _, k := range []string{objKey, emptyKey} { + if err := store.Delete(k); err != nil { + t.Logf("cleanup Delete %s: %v", k, err) + } + } + }) + + // Upload the fixtures through the library's own Save, then exercise the + // streaming and plain-object interfaces end to end. + if err := store.Save(objKey, fixtureBytes(objectSize)); err != nil { + t.Fatalf("Save fixture: %v", err) + } + if err := store.Save(emptyKey, nil); err != nil { + t.Fatalf("Save empty: %v", err) + } runStreamingChecks(t, store, objKey, emptyKey) + runInterfaceChecks(t, store, objKey, emptyKey) } From 453e5128231db9f24b536492de28c2f5a9d3103e Mon Sep 17 00:00:00 2001 From: "yunlu.wen" Date: Mon, 9 Nov 2026 16:46:16 +0800 Subject: [PATCH 07/13] test(oss): cover single-byte and to-EOF unsatisfiable ranges in integration suite Extend the shared streaming checks with single-byte, last-byte, and open-ended unsatisfiable range cases, and verify Prepare idempotency in the S3/GCS emulator tests. GCS now maps an empty-object open-ended range to ErrRangeNotSatisfiable even when the server answers 200 with an empty body instead of 416 (fake-gcs-server behavior). Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- oss/gcsblob/gcs.go | 7 +++++++ oss/gcsblob/gcs_stream_test.go | 12 ++++++++++++ tests/integration/common_test.go | 33 ++++++++++++++++++++++++++++++++ tests/integration/gcs_test.go | 6 ++++++ tests/integration/s3_test.go | 6 ++++++ 5 files changed, 64 insertions(+) diff --git a/oss/gcsblob/gcs.go b/oss/gcsblob/gcs.go index 4fcb9a7..7c116f4 100644 --- a/oss/gcsblob/gcs.go +++ b/oss/gcsblob/gcs.go @@ -129,6 +129,13 @@ func (g *GoogleCloudStorage) Range(ctx context.Context, key string, byteRange *o } if byteRange != nil { + // An empty object cannot satisfy any range request. Most servers + // answer 416, but some (e.g. fake-gcs-server) return 200 with an + // empty body for open-ended ranges; reject it either way. + if rc.Attrs.Size == 0 { + rc.Close() + return nil, oss.ErrRangeNotSatisfiable + } // The GCS SDK enforces that a range starting at a non-zero offset // returns 206; reconstruct the Content-Range from the reader // attributes and verify it the same way as other providers so a diff --git a/oss/gcsblob/gcs_stream_test.go b/oss/gcsblob/gcs_stream_test.go index 4f64a00..32f8946 100644 --- a/oss/gcsblob/gcs_stream_test.go +++ b/oss/gcsblob/gcs_stream_test.go @@ -226,6 +226,18 @@ func TestGCSRangeEmptyObject(t *testing.T) { } } +func TestGCSRangeEmptyObjectToEOFSatisfiedAs416(t *testing.T) { + // Some emulators answer an open-ended range on an empty object with + // 200 + empty body instead of 416; the library must still report + // ErrRangeNotSatisfiable. + st, _ := newTestStorage(t, &objectHandler{body: nil, ignore: true}) + + _, err := st.Range(context.Background(), "key", &oss.ByteRange{Offset: 0, Length: -1}) + if !errors.Is(err, oss.ErrRangeNotSatisfiable) { + t.Fatalf("expected ErrRangeNotSatisfiable, got %v", err) + } +} + func TestGCSRangeServerIgnoresRange(t *testing.T) { st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789"), ignore: true}) diff --git a/tests/integration/common_test.go b/tests/integration/common_test.go index 839ab29..51261c5 100644 --- a/tests/integration/common_test.go +++ b/tests/integration/common_test.go @@ -135,6 +135,15 @@ func runStreamingChecks(t *testing.T, store oss.OSS, objKey, emptyKey string) { t.Run("clamped end", func(t *testing.T) { verify(t, objKey, &oss.ByteRange{Offset: objectSize - 8, Length: 100}, objectSize-8, 8) }) + t.Run("single byte", func(t *testing.T) { + verify(t, objKey, &oss.ByteRange{Offset: 2, Length: 1}, 2, 1) + }) + t.Run("last byte bounded", func(t *testing.T) { + verify(t, objKey, &oss.ByteRange{Offset: objectSize - 1, Length: 1}, objectSize-1, 1) + }) + t.Run("last byte to EOF", func(t *testing.T) { + verify(t, objKey, &oss.ByteRange{Offset: objectSize - 1, Length: -1}, objectSize-1, 1) + }) t.Run("empty object", func(t *testing.T) { verify(t, emptyKey, nil, 0, 0) }) t.Run("empty object ranged unsatisfiable", func(t *testing.T) { @@ -155,6 +164,30 @@ func runStreamingChecks(t *testing.T, store oss.OSS, objKey, emptyKey string) { } }) + t.Run("empty object to EOF unsatisfiable", func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + rc, err := oss.OpenStream(ctx, store, emptyKey, &oss.ByteRange{Offset: 0, Length: -1}) + if rc != nil { + rc.Close() + } + if !errors.Is(err, oss.ErrRangeNotSatisfiable) { + t.Fatalf("expected ErrRangeNotSatisfiable, got %v", err) + } + }) + + t.Run("offset equals size to EOF unsatisfiable", func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + rc, err := oss.OpenStream(ctx, store, objKey, &oss.ByteRange{Offset: objectSize, Length: -1}) + if rc != nil { + rc.Close() + } + if !errors.Is(err, oss.ErrRangeNotSatisfiable) { + t.Fatalf("expected ErrRangeNotSatisfiable, got %v", err) + } + }) + t.Run("missing key", func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) defer cancel() diff --git a/tests/integration/gcs_test.go b/tests/integration/gcs_test.go index 36525f9..63efaf5 100644 --- a/tests/integration/gcs_test.go +++ b/tests/integration/gcs_test.go @@ -44,6 +44,12 @@ func TestGCSIntegrationStreaming(t *testing.T) { } t.Logf("prepared bucket %s on %s", bucket, gcsEmulatorEndpoint) + t.Run("repeated Prepare", func(t *testing.T) { + if err := oss.Prepare(ctx, store); err != nil { + t.Fatalf("second Prepare: %v", err) + } + }) + t.Cleanup(func() { for _, k := range []string{objKey, emptyKey} { if err := store.Delete(k); err != nil { diff --git a/tests/integration/s3_test.go b/tests/integration/s3_test.go index 076f7ed..c854fa3 100644 --- a/tests/integration/s3_test.go +++ b/tests/integration/s3_test.go @@ -48,6 +48,12 @@ func TestS3IntegrationStreaming(t *testing.T) { } t.Logf("prepared bucket %s on %s", bucket, localstackEndpoint) + t.Run("repeated Prepare", func(t *testing.T) { + if err := oss.Prepare(ctx, store); err != nil { + t.Fatalf("second Prepare: %v", err) + } + }) + t.Cleanup(func() { for _, k := range []string{objKey, emptyKey} { if err := store.Delete(k); err != nil { From 38100b889a39c0224c49a88c6d1809a0fc90157f Mon Sep 17 00:00:00 2001 From: "yunlu.wen" Date: Mon, 9 Nov 2026 17:40:10 +0800 Subject: [PATCH 08/13] fix(oss): reject buckets owned by others in S3/GCS Prepare Prepare treated S3 BucketAlreadyExists and any GCS 409 as success, so a bucket name taken by another account/project reported ready and only failed later on the first write. On a create conflict, now re-check that the bucket is accessible and fail otherwise. GCS also checks access before creating, so repeated Prepare no longer hits the rate-limited create API. The check lists at most one object, which needs only storage.objects.list instead of storage.buckets.get. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- oss/gcsblob/gcs.go | 37 +++++++++- oss/gcsblob/gcs_prepare_test.go | 116 +++++++++++++++++++++++++++----- oss/s3/s3.go | 15 ++++- oss/s3/s3_prepare_test.go | 49 ++++++++++++++ 4 files changed, 195 insertions(+), 22 deletions(-) diff --git a/oss/gcsblob/gcs.go b/oss/gcsblob/gcs.go index 7c116f4..f951997 100644 --- a/oss/gcsblob/gcs.go +++ b/oss/gcsblob/gcs.go @@ -58,7 +58,8 @@ func NewGoogleCloudStorage(args oss.OSSArgs) (oss.OSS, error) { } // Prepare creates the configured bucket if it does not exist. It is -// idempotent: a 409 Conflict (bucket already exists) is a success, and every +// idempotent: an existing bucket that this client can access is a success, +// a 409 Conflict for a bucket owned by someone else is an error, and every // other error is returned to the caller. It is never called implicitly. func (g *GoogleCloudStorage) Prepare(ctx context.Context) error { if err := ctx.Err(); err != nil { @@ -67,17 +68,47 @@ func (g *GoogleCloudStorage) Prepare(ctx context.Context) error { if g.project == "" { return fmt.Errorf("gcs: cannot prepare bucket %q without a project ID (set GoogleCloudStorage.Project)", g.bucket) } - err := g.client.Bucket(g.bucket).Create(ctx, g.project, nil) + err := g.checkBucketAccess(ctx) + if err == nil { + return nil + } + if !isBucketNotFound(err) { + return fmt.Errorf("failed to prepare bucket %q: %w", g.bucket, err) + } + err = g.client.Bucket(g.bucket).Create(ctx, g.project, nil) if err == nil { return nil } var apiErr *googleapi.Error if errors.As(err, &apiErr) && apiErr.Code == http.StatusConflict { - return nil + if g.checkBucketAccess(ctx) == nil { + return nil + } + return fmt.Errorf("failed to prepare bucket %q: name is taken and the bucket is not accessible: %w", g.bucket, err) } return fmt.Errorf("failed to prepare bucket %q: %w", g.bucket, err) } +// checkBucketAccess lists at most one object, which needs only +// storage.objects.list rather than storage.buckets.get. +func (g *GoogleCloudStorage) checkBucketAccess(ctx context.Context) error { + it := g.client.Bucket(g.bucket).Objects(ctx, nil) + it.PageInfo().MaxSize = 1 + _, err := it.Next() + if errors.Is(err, iterator.Done) { + return nil + } + return err +} + +func isBucketNotFound(err error) bool { + if errors.Is(err, storage.ErrBucketNotExist) { + return true + } + var apiErr *googleapi.Error + return errors.As(err, &apiErr) && apiErr.Code == http.StatusNotFound +} + func (g *GoogleCloudStorage) Save(key string, data []byte) error { ctx := context.Background() obj := g.client.Bucket(g.bucket).Object(key) diff --git a/oss/gcsblob/gcs_prepare_test.go b/oss/gcsblob/gcs_prepare_test.go index 1e003cd..812139e 100644 --- a/oss/gcsblob/gcs_prepare_test.go +++ b/oss/gcsblob/gcs_prepare_test.go @@ -28,32 +28,116 @@ func (h *bucketHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNotFound) } -func TestGCSPrepareCreatesBucket(t *testing.T) { - var creates int32 - handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.Method == http.MethodPost && strings.HasPrefix(r.URL.Path, "/storage/v1/b") { - if atomic.AddInt32(&creates, 1) == 1 { - w.WriteHeader(http.StatusOK) - fmt.Fprint(w, `{"kind":"storage#bucket","name":"bkt"}`) - return - } - w.WriteHeader(http.StatusConflict) - fmt.Fprint(w, `{"error":{"code":409,"message":"conflict"}}`) +// prepareHandler serves the object-list access probe and bucket create. +// listOK reports whether the bucket is accessible; createCode is the status +// for bucket creation (200 marks the bucket accessible afterwards). +type prepareHandler struct { + listOK atomic.Bool + createCode int + lists int32 + creates int32 +} + +func (h *prepareHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + switch { + case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/o"): + atomic.AddInt32(&h.lists, 1) + if h.listOK.Load() { + fmt.Fprint(w, `{"kind":"storage#objects"}`) return } w.WriteHeader(http.StatusNotFound) - }) - st, _ := newTestStorage(t, handler) + fmt.Fprint(w, `{"error":{"code":404,"message":"The specified bucket does not exist."}}`) + case r.Method == http.MethodPost && strings.HasPrefix(r.URL.Path, "/storage/v1/b"): + atomic.AddInt32(&h.creates, 1) + if h.createCode == http.StatusOK { + h.listOK.Store(true) + fmt.Fprint(w, `{"kind":"storage#bucket","name":"bkt"}`) + return + } + w.WriteHeader(h.createCode) + fmt.Fprintf(w, `{"error":{"code":%d,"message":"The requested bucket name is not available."}}`, h.createCode) + default: + w.WriteHeader(http.StatusNotFound) + } +} + +func TestGCSPrepareCreatesBucket(t *testing.T) { + h := &prepareHandler{createCode: http.StatusOK} + st, _ := newTestStorage(t, h) st.project = "test-project" if err := st.Prepare(context.Background()); err != nil { t.Fatalf("Prepare: %v", err) } if err := st.Prepare(context.Background()); err != nil { - t.Fatalf("second Prepare (409): %v", err) + t.Fatalf("second Prepare: %v", err) + } + if h.creates != 1 { + t.Fatalf("expected 1 create call, got %d", h.creates) + } +} + +func TestGCSPrepareExistingBucketSkipsCreate(t *testing.T) { + h := &prepareHandler{createCode: http.StatusOK} + h.listOK.Store(true) + st, _ := newTestStorage(t, h) + st.project = "test-project" + + if err := st.Prepare(context.Background()); err != nil { + t.Fatalf("Prepare: %v", err) + } + if h.creates != 0 { + t.Fatalf("expected no create call, got %d", h.creates) + } +} + +func TestGCSPrepareConflictNotAccessibleFails(t *testing.T) { + h := &prepareHandler{createCode: http.StatusConflict} + st, _ := newTestStorage(t, h) + st.project = "test-project" + + if err := st.Prepare(context.Background()); err == nil { + t.Fatal("expected error when the bucket name is owned by another project") + } + if h.lists != 2 || h.creates != 1 { + t.Fatalf("expected 2 access checks and 1 create, got %d and %d", h.lists, h.creates) + } +} + +func TestGCSPrepareConflictAccessibleTolerated(t *testing.T) { + h := &prepareHandler{createCode: http.StatusConflict} + handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodPost { + h.listOK.Store(true) + } + h.ServeHTTP(w, r) + }) + st, _ := newTestStorage(t, handler) + st.project = "test-project" + + if err := st.Prepare(context.Background()); err != nil { + t.Fatalf("Prepare after concurrent create: %v", err) + } +} + +func TestGCSPrepareAccessCheckFails(t *testing.T) { + var creates int32 + handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodPost { + atomic.AddInt32(&creates, 1) + } + w.WriteHeader(http.StatusForbidden) + fmt.Fprint(w, `{"error":{"code":403,"message":"forbidden"}}`) + }) + st, _ := newTestStorage(t, handler) + st.project = "test-project" + + if err := st.Prepare(context.Background()); err == nil { + t.Fatal("expected error when the access check is forbidden") } - if creates != 2 { - t.Fatalf("expected 2 create calls, got %d", creates) + if creates != 0 { + t.Fatalf("expected no create call, got %d", creates) } } diff --git a/oss/s3/s3.go b/oss/s3/s3.go index 96474f4..bd7f3e9 100644 --- a/oss/s3/s3.go +++ b/oss/s3/s3.go @@ -304,9 +304,18 @@ func (s *S3Storage) Prepare(ctx context.Context) error { return nil } var createErr smithy.APIError - if errors.As(err, &createErr) && - (createErr.ErrorCode() == "BucketAlreadyOwnedByYou" || createErr.ErrorCode() == "BucketAlreadyExists") { - return nil + if errors.As(err, &createErr) { + switch createErr.ErrorCode() { + case "BucketAlreadyOwnedByYou": + return nil + case "BucketAlreadyExists": + if _, headErr := s.client.HeadBucket(ctx, &s3.HeadBucketInput{ + Bucket: aws.String(s.bucket), + }); headErr == nil { + return nil + } + return fmt.Errorf("failed to prepare bucket %q: name is taken and the bucket is not accessible: %w", s.bucket, err) + } } return fmt.Errorf("failed to prepare bucket %q: %w", s.bucket, err) } diff --git a/oss/s3/s3_prepare_test.go b/oss/s3/s3_prepare_test.go index fedc637..c1676b0 100644 --- a/oss/s3/s3_prepare_test.go +++ b/oss/s3/s3_prepare_test.go @@ -92,6 +92,55 @@ func TestS3PrepareCreateRaceTolerated(t *testing.T) { } } +func TestS3PrepareBucketOwnedByOtherFails(t *testing.T) { + var heads, creates int32 + handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodHead: + atomic.AddInt32(&heads, 1) + w.WriteHeader(http.StatusNotFound) + case http.MethodPut: + atomic.AddInt32(&creates, 1) + w.WriteHeader(http.StatusConflict) + fmt.Fprint(w, `BucketAlreadyExiststaken`) + default: + w.WriteHeader(http.StatusBadRequest) + } + }) + st, _ := newTestStorage(t, handler) + + if err := st.Prepare(context.Background()); err == nil { + t.Fatal("expected error when the bucket name is owned by another account") + } + if heads != 2 || creates != 1 { + t.Fatalf("expected 2 HEADs and 1 create, got %d HEADs and %d creates", heads, creates) + } +} + +func TestS3PrepareBucketAlreadyExistsAccessibleTolerated(t *testing.T) { + var heads int32 + handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodHead: + if atomic.AddInt32(&heads, 1) == 1 { + w.WriteHeader(http.StatusNotFound) + return + } + w.WriteHeader(http.StatusOK) + case http.MethodPut: + w.WriteHeader(http.StatusConflict) + fmt.Fprint(w, `BucketAlreadyExistsexists`) + default: + w.WriteHeader(http.StatusBadRequest) + } + }) + st, _ := newTestStorage(t, handler) + + if err := st.Prepare(context.Background()); err != nil { + t.Fatalf("Prepare with accessible BucketAlreadyExists: %v", err) + } +} + func TestS3PrepareHeadFails(t *testing.T) { st, _ := newTestStorage(t, &bucketHandler{headCode: http.StatusForbidden}) From dcec08037ed4c442a6bb7c6239a459cd6e037d8b Mon Sep 17 00:00:00 2001 From: "yunlu.wen" Date: Mon, 9 Nov 2026 18:05:26 +0800 Subject: [PATCH 09/13] fix(oss): honor OBS range/cancellation and S3 bucket region Huawei OBS: the SDK's RangeStart/RangeEnd cannot express "bytes=N-" or "bytes=N-N", so single-byte and last-byte-to-EOF reads (including any read of a one-byte object) failed Content-Range verification. Send the Range header verbatim instead, which also drops the extra HEAD request. The SDK takes no per-request context, so cancellation now abandons the in-flight GET and closes the body on ctx done, letting blocked reads return ctx.Err(). S3: bucket creation outside us-east-1 failed without a LocationConstraint. Set it from the region for AWS, in both Prepare and the legacy constructor; S3-compatible endpoints keep their default. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- README.md | 31 +++--- oss/huaweiobs/obs.go | 104 ++++++++++++------- oss/huaweiobs/obs_stream_test.go | 165 +++++++++++++++++++++++++------ oss/s3/s3.go | 29 ++++-- oss/s3/s3_prepare_test.go | 44 +++++++++ 5 files changed, 282 insertions(+), 91 deletions(-) diff --git a/README.md b/README.md index deb49e0..afd2e25 100644 --- a/README.md +++ b/README.md @@ -112,14 +112,13 @@ Semantics: | Azure Blob | โœ… | `DownloadStreamOptions.Range`, `NewRetryReader` resumes interrupted reads | | Google GCS | โœ… | `NewRangeReader`, 416 mapped to `ErrRangeNotSatisfiable` | | Tencent COS| โœ… | `ObjectGetOptions.Range`, body streamed | -| Huawei OBS | โœ… | `GetObjectInput.RangeStart/RangeEnd`; `Length == -1` resolves the size with a HEAD first (the SDK cannot emit `bytes=N-`) | +| Huawei OBS | โœ… | Range header sent verbatim via `WithCustomHeader` (the SDK's `RangeStart/RangeEnd` cannot express `bytes=N-` or `bytes=N-N`) | | Volcengine TOS| โœ… | `GetObjectV2Input.Range`, body streamed | -Huawei OBS caveat: the SDK only emits `bytes=start-end` when `end > start`, -so a single-byte range (`Length == 1`) cannot be expressed. Such requests -still fail loudly (Content-Range verification) instead of returning wrong -data, and an unsatisfiable single-byte range still maps to -`ErrRangeNotSatisfiable` via a size check. +Huawei OBS caveat: the SDK has no per-request context. Cancelling `ctx` +makes `Range` return `ctx.Err()` immediately and aborts an in-progress body +read, but a request still waiting for response headers is only torn down by +the SDK's own response-header timeout. ### Capability detection @@ -245,14 +244,18 @@ if errors.Is(err, oss.ErrPrepareNotSupported) { - **Azure Blob** โ€” creates the configured container in the existing storage account (requires create permission). `ContainerAlreadyExists` is treated as success. -- **Google GCS** โ€” creates the configured bucket, requiring - `GoogleCloudStorage.Project`. A 409 Conflict (bucket already exists) is - treated as success. -- **AWS S3** โ€” creates the configured bucket when missing. `NotFound` / - `NoSuchBucket` on the bucket probe triggers creation; - `BucketAlreadyOwnedByYou` / `BucketAlreadyExists` are treated as success. - (The legacy constructor's ensure-bucket behavior is unchanged and - unrelated.) +- **Google GCS** โ€” requires `GoogleCloudStorage.Project`. Probes access by + listing at most one object (needs only `storage.objects.list`) and creates + the bucket only when it does not exist. A 409 Conflict on create is a + success only if the bucket is then accessible; a name owned by another + project is an error. +- **AWS S3** โ€” `NotFound` / `NoSuchBucket` on the bucket probe triggers + creation, with `LocationConstraint` set from the region outside + `us-east-1` (AWS only; S3-compatible endpoints keep their default). + `BucketAlreadyOwnedByYou` is a success; `BucketAlreadyExists` is a success + only if the bucket is then accessible, otherwise the name belongs to + another account and an error is returned. (The legacy constructor still + ensures the bucket at load time.) Every other error โ€” 403, other 409 codes, 5xx, network, cancellation โ€” is returned to the caller. Remaining providers (Aliyun, Tencent COS, Huawei diff --git a/oss/huaweiobs/obs.go b/oss/huaweiobs/obs.go index a575d51..410ca90 100644 --- a/oss/huaweiobs/obs.go +++ b/oss/huaweiobs/obs.go @@ -79,9 +79,16 @@ func (h *HuaweiOBSStorage) Load(key string) ([]byte, error) { return io.ReadAll(reader) } +type getObjectResult struct { + output *obs.GetObjectOutput + err error +} + func (h *HuaweiOBSStorage) Range(ctx context.Context, key string, byteRange *oss.ByteRange) (io.ReadCloser, error) { + rangeHeader := "" if byteRange != nil { - if _, err := byteRange.HTTPRange(); err != nil { + var err error + if rangeHeader, err = byteRange.HTTPRange(); err != nil { return nil, err } } @@ -95,39 +102,43 @@ func (h *HuaweiOBSStorage) Range(ctx context.Context, key string, byteRange *oss Key: key, }, } - if byteRange != nil { - input.RangeStart = byteRange.Offset - // The OBS SDK only emits "bytes=start-end" when end > start; it can - // neither express "bytes=start-" nor a single-byte range. Both cases - // resolve the object size first so an unsatisfiable range maps to - // ErrRangeNotSatisfiable instead of a silent full download. - if byteRange.Length == -1 || byteRange.Length == 1 { - size, err := h.objectSize(key) - if err != nil { - return nil, err - } - if byteRange.Offset >= size { - return nil, oss.ErrRangeNotSatisfiable - } - if byteRange.Length == -1 { - input.RangeEnd = size - 1 - } - // Length == 1 keeps RangeEnd == RangeStart, so the SDK sends no - // Range header; the GET below then fails Content-Range - // verification loudly instead of returning wrong data. + + // The OBS SDK takes no per-request context, so the GET runs in the + // background and is abandoned on cancellation; a response that still + // arrives afterwards is closed. The SDK's RangeStart/RangeEnd cannot + // express "bytes=N-" or "bytes=N-N", so the Range header is sent + // verbatim instead (custom headers are applied before signing). + done := make(chan getObjectResult, 1) + go func() { + var res getObjectResult + if rangeHeader == "" { + res.output, res.err = h.client.GetObject(input) } else { - input.RangeEnd = byteRange.Offset + byteRange.Length - 1 + res.output, res.err = h.client.GetObject(input, obs.WithCustomHeader("Range", rangeHeader)) } + done <- res + }() + + var res getObjectResult + select { + case res = <-done: + case <-ctx.Done(): + go func() { + if late := <-done; late.output != nil { + late.output.Body.Close() + } + }() + return nil, ctx.Err() } - output, err := h.client.GetObject(input) - if err != nil { + if res.err != nil { var apiErr obs.ObsError - if errors.As(err, &apiErr) && apiErr.StatusCode == http.StatusRequestedRangeNotSatisfiable { + if errors.As(res.err, &apiErr) && apiErr.StatusCode == http.StatusRequestedRangeNotSatisfiable { return nil, oss.ErrRangeNotSatisfiable } - return nil, err + return nil, res.err } + output := res.output if byteRange != nil { contentRange := "" @@ -141,21 +152,38 @@ func (h *HuaweiOBSStorage) Range(ctx context.Context, key string, byteRange *oss } } - return output.Body, nil + return newCtxBody(ctx, output.Body), nil } -// objectSize resolves the object's content length via a HEAD request. -func (h *HuaweiOBSStorage) objectSize(key string) (int64, error) { - attrs, err := h.client.GetAttribute(&obs.GetAttributeInput{ - GetObjectMetadataInput: obs.GetObjectMetadataInput{ - Bucket: h.bucket, - Key: key, - }, - }) - if err != nil { - return 0, err +// ctxBody closes the response body when ctx is done so a blocked Read +// returns, and reports the context error instead of the close error. +type ctxBody struct { + ctx context.Context + body io.ReadCloser + stop func() bool +} + +func newCtxBody(ctx context.Context, body io.ReadCloser) *ctxBody { + return &ctxBody{ + ctx: ctx, + body: body, + stop: context.AfterFunc(ctx, func() { body.Close() }), } - return attrs.ContentLength, nil +} + +func (b *ctxBody) Read(p []byte) (int, error) { + n, err := b.body.Read(p) + if err != nil && err != io.EOF { + if ctxErr := b.ctx.Err(); ctxErr != nil { + return n, ctxErr + } + } + return n, err +} + +func (b *ctxBody) Close() error { + b.stop() + return b.body.Close() } func (h *HuaweiOBSStorage) Exists(key string) (bool, error) { diff --git a/oss/huaweiobs/obs_stream_test.go b/oss/huaweiobs/obs_stream_test.go index e2e7221..197f699 100644 --- a/oss/huaweiobs/obs_stream_test.go +++ b/oss/huaweiobs/obs_stream_test.go @@ -10,6 +10,7 @@ import ( "strings" "sync/atomic" "testing" + "time" "github.com/huaweicloud/huaweicloud-sdk-go-obs/obs" "github.com/langgenius/dify-cloud-kit/oss" @@ -147,52 +148,152 @@ func TestOBSRangeOpenEnded(t *testing.T) { if string(data) != "456789" { t.Fatalf("got %q", data) } - // OBS can only express bounded ranges; open-ended is resolved via a HEAD - // first, so the GET must carry the computed last byte. - if rangeHdr != "bytes=4-9" { + if rangeHdr != "bytes=4-" { t.Fatalf("got Range header %q", rangeHdr) } } -func TestOBSRangeOpenEndedUnsatisfiable(t *testing.T) { - var requests int32 - st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789"), requests: &requests}) - - // offset == size: detected locally after the HEAD, no GET is issued. - _, err := st.Range(context.Background(), "key", &oss.ByteRange{Offset: 10, Length: -1}) - if !errors.Is(err, oss.ErrRangeNotSatisfiable) { - t.Fatalf("expected ErrRangeNotSatisfiable, got %v", err) +func TestOBSRangeSingleByteForms(t *testing.T) { + for _, tc := range []struct { + name string + body string + r oss.ByteRange + want string + wantHdr string + }{ + {"single byte", "0123456789", oss.ByteRange{Offset: 2, Length: 1}, "2", "bytes=2-2"}, + {"last byte bounded", "0123456789", oss.ByteRange{Offset: 9, Length: 1}, "9", "bytes=9-9"}, + {"last byte to EOF", "0123456789", oss.ByteRange{Offset: 9, Length: -1}, "9", "bytes=9-"}, + {"one-byte object to EOF", "x", oss.ByteRange{Offset: 0, Length: -1}, "x", "bytes=0-"}, + } { + t.Run(tc.name, func(t *testing.T) { + var rangeHdr string + st, _ := newTestStorage(t, &objectHandler{body: []byte(tc.body), rangeHdr: &rangeHdr}) + + rc, err := st.Range(context.Background(), "key", &tc.r) + if err != nil { + t.Fatalf("Range: %v", err) + } + defer rc.Close() + data, err := io.ReadAll(rc) + if err != nil { + t.Fatalf("ReadAll: %v", err) + } + if string(data) != tc.want { + t.Fatalf("got %q, want %q", data, tc.want) + } + if rangeHdr != tc.wantHdr { + t.Fatalf("got Range header %q, want %q", rangeHdr, tc.wantHdr) + } + }) } - if requests != 1 { - t.Fatalf("expected a single HEAD request, got %d", requests) +} + +func TestOBSRangeUnsatisfiableSingleRequest(t *testing.T) { + for _, tc := range []struct { + name string + body []byte + r oss.ByteRange + }{ + {"offset equals size to EOF", []byte("0123456789"), oss.ByteRange{Offset: 10, Length: -1}}, + {"offset equals size single byte", []byte("0123456789"), oss.ByteRange{Offset: 10, Length: 1}}, + {"empty object to EOF", nil, oss.ByteRange{Offset: 0, Length: -1}}, + } { + t.Run(tc.name, func(t *testing.T) { + var requests int32 + st, _ := newTestStorage(t, &objectHandler{body: tc.body, requests: &requests}) + + _, err := st.Range(context.Background(), "key", &tc.r) + if !errors.Is(err, oss.ErrRangeNotSatisfiable) { + t.Fatalf("expected ErrRangeNotSatisfiable, got %v", err) + } + if requests != 1 { + t.Fatalf("expected a single GET request, got %d", requests) + } + }) } } -func TestOBSRangeSingleByteUnsatisfiable(t *testing.T) { - var requests int32 - st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789"), requests: &requests}) +// newBlockingStorage serves a handler that blocks until released or the +// client disconnects. With sendHeaders it first flushes a partial 200 +// response so the block happens during the body read; otherwise it blocks +// before sending headers. The handler is released before the server closes, +// because an abandoned OBS request is only torn down by the SDK's own +// response-header timeout. +func newBlockingStorage(t *testing.T, sendHeaders bool) (*HuaweiOBSStorage, chan struct{}) { + t.Helper() + entered := make(chan struct{}, 1) + release := make(chan struct{}) + st, _ := newTestStorage(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + select { + case entered <- struct{}{}: + default: + } + if sendHeaders { + w.Header().Set("Content-Length", "10") + w.WriteHeader(http.StatusOK) + w.Write([]byte("abc")) + w.(http.Flusher).Flush() + } + select { + case <-r.Context().Done(): + case <-release: + } + })) + t.Cleanup(func() { close(release) }) + return st, entered +} - // A single-byte range cannot be expressed by the SDK (it only sends - // "bytes=start-end" when end > start); the size check must still map - // offset >= size to ErrRangeNotSatisfiable. - _, err := st.Range(context.Background(), "key", &oss.ByteRange{Offset: 10, Length: 1}) - if !errors.Is(err, oss.ErrRangeNotSatisfiable) { - t.Fatalf("expected ErrRangeNotSatisfiable, got %v", err) +func TestOBSRangeCanceledInflight(t *testing.T) { + st, entered := newBlockingStorage(t, false) + + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan error, 1) + go func() { + _, err := st.Range(ctx, "key", nil) + done <- err + }() + select { + case <-entered: + case <-time.After(5 * time.Second): + t.Fatal("handler never received request") } - if requests != 1 { - t.Fatalf("expected a single HEAD request, got %d", requests) + cancel() + select { + case err := <-done: + if !errors.Is(err, context.Canceled) { + t.Fatalf("expected context.Canceled, got %v", err) + } + case <-time.After(5 * time.Second): + t.Fatal("Range did not return after cancel") } } -func TestOBSRangeSingleByteSatisfiableFailsLoudly(t *testing.T) { - st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789")}) +func TestOBSRangeCanceledDuringBodyRead(t *testing.T) { + st, _ := newBlockingStorage(t, true) - // Satisfiable single-byte ranges are not expressible via the OBS SDK: - // the GET is issued without a Range header and the full object comes - // back, which fails Content-Range verification instead of returning - // wrong data. - if _, err := st.Range(context.Background(), "key", &oss.ByteRange{Offset: 2, Length: 1}); err == nil { - t.Fatal("expected an error for a single-byte range") + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + rc, err := st.Range(ctx, "key", nil) + if err != nil { + t.Fatalf("Range: %v", err) + } + defer rc.Close() + + readDone := make(chan error, 1) + go func() { + _, err := io.ReadFull(rc, make([]byte, 10)) + readDone <- err + }() + time.Sleep(50 * time.Millisecond) + cancel() + select { + case err := <-readDone: + if !errors.Is(err, context.Canceled) { + t.Fatalf("expected context.Canceled, got %v", err) + } + case <-time.After(5 * time.Second): + t.Fatal("Read did not return after cancel") } } diff --git a/oss/s3/s3.go b/oss/s3/s3.go index bd7f3e9..73c5097 100644 --- a/oss/s3/s3.go +++ b/oss/s3/s3.go @@ -15,6 +15,7 @@ import ( "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/credentials" "github.com/aws/aws-sdk-go-v2/service/s3" + "github.com/aws/aws-sdk-go-v2/service/s3/types" "github.com/aws/smithy-go" "github.com/langgenius/dify-cloud-kit/oss" ) @@ -24,6 +25,19 @@ var _ oss.StreamingOSS = (*S3Storage)(nil) type S3Storage struct { bucket string client *s3.Client + // locationConstraint is the AWS region to create buckets in; empty for + // us-east-1 and for S3-compatible endpoints, which keep their default. + locationConstraint string +} + +func (s *S3Storage) createBucketInput() *s3.CreateBucketInput { + input := &s3.CreateBucketInput{Bucket: aws.String(s.bucket)} + if s.locationConstraint != "" { + input.CreateBucketConfiguration = &types.CreateBucketConfiguration{ + LocationConstraint: types.BucketLocationConstraint(s.locationConstraint), + } + } + return input } func NewS3Storage(args oss.OSSArgs) (oss.OSS, error) { @@ -110,6 +124,11 @@ func NewS3Storage(args oss.OSSArgs) (oss.OSS, error) { }) } + store := &S3Storage{bucket: bucket, client: client} + if useAws && region != "" && region != "us-east-1" { + store.locationConstraint = region + } + // check bucket _, err = client.HeadBucket(context.TODO(), &s3.HeadBucketInput{ Bucket: aws.String(bucket), @@ -117,15 +136,13 @@ func NewS3Storage(args oss.OSSArgs) (oss.OSS, error) { if err != nil { var apiErr smithy.APIError if errors.As(err, &apiErr) && apiErr.ErrorCode() == "NotFound" { - _, err = client.CreateBucket(context.TODO(), &s3.CreateBucketInput{ - Bucket: aws.String(bucket), - }) + _, err = client.CreateBucket(context.TODO(), store.createBucketInput()) if err != nil { return nil, oss.ErrProviderInit.WithError(err) } } } - return &S3Storage{bucket: bucket, client: client}, nil + return store, nil } func normalizeSignatureVersion(version string) string { @@ -297,9 +314,7 @@ func (s *S3Storage) Prepare(ctx context.Context) error { (apiErr.ErrorCode() != "NotFound" && apiErr.ErrorCode() != "NoSuchBucket") { return fmt.Errorf("failed to prepare bucket %q: %w", s.bucket, err) } - _, err = s.client.CreateBucket(ctx, &s3.CreateBucketInput{ - Bucket: aws.String(s.bucket), - }) + _, err = s.client.CreateBucket(ctx, s.createBucketInput()) if err == nil { return nil } diff --git a/oss/s3/s3_prepare_test.go b/oss/s3/s3_prepare_test.go index c1676b0..17d10c7 100644 --- a/oss/s3/s3_prepare_test.go +++ b/oss/s3/s3_prepare_test.go @@ -4,7 +4,9 @@ import ( "context" "errors" "fmt" + "io" "net/http" + "strings" "sync/atomic" "testing" ) @@ -141,6 +143,48 @@ func TestS3PrepareBucketAlreadyExistsAccessibleTolerated(t *testing.T) { } } +func TestS3PrepareLocationConstraint(t *testing.T) { + for _, tc := range []struct { + name string + constraint string + want string + }{ + {"non-default region", "eu-west-1", "eu-west-1"}, + {"default region", "", ""}, + } { + t.Run(tc.name, func(t *testing.T) { + var createBody string + handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodHead: + w.WriteHeader(http.StatusNotFound) + case http.MethodPut: + body, _ := io.ReadAll(r.Body) + createBody = string(body) + w.WriteHeader(http.StatusOK) + default: + w.WriteHeader(http.StatusBadRequest) + } + }) + st, _ := newTestStorage(t, handler) + st.locationConstraint = tc.constraint + + if err := st.Prepare(context.Background()); err != nil { + t.Fatalf("Prepare: %v", err) + } + if tc.want == "" { + if createBody != "" { + t.Fatalf("expected empty create body, got %q", createBody) + } + return + } + if !strings.Contains(createBody, tc.want) { + t.Fatalf("create body %q does not contain %q", createBody, tc.want) + } + }) + } +} + func TestS3PrepareHeadFails(t *testing.T) { st, _ := newTestStorage(t, &bucketHandler{headCode: http.StatusForbidden}) From 100d9719d56f90ae1afd668c903dfd0d2db07526 Mon Sep 17 00:00:00 2001 From: "yunlu.wen" Date: Mon, 9 Nov 2026 18:09:36 +0800 Subject: [PATCH 10/13] feat(oss)!: drop streaming range support for Huawei OBS The OBS SDK cannot express "bytes=N-" or single-byte ranges through its typed fields and takes no per-request context, so a cancelled request can only be abandoned, not aborted. Rather than ship a Range with these caveats, OBS no longer implements StreamingOSS: OpenStream fails with ErrStreamingNotSupported and callers use the buffered Load, which is restored to the main-branch implementation. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- README.md | 15 +- oss/huaweiobs/obs.go | 117 +-------- oss/huaweiobs/obs_stream_test.go | 394 ------------------------------- oss/huaweiobs/obs_test.go | 12 +- 4 files changed, 22 insertions(+), 516 deletions(-) delete mode 100644 oss/huaweiobs/obs_stream_test.go diff --git a/README.md b/README.md index afd2e25..4b41eff 100644 --- a/README.md +++ b/README.md @@ -112,14 +112,9 @@ Semantics: | Azure Blob | โœ… | `DownloadStreamOptions.Range`, `NewRetryReader` resumes interrupted reads | | Google GCS | โœ… | `NewRangeReader`, 416 mapped to `ErrRangeNotSatisfiable` | | Tencent COS| โœ… | `ObjectGetOptions.Range`, body streamed | -| Huawei OBS | โœ… | Range header sent verbatim via `WithCustomHeader` (the SDK's `RangeStart/RangeEnd` cannot express `bytes=N-` or `bytes=N-N`) | +| Huawei OBS | โŒ | Not supported: the SDK cannot express every range form and takes no per-request context; use `Load` | | Volcengine TOS| โœ… | `GetObjectV2Input.Range`, body streamed | -Huawei OBS caveat: the SDK has no per-request context. Cancelling `ctx` -makes `Range` return `ctx.Err()` immediately and aborts an in-progress body -read, but a request still waiting for response headers is only torn down by -the SDK's own response-header timeout. - ### Capability detection Callers can check support explicitly instead of relying on a raw type @@ -300,11 +295,11 @@ services are always torn down at the end. - Offline unit tests live under `./oss/...` and run with a plain `go test` (every provider that implements `Range` โ€” Local, S3, Aliyun, Azure, GCS, - Tencent COS, Huawei OBS, Volcengine TOS โ€” has mock-server coverage). + Tencent COS, Volcengine TOS โ€” has mock-server coverage). - Emulator-backed integration tests cover S3 (LocalStack), Azure Blob - (Azurite) and GCS (fake-gcs-server). Tencent COS, Huawei OBS and - Volcengine TOS have no official emulator, so they are covered by the - offline mock-server suite only. + (Azurite) and GCS (fake-gcs-server). Tencent COS and Volcengine TOS have + no official emulator, so they are covered by the offline mock-server + suite only. - `tests/oss/` is the legacy real-cloud suite (requires credentials) and is not part of the hermetic integration gate. - A true-cloud opt-in test (`oss/azureblob/blob_live_test.go`, requires diff --git a/oss/huaweiobs/obs.go b/oss/huaweiobs/obs.go index 410ca90..e3a3d26 100644 --- a/oss/huaweiobs/obs.go +++ b/oss/huaweiobs/obs.go @@ -1,11 +1,8 @@ package huaweiobs import ( - "context" - "errors" "io" "math/rand" - "net/http" "os" "strings" "time" @@ -70,120 +67,18 @@ func (h *HuaweiOBSStorage) Save(key string, data []byte) error { } func (h *HuaweiOBSStorage) Load(key string) ([]byte, error) { - reader, err := h.Range(context.Background(), key, nil) - if err != nil { - return nil, err - } - defer reader.Close() - - return io.ReadAll(reader) -} - -type getObjectResult struct { - output *obs.GetObjectOutput - err error -} - -func (h *HuaweiOBSStorage) Range(ctx context.Context, key string, byteRange *oss.ByteRange) (io.ReadCloser, error) { - rangeHeader := "" - if byteRange != nil { - var err error - if rangeHeader, err = byteRange.HTTPRange(); err != nil { - return nil, err - } - } - if err := ctx.Err(); err != nil { - return nil, err - } - - input := &obs.GetObjectInput{ + output, err := h.client.GetObject(&obs.GetObjectInput{ GetObjectMetadataInput: obs.GetObjectMetadataInput{ Bucket: h.bucket, Key: key, }, + }) + if err != nil { + return nil, err } + defer output.Body.Close() - // The OBS SDK takes no per-request context, so the GET runs in the - // background and is abandoned on cancellation; a response that still - // arrives afterwards is closed. The SDK's RangeStart/RangeEnd cannot - // express "bytes=N-" or "bytes=N-N", so the Range header is sent - // verbatim instead (custom headers are applied before signing). - done := make(chan getObjectResult, 1) - go func() { - var res getObjectResult - if rangeHeader == "" { - res.output, res.err = h.client.GetObject(input) - } else { - res.output, res.err = h.client.GetObject(input, obs.WithCustomHeader("Range", rangeHeader)) - } - done <- res - }() - - var res getObjectResult - select { - case res = <-done: - case <-ctx.Done(): - go func() { - if late := <-done; late.output != nil { - late.output.Body.Close() - } - }() - return nil, ctx.Err() - } - - if res.err != nil { - var apiErr obs.ObsError - if errors.As(res.err, &apiErr) && apiErr.StatusCode == http.StatusRequestedRangeNotSatisfiable { - return nil, oss.ErrRangeNotSatisfiable - } - return nil, res.err - } - output := res.output - - if byteRange != nil { - contentRange := "" - // The OBS SDK lower-cases response header keys. - if values := output.ResponseHeaders["content-range"]; len(values) > 0 { - contentRange = values[0] - } - if err := oss.VerifyContentRange(contentRange, byteRange); err != nil { - output.Body.Close() - return nil, err - } - } - - return newCtxBody(ctx, output.Body), nil -} - -// ctxBody closes the response body when ctx is done so a blocked Read -// returns, and reports the context error instead of the close error. -type ctxBody struct { - ctx context.Context - body io.ReadCloser - stop func() bool -} - -func newCtxBody(ctx context.Context, body io.ReadCloser) *ctxBody { - return &ctxBody{ - ctx: ctx, - body: body, - stop: context.AfterFunc(ctx, func() { body.Close() }), - } -} - -func (b *ctxBody) Read(p []byte) (int, error) { - n, err := b.body.Read(p) - if err != nil && err != io.EOF { - if ctxErr := b.ctx.Err(); ctxErr != nil { - return n, ctxErr - } - } - return n, err -} - -func (b *ctxBody) Close() error { - b.stop() - return b.body.Close() + return io.ReadAll(output.Body) } func (h *HuaweiOBSStorage) Exists(key string) (bool, error) { diff --git a/oss/huaweiobs/obs_stream_test.go b/oss/huaweiobs/obs_stream_test.go deleted file mode 100644 index 197f699..0000000 --- a/oss/huaweiobs/obs_stream_test.go +++ /dev/null @@ -1,394 +0,0 @@ -package huaweiobs - -import ( - "context" - "errors" - "fmt" - "io" - "net/http" - "net/http/httptest" - "strings" - "sync/atomic" - "testing" - "time" - - "github.com/huaweicloud/huaweicloud-sdk-go-obs/obs" - "github.com/langgenius/dify-cloud-kit/oss" -) - -// newTestStorage points an OBS client at a mock server using path-style -// addressing (http://host/bucket/key). -func newTestStorage(t *testing.T, handler http.Handler) (*HuaweiOBSStorage, *httptest.Server) { - t.Helper() - srv := httptest.NewServer(handler) - t.Cleanup(srv.Close) - - client, err := obs.New("ak", "sk", srv.URL, obs.WithPathStyle(true)) - if err != nil { - t.Fatalf("obs.New: %v", err) - } - return &HuaweiOBSStorage{bucket: "bkt", client: client}, srv -} - -// objectHandler serves a fixed body, honoring Range the way OBS does, and -// records the received Range header and request count. HEAD requests answer -// with Content-Length like OBS's GetObjectMetadata. -type objectHandler struct { - body []byte - rangeHdr *string - requests *int32 - ignore bool - statusCode int -} - -func (h *objectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { - if h.requests != nil { - atomic.AddInt32(h.requests, 1) - } - if r.Method == http.MethodHead { - w.Header().Set("Content-Length", fmt.Sprint(len(h.body))) - w.WriteHeader(http.StatusOK) - return - } - if h.statusCode > 0 { - w.WriteHeader(h.statusCode) - fmt.Fprintf(w, `%serr`, "InvalidRange") - return - } - rangeHdr := r.Header.Get("Range") - if h.rangeHdr != nil { - *h.rangeHdr = rangeHdr - } - if rangeHdr == "" || h.ignore { - w.Header().Set("Content-Length", fmt.Sprint(len(h.body))) - w.WriteHeader(http.StatusOK) - w.Write(h.body) - return - } - var start, end int64 - spec := strings.TrimPrefix(rangeHdr, "bytes=") - if dash := strings.Index(spec, "-"); dash >= 0 { - fmt.Sscan(spec[:dash], &start) - if spec[dash+1:] == "" { - end = int64(len(h.body)) - 1 - } else { - fmt.Sscan(spec[dash+1:], &end) - } - } - if start >= int64(len(h.body)) { - w.WriteHeader(http.StatusRequestedRangeNotSatisfiable) - fmt.Fprintf(w, `%sbad range`, "InvalidRange") - return - } - if end >= int64(len(h.body)) { - end = int64(len(h.body)) - 1 - } - part := h.body[start : end+1] - w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", start, end, len(h.body))) - w.Header().Set("Content-Length", fmt.Sprint(len(part))) - w.WriteHeader(http.StatusPartialContent) - w.Write(part) -} - -func TestOBSRangeFull(t *testing.T) { - var rangeHdr string - st, _ := newTestStorage(t, &objectHandler{body: []byte("hello world"), rangeHdr: &rangeHdr}) - - rc, err := st.Range(context.Background(), "key", nil) - if err != nil { - t.Fatalf("Range: %v", err) - } - defer rc.Close() - data, err := io.ReadAll(rc) - if err != nil { - t.Fatalf("ReadAll: %v", err) - } - if string(data) != "hello world" { - t.Fatalf("got %q", data) - } - if rangeHdr != "" { - t.Fatalf("unexpected Range header %q", rangeHdr) - } -} - -func TestOBSRangeBounded(t *testing.T) { - var rangeHdr string - st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789"), rangeHdr: &rangeHdr}) - - rc, err := st.Range(context.Background(), "key", &oss.ByteRange{Offset: 2, Length: 4}) - if err != nil { - t.Fatalf("Range: %v", err) - } - defer rc.Close() - data, err := io.ReadAll(rc) - if err != nil { - t.Fatalf("ReadAll: %v", err) - } - if string(data) != "2345" { - t.Fatalf("got %q", data) - } - if rangeHdr != "bytes=2-5" { - t.Fatalf("got Range header %q", rangeHdr) - } -} - -func TestOBSRangeOpenEnded(t *testing.T) { - var rangeHdr string - st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789"), rangeHdr: &rangeHdr}) - - rc, err := st.Range(context.Background(), "key", &oss.ByteRange{Offset: 4, Length: -1}) - if err != nil { - t.Fatalf("Range: %v", err) - } - defer rc.Close() - data, err := io.ReadAll(rc) - if err != nil { - t.Fatalf("ReadAll: %v", err) - } - if string(data) != "456789" { - t.Fatalf("got %q", data) - } - if rangeHdr != "bytes=4-" { - t.Fatalf("got Range header %q", rangeHdr) - } -} - -func TestOBSRangeSingleByteForms(t *testing.T) { - for _, tc := range []struct { - name string - body string - r oss.ByteRange - want string - wantHdr string - }{ - {"single byte", "0123456789", oss.ByteRange{Offset: 2, Length: 1}, "2", "bytes=2-2"}, - {"last byte bounded", "0123456789", oss.ByteRange{Offset: 9, Length: 1}, "9", "bytes=9-9"}, - {"last byte to EOF", "0123456789", oss.ByteRange{Offset: 9, Length: -1}, "9", "bytes=9-"}, - {"one-byte object to EOF", "x", oss.ByteRange{Offset: 0, Length: -1}, "x", "bytes=0-"}, - } { - t.Run(tc.name, func(t *testing.T) { - var rangeHdr string - st, _ := newTestStorage(t, &objectHandler{body: []byte(tc.body), rangeHdr: &rangeHdr}) - - rc, err := st.Range(context.Background(), "key", &tc.r) - if err != nil { - t.Fatalf("Range: %v", err) - } - defer rc.Close() - data, err := io.ReadAll(rc) - if err != nil { - t.Fatalf("ReadAll: %v", err) - } - if string(data) != tc.want { - t.Fatalf("got %q, want %q", data, tc.want) - } - if rangeHdr != tc.wantHdr { - t.Fatalf("got Range header %q, want %q", rangeHdr, tc.wantHdr) - } - }) - } -} - -func TestOBSRangeUnsatisfiableSingleRequest(t *testing.T) { - for _, tc := range []struct { - name string - body []byte - r oss.ByteRange - }{ - {"offset equals size to EOF", []byte("0123456789"), oss.ByteRange{Offset: 10, Length: -1}}, - {"offset equals size single byte", []byte("0123456789"), oss.ByteRange{Offset: 10, Length: 1}}, - {"empty object to EOF", nil, oss.ByteRange{Offset: 0, Length: -1}}, - } { - t.Run(tc.name, func(t *testing.T) { - var requests int32 - st, _ := newTestStorage(t, &objectHandler{body: tc.body, requests: &requests}) - - _, err := st.Range(context.Background(), "key", &tc.r) - if !errors.Is(err, oss.ErrRangeNotSatisfiable) { - t.Fatalf("expected ErrRangeNotSatisfiable, got %v", err) - } - if requests != 1 { - t.Fatalf("expected a single GET request, got %d", requests) - } - }) - } -} - -// newBlockingStorage serves a handler that blocks until released or the -// client disconnects. With sendHeaders it first flushes a partial 200 -// response so the block happens during the body read; otherwise it blocks -// before sending headers. The handler is released before the server closes, -// because an abandoned OBS request is only torn down by the SDK's own -// response-header timeout. -func newBlockingStorage(t *testing.T, sendHeaders bool) (*HuaweiOBSStorage, chan struct{}) { - t.Helper() - entered := make(chan struct{}, 1) - release := make(chan struct{}) - st, _ := newTestStorage(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - select { - case entered <- struct{}{}: - default: - } - if sendHeaders { - w.Header().Set("Content-Length", "10") - w.WriteHeader(http.StatusOK) - w.Write([]byte("abc")) - w.(http.Flusher).Flush() - } - select { - case <-r.Context().Done(): - case <-release: - } - })) - t.Cleanup(func() { close(release) }) - return st, entered -} - -func TestOBSRangeCanceledInflight(t *testing.T) { - st, entered := newBlockingStorage(t, false) - - ctx, cancel := context.WithCancel(context.Background()) - done := make(chan error, 1) - go func() { - _, err := st.Range(ctx, "key", nil) - done <- err - }() - select { - case <-entered: - case <-time.After(5 * time.Second): - t.Fatal("handler never received request") - } - cancel() - select { - case err := <-done: - if !errors.Is(err, context.Canceled) { - t.Fatalf("expected context.Canceled, got %v", err) - } - case <-time.After(5 * time.Second): - t.Fatal("Range did not return after cancel") - } -} - -func TestOBSRangeCanceledDuringBodyRead(t *testing.T) { - st, _ := newBlockingStorage(t, true) - - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - rc, err := st.Range(ctx, "key", nil) - if err != nil { - t.Fatalf("Range: %v", err) - } - defer rc.Close() - - readDone := make(chan error, 1) - go func() { - _, err := io.ReadFull(rc, make([]byte, 10)) - readDone <- err - }() - time.Sleep(50 * time.Millisecond) - cancel() - select { - case err := <-readDone: - if !errors.Is(err, context.Canceled) { - t.Fatalf("expected context.Canceled, got %v", err) - } - case <-time.After(5 * time.Second): - t.Fatal("Read did not return after cancel") - } -} - -func TestOBSRangeOversizedEndClamped(t *testing.T) { - st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789")}) - - rc, err := st.Range(context.Background(), "key", &oss.ByteRange{Offset: 8, Length: 100}) - if err != nil { - t.Fatalf("Range: %v", err) - } - defer rc.Close() - data, err := io.ReadAll(rc) - if err != nil { - t.Fatalf("ReadAll: %v", err) - } - if string(data) != "89" { - t.Fatalf("got %q", data) - } -} - -func TestOBSRangeInvalidRangeNoRequest(t *testing.T) { - var requests int32 - st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789"), requests: &requests}) - - for _, r := range []oss.ByteRange{ - {Offset: -1, Length: 1}, - {Offset: 0, Length: 0}, - {Offset: 0, Length: -2}, - } { - if _, err := st.Range(context.Background(), "key", &r); !errors.Is(err, oss.ErrInvalidRange) { - t.Fatalf("range=%+v: expected ErrInvalidRange, got %v", r, err) - } - } - if requests != 0 { - t.Fatalf("expected no request, got %d", requests) - } -} - -func TestOBSRangeCanceledBeforeRequest(t *testing.T) { - var requests int32 - st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789"), requests: &requests}) - - ctx, cancel := context.WithCancel(context.Background()) - cancel() - if _, err := st.Range(ctx, "key", nil); !errors.Is(err, context.Canceled) { - t.Fatalf("expected context.Canceled, got %v", err) - } - if requests != 0 { - t.Fatalf("expected no request, got %d", requests) - } -} - -func TestOBSRangeRangeNotSatisfiable(t *testing.T) { - st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789")}) - - _, err := st.Range(context.Background(), "key", &oss.ByteRange{Offset: 100, Length: 1}) - if !errors.Is(err, oss.ErrRangeNotSatisfiable) { - t.Fatalf("expected ErrRangeNotSatisfiable, got %v", err) - } -} - -func TestOBSRangeEmptyObject(t *testing.T) { - st, _ := newTestStorage(t, &objectHandler{body: nil}) - - rc, err := st.Range(context.Background(), "key", nil) - if err != nil { - t.Fatalf("Range: %v", err) - } - defer rc.Close() - data, err := io.ReadAll(rc) - if err != nil { - t.Fatalf("ReadAll: %v", err) - } - if len(data) != 0 { - t.Fatalf("expected empty body, got %q", data) - } -} - -func TestOBSRangeServerIgnoresRange(t *testing.T) { - st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789"), ignore: true}) - - _, err := st.Range(context.Background(), "key", &oss.ByteRange{Offset: 2, Length: 4}) - if err == nil { - t.Fatal("expected error when server ignores the range") - } -} - -func TestOBSLoadStillWorks(t *testing.T) { - st, _ := newTestStorage(t, &objectHandler{body: []byte("hello world")}) - - data, err := st.Load("key") - if err != nil { - t.Fatalf("Load: %v", err) - } - if string(data) != "hello world" { - t.Fatalf("got %q", data) - } -} diff --git a/oss/huaweiobs/obs_test.go b/oss/huaweiobs/obs_test.go index ff38049..eb3fdc4 100644 --- a/oss/huaweiobs/obs_test.go +++ b/oss/huaweiobs/obs_test.go @@ -1,6 +1,16 @@ package huaweiobs -import "testing" +import ( + "testing" + + "github.com/langgenius/dify-cloud-kit/oss" +) + +func TestOBSDoesNotSupportStreaming(t *testing.T) { + if oss.SupportsStreaming(&HuaweiOBSStorage{}) { + t.Fatal("Huawei OBS must not report streaming support") + } +} func TestListedObjectPath(t *testing.T) { tests := []struct { From cb3a046857282d5bb80f8f5f450427449bab8afe Mon Sep 17 00:00:00 2001 From: "yunlu.wen" Date: Fri, 20 Nov 2026 10:37:25 +0800 Subject: [PATCH 11/13] fix: use Accept-Encoding: identity to prevent implicit decompression --- oss/azureblob/blob.go | 22 +++++- oss/azureblob/blob_stream_test.go | 21 +++-- tests/integration/azure_test.go | 126 ++++++++++++++++++++++++++++++ 3 files changed, 160 insertions(+), 9 deletions(-) diff --git a/oss/azureblob/blob.go b/oss/azureblob/blob.go index c0c42f7..defd8fe 100644 --- a/oss/azureblob/blob.go +++ b/oss/azureblob/blob.go @@ -10,6 +10,7 @@ import ( "strings" "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" "github.com/Azure/azure-sdk-for-go/sdk/azidentity" "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob" "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/bloberror" @@ -26,6 +27,23 @@ type AzureBlobStorage struct { containerName string } +// identityEncodingPolicy prevents net/http from implicitly decompressing gzipped +// content, which would break range requests on compressed blobs. +type identityEncodingPolicy struct{} + +func (identityEncodingPolicy) Do(req *policy.Request) (*http.Response, error) { + req.Raw().Header.Set("Accept-Encoding", "identity") + return req.Next() +} + +func newClientOptions() *azblob.ClientOptions { + return &azblob.ClientOptions{ + ClientOptions: azcore.ClientOptions{ + PerCallPolicies: []policy.Policy{identityEncodingPolicy{}}, + }, + } +} + func NewAzureBlobStorage(args oss.OSSArgs) (oss.OSS, error) { var client *azblob.Client var err error @@ -43,13 +61,13 @@ func NewAzureBlobStorage(args oss.OSSArgs) (oss.OSS, error) { if err != nil { return nil, oss.ErrProviderInit.WithError(err) } - client, err = azblob.NewClient(args.AzureBlob.ServiceURL, cred, nil) + client, err = azblob.NewClient(args.AzureBlob.ServiceURL, cred, newClientOptions()) if err != nil { return nil, oss.ErrProviderInit.WithError(err) } } else { connectionString := args.AzureBlob.ConnectionString - client, err = azblob.NewClientFromConnectionString(connectionString, nil) + client, err = azblob.NewClientFromConnectionString(connectionString, newClientOptions()) if err != nil { return nil, oss.ErrProviderInit.WithError(err) } diff --git a/oss/azureblob/blob_stream_test.go b/oss/azureblob/blob_stream_test.go index b54a4a5..e8487fc 100644 --- a/oss/azureblob/blob_stream_test.go +++ b/oss/azureblob/blob_stream_test.go @@ -22,7 +22,7 @@ func newTestStorage(t *testing.T, handler http.Handler) (*AzureBlobStorage, *htt srv := httptest.NewServer(handler) t.Cleanup(srv.Close) - client, err := azblob.NewClientWithNoCredential(srv.URL, nil) + client, err := azblob.NewClientWithNoCredential(srv.URL, newClientOptions()) if err != nil { t.Fatalf("NewClientWithNoCredential: %v", err) } @@ -513,12 +513,13 @@ func TestAzureRangeStreamsBeforeFullDownload(t *testing.T) { // for the whole object but closes early), then asserts the retry carries an // advanced x-ms-range and If-Match ETag, and completes the remaining bytes. type retryHandler struct { - full string // full object content - served int // bytes served on the first response - retried chan struct{} - gotRange string - gotIfMatch string - t *testing.T + full string // full object content + served int // bytes served on the first response + retried chan struct{} + gotRange string + gotIfMatch string + gotAcceptEncoding string + t *testing.T } func (h *retryHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { @@ -534,6 +535,7 @@ func (h *retryHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { // retry request h.gotRange = rangeHdr h.gotIfMatch = r.Header.Get("If-Match") + h.gotAcceptEncoding = r.Header.Get("Accept-Encoding") var start int64 fmt.Sscan(strings.TrimSuffix(strings.TrimPrefix(rangeHdr, "bytes="), "-"), &start) part := h.full[start:] @@ -580,6 +582,11 @@ func runRetryTest(t *testing.T, byteRange *oss.ByteRange, body string, served in if h.gotIfMatch != `"etag1"` { t.Fatalf("retry If-Match %q", h.gotIfMatch) } + // Retries must keep asking for raw bytes: without it Go's transport + // would gunzip a Content-Encoding: gzip blob on the retry leg only. + if h.gotAcceptEncoding != "identity" { + t.Fatalf("retry Accept-Encoding %q, want identity", h.gotAcceptEncoding) + } if h.gotRange != wantRetryRange { t.Fatalf("retry x-ms-range %q, want %q", h.gotRange, wantRetryRange) } diff --git a/tests/integration/azure_test.go b/tests/integration/azure_test.go index 186cef2..a4b87fd 100644 --- a/tests/integration/azure_test.go +++ b/tests/integration/azure_test.go @@ -1,11 +1,17 @@ package integration import ( + "bytes" + "compress/gzip" "context" "fmt" + "io" "testing" "time" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob" + "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/blob" "github.com/google/uuid" "github.com/langgenius/dify-cloud-kit/oss" "github.com/langgenius/dify-cloud-kit/oss/factory" @@ -92,3 +98,123 @@ func TestAzureIntegrationStreaming(t *testing.T) { runStreamingChecks(t, store, objKey, emptyKey) runInterfaceChecks(t, store, objKey, emptyKey) } + +// TestAzureIntegrationGzipContentEncoding uploads a blob whose stored metadata +// carries Content-Encoding: gzip and reads it back through the library. +// +// Azure (and Azurite) return the stored Content-Encoding on GET, so Go's HTTP +// transport transparently gunzips the body whenever it injected +// Accept-Encoding: gzip itself. A whole-object read then yields the +// decompressed payload instead of the stored bytes, and a ranged read yields a +// partial gzip member that fails mid-stream โ€” even though Content-Range looked +// valid. The library must request raw bytes and hand back exactly what the +// service stored. +func TestAzureIntegrationGzipContentEncoding(t *testing.T) { + requireIntegration(t) + + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + + container := fmt.Sprintf("cloudkit-gzip-%s", uuid.NewString()) + key := "gzip.bin" + + store, err := factory.Load("azure_blob", oss.OSSArgs{ + AzureBlob: &oss.AzureBlob{ + ConnectionString: azuriteConnStr, + ContainerName: container, + }, + }) + if err != nil { + t.Fatalf("factory.Load azure_blob: %v", err) + } + t.Cleanup(func() { + if err := store.Delete(key); err != nil { + t.Logf("cleanup Delete %s: %v", key, err) + } + }) + if err := oss.Prepare(ctx, store); err != nil { + t.Fatalf("Prepare: %v", err) + } + + payload := bytes.Repeat([]byte("dify-cloud-kit gzip fixture "), 4096) + var buf bytes.Buffer + zw := gzip.NewWriter(&buf) + if _, err := zw.Write(payload); err != nil { + t.Fatalf("gzip.Write: %v", err) + } + if err := zw.Close(); err != nil { + t.Fatalf("gzip.Close: %v", err) + } + stored := buf.Bytes() + if len(stored) < 64 || len(stored) >= len(payload) { + t.Fatalf("unexpected compressed size %d (payload %d)", len(stored), len(payload)) + } + + // Upload with the SDK directly: the library's Save has no way to set + // content headers, and this test is about reading blobs that other + // writers stored gzip-encoded. + uploader, err := azblob.NewClientFromConnectionString(azuriteConnStr, nil) + if err != nil { + t.Fatalf("NewClientFromConnectionString: %v", err) + } + if _, err := uploader.UploadBuffer(ctx, container, key, stored, &azblob.UploadBufferOptions{ + HTTPHeaders: &blob.HTTPHeaders{BlobContentEncoding: to.Ptr("gzip")}, + }); err != nil { + t.Fatalf("UploadBuffer: %v", err) + } + + state, err := store.State(key) + if err != nil { + t.Fatalf("State: %v", err) + } + if state.Size != int64(len(stored)) { + t.Fatalf("State.Size = %d, want stored size %d", state.Size, len(stored)) + } + + readAll := func(t *testing.T, r *oss.ByteRange) []byte { + t.Helper() + rc, err := oss.OpenStream(ctx, store, key, r) + if err != nil { + t.Fatalf("OpenStream(%+v): %v", r, err) + } + defer rc.Close() + got, err := io.ReadAll(rc) + if err != nil { + t.Fatalf("ReadAll(%+v): %v", r, err) + } + return got + } + + t.Run("Load", func(t *testing.T) { + got, err := store.Load(key) + if err != nil { + t.Fatalf("Load: %v", err) + } + if !bytes.Equal(got, stored) { + t.Fatalf("Load returned %d bytes (payload=%v), want %d stored bytes", + len(got), bytes.Equal(got, payload), len(stored)) + } + }) + + for _, tc := range []struct { + name string + r *oss.ByteRange + start int + }{ + {"full stream", nil, 0}, + {"bounded head", &oss.ByteRange{Offset: 0, Length: 16}, 0}, + {"bounded mid", &oss.ByteRange{Offset: 10, Length: 20}, 10}, + {"tail to EOF", &oss.ByteRange{Offset: int64(len(stored) - 8), Length: -1}, len(stored) - 8}, + } { + t.Run(tc.name, func(t *testing.T) { + want := stored[tc.start:] + if tc.r != nil && tc.r.Length > 0 { + want = stored[tc.start : tc.start+int(tc.r.Length)] + } + got := readAll(t, tc.r) + if !bytes.Equal(got, want) { + t.Fatalf("read %d bytes, want raw stored slice %d bytes", len(got), len(want)) + } + }) + } +} From 1b780f2ad2aa23d3f5ba1def89c737d74f67ca0b Mon Sep 17 00:00:00 2001 From: "yunlu.wen" Date: Fri, 20 Nov 2026 11:12:35 +0800 Subject: [PATCH 12/13] fix result validation when remaining size is unknown --- oss/gcsblob/gcs.go | 30 +++-- oss/gcsblob/gcs_stream_test.go | 234 +++++++++++++++++++++++++++++++-- 2 files changed, 247 insertions(+), 17 deletions(-) diff --git a/oss/gcsblob/gcs.go b/oss/gcsblob/gcs.go index 9884e0d..ba97e94 100644 --- a/oss/gcsblob/gcs.go +++ b/oss/gcsblob/gcs.go @@ -167,16 +167,28 @@ func (g *GoogleCloudStorage) Range(ctx context.Context, key string, byteRange *o rc.Close() return nil, oss.ErrRangeNotSatisfiable } - // The GCS SDK enforces that a range starting at a non-zero offset - // returns 206; reconstruct the Content-Range from the reader - // attributes and verify it the same way as other providers so a - // server that ignores the range (e.g. decompressive transcoding) - // fails loudly instead of streaming the whole object. - contentRange := fmt.Sprintf("bytes %d-%d/%d", - rc.Attrs.StartOffset, rc.Attrs.StartOffset+rc.Remain()-1, rc.Attrs.Size) - if err := oss.VerifyContentRange(contentRange, byteRange); err != nil { + // Verify the server honored the range instead of streaming the whole + // object. Remain is -1 without Content-Length; Attrs.Size still tells a + // parsed 206 (total from Content-Range) from a bare 200. + start, size, remain := rc.Attrs.StartOffset, rc.Attrs.Size, rc.Remain() + switch { + case remain >= 0: + // Content-Length present: verify the full reconstructed range. + contentRange := fmt.Sprintf("bytes %d-%d/%d", start, start+remain-1, size) + if err := oss.VerifyContentRange(contentRange, byteRange); err != nil { + rc.Close() + return nil, err + } + case size >= 0: + // 206 without Content-Length: start is known, the end is not. + if start != byteRange.Offset { + rc.Close() + return nil, fmt.Errorf("server did not honor requested range %v: Content-Range starts at %d", *byteRange, start) + } + case byteRange.Offset != 0 || byteRange.Length != -1: + // 200 without Content-Length: range ignored, only whole-object reads are safe. rc.Close() - return nil, err + return nil, fmt.Errorf("server did not honor requested range %v: response has neither Content-Range nor Content-Length", *byteRange) } } diff --git a/oss/gcsblob/gcs_stream_test.go b/oss/gcsblob/gcs_stream_test.go index 32f8946..f23bba3 100644 --- a/oss/gcsblob/gcs_stream_test.go +++ b/oss/gcsblob/gcs_stream_test.go @@ -1,6 +1,8 @@ package gcsblob import ( + "bytes" + "compress/gzip" "context" "errors" "fmt" @@ -39,9 +41,28 @@ type objectHandler struct { rangeHdr *string requests *int32 ignore bool // respond 200 with full body regardless of Range + chunked bool // omit Content-Length to force chunked transfer encoding statusCode int // if >0, respond with this status + XML error instead } +// write emits body, leaving Content-Length out when chunked is set so the +// response is delimited by chunked transfer encoding instead. +func (h *objectHandler) write(w http.ResponseWriter, status int, contentRange string, body []byte) { + if contentRange != "" { + w.Header().Set("Content-Range", contentRange) + } + if !h.chunked { + w.Header().Set("Content-Length", fmt.Sprint(len(body))) + } + w.WriteHeader(status) + if h.chunked { + // Commit the headers before the body so the server does not + // buffer the response and add a Content-Length. + w.(http.Flusher).Flush() + } + w.Write(body) +} + func (h *objectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { if h.requests != nil { atomic.AddInt32(h.requests, 1) @@ -56,9 +77,7 @@ func (h *objectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { *h.rangeHdr = rangeHdr } if rangeHdr == "" || h.ignore { - w.Header().Set("Content-Length", fmt.Sprint(len(h.body))) - w.WriteHeader(http.StatusOK) - w.Write(h.body) + h.write(w, http.StatusOK, "", h.body) return } // parse "bytes=start-end" / "bytes=start-" @@ -81,11 +100,7 @@ func (h *objectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { if end >= int64(len(h.body)) { end = int64(len(h.body)) - 1 } - part := h.body[start : end+1] - w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", start, end, len(h.body))) - w.Header().Set("Content-Length", fmt.Sprint(len(part))) - w.WriteHeader(http.StatusPartialContent) - w.Write(part) + h.write(w, http.StatusPartialContent, fmt.Sprintf("bytes %d-%d/%d", start, end, len(h.body)), h.body[start:end+1]) } func TestGCSRangeFull(t *testing.T) { @@ -247,6 +262,209 @@ func TestGCSRangeServerIgnoresRange(t *testing.T) { } } +// TestGCSRangeChunkedHonored covers responses without Content-Length where the +// server did honor the range: the end cannot be reconstructed, but the start +// offset and total are still parsed from Content-Range. +func TestGCSRangeChunkedHonored(t *testing.T) { + var rangeHdr string + st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789"), rangeHdr: &rangeHdr, chunked: true}) + + tests := []struct { + name string + r *oss.ByteRange + want string + wantHdr string + }{ + {name: "bounded", r: &oss.ByteRange{Offset: 2, Length: 4}, want: "2345", wantHdr: "bytes=2-5"}, + {name: "open ended", r: &oss.ByteRange{Offset: 4, Length: -1}, want: "456789", wantHdr: "bytes=4-"}, + {name: "clamped end", r: &oss.ByteRange{Offset: 8, Length: 100}, want: "89", wantHdr: "bytes=8-107"}, + {name: "zero to EOF", r: &oss.ByteRange{Offset: 0, Length: -1}, want: "0123456789"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + rc, err := st.Range(context.Background(), "key", tt.r) + if err != nil { + t.Fatalf("Range(%+v): %v", *tt.r, err) + } + defer rc.Close() + data, err := io.ReadAll(rc) + if err != nil { + t.Fatalf("ReadAll: %v", err) + } + if string(data) != tt.want { + t.Fatalf("got %q, want %q", data, tt.want) + } + if rangeHdr != tt.wantHdr { + t.Fatalf("got Range header %q, want %q", rangeHdr, tt.wantHdr) + } + }) + } +} + +// TestGCSRangeChunkedIgnored covers a 200 with no Content-Length for a ranged +// request, regardless of why the response was re-framed. The whole object is +// streamed, so only a whole-object request may be served. +func TestGCSRangeChunkedIgnored(t *testing.T) { + st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789"), ignore: true, chunked: true}) + + for _, r := range []oss.ByteRange{ + {Offset: 0, Length: 5}, + {Offset: 0, Length: 1}, + {Offset: 2, Length: 4}, + {Offset: 2, Length: -1}, + } { + rc, err := st.Range(context.Background(), "key", &r) + if rc != nil { + rc.Close() + } + if err == nil { + t.Fatalf("range=%+v: expected error when the server ignores the range", r) + } + } + + rc, err := st.Range(context.Background(), "key", &oss.ByteRange{Offset: 0, Length: -1}) + if err != nil { + t.Fatalf("whole-object Range: %v", err) + } + defer rc.Close() + data, err := io.ReadAll(rc) + if err != nil { + t.Fatalf("ReadAll: %v", err) + } + if string(data) != "0123456789" { + t.Fatalf("got %q", data) + } +} + +// transcodingHandler serves the response GCS produces for an object stored +// with Content-Encoding: gzip when it is decompressively transcoded: the body +// is decompressed, Content-Encoding and Content-Length are dropped, and the +// stored metadata is reported through the X-Goog-Stored-* headers. Range +// requests are silently ignored, as documented. +type transcodingHandler struct { + stored []byte // object bytes as stored (gzip-compressed) + served []byte // object bytes as served (decompressed) +} + +func (h *transcodingHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/plain") + w.Header().Set("X-Goog-Stored-Content-Encoding", "gzip") + w.Header().Set("X-Goog-Stored-Content-Length", fmt.Sprint(len(h.stored))) + w.WriteHeader(http.StatusOK) + // No Content-Length: commit the headers first so the body is chunked. + w.(http.Flusher).Flush() + w.Write(h.served) +} + +// gzipFixture compresses served and returns the stored bytes. +func gzipFixture(t *testing.T, served []byte) []byte { + t.Helper() + var stored bytes.Buffer + zw := gzip.NewWriter(&stored) + if _, err := zw.Write(served); err != nil { + t.Fatalf("gzip write: %v", err) + } + if err := zw.Close(); err != nil { + t.Fatalf("gzip close: %v", err) + } + if stored.Len() == len(served) { + t.Fatalf("fixture is not compressed: stored %d, served %d", stored.Len(), len(served)) + } + return stored.Bytes() +} + +// TestGCSRangeTranscoded pins the server-side decompressive-transcoding shape: +// a gzip-stored object whose response is decompressed, chunked, and carries +// neither Content-Encoding nor Content-Length. The stored and served sizes +// differ and Range is ignored, so only a whole-object request can be served. +func TestGCSRangeTranscoded(t *testing.T) { + served := bytes.Repeat([]byte("dify"), 1024) + stored := gzipFixture(t, served) + st, _ := newTestStorage(t, &transcodingHandler{stored: stored, served: served}) + + for _, r := range []oss.ByteRange{ + {Offset: 0, Length: 5}, + {Offset: 0, Length: 1}, + {Offset: 2, Length: 4}, + {Offset: 2, Length: -1}, + } { + rc, err := st.Range(context.Background(), "key", &r) + if rc != nil { + rc.Close() + } + if err == nil { + t.Fatalf("range=%+v: expected error for a transcoded response", r) + } + } + + rc, err := st.Range(context.Background(), "key", &oss.ByteRange{Offset: 0, Length: -1}) + if err != nil { + t.Fatalf("whole-object Range: %v", err) + } + defer rc.Close() + + reader, ok := rc.(*storage.Reader) + if !ok { + t.Fatalf("Range returned %T, want *storage.Reader", rc) + } + if !reader.Attrs.Decompressed { + t.Fatal("SDK did not report the response as decompressed; fixture is not faithful") + } + if reader.Attrs.Size != -1 || reader.Remain() != -1 { + t.Fatalf("Attrs.Size = %d, Remain() = %d; want -1 without Content-Length", reader.Attrs.Size, reader.Remain()) + } + + data, err := io.ReadAll(rc) + if err != nil { + t.Fatalf("ReadAll: %v", err) + } + if !bytes.Equal(data, served) { + t.Fatalf("read %d bytes, want %d", len(data), len(served)) + } +} + +// TestGCSRangeTransportDecompressed covers the other path to an unknown +// length. The HTTP transport only asks for gzip when the request carries no +// Range header, so whole-object reads of a gzip-stored object are decompressed +// by the transport itself; a response that had a Content-Length on the wire +// still reaches the provider with Remain() == -1. +func TestGCSRangeTransportDecompressed(t *testing.T) { + served := bytes.Repeat([]byte("dify"), 1024) + stored := gzipFixture(t, served) + st, _ := newTestStorage(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/plain") + w.Header().Set("Content-Encoding", "gzip") + w.Header().Set("Content-Length", fmt.Sprint(len(stored))) + w.WriteHeader(http.StatusOK) + w.Write(stored) + })) + + rc, err := st.Range(context.Background(), "key", &oss.ByteRange{Offset: 0, Length: -1}) + if err != nil { + t.Fatalf("whole-object Range: %v", err) + } + defer rc.Close() + + reader, ok := rc.(*storage.Reader) + if !ok { + t.Fatalf("Range returned %T, want *storage.Reader", rc) + } + if !reader.Attrs.Decompressed { + t.Fatal("SDK did not report the response as decompressed; transport did not negotiate gzip") + } + if reader.Remain() != -1 { + t.Fatalf("Remain() = %d, want -1 after transport decompression", reader.Remain()) + } + + data, err := io.ReadAll(rc) + if err != nil { + t.Fatalf("ReadAll: %v", err) + } + if !bytes.Equal(data, served) { + t.Fatalf("read %d bytes, want %d", len(data), len(served)) + } +} + func TestGCSLoadStillWorks(t *testing.T) { st, _ := newTestStorage(t, &objectHandler{body: []byte("hello world")}) From d6ffeead178ae00dce4140f55b4398212e84b48a Mon Sep 17 00:00:00 2001 From: "yunlu.wen" Date: Fri, 20 Nov 2026 11:19:53 +0800 Subject: [PATCH 13/13] fix: remove implicit retry --- oss/azureblob/blob.go | 2 +- oss/azureblob/blob_stream_test.go | 160 ++++++++++++++---------------- 2 files changed, 75 insertions(+), 87 deletions(-) diff --git a/oss/azureblob/blob.go b/oss/azureblob/blob.go index defd8fe..6597011 100644 --- a/oss/azureblob/blob.go +++ b/oss/azureblob/blob.go @@ -165,7 +165,7 @@ func (a *AzureBlobStorage) Range(ctx context.Context, key string, byteRange *oss } } - return resp.NewRetryReader(ctx, &azblob.RetryReaderOptions{EarlyCloseAsError: true}), nil + return resp.Body, nil } func (a *AzureBlobStorage) Exists(key string) (bool, error) { diff --git a/oss/azureblob/blob_stream_test.go b/oss/azureblob/blob_stream_test.go index e8487fc..3c4795f 100644 --- a/oss/azureblob/blob_stream_test.go +++ b/oss/azureblob/blob_stream_test.go @@ -509,105 +509,93 @@ func TestAzureRangeStreamsBeforeFullDownload(t *testing.T) { } } -// retryHandler serves a truncated first response (declares Content-Length -// for the whole object but closes early), then asserts the retry carries an -// advanced x-ms-range and If-Match ETag, and completes the remaining bytes. -type retryHandler struct { - full string // full object content - served int // bytes served on the first response - retried chan struct{} - gotRange string - gotIfMatch string - gotAcceptEncoding string - t *testing.T -} - -func (h *retryHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { - rangeHdr := r.Header.Get("x-ms-range") - if strings.HasPrefix(rangeHdr, "bytes=0-") || rangeHdr == "" { - w.Header().Set("ETag", `"etag1"`) - w.Header().Set("Content-Range", fmt.Sprintf("bytes 0-%d/%d", len(h.full)-1, len(h.full))) - w.Header().Set("Content-Length", fmt.Sprint(len(h.full))) - w.WriteHeader(http.StatusPartialContent) - w.Write([]byte(h.full[:h.served])) // truncated: unexpected EOF for the client - return +// TestAzureRangeTruncatedBodySurfacesError proves a truncated response is +// returned to the caller instead of being retried transparently, and that the +// bytes delivered before the failure are preserved. +func TestAzureRangeTruncatedBodySurfacesError(t *testing.T) { + var requests int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + atomic.AddInt32(&requests, 1) + w.Header().Set("Content-Length", "10") + w.WriteHeader(http.StatusOK) + w.Write([]byte("abc")) + })) + t.Cleanup(srv.Close) + client, err := azblob.NewClientWithNoCredential(srv.URL, nil) + if err != nil { + t.Fatalf("NewClientWithNoCredential: %v", err) } - // retry request - h.gotRange = rangeHdr - h.gotIfMatch = r.Header.Get("If-Match") - h.gotAcceptEncoding = r.Header.Get("Accept-Encoding") - var start int64 - fmt.Sscan(strings.TrimSuffix(strings.TrimPrefix(rangeHdr, "bytes="), "-"), &start) - part := h.full[start:] - w.Header().Set("ETag", `"etag1"`) - w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", start, len(h.full)-1, len(h.full))) - w.Header().Set("Content-Length", fmt.Sprint(len(part))) - w.WriteHeader(http.StatusPartialContent) - w.Write([]byte(part)) - close(h.retried) -} - -func runRetryTest(t *testing.T, byteRange *oss.ByteRange, body string, served int, wantRetryRange string) string { - t.Helper() - h := &retryHandler{full: body, served: served, retried: make(chan struct{}), t: t} - st, _ := newTestStorage(t, h) + st := &AzureBlobStorage{client: client, containerName: "cont"} - rc, err := st.Range(context.Background(), "key", byteRange) + rc, err := st.Range(context.Background(), "key", nil) if err != nil { t.Fatalf("Range: %v", err) } defer rc.Close() - readDone := make(chan struct { - data []byte - err error - }, 1) - go func() { - data, err := io.ReadAll(rc) - readDone <- struct { - data []byte - err error - }{data, err} - }() - - select { - case <-h.retried: - case <-time.After(10 * time.Second): - t.Fatal("retry never issued") + data, err := io.ReadAll(rc) + if err == nil { + t.Fatal("expected truncated read to fail") } - res := <-readDone - if res.err != nil { - t.Fatalf("ReadAll: %v", res.err) + if string(data) != "abc" { + t.Fatalf("got %q", data) } - if h.gotIfMatch != `"etag1"` { - t.Fatalf("retry If-Match %q", h.gotIfMatch) + if n := atomic.LoadInt32(&requests); n != 1 { + t.Fatalf("expected 1 request, got %d", n) } - // Retries must keep asking for raw bytes: without it Go's transport - // would gunzip a Content-Encoding: gzip blob on the retry leg only. - if h.gotAcceptEncoding != "identity" { - t.Fatalf("retry Accept-Encoding %q, want identity", h.gotAcceptEncoding) +} + +// TestAzureRangeCloseIsTerminal proves Close stops a read that is blocked in +// another goroutine without issuing a retry. +func TestAzureRangeCloseIsTerminal(t *testing.T) { + var requests int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + atomic.AddInt32(&requests, 1) + w.Header().Set("Content-Length", "10") + w.WriteHeader(http.StatusOK) + w.Write([]byte("abc")) + w.(http.Flusher).Flush() + <-r.Context().Done() + })) + t.Cleanup(srv.Close) + client, err := azblob.NewClientWithNoCredential(srv.URL, nil) + if err != nil { + t.Fatalf("NewClientWithNoCredential: %v", err) } - if h.gotRange != wantRetryRange { - t.Fatalf("retry x-ms-range %q, want %q", h.gotRange, wantRetryRange) + st := &AzureBlobStorage{client: client, containerName: "cont"} + + rc, err := st.Range(context.Background(), "key", nil) + if err != nil { + t.Fatalf("Range: %v", err) + } + + buf := make([]byte, 3) + if _, err := io.ReadFull(rc, buf); err != nil { + t.Fatalf("Read: %v", err) } - return string(res.data) -} -func TestAzureRetryReaderAdvancesRange(t *testing.T) { - // bounded range 0-9 of a 10-byte object; first response truncates at 3 - // bytes, retry must advance the offset while keeping the requested end. - got := runRetryTest(t, &oss.ByteRange{Offset: 0, Length: 10}, "0123456789", 3, "bytes=3-9") - if got != "0123456789" { - t.Fatalf("got %q", got) + readDone := make(chan error, 1) + go func() { + _, err := io.ReadFull(rc, make([]byte, 7)) + readDone <- err + }() + time.Sleep(50 * time.Millisecond) + + if err := rc.Close(); err != nil { + t.Fatalf("Close: %v", err) + } + select { + case err := <-readDone: + if err == nil { + t.Fatal("expected read error after Close") + } + case <-time.After(5 * time.Second): + t.Fatal("Read did not return after Close") } -} -// TestAzureRetryAfterZeroToEOF proves retries after a {0,-1} request advance -// the range correctly instead of re-requesting from 0. -func TestAzureRetryAfterZeroToEOF(t *testing.T) { - got := runRetryTest(t, &oss.ByteRange{Offset: 0, Length: -1}, "0123456789", 3, "bytes=3-9223372036854775806") - if got != "0123456789" { - t.Fatalf("got %q", got) + time.Sleep(100 * time.Millisecond) + if n := atomic.LoadInt32(&requests); n != 1 { + t.Fatalf("expected 1 request after Close, got %d", n) } } @@ -638,8 +626,8 @@ func TestAzureLoadClosesBodyOnReadError(t *testing.T) { }) st := newTrackingStorage(t, rt) - // Reads fail immediately; the retry reader must close each failed body - // before retrying, and Load returns the error. + // Reads fail immediately; Load's deferred Close must release the body + // before returning the error. _, err := st.Load("key") if err == nil { t.Fatal("expected Load to fail")