This commit is contained in:
Vladislav Kunetskiy
2026-11-06 17:30:30 +03:00
parent 470d9d6f1e
commit 5fda36b723
481 changed files with 84873 additions and 57 deletions
@@ -0,0 +1,34 @@
// Package objectstore defines the S3-compatible port used by attachments.
// Metadata never belongs here: PostgreSQL is the source of truth, this package
// only moves bytes and exposes object timestamps for the orphan sweeper.
package objectstore
import (
"context"
"io"
"time"
)
// Object is the provider-neutral view of one stored object.
type Object struct {
Key string
Size int64
ContentType string
LastModified time.Time
Metadata map[string]string
}
// Store is implemented by S3-compatible backends. Put requires a seekable body
// because AWS SigV4 may need to rewind the payload; the proxy upload path always
// passes an *os.File.
type Store interface {
// Ping verifies that the bucket is reachable and the credentials are valid.
Ping(ctx context.Context) error
Put(ctx context.Context, key string, body io.ReadSeeker, size int64, contentType string, metadata map[string]string) error
Open(ctx context.Context, key string) (io.ReadCloser, Object, error)
Head(ctx context.Context, key string) (Object, error)
Copy(ctx context.Context, src, dst, contentType string, metadata map[string]string) error
Delete(ctx context.Context, key string) error
List(ctx context.Context, prefix string) ([]Object, error)
PresignPut(ctx context.Context, key string, size int64, ttl time.Duration) (string, time.Time, error)
}
+305
View File
@@ -0,0 +1,305 @@
package objectstore
import (
"context"
"errors"
"fmt"
"io"
"net"
"net/http"
"strings"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/credentials"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/aws-sdk-go-v2/service/s3/types"
"github.com/aws/smithy-go"
"mtusi-messenger/internal/domain"
)
// Config is the S3 connection subset. Limits belong to the attachment service.
type Config struct {
Endpoint string
PublicEndpoint string
Region string
Bucket string
AccessKeyID string
SecretAccessKey string
UsePathStyle bool
Timeout time.Duration
}
// S3 is an object store backed by an S3-compatible server (SeaweedFS in the
// lab stand, MinIO/AWS in other deployments).
type S3 struct {
bucket string
internal *s3.Client
public *s3.Client
timeout time.Duration
}
var _ Store = (*S3)(nil)
func New(cfg Config) (*S3, error) {
if cfg.Endpoint == "" || cfg.Region == "" || cfg.Bucket == "" {
return nil, errors.New("object store: endpoint, region and bucket are required")
}
if cfg.AccessKeyID == "" || cfg.SecretAccessKey == "" {
return nil, errors.New("object store: access key id and secret access key are required")
}
if cfg.PublicEndpoint == "" {
cfg.PublicEndpoint = cfg.Endpoint
}
httpClient := &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 3 * time.Second,
KeepAlive: 30 * time.Second,
}).DialContext,
TLSHandshakeTimeout: 3 * time.Second,
ResponseHeaderTimeout: 15 * time.Second,
MaxIdleConnsPerHost: 16,
IdleConnTimeout: 90 * time.Second,
},
// Downloads stream through the response body; an overall client
// timeout would abort them.
}
newClient := func(endpoint string) *s3.Client {
return s3.New(s3.Options{
Region: cfg.Region,
BaseEndpoint: aws.String(endpoint),
UsePathStyle: cfg.UsePathStyle,
Credentials: credentials.NewStaticCredentialsProvider(cfg.AccessKeyID, cfg.SecretAccessKey, ""),
HTTPClient: httpClient,
})
}
st := &S3{
bucket: cfg.Bucket,
internal: newClient(cfg.Endpoint),
public: newClient(cfg.PublicEndpoint),
timeout: cfg.Timeout,
}
return st, nil
}
func (s *S3) Ping(ctx context.Context) error {
// HeadBucket needs bucket-level permissions that the application identity
// intentionally does not have. A HeadObject on a sentinel staging key is
// enough to prove connectivity and the object-level credentials; a missing
// sentinel is the expected healthy result.
_, err := s.Head(ctx, "staging/.health/ping")
if err == nil || errors.Is(err, domain.ErrNotFound) {
return nil
}
return err
}
func (s *S3) Put(
ctx context.Context,
key string,
body io.ReadSeeker,
size int64,
contentType string,
metadata map[string]string,
) error {
ctx, cancel := s.operationContext(ctx)
defer cancel()
_, err := s.internal.PutObject(ctx, &s3.PutObjectInput{
Bucket: aws.String(s.bucket),
Key: aws.String(key),
Body: body,
ContentLength: aws.Int64(size),
ContentType: aws.String(contentType),
Metadata: metadata,
})
if err != nil {
return mapObjectError("put object", key, err)
}
return nil
}
func (s *S3) Open(ctx context.Context, key string) (io.ReadCloser, Object, error) {
output, err := s.internal.GetObject(ctx, &s3.GetObjectInput{
Bucket: aws.String(s.bucket),
Key: aws.String(key),
})
if err != nil {
return nil, Object{}, mapObjectError("open object", key, err)
}
object := Object{
Key: key,
Size: aws.ToInt64(output.ContentLength),
ContentType: aws.ToString(output.ContentType),
LastModified: aws.ToTime(output.LastModified),
Metadata: output.Metadata,
}
return output.Body, object, nil
}
func (s *S3) Head(ctx context.Context, key string) (Object, error) {
output, err := s.internal.HeadObject(ctx, &s3.HeadObjectInput{
Bucket: aws.String(s.bucket),
Key: aws.String(key),
})
if err != nil {
return Object{}, mapObjectError("head object", key, err)
}
return Object{
Key: key,
Size: aws.ToInt64(output.ContentLength),
ContentType: aws.ToString(output.ContentType),
LastModified: aws.ToTime(output.LastModified),
Metadata: output.Metadata,
}, nil
}
func (s *S3) Copy(ctx context.Context, src, dst, contentType string, metadata map[string]string) error {
ctx, cancel := s.operationContext(ctx)
defer cancel()
_, err := s.internal.CopyObject(ctx, &s3.CopyObjectInput{
Bucket: aws.String(s.bucket),
Key: aws.String(dst),
CopySource: aws.String(s.bucket + "/" + src),
MetadataDirective: types.MetadataDirectiveReplace,
ContentType: aws.String(contentType),
Metadata: metadata,
})
if err != nil {
return mapObjectError("copy object", src+" -> "+dst, err)
}
return nil
}
func (s *S3) Delete(ctx context.Context, key string) error {
ctx, cancel := s.operationContext(ctx)
defer cancel()
_, err := s.internal.DeleteObject(ctx, &s3.DeleteObjectInput{
Bucket: aws.String(s.bucket),
Key: aws.String(key),
})
if err != nil {
return mapObjectError("delete object", key, err)
}
return nil
}
func (s *S3) List(ctx context.Context, prefix string) ([]Object, error) {
ctx, cancel := s.operationContext(ctx)
defer cancel()
var (
objects []Object
token *string
)
for {
output, err := s.internal.ListObjectsV2(ctx, &s3.ListObjectsV2Input{
Bucket: aws.String(s.bucket),
Prefix: aws.String(prefix),
ContinuationToken: token,
})
if err != nil {
return nil, mapObjectError("list objects", prefix, err)
}
for _, item := range output.Contents {
objects = append(objects, Object{
Key: aws.ToString(item.Key),
Size: aws.ToInt64(item.Size),
LastModified: aws.ToTime(item.LastModified),
})
}
if !aws.ToBool(output.IsTruncated) {
break
}
token = output.NextContinuationToken
if token == nil || *token == "" {
break
}
}
return objects, nil
}
// PresignPut signs the bucket, key, host and exact Content-Length. The size is
// therefore enforced by S3 at write time: a client that uploads a different
// number of bytes gets 403 SignatureDoesNotMatch. Content-Type and checksums
// are not signed (SeaweedFS does not validate checksums); completion verifies
// the actual bytes and their structure.
func (s *S3) PresignPut(
ctx context.Context,
key string,
size int64,
ttl time.Duration,
) (string, time.Time, error) {
expiresAt := time.Now().UTC().Add(ttl)
presigned, err := s3.NewPresignClient(s.public).PresignPutObject(
ctx,
&s3.PutObjectInput{
Bucket: aws.String(s.bucket),
Key: aws.String(key),
ContentLength: aws.Int64(size),
},
func(options *s3.PresignOptions) {
options.Expires = ttl
},
)
if err != nil {
return "", time.Time{}, mapObjectError("presign put", key, err)
}
return presigned.URL, expiresAt, nil
}
func (s *S3) operationContext(ctx context.Context) (context.Context, context.CancelFunc) {
if s.timeout <= 0 {
return context.WithCancel(ctx)
}
return context.WithTimeout(ctx, s.timeout)
}
func mapObjectError(operation, subject string, err error) error {
var apiErr smithy.APIError
if errors.As(err, &apiErr) {
switch apiErr.ErrorCode() {
case "NoSuchBucket":
return fmt.Errorf("%w: %s %q: %w", domain.ErrUnavailable, operation, subject, err)
case "NotFound", "NoSuchKey":
return fmt.Errorf("%s %q: %w", operation, subject, domain.ErrNotFound)
}
}
if errors.Is(err, context.Canceled) {
return fmt.Errorf("%s %q: %w", operation, subject, err)
}
if strings.Contains(strings.ToLower(err.Error()), "no such key") {
return fmt.Errorf("%s %q: %w", operation, subject, domain.ErrNotFound)
}
return fmt.Errorf("%w: %s %q: %w", domain.ErrUnavailable, operation, subject, err)
}
+26
View File
@@ -0,0 +1,26 @@
package objectstore
import (
"testing"
"github.com/aws/smithy-go"
"github.com/stretchr/testify/require"
"mtusi-messenger/internal/domain"
)
func TestMapObjectErrorBucketIsUnavailable(t *testing.T) {
err := mapObjectError("put object", "key", &smithy.GenericAPIError{
Code: "NoSuchBucket",
Message: "bucket is missing",
})
require.ErrorIs(t, err, domain.ErrUnavailable)
}
func TestMapObjectErrorMissingKeyIsNotFound(t *testing.T) {
err := mapObjectError("open object", "key", &smithy.GenericAPIError{
Code: "NoSuchKey",
Message: "object is missing",
})
require.ErrorIs(t, err, domain.ErrNotFound)
}