package seaweedfs import ( "context" "errors" "fmt" "io" "net" "net/http" "time" "github.com/aws/aws-sdk-go-v2/aws" v4 "github.com/aws/aws-sdk-go-v2/aws/signer/v4" "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" smithyhttp "github.com/aws/smithy-go/transport/http" "lincodex/backend/config" "lincodex/backend/internal/port/outbound" ) const ( connectionKeepAlive = 30 * time.Second maxIdleConnections = 10 maxConnectionsPerHost = 20 idleConnectionTimeout = 90 * time.Second expectContinueTimeout = time.Second ) type Storage struct { client *s3.Client bucket string timeout time.Duration } var ( _ outbound.ObjectStorage = (*Storage)(nil) _ outbound.ReadinessChecker = (*Storage)(nil) ) // 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 } transport := &http.Transport{ DialContext: (&net.Dialer{Timeout: settings.SeaweedFSTimeout, KeepAlive: connectionKeepAlive}).DialContext, ForceAttemptHTTP2: true, MaxIdleConns: maxIdleConnections, MaxIdleConnsPerHost: maxIdleConnections, MaxConnsPerHost: maxConnectionsPerHost, IdleConnTimeout: idleConnectionTimeout, TLSHandshakeTimeout: settings.SeaweedFSTimeout, ResponseHeaderTimeout: settings.SeaweedFSTimeout, ExpectContinueTimeout: expectContinueTimeout, } client := s3.New(s3.Options{ Region: settings.SeaweedFSRegion, 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, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, }, // A non-seekable upload cannot be replayed safely. Retryer: aws.NopRetryer{}, RequestChecksumCalculation: aws.RequestChecksumCalculationWhenRequired, ResponseChecksumValidation: aws.ResponseChecksumValidationWhenRequired, DisableLogOutputChecksumValidationSkipped: true, }) return &Storage{client: client, bucket: settings.SeaweedFSBucket, timeout: settings.SeaweedFSTimeout}, transport.CloseIdleConnections, nil } func (storage *Storage) Put(ctx context.Context, key string, body io.Reader, size int64, contentType string) error { if key == "" || body == nil || size < 0 { return fmt.Errorf("Storage.Put - validate input: %w", outbound.ErrInvalidObject) } _, err := storage.client.PutObject(ctx, &s3.PutObjectInput{ Bucket: aws.String(storage.bucket), Key: aws.String(key), Body: body, ContentLength: aws.Int64(size), ContentType: aws.String(contentType), }, s3.WithAPIOptions(v4.SwapComputePayloadSHA256ForUnsignedPayloadMiddleware)) if err != nil { return fmt.Errorf("Storage.Put - put object: %w", safeError(err)) } return nil } func (storage *Storage) Get(ctx context.Context, key string) (outbound.Object, error) { if key == "" { return outbound.Object{}, fmt.Errorf("Storage.Get - validate key: %w", outbound.ErrInvalidObject) } // 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() var missing *types.NoSuchKey if errors.As(err, &missing) { return outbound.Object{}, fmt.Errorf("Storage.Get - get object: %w", outbound.ErrObjectNotFound) } return outbound.Object{}, fmt.Errorf("Storage.Get - get object: %w", safeError(err)) } return outbound.Object{ Body: &objectBody{body: result.Body, cancel: cancel}, Size: aws.ToInt64(result.ContentLength), ContentType: aws.ToString(result.ContentType), }, nil } func (storage *Storage) Delete(ctx context.Context, key string) error { if key == "" { return fmt.Errorf("Storage.Delete - validate key: %w", outbound.ErrInvalidObject) } ctx, cancel := context.WithTimeout(ctx, storage.timeout) defer cancel() _, err := storage.client.DeleteObject(ctx, &s3.DeleteObjectInput{Bucket: aws.String(storage.bucket), Key: aws.String(key)}) if err != nil { return fmt.Errorf("Storage.Delete - delete object: %w", safeError(err)) } return nil } func (storage *Storage) Check(ctx context.Context) error { ctx, cancel := context.WithTimeout(ctx, storage.timeout) defer cancel() _, err := storage.client.HeadBucket(ctx, &s3.HeadBucketInput{Bucket: aws.String(storage.bucket)}) if err != nil { return fmt.Errorf("Storage.Check - check bucket: %w", safeError(err)) } return nil } // safeError keeps cancellation identifiable without exposing SDK URLs, keys, // credentials, or server-controlled messages in application errors and logs. func safeError(err error) error { switch { case errors.Is(err, context.Canceled): return context.Canceled case errors.Is(err, context.DeadlineExceeded): return context.DeadlineExceeded default: var response *smithyhttp.ResponseError if errors.As(err, &response) { return fmt.Errorf("seaweedfs.safeError - HTTP %d: %w", response.HTTPStatusCode(), outbound.ErrObjectStorage) } return outbound.ErrObjectStorage } } type objectBody struct { body io.ReadCloser cancel context.CancelFunc } func (body *objectBody) Read(buffer []byte) (int, error) { n, err := body.body.Read(buffer) if err != nil { body.cancel() if !errors.Is(err, io.EOF) { return n, fmt.Errorf("objectBody.Read - read object body: %w", safeError(err)) } } return n, err } func (body *objectBody) Close() error { defer body.cancel() if err := body.body.Close(); err != nil { return fmt.Errorf("objectBody.Close - close object body: %w", safeError(err)) } return nil }