forked from mtusi2026/mtusi2026lab4
S3-вложения и сверка Postgresql с MinIO
This commit is contained in:
@@ -0,0 +1,32 @@
|
||||
// Хранилище байтов вложения. Реализация — приватный S3-совместимый bucket.
|
||||
// Ключ задаёт вызывающий код; имя файла пользователя сюда не попадает.
|
||||
package blob
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrNotFound = errors.New("blob not found")
|
||||
ErrUnavailable = errors.New("blob unavailable")
|
||||
)
|
||||
|
||||
// Object — запись листинга. LastModified нужен сверке, чтобы не удалять свежий объект.
|
||||
type Object struct {
|
||||
Key string
|
||||
Size int64
|
||||
Modified time.Time
|
||||
}
|
||||
|
||||
// Store — операции, которые нужны загрузке, скачиванию и сверке.
|
||||
type Store interface {
|
||||
Ping(ctx context.Context) error
|
||||
Put(ctx context.Context, key, contentType string, body []byte) error
|
||||
Get(ctx context.Context, key string) (io.ReadCloser, error)
|
||||
Delete(ctx context.Context, key string) error
|
||||
// List обходит bucket одним листингом. pages — сколько страниц S3 прочитано.
|
||||
List(ctx context.Context) (objects []Object, pages int, err error)
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package blob
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type memObj struct {
|
||||
body []byte
|
||||
modified time.Time
|
||||
}
|
||||
|
||||
// Memory - двойник bucket для тестов без MinIO.
|
||||
type Memory struct {
|
||||
mu sync.Mutex
|
||||
m map[string]memObj
|
||||
}
|
||||
|
||||
func NewMemory() *Memory {
|
||||
return &Memory{m: map[string]memObj{}}
|
||||
}
|
||||
|
||||
func (m *Memory) Ping(ctx context.Context) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Memory) Put(ctx context.Context, key, _ string, body []byte) error {
|
||||
return m.PutAt(ctx, key, body, time.Now().UTC())
|
||||
}
|
||||
|
||||
// PutAt записывает объект с заданным временем.
|
||||
func (m *Memory) PutAt(ctx context.Context, key string, body []byte, modified time.Time) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.m[key] = memObj{body: append([]byte(nil), body...), modified: modified.UTC()}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Memory) Get(ctx context.Context, key string) (io.ReadCloser, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
obj, ok := m.m[key]
|
||||
if !ok {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return io.NopCloser(bytes.NewReader(obj.body)), nil
|
||||
}
|
||||
|
||||
func (m *Memory) Delete(ctx context.Context, key string) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
delete(m.m, key)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Memory) List(ctx context.Context) ([]Object, int, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, 0, ErrUnavailable
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
out := make([]Object, 0, len(m.m))
|
||||
for key, obj := range m.m {
|
||||
out = append(out, Object{Key: key, Size: int64(len(obj.body)), Modified: obj.modified})
|
||||
}
|
||||
pages := 1
|
||||
if len(out) == 0 {
|
||||
pages = 1
|
||||
}
|
||||
return out, pages, nil
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package blob
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio-go/v7/pkg/credentials"
|
||||
)
|
||||
|
||||
// S3 - path-style клиент одного bucket. Учётные данные - отдельный пользователь.
|
||||
type S3 struct {
|
||||
client *minio.Client
|
||||
bucket string
|
||||
}
|
||||
|
||||
func Open(endpoint, region, bucket, accessKey, secretKey string) (*S3, error) {
|
||||
u, err := url.Parse(endpoint)
|
||||
if err != nil || u.Host == "" || bucket == "" || accessKey == "" || secretKey == "" {
|
||||
return nil, errors.New("s3 config")
|
||||
}
|
||||
secure := u.Scheme == "https"
|
||||
client, err := minio.New(u.Host, &minio.Options{
|
||||
Creds: credentials.NewStaticV4(accessKey, secretKey, ""),
|
||||
Secure: secure,
|
||||
Region: region,
|
||||
BucketLookup: minio.BucketLookupPath,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &S3{client: client, bucket: bucket}, nil
|
||||
}
|
||||
|
||||
func (s *S3) Ping(ctx context.Context) error {
|
||||
ok, err := s.client.BucketExists(ctx, s.bucket)
|
||||
if err != nil || !ok {
|
||||
return ErrUnavailable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *S3) Put(ctx context.Context, key, contentType string, body []byte) error {
|
||||
_, err := s.client.PutObject(ctx, s.bucket, key, bytes.NewReader(body), int64(len(body)), minio.PutObjectOptions{
|
||||
ContentType: contentType,
|
||||
})
|
||||
if err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *S3) Get(ctx context.Context, key string) (io.ReadCloser, error) {
|
||||
_, err := s.client.StatObject(ctx, s.bucket, key, minio.StatObjectOptions{})
|
||||
if err != nil {
|
||||
if isMissing(err) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
obj, err := s.client.GetObject(ctx, s.bucket, key, minio.GetObjectOptions{})
|
||||
if err != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
return obj, nil
|
||||
}
|
||||
|
||||
func (s *S3) Delete(ctx context.Context, key string) error {
|
||||
err := s.client.RemoveObject(ctx, s.bucket, key, minio.RemoveObjectOptions{})
|
||||
if err != nil && !isMissing(err) {
|
||||
return ErrUnavailable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *S3) List(ctx context.Context) ([]Object, int, error) {
|
||||
ch := s.client.ListObjects(ctx, s.bucket, minio.ListObjectsOptions{Recursive: true})
|
||||
out := make([]Object, 0)
|
||||
for obj := range ch {
|
||||
if obj.Err != nil {
|
||||
return nil, 0, ErrUnavailable
|
||||
}
|
||||
out = append(out, Object{Key: obj.Key, Size: obj.Size, Modified: obj.LastModified.UTC()})
|
||||
}
|
||||
pages := 1
|
||||
if n := len(out); n > 0 {
|
||||
pages = (n + 999) / 1000
|
||||
}
|
||||
return out, pages, nil
|
||||
}
|
||||
|
||||
func isMissing(err error) bool {
|
||||
resp := minio.ToErrorResponse(err)
|
||||
switch resp.Code {
|
||||
case "NoSuchKey", "NoSuchBucket", "NotFound":
|
||||
return true
|
||||
default:
|
||||
return strings.Contains(resp.Code, "NoSuch")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user