Files
lincodex/backend/internal/usecase/files/store.go
T

150 lines
5.6 KiB
Go

package files
import (
"context"
"encoding/hex"
"errors"
"fmt"
"io"
"time"
"lincodex/backend/internal/port/outbound"
)
// cleanupTimeout bounds deletion of a failed write after the caller's context
// has been canceled.
const cleanupTimeout = 30 * time.Second
// Upload is one file write. Size is the exact declared length in bytes; the
// store does not buffer sources of unknown length. ContentType is the type the
// caller declared or detected and must be allowed by the policy. The store
// does not inspect content.
//
// Body needs its own deadline, for example an HTTP request body after
// http.ResponseController.SetReadDeadline. Put waits for a blocked Read, and
// canceling the context does not interrupt a Read that never returns.
type Upload struct {
Body io.Reader
Size int64
ContentType string
OriginalName string
}
// Record is the content metadata of a stored file. Callers persist it next to
// their own ownership and access rules; the store keeps no index. Key is an
// internal locator: never return it, the bucket, or a storage URL to clients.
//
// Callers follow one order: Put, then persist the Record in their database
// transaction, then Delete the key if that transaction fails. An object
// without a committed record is an orphan that no request can reach.
type Record struct {
Key string
ContentType string
Size int64
SHA256 string
OriginalName string
}
// Store applies a Policy to private object storage. It creates no public or
// presigned URLs; downloads go through an authorized backend endpoint that
// streams File.
type Store struct {
storage outbound.ObjectStorage
}
func NewStore(storage outbound.ObjectStorage) *Store {
return &Store{storage: storage}
}
// Put streams upload to a new opaque key. Any failure after the write started
// deletes the key, so a rejected or interrupted upload normally leaves no
// object. One race remains: when the whole body was sent before the caller
// canceled, the server may still commit after the cleanup Delete returned.
// Such an orphan has no Record, so a planned namespace sweeper that removes
// keys without a record (with backups) is the final
// cleanup. See Record for the caller's order of operations.
func (store *Store) Put(ctx context.Context, policy Policy, upload Upload) (Record, error) {
if !policy.valid() {
return Record{}, fmt.Errorf("Store.Put - validate policy: %w", ErrInvalidPolicy)
}
if upload.Body == nil || upload.Size < 0 {
return Record{}, fmt.Errorf("Store.Put - validate upload: %w", ErrInvalidUpload)
}
if upload.Size > policy.maxSize {
return Record{}, fmt.Errorf("Store.Put - check declared size: %w", ErrTooLarge)
}
contentType, allowed := policy.allow(upload.ContentType)
if !allowed {
return Record{}, fmt.Errorf("Store.Put - check content type: %w", ErrUnsupportedType)
}
key := newKey(policy.namespace)
reader := newUploadReader(upload.Body, upload.Size)
if err := store.storage.Put(ctx, key, reader, upload.Size, contentType); err != nil {
// The storage error is sanitized; a stream violation explains more.
if reader.err != nil {
err = reader.err
}
return Record{}, store.discard(ctx, key, fmt.Errorf("Store.Put - put object: %w", err))
}
if err := reader.finish(); err != nil {
return Record{}, store.discard(ctx, key, fmt.Errorf("Store.Put - verify stream: %w", err))
}
return Record{
Key: key,
ContentType: contentType,
Size: upload.Size,
SHA256: hex.EncodeToString(reader.sum()),
OriginalName: SanitizeOriginalName(upload.OriginalName),
}, nil
}
// Open streams a file owned by policy. It rejects stored objects that no
// longer satisfy the policy and closes their bodies before returning.
func (store *Store) Open(ctx context.Context, policy Policy, key string) (*File, error) {
if !policy.ownsKey(key) {
return nil, fmt.Errorf("Store.Open - validate key: %w", ErrInvalidKey)
}
object, err := store.storage.Get(ctx, key)
if err != nil {
return nil, fmt.Errorf("Store.Open - get object: %w", err)
}
if object.Size < 0 || object.Size > policy.maxSize {
return nil, closeAfter(object.Body, fmt.Errorf("Store.Open - check stored size: %w", ErrTooLarge))
}
contentType, allowed := policy.allow(object.ContentType)
if !allowed {
return nil, closeAfter(object.Body, fmt.Errorf("Store.Open - check stored content type: %w", ErrUnsupportedType))
}
return &File{Size: object.Size, ContentType: contentType, body: object.Body, remaining: object.Size}, nil
}
// Delete removes a file owned by policy. Deleting an absent file succeeds.
func (store *Store) Delete(ctx context.Context, policy Policy, key string) error {
if !policy.ownsKey(key) {
return fmt.Errorf("Store.Delete - validate key: %w", ErrInvalidKey)
}
if err := store.storage.Delete(ctx, key); err != nil {
return fmt.Errorf("Store.Delete - delete object: %w", err)
}
return nil
}
// discard deletes a key after a failed write. Storage may have committed the
// object before the failure was reported, and the caller never learns the key,
// so cleanup runs even when the caller's context is already canceled.
func (store *Store) discard(ctx context.Context, key string, cause error) error {
ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), cleanupTimeout)
defer cancel()
if err := store.storage.Delete(ctx, key); err != nil {
return errors.Join(cause, fmt.Errorf("Store.discard - delete failed write: %w", err))
}
return cause
}
func closeAfter(body io.Closer, cause error) error {
if err := body.Close(); err != nil {
return errors.Join(cause, fmt.Errorf("files.closeAfter - close object body: %w", err))
}
return cause
}