Реализовать lab4: вложения S3/MinIO, уровень 4 и трек 2 reconciler.
Метаданные в PostgreSQL, байты в приватном bucket; sync upload 201 ready; компенсация orphan и cmd/reconcile с dry-run/apply и grace period.
This commit is contained in:
@@ -0,0 +1,162 @@
|
||||
package blob
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Memory — in-memory BlobStore для student-tests без живого MinIO.
|
||||
// Не для production: нет persistence между процессами.
|
||||
type Memory struct {
|
||||
mu sync.Mutex
|
||||
objects map[string]memObj
|
||||
down bool
|
||||
bucketOK bool
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
type memObj struct {
|
||||
data []byte
|
||||
modTime time.Time
|
||||
}
|
||||
|
||||
// NewMemory создаёт пустое хранилище с «живым» бакетом.
|
||||
func NewMemory() *Memory {
|
||||
return &Memory{
|
||||
objects: make(map[string]memObj),
|
||||
bucketOK: true,
|
||||
now: time.Now,
|
||||
}
|
||||
}
|
||||
|
||||
// SetUnavailable имитирует падение S3 (Ping/Put/Get → ErrUnavailable).
|
||||
func (m *Memory) SetUnavailable(v bool) { m.mu.Lock(); m.down = v; m.mu.Unlock() }
|
||||
|
||||
func (m *Memory) Bucket() string { return "memory" }
|
||||
|
||||
func (m *Memory) Ping(ctx context.Context) error {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
default:
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if m.down || !m.bucketOK {
|
||||
return ErrUnavailable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Memory) Put(ctx context.Context, key string, r io.Reader, size int64, _ string) error {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
default:
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if m.down {
|
||||
return ErrUnavailable
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(r, size+1))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if int64(len(data)) != size {
|
||||
return ErrUnavailable
|
||||
}
|
||||
m.objects[key] = memObj{data: append([]byte(nil), data...), modTime: m.now()}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Memory) Get(ctx context.Context, key string) (io.ReadCloser, error) {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
default:
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if m.down {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
o, ok := m.objects[key]
|
||||
if !ok {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return io.NopCloser(bytes.NewReader(o.data)), nil
|
||||
}
|
||||
|
||||
func (m *Memory) Stat(ctx context.Context, key string) (ObjectInfo, error) {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ObjectInfo{}, ctx.Err()
|
||||
default:
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if m.down {
|
||||
return ObjectInfo{}, ErrUnavailable
|
||||
}
|
||||
o, ok := m.objects[key]
|
||||
if !ok {
|
||||
return ObjectInfo{}, ErrNotFound
|
||||
}
|
||||
return ObjectInfo{Key: key, Size: int64(len(o.data)), LastModified: o.modTime}, nil
|
||||
}
|
||||
|
||||
func (m *Memory) Delete(ctx context.Context, key string) error {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
default:
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if m.down {
|
||||
return ErrUnavailable
|
||||
}
|
||||
delete(m.objects, key)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Memory) ListKeys(ctx context.Context, prefix string) ([]ObjectInfo, error) {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
default:
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if m.down {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
var out []ObjectInfo
|
||||
for k, o := range m.objects {
|
||||
if len(prefix) == 0 || (len(k) >= len(prefix) && k[:len(prefix)] == prefix) {
|
||||
out = append(out, ObjectInfo{Key: k, Size: int64(len(o.data)), LastModified: o.modTime})
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Seed кладёт объект напрямую (для тестов reconciler).
|
||||
func (m *Memory) Seed(key string, data []byte, modTime time.Time) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if modTime.IsZero() {
|
||||
modTime = m.now()
|
||||
}
|
||||
m.objects[key] = memObj{data: append([]byte(nil), data...), modTime: modTime}
|
||||
}
|
||||
|
||||
var _ interface {
|
||||
Put(ctx context.Context, key string, r io.Reader, size int64, contentType string) error
|
||||
Get(ctx context.Context, key string) (io.ReadCloser, error)
|
||||
Delete(ctx context.Context, key string) error
|
||||
Ping(ctx context.Context) error
|
||||
} = (*Memory)(nil)
|
||||
@@ -0,0 +1,197 @@
|
||||
// Package blob — тонкая обёртка над MinIO (S3 API) для оригиналов вложений lab4.
|
||||
//
|
||||
// Байты файлов живут только здесь, а не в PostgreSQL и не на диске API-реплики.
|
||||
// Ключ объекта назначает сервер (originals/<uuid>); filename клиента в ключ не попадает.
|
||||
// Bucket приватный: прямого доступа без подписи нет, скачивание идёт через авторизованный API.
|
||||
//
|
||||
// Ошибки сведены к двум классам, чтобы HTTP-слой не знал про minio-go:
|
||||
// ErrNotFound — объекта нет (404/500 по контексту), ErrUnavailable — S3 недоступен (503).
|
||||
package blob
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio-go/v7/pkg/credentials"
|
||||
)
|
||||
|
||||
// KeyPrefix — префикс ключей оригиналов. Reconciler обходит только его.
|
||||
const KeyPrefix = "originals/"
|
||||
|
||||
var (
|
||||
// ErrNotFound — такого объекта в бакете нет.
|
||||
ErrNotFound = errors.New("blob: not found")
|
||||
// ErrUnavailable — S3 не отвечает, отказал в доступе или вернул неожиданную ошибку.
|
||||
ErrUnavailable = errors.New("blob: unavailable")
|
||||
)
|
||||
|
||||
// Config — параметры подключения. Секреты приходят из окружения/файла, в логи не попадают.
|
||||
type Config struct {
|
||||
Endpoint string // host:port без схемы, например minio:9000
|
||||
UseSSL bool
|
||||
Region string
|
||||
Bucket string
|
||||
AccessKey string
|
||||
SecretKey string
|
||||
}
|
||||
|
||||
// ObjectInfo — то, что reconciler и тесты знают об объекте.
|
||||
type ObjectInfo struct {
|
||||
Key string
|
||||
Size int64
|
||||
LastModified time.Time
|
||||
}
|
||||
|
||||
// Client — клиент одного бакета.
|
||||
type Client struct {
|
||||
mc *minio.Client
|
||||
bucket string
|
||||
}
|
||||
|
||||
// New создаёт клиента. Сеть не трогает: доступность проверяют Ping/EnsureBucket.
|
||||
//
|
||||
// Таймауты заданы явно. Без них connection refused ретраится minio-go десяток раз,
|
||||
// и «S3 лежит» вместо быстрого 503 превращается в зависший запрос.
|
||||
func New(cfg Config) (*Client, error) {
|
||||
if cfg.Endpoint == "" || cfg.Bucket == "" {
|
||||
return nil, fmt.Errorf("blob: endpoint and bucket are required")
|
||||
}
|
||||
tr := &http.Transport{
|
||||
Proxy: nil,
|
||||
DialContext: (&net.Dialer{
|
||||
Timeout: 2 * time.Second,
|
||||
KeepAlive: 30 * time.Second,
|
||||
}).DialContext,
|
||||
MaxIdleConns: 64,
|
||||
MaxIdleConnsPerHost: 32,
|
||||
IdleConnTimeout: 60 * time.Second,
|
||||
TLSHandshakeTimeout: 3 * time.Second,
|
||||
ResponseHeaderTimeout: 20 * time.Second,
|
||||
}
|
||||
mc, err := minio.New(cfg.Endpoint, &minio.Options{
|
||||
Creds: credentials.NewStaticV4(cfg.AccessKey, cfg.SecretKey, ""),
|
||||
Secure: cfg.UseSSL,
|
||||
Region: cfg.Region,
|
||||
Transport: tr,
|
||||
MaxRetries: 2,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("blob: init client: %w", err)
|
||||
}
|
||||
return &Client{mc: mc, bucket: cfg.Bucket}, nil
|
||||
}
|
||||
|
||||
// Bucket возвращает имя бакета (для логов и отчётов).
|
||||
func (c *Client) Bucket() string { return c.bucket }
|
||||
|
||||
// EnsureBucket создаёт бакет, если его нет. Идемпотентно.
|
||||
// В Compose бакет создаёт minio-init с root-правами, а у app-пользователя прав на
|
||||
// создание нет — функция нужна локальным тестам и ручному запуску на «голом» MinIO.
|
||||
func (c *Client) EnsureBucket(ctx context.Context) error {
|
||||
ok, err := c.mc.BucketExists(ctx, c.bucket)
|
||||
if err != nil {
|
||||
return classify(err)
|
||||
}
|
||||
if ok {
|
||||
return nil
|
||||
}
|
||||
if err := c.mc.MakeBucket(ctx, c.bucket, minio.MakeBucketOptions{}); err != nil {
|
||||
// Гонка двух инициализаторов: бакет уже создан соседом.
|
||||
code := minio.ToErrorResponse(err).Code
|
||||
if code == "BucketAlreadyOwnedByYou" || code == "BucketAlreadyExists" {
|
||||
return nil
|
||||
}
|
||||
return classify(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Ping — проверка для /health/ready. Короткий таймаут: readiness не должна висеть.
|
||||
func (c *Client) Ping(ctx context.Context) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, 500*time.Millisecond)
|
||||
defer cancel()
|
||||
ok, err := c.mc.BucketExists(ctx, c.bucket)
|
||||
if err != nil || !ok {
|
||||
return ErrUnavailable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Put кладёт объект известного размера. r должен уметь Seek (файл или bytes.Reader):
|
||||
// тогда minio-go отправляет тело одним запросом без буферизации в памяти.
|
||||
func (c *Client) Put(ctx context.Context, key string, r io.Reader, size int64, contentType string) error {
|
||||
_, err := c.mc.PutObject(ctx, c.bucket, key, r, size, minio.PutObjectOptions{
|
||||
ContentType: contentType,
|
||||
// Один PUT для файлов до лимита lab4 (10 MiB): multipart не нужен.
|
||||
DisableMultipart: true,
|
||||
})
|
||||
return classify(err)
|
||||
}
|
||||
|
||||
// Get открывает объект на чтение. Существование проверяется сразу (Stat), чтобы HTTP-слой
|
||||
// успел вернуть 404/503 до отправки заголовков 200.
|
||||
func (c *Client) Get(ctx context.Context, key string) (io.ReadCloser, error) {
|
||||
obj, err := c.mc.GetObject(ctx, c.bucket, key, minio.GetObjectOptions{})
|
||||
if err != nil {
|
||||
return nil, classify(err)
|
||||
}
|
||||
if _, err := obj.Stat(); err != nil {
|
||||
_ = obj.Close()
|
||||
return nil, classify(err)
|
||||
}
|
||||
return obj, nil
|
||||
}
|
||||
|
||||
// Stat возвращает метаданные объекта или ErrNotFound.
|
||||
func (c *Client) Stat(ctx context.Context, key string) (ObjectInfo, error) {
|
||||
st, err := c.mc.StatObject(ctx, c.bucket, key, minio.StatObjectOptions{})
|
||||
if err != nil {
|
||||
return ObjectInfo{}, classify(err)
|
||||
}
|
||||
return ObjectInfo{Key: st.Key, Size: st.Size, LastModified: st.LastModified}, nil
|
||||
}
|
||||
|
||||
// Delete удаляет объект. Отсутствие объекта — не ошибка (S3 DELETE идемпотентен).
|
||||
func (c *Client) Delete(ctx context.Context, key string) error {
|
||||
err := c.mc.RemoveObject(ctx, c.bucket, key, minio.RemoveObjectOptions{})
|
||||
if err != nil && errors.Is(classify(err), ErrNotFound) {
|
||||
return nil
|
||||
}
|
||||
return classify(err)
|
||||
}
|
||||
|
||||
// ListKeys возвращает все объекты с префиксом (рекурсивно). Для reconciler:
|
||||
// стоимость обхода — O(число объектов), память — по записи на объект.
|
||||
func (c *Client) ListKeys(ctx context.Context, prefix string) ([]ObjectInfo, error) {
|
||||
var out []ObjectInfo
|
||||
for o := range c.mc.ListObjects(ctx, c.bucket, minio.ListObjectsOptions{Prefix: prefix, Recursive: true}) {
|
||||
if o.Err != nil {
|
||||
return nil, classify(o.Err)
|
||||
}
|
||||
out = append(out, ObjectInfo{Key: o.Key, Size: o.Size, LastModified: o.LastModified})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// classify сводит ошибки minio-go к ErrNotFound/ErrUnavailable. Текст исходной ошибки
|
||||
// наружу не возвращаем: в нём могут быть endpoint и имя бакета.
|
||||
func classify(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
switch minio.ToErrorResponse(err).Code {
|
||||
case "NoSuchKey", "NotFound":
|
||||
return ErrNotFound
|
||||
}
|
||||
if minio.ToErrorResponse(err).StatusCode == http.StatusNotFound &&
|
||||
minio.ToErrorResponse(err).Code != "NoSuchBucket" {
|
||||
return ErrNotFound
|
||||
}
|
||||
return ErrUnavailable
|
||||
}
|
||||
Reference in New Issue
Block a user