diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml new file mode 100644 index 0000000..658b91f --- /dev/null +++ b/.github/workflows/integration.yml @@ -0,0 +1,52 @@ +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: 20 + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-go@v5 + with: + 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 + + - 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..9b0f551 --- /dev/null +++ b/Makefile @@ -0,0 +1,18 @@ +COMPOSE_INTEGRATION := docker compose -f compose.integration.yaml + +# 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 + +# 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 ff9c6e8..4b41eff 100644 --- a/README.md +++ b/README.md @@ -66,6 +66,105 @@ 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 + Range(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 `Range` fail the type assertion; + the library never secretly buffers a ranged request via `Load`. +- 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 | `Range` 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 | +| Google GCS | โœ… | `NewRangeReader`, 416 mapped to `ErrRangeNotSatisfiable` | +| Tencent COS| โœ… | `ObjectGetOptions.Range`, body streamed | +| 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 | + +### 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 `Range`, 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.Range(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`. @@ -109,3 +208,102 @@ 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| + +## ๐Ÿ› ๏ธ 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 +} +``` + +`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** โ€” 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 +OBS, Volcengine TOS) do not implement `Preparer` yet. + +## ๐Ÿงฉ Integration Tests (Emulators) + +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 + +```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 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 + +- 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, Volcengine TOS โ€” has mock-server coverage). +- Emulator-backed integration tests cover S3 (LocalStack), Azure Blob + (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 + `CLOUDKIT_AZURE_LIVE_*` env vars and an existing blob) is separate. + +The streaming feature and these emulator/CI tests ship together in the same +PR โ€” there is no stacked-branch dependency. diff --git a/compose.integration.yaml b/compose.integration.yaml new file mode 100644 index 0000000..933b28b --- /dev/null +++ b/compose.integration.yaml @@ -0,0 +1,44 @@ +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 + + 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/aliyun/aliyun.go b/oss/aliyun/aliyun.go index a9d837f..a8a74bf 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.Range(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) 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() + 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..ffff057 --- /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 TestAliyunRangeFull(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 TestAliyunRangeBounded(t *testing.T) { + var rangeHdr, behavior string + st := newTestStorage(t, &objectHandler{body: []byte("0123456789"), rangeHdr: &rangeHdr, behavior: &behavior}, "") + + rc, err := st.Range(context.Background(), "key", &difyoss.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 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 TestAliyunRangeOpenEnded(t *testing.T) { + var rangeHdr string + st := newTestStorage(t, &objectHandler{body: []byte("0123456789"), rangeHdr: &rangeHdr}, "") + + rc, err := st.Range(context.Background(), "key", &difyoss.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 rangeHdr != "bytes=4-" { + t.Fatalf("Range header %q", rangeHdr) + } + if string(data) != "456789" { + t.Fatalf("got %q", data) + } +} + +func TestAliyunRangeHonorsConfiguredPrefix(t *testing.T) { + var reqPath string + st := newTestStorage(t, &objectHandler{body: []byte("x"), path: &reqPath}, "prefix/") + + rc, err := st.Range(context.Background(), "dir/key", nil) + if err != nil { + t.Fatalf("Range: %v", err) + } + rc.Close() + if !strings.HasSuffix(reqPath, "/prefix/dir/key") { + t.Fatalf("request path %q does not include configured prefix", reqPath) + } +} + +func TestAliyunRangeInvalidRangeNoRequest(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.Range(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 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.Range(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 TestAliyunRangeCanceledInflight(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.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 err == nil { + t.Fatal("expected error after cancel") + } + case <-time.After(5 * time.Second): + t.Fatal("Range did not return after cancel") + } +} + +// TestAliyunRangeCanceledDuringBodyRead cancels the context after Range +// succeeded while a Read is blocked on an in-flight body. +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") + 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.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 err == nil { + t.Fatal("expected read error after cancel") + } + case <-time.After(5 * time.Second): + t.Fatal("Read did not return after cancel") + } +} + +func TestAliyunRangeMissing(t *testing.T) { + st := newTestStorage(t, &objectHandler{statusCode: http.StatusNotFound, errCode: "NoSuchKey"}, "") + if _, err := st.Range(context.Background(), "missing", nil); err == nil { + t.Fatal("expected error") + } +} + +func TestAliyunRangeRangeNotSatisfiable(t *testing.T) { + st := newTestStorage(t, &objectHandler{statusCode: http.StatusRequestedRangeNotSatisfiable, errCode: "InvalidRange"}, "") + _, 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 TestAliyunRangeServerIgnoresRange(t *testing.T) { + st := newTestStorage(t, &objectHandler{body: []byte("0123456789"), ignore: true}, "") + 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") + } +} + +// TestAliyunRangeRejectedRangeClosesBody ensures the response body is closed +// when a ranged response is rejected for missing Content-Range. +func TestAliyunRangeRejectedRangeClosesBody(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.Range(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") + } +} + +// TestAliyunRangeOversizedEndClamped verifies a bounded range extending past +// EOF is accepted when the server clamps the end to the last byte. +func TestAliyunRangeOversizedEndClamped(t *testing.T) { + var rangeHdr string + st := newTestStorage(t, &objectHandler{body: []byte("0123456789"), rangeHdr: &rangeHdr}, "") + + rc, err := st.Range(context.Background(), "key", &difyoss.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 rangeHdr != "bytes=8-107" { + t.Fatalf("Range header %q", rangeHdr) + } + if string(data) != "89" { + t.Fatalf("got %q", data) + } +} + +func TestAliyunRangeEmptyObject(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) + } +} + +// 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) +} + +// TestAliyunRangeStreamsBeforeFullDownload proves Range returns after headers +// and first bytes are readable while the rest is still in flight. +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") + 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.Range(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("Range: %v", r.err) + } + rc = r.rc + case <-time.After(5 * time.Second): + t.Fatal("Range 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..6597011 100644 --- a/oss/azureblob/blob.go +++ b/oss/azureblob/blob.go @@ -1,20 +1,49 @@ 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/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" "github.com/langgenius/dify-cloud-kit/oss" ) +var ( + _ oss.StreamingOSS = (*AzureBlobStorage)(nil) + _ oss.Preparer = (*AzureBlobStorage)(nil) +) + type AzureBlobStorage struct { client *azblob.Client 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 @@ -32,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) } @@ -50,30 +79,93 @@ 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 } func (a *AzureBlobStorage) Load(key string) ([]byte, error) { - get, err := a.client.DownloadStream(context.TODO(), a.containerName, key, nil) + reader, err := a.Range(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) Range(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.Body, nil } func (a *AzureBlobStorage) Exists(key string) (bool, error) { 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/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/azureblob/blob_stream_test.go b/oss/azureblob/blob_stream_test.go new file mode 100644 index 0000000..3c4795f --- /dev/null +++ b/oss/azureblob/blob_stream_test.go @@ -0,0 +1,659 @@ +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, newClientOptions()) + 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 TestAzureRangeFull(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 x-ms-range header %q", rangeHdr) + } +} + +func TestAzureRangeEmptyObject(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 TestAzureRangeBounded(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 rangeHdr != "bytes=2-5" { + t.Fatalf("x-ms-range header %q", rangeHdr) + } + if string(data) != "2345" { + t.Fatalf("got %q", data) + } +} + +func TestAzureRangeToEOF(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 rangeHdr != "bytes=4-" { + t.Fatalf("x-ms-range header %q", rangeHdr) + } + if string(data) != "456789" { + t.Fatalf("got %q", data) + } +} + +// 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 TestAzureRangeZeroToEOF(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: 0, 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 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.Range(context.Background(), "key", &oss.ByteRange{Offset: 0, Length: -1}) + if !errors.Is(err, oss.ErrRangeNotSatisfiable) { + t.Fatalf("expected ErrRangeNotSatisfiable, got %v", err) + } +} + +func TestAzureRangeOversizedEndClamped(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: 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 rangeHdr != "bytes=8-107" { + t.Fatalf("x-ms-range header %q", rangeHdr) + } + if string(data) != "89" { + t.Fatalf("got %q", data) + } +} + +func TestAzureRangeInvalidRangeNoRequest(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.Range(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 TestAzureRangeMissing(t *testing.T) { + st, _ := newTestStorage(t, &objectHandler{statusCode: http.StatusNotFound, errCode: "BlobNotFound"}) + if _, err := st.Range(context.Background(), "missing", nil); err == nil { + t.Fatal("expected error") + } +} + +func TestAzureRangeRangeNotSatisfiable(t *testing.T) { + st, _ := newTestStorage(t, &objectHandler{statusCode: http.StatusRequestedRangeNotSatisfiable, errCode: "InvalidRange"}) + _, 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) + } +} + +// TestAzureRangePlain416 verifies HTTP 416 maps to ErrRangeNotSatisfiable even +// without an XML error body. +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")) + })) + 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.Range(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"} +} + +// TestAzureRangeRejectedRangeClosesBody ensures the response body is closed +// when a ranged response is rejected for a missing or mismatched +// Content-Range. +func TestAzureRangeRejectedRangeClosesBody(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.Range(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 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.Range(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 TestAzureRangeCanceledInflight(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.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 err == nil { + t.Fatal("expected error after cancel") + } + case <-time.After(5 * time.Second): + t.Fatal("Range did not return after cancel") + } +} + +// TestAzureRangeCanceledDuringBodyRead cancels the context after Range +// succeeded while a Read is blocked on an in-flight body. +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") + 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.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 err == nil { + t.Fatal("expected read error after cancel") + } + case <-time.After(5 * time.Second): + t.Fatal("Read did not return after cancel") + } +} + +// 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 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") + 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.Range(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("Range: %v", r.err) + } + rc = r.rc + case <-time.After(5 * time.Second): + t.Fatal("Range 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") + } +} + +// 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) + } + st := &AzureBlobStorage{client: client, containerName: "cont"} + + 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.Fatal("expected truncated read to fail") + } + if string(data) != "abc" { + t.Fatalf("got %q", data) + } + if n := atomic.LoadInt32(&requests); n != 1 { + t.Fatalf("expected 1 request, got %d", n) + } +} + +// 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) + } + 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) + } + + 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") + } + + time.Sleep(100 * time.Millisecond) + if n := atomic.LoadInt32(&requests); n != 1 { + t.Fatalf("expected 1 request after Close, got %d", n) + } +} + +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; 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") + } + 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/gcsblob/gcs.go b/oss/gcsblob/gcs.go index 7de2566..ba97e94 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,64 @@ 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: 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 { + return err + } + if g.project == "" { + return fmt.Errorf("gcs: cannot prepare bucket %q without a project ID (set GoogleCloudStorage.Project)", g.bucket) + } + 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 { + 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) @@ -64,17 +121,78 @@ 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() + + 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) - data, err := io.ReadAll(rc) + 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 { + // 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 + } + // 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, fmt.Errorf("server did not honor requested range %v: response has neither Content-Range nor Content-Length", *byteRange) + } + } + + 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..812139e --- /dev/null +++ b/oss/gcsblob/gcs_prepare_test.go @@ -0,0 +1,169 @@ +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) +} + +// 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) + 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: %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 != 0 { + t.Fatalf("expected no create call, 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..f23bba3 --- /dev/null +++ b/oss/gcsblob/gcs_stream_test.go @@ -0,0 +1,478 @@ +package gcsblob + +import ( + "bytes" + "compress/gzip" + "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 + 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) + } + 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 { + h.write(w, http.StatusOK, "", 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 + } + 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) { + 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 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}) + + _, err := st.Range(context.Background(), "key", &oss.ByteRange{Offset: 2, Length: 4}) + if err == nil { + t.Fatal("expected error when server ignores the range") + } +} + +// 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")}) + + 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 { diff --git a/oss/local/localfile.go b/oss/local/localfile.go index aebe0fb..be22f94 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.Range(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) 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 + } + 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..2b92e10 --- /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 rangeReader(t *testing.T, st *LocalStorage, key string, r *oss.ByteRange) io.ReadCloser { + t.Helper() + rc, err := st.Range(context.Background(), key, r) + if err != nil { + t.Fatalf("Range: %v", err) + } + t.Cleanup(func() { rc.Close() }) + return rc +} + +func TestLocalRangeFull(t *testing.T) { + st := newTestStorage(t) + writeFile(t, st, "a/b.bin", []byte("hello world")) + + rc := rangeReader(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 TestLocalRangeFullEmptyFile(t *testing.T) { + st := newTestStorage(t) + writeFile(t, st, "empty", nil) + + rc := rangeReader(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 TestLocalRangeBounded(t *testing.T) { + st := newTestStorage(t) + writeFile(t, st, "f", []byte("0123456789")) + + rc := rangeReader(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 TestLocalRangeToEOF(t *testing.T) { + st := newTestStorage(t) + writeFile(t, st, "f", []byte("0123456789")) + + rc := rangeReader(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 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 := rangeReader(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 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 := rangeReader(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 TestLocalRangeMissing(t *testing.T) { + st := newTestStorage(t) + if _, err := st.Range(context.Background(), "nope", nil); err == nil { + t.Fatal("expected error for missing key") + } +} + +func TestLocalRangeUnsatisfiable(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.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 TestLocalRangeInvalidRange(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.Range(context.Background(), "f", &r); !errors.Is(err, oss.ErrInvalidRange) { + t.Fatalf("range=%+v: expected ErrInvalidRange, got %v", r, err) + } + } +} + +func TestLocalRangeCanceledBefore(t *testing.T) { + st := newTestStorage(t) + writeFile(t, st, "f", []byte("0123456789")) + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if _, err := st.Range(ctx, "f", nil); err == nil { + t.Fatal("expected context error") + } +} + +func TestLocalRangeCanceledDuringRead(t *testing.T) { + st := newTestStorage(t) + writeFile(t, st, "f", []byte("0123456789")) + + ctx, cancel := context.WithCancel(context.Background()) + rc, err := st.Range(ctx, "f", nil) + if err != nil { + t.Fatalf("Range: %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 TestLocalRangeClosedResource(t *testing.T) { + st := newTestStorage(t) + writeFile(t, st, "f", []byte("0123456789")) + + rc, err := st.Range(context.Background(), "f", nil) + if err != nil { + t.Fatalf("Range: %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 TestLocalRangeLoadStillWorks(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/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/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/oss/s3/s3.go b/oss/s3/s3.go index 408e7f0..73c5097 100644 --- a/oss/s3/s3.go +++ b/oss/s3/s3.go @@ -4,21 +4,40 @@ import ( "bytes" "context" "errors" + "fmt" "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" + "github.com/aws/aws-sdk-go-v2/service/s3/types" "github.com/aws/smithy-go" "github.com/langgenius/dify-cloud-kit/oss" ) +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) { @@ -105,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), @@ -112,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 { @@ -128,7 +150,7 @@ func normalizeSignatureVersion(version string) string { case "unsigned": return "" case "": - return "v4" // ้ป˜่ฎคไฝฟ็”จ v4 + return "v4" // ้ป˜่ฎคไฝฟ็”จ v4 default: return version } @@ -144,15 +166,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.Range(context.Background(), key, nil) + if err != nil { + return nil, err + } + defer reader.Close() + + return io.ReadAll(reader) +} + +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), - }) + } + 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) { @@ -230,6 +294,47 @@ 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, s.createBucketInput()) + if err == nil { + return nil + } + var createErr smithy.APIError + 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) +} + 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..17d10c7 --- /dev/null +++ b/oss/s3/s3_prepare_test.go @@ -0,0 +1,208 @@ +package s3 + +import ( + "context" + "errors" + "fmt" + "io" + "net/http" + "strings" + "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 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 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}) + + 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/s3/s3_stream_test.go b/oss/s3/s3_stream_test.go new file mode 100644 index 0000000..7e1f1e5 --- /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 TestS3RangeFull(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 TestS3RangeBounded(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 rangeHdr != "bytes=2-5" { + t.Fatalf("Range header %q", rangeHdr) + } + if string(data) != "2345" { + t.Fatalf("got %q", data) + } +} + +func TestS3RangeOpenEnded(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 rangeHdr != "bytes=4-" { + t.Fatalf("Range header %q", rangeHdr) + } + if string(data) != "456789" { + t.Fatalf("got %q", data) + } +} + +func TestS3RangeInvalidRangeNoRequest(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.Range(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 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.Range(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 TestS3RangeCanceledInflight(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.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") + } +} + +// TestS3RangeCanceledDuringBodyRead cancels the context after Range succeeded +// while a Read is blocked on an in-flight body. +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") + 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.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 err == nil { + t.Fatal("expected read error after cancel") + } + case <-time.After(5 * time.Second): + t.Fatal("Read did not return after cancel") + } +} + +func TestS3RangeMissing(t *testing.T) { + st, _ := newTestStorage(t, &objectHandler{statusCode: http.StatusNotFound, errCode: "NoSuchKey"}) + if _, err := st.Range(context.Background(), "missing", nil); err == nil { + t.Fatal("expected error") + } +} + +func TestS3RangeRangeNotSatisfiable(t *testing.T) { + st, _ := newTestStorage(t, &objectHandler{statusCode: http.StatusRequestedRangeNotSatisfiable, errCode: "InvalidRange"}) + _, 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) + } +} + +// TestS3RangePlain416 verifies HTTP 416 maps to ErrRangeNotSatisfiable even +// when the error body carries no InvalidRange code. +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")) + })) + 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.Range(context.Background(), "key", &oss.ByteRange{Offset: 100, Length: 1}) + if !errors.Is(err, oss.ErrRangeNotSatisfiable) { + t.Fatalf("expected ErrRangeNotSatisfiable, got %v", err) + } +} + +// TestS3RangeOversizedEndClamped verifies a bounded range extending past EOF +// is accepted when the server clamps the end to the last byte. +func TestS3RangeOversizedEndClamped(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: 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 rangeHdr != "bytes=8-107" { + t.Fatalf("Range header %q", rangeHdr) + } + if string(data) != "89" { + t.Fatalf("got %q", data) + } +} + +func TestS3RangeEmptyObject(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) + } +} + +// TestS3RangeRejectedRangeClosesBody ensures the response body is closed when +// a ranged response is rejected for missing Content-Range. +func TestS3RangeRejectedRangeClosesBody(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.Range(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 TestS3RangeServerIgnoresRange(t *testing.T) { + st, _ := newTestStorage(t, &objectHandler{body: []byte("0123456789"), ignore: true}) + 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") + } +} + +// TestS3RangeStreamsBeforeFullDownload proves Range returns after headers and +// the first bytes are readable while the rest of the body is still in flight. +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") + 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.Range(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("Range: %v", r.err) + } + rc = r.rc + case <-time.After(5 * time.Second): + t.Fatal("Range 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..0e4d0ef --- /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 + // 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. + Range(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 Range. 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.Range(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..2b687d9 --- /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) Range(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("Range 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) + } +} 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 new file mode 100644 index 0000000..a4b87fd --- /dev/null +++ b/tests/integration/azure_test.go @@ -0,0 +1,220 @@ +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" +) + +// 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" + + // 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") + } + + t.Cleanup(func() { + for _, k := range []string{objKey, emptyKey} { + if err := store.Delete(k); err != nil { + t.Logf("cleanup Delete %s: %v", k, 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) + } + 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) + } + } + + // 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) +} + +// 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)) + } + }) + } +} diff --git a/tests/integration/common_test.go b/tests/integration/common_test.go new file mode 100644 index 0000000..51261c5 --- /dev/null +++ b/tests/integration/common_test.go @@ -0,0 +1,251 @@ +package integration + +import ( + "context" + "errors" + "io" + "math" + "testing" + "time" + + "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. +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("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) { + 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("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() + 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/gcs_test.go b/tests/integration/gcs_test.go new file mode 100644 index 0000000..63efaf5 --- /dev/null +++ b/tests/integration/gcs_test.go @@ -0,0 +1,72 @@ +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.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 { + 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 new file mode 100644 index 0000000..c854fa3 --- /dev/null +++ b/tests/integration/s3_test.go @@ -0,0 +1,76 @@ +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 localstackEndpoint = "http://127.0.0.1:14566" + +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" + + // 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, + 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) + } + 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.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 { + 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) +}