293 lines
7.3 KiB
Go
293 lines
7.3 KiB
Go
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) 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)
|
|
}
|