feat(storage): add private file layer and isolate SeaweedFS on a storage network

This commit is contained in:
shira committed 2026-10-06 13:51:53 +03:00
1 parent f5b07e8f4d
commit 8378ad45b0
22 files changed
+1668 -40

No files matched your search

@@ -40,6 +40,12 @@ var (
)
// NewStorage creates a lazy S3 client. Deployment owns bucket provisioning.
//
// SEAWEEDFS_TIMEOUT bounds connection setup, the TLS handshake, the wait for
// response headers, and whole Delete and readiness calls. It does not bound
// object body transfer in Put and Get: the duration depends on file size and
// client speed, which only the caller knows, so the caller's context and the
// source deadline govern the stream.
func NewStorage(settings config.Config) (*Storage, func(), error) {
if err := settings.ValidateSeaweedFS(); err != nil {
return nil, nil, err
@@ -60,9 +66,9 @@ func NewStorage(settings config.Config) (*Storage, func(), error) {
BaseEndpoint: aws.String(settings.SeaweedFSEndpoint),
UsePathStyle: true,
Credentials: credentials.NewStaticCredentialsProvider(settings.SeaweedFSAccessKey, settings.SeaweedFSSecretKey, ""),
// No Client.Timeout: it would cut long object bodies; see above.
HTTPClient: &http.Client{
Transport: transport,
Timeout: settings.SeaweedFSTimeout,
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
},
// A non-seekable upload cannot be replayed safely.
@@ -78,8 +84,6 @@ func (storage *Storage) Put(ctx context.Context, key string, body io.Reader, siz
if key == "" || body == nil || size < 0 {
return fmt.Errorf("Storage.Put - validate input: %w", outbound.ErrInvalidObject)
}
ctx, cancel := context.WithTimeout(ctx, storage.timeout)
defer cancel()
_, err := storage.client.PutObject(ctx, &s3.PutObjectInput{
Bucket: aws.String(storage.bucket),
Key: aws.String(key),
@@ -97,7 +101,9 @@ func (storage *Storage) Get(ctx context.Context, key string) (outbound.Object, e
if key == "" {
return outbound.Object{}, fmt.Errorf("Storage.Get - validate key: %w", outbound.ErrInvalidObject)
}
ctx, cancel := context.WithTimeout(ctx, storage.timeout)
// Close or a read error cancels the request; the transfer itself is bounded
// only by the caller's context.
ctx, cancel := context.WithCancel(ctx)
result, err := storage.client.GetObject(ctx, &s3.GetObjectInput{Bucket: aws.String(storage.bucket), Key: aws.String(key)})
if err != nil {
cancel()
@@ -8,6 +8,7 @@ import (
"io"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"sync/atomic"
"testing"
@@ -81,8 +82,8 @@ func TestStorageGetKeepsBodyAliveUntilClose(t *testing.T) {
}
}
func TestStorageGetBodyHonorsCancellationAndTimeout(t *testing.T) {
for _, mode := range []string{"caller", "timeout", "close"} {
func TestStorageGetBodyHonorsCancellationAndDeadline(t *testing.T) {
for _, mode := range []string{"caller", "deadline", "close"} {
t.Run(mode, func(t *testing.T) {
disconnected := make(chan struct{})
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -93,13 +94,13 @@ func TestStorageGetBodyHonorsCancellationAndTimeout(t *testing.T) {
close(disconnected)
}))
defer server.Close()
timeout := time.Second
if mode == "timeout" {
timeout = 100 * time.Millisecond
}
storage := newTestStorage(t, server.URL, timeout)
storage := newTestStorage(t, server.URL, time.Second)
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
if mode == "deadline" {
ctx, cancel = context.WithTimeout(ctx, 100*time.Millisecond)
defer cancel()
}
object, err := storage.Get(ctx, "private/file")
if err != nil {
t.Fatal(err)
@@ -110,7 +111,7 @@ func TestStorageGetBodyHonorsCancellationAndTimeout(t *testing.T) {
if err := object.Body.Close(); err != nil {
t.Fatal(err)
}
case "caller", "timeout":
case "caller", "deadline":
want := context.DeadlineExceeded
if mode == "caller" {
cancel()
@@ -129,6 +130,110 @@ func TestStorageGetBodyHonorsCancellationAndTimeout(t *testing.T) {
}
}
func TestStorageStreamsBodiesLongerThanTimeout(t *testing.T) {
const (
timeout = 100 * time.Millisecond
chunks = 5
pause = 60 * time.Millisecond
)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPut {
if _, err := io.Copy(io.Discard, r.Body); err != nil {
t.Errorf("read slow upload: %v", err)
}
w.WriteHeader(http.StatusOK)
return
}
w.Header().Set("Content-Length", strconv.Itoa(chunks))
w.WriteHeader(http.StatusOK)
for range chunks {
_, _ = io.WriteString(w, "x")
w.(http.Flusher).Flush()
time.Sleep(pause)
}
}))
defer server.Close()
storage := newTestStorage(t, server.URL, timeout)
start := time.Now()
source := &slowReader{data: bytes.Repeat([]byte("x"), chunks), pause: pause}
if err := storage.Put(t.Context(), "private/file", source, chunks, "text/plain"); err != nil {
t.Fatalf("slow upload was cut: %v", err)
}
object, err := storage.Get(t.Context(), "private/file")
if err != nil {
t.Fatal(err)
}
defer object.Body.Close()
data, err := io.ReadAll(object.Body)
if err != nil || len(data) != chunks {
t.Fatalf("slow download was cut: %d bytes, %v", len(data), err)
}
if elapsed := time.Since(start); elapsed < 2*timeout {
t.Fatalf("transfers took %v, too fast to prove the timeout does not apply", elapsed)
}
}
func TestStorageBoundsResponseHeaders(t *testing.T) {
const timeout = 100 * time.Millisecond
release := make(chan struct{})
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = io.Copy(io.Discard, r.Body)
select {
case <-release:
case <-r.Context().Done():
}
w.WriteHeader(http.StatusOK)
}))
defer server.Close()
defer close(release)
storage := newTestStorage(t, server.URL, timeout)
for name, call := range map[string]func() error{
"get": func() error { _, err := storage.Get(t.Context(), "file"); return err },
"put": func() error { return storage.Put(t.Context(), "file", strings.NewReader("data"), 4, "text/plain") },
} {
t.Run(name, func(t *testing.T) {
start := time.Now()
// The caller's context has no deadline, so this is the adapter bound.
if err := call(); !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("stalled headers: %v", err)
}
if elapsed := time.Since(start); elapsed > 10*timeout {
t.Fatalf("response header bound took %v", elapsed)
}
})
}
}
func TestStorageBoundsConnectionSetup(t *testing.T) {
const timeout = 100 * time.Millisecond
// A TEST-NET-1 address (RFC 5737) is never routed, so the dial either
// times out or fails at once; it must not wait for the caller.
storage := newTestStorage(t, "http://192.0.2.1:8333", timeout)
start := time.Now()
if _, err := storage.Get(t.Context(), "file"); err == nil {
t.Fatal("unreachable endpoint returned an object")
}
if elapsed := time.Since(start); elapsed > 10*timeout {
t.Fatalf("dial bound took %v", elapsed)
}
}
type slowReader struct {
data []byte
pause time.Duration
}
func (reader *slowReader) Read(buffer []byte) (int, error) {
if len(reader.data) == 0 {
return 0, io.EOF
}
time.Sleep(reader.pause)
n := copy(buffer[:1], reader.data)
reader.data = reader.data[n:]
return n, nil
}
func TestStorageClassifiesOnlyMissingObjectsAsNotFound(t *testing.T) {
for _, test := range []struct {
name, code string