forked from mtusi2026/mtusi2026lab6
151 lines
6.6 KiB
Go
151 lines
6.6 KiB
Go
package repositories
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
)
|
|
|
|
// UploadError is also persisted for terminal validation failures, so retries agree.
|
|
type UploadError struct {
|
|
Status int
|
|
Code, Message string
|
|
}
|
|
|
|
func (e UploadError) Error() string { return e.Message }
|
|
|
|
func DirectError(code string) UploadError {
|
|
switch code {
|
|
case "upload_not_uploaded":
|
|
return UploadError{409, code, "file has not been uploaded"}
|
|
case "upload_expired":
|
|
return UploadError{409, code, "upload confirmation period has expired"}
|
|
case "upload_size_mismatch":
|
|
return UploadError{400, code, "uploaded size differs from declared size"}
|
|
case "upload_checksum_mismatch":
|
|
return UploadError{400, code, "uploaded SHA-256 differs from declared checksum"}
|
|
case "payload_too_large":
|
|
return UploadError{413, code, "image exceeds upload limits"}
|
|
default:
|
|
return UploadError{415, "unsupported_media_type", "a valid PNG or JPEG matching Content-Type is required"}
|
|
}
|
|
}
|
|
|
|
type DirectUpload struct {
|
|
ID string `json:"upload_id"`
|
|
AttachmentID string `json:"-"`
|
|
OwnerID string `json:"-"`
|
|
ChatID string `json:"-"`
|
|
Filename string `json:"-"`
|
|
ContentType string `json:"-"`
|
|
SizeBytes int64 `json:"-"`
|
|
SHA256 string `json:"-"`
|
|
StagingKey string `json:"-"`
|
|
FinalKey string `json:"-"`
|
|
State string `json:"-"`
|
|
ErrorCode *string `json:"-"`
|
|
ExpiresAt time.Time `json:"expires_at"`
|
|
CompleteBefore time.Time `json:"complete_before"`
|
|
}
|
|
|
|
const directColumns = `d.id,d.attachment_id,d.owner_id,d.chat_id,d.filename,d.content_type,d.size_bytes,d.sha256,d.staging_key,d.final_key,d.state,d.error_code,d.expires_at,d.complete_before`
|
|
|
|
func scanDirect(row pgx.Row) (DirectUpload, error) {
|
|
var u DirectUpload
|
|
err := row.Scan(&u.ID, &u.AttachmentID, &u.OwnerID, &u.ChatID, &u.Filename, &u.ContentType, &u.SizeBytes, &u.SHA256, &u.StagingKey, &u.FinalKey, &u.State, &u.ErrorCode, &u.ExpiresAt, &u.CompleteBefore)
|
|
return u, err
|
|
}
|
|
|
|
func (s *AttachmentStore) CreateDirect(ctx context.Context, u DirectUpload) (DirectUpload, error) {
|
|
ctx, cancel := boundedQuery(ctx)
|
|
defer cancel()
|
|
return scanDirect(s.db.QueryRow(ctx, `INSERT INTO direct_uploads AS d(id,attachment_id,owner_id,chat_id,filename,content_type,size_bytes,sha256,staging_key,final_key) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10) RETURNING `+directColumns, u.ID, u.AttachmentID, u.OwnerID, u.ChatID, u.Filename, u.ContentType, u.SizeBytes, u.SHA256, u.StagingKey, u.FinalKey))
|
|
}
|
|
|
|
func (s *AttachmentStore) GetDirect(ctx context.Context, id, chat, user string) (DirectUpload, error) {
|
|
ctx, cancel := boundedQuery(ctx)
|
|
defer cancel()
|
|
return scanDirect(s.db.QueryRow(ctx, `SELECT `+directColumns+` FROM direct_uploads d JOIN chat_members cm ON cm.chat_id=d.chat_id AND cm.user_id=$3 WHERE d.id=$1 AND d.chat_id=$2 AND d.owner_id=$3`, id, chat, user))
|
|
}
|
|
|
|
// The session lock serializes complete across replicas. A separately committed
|
|
// reservation survives rollback/crash, while its row lock protects the final key.
|
|
func (s *AttachmentStore) CompleteDirect(ctx context.Context, id, chat, user string, validate func(context.Context, DirectUpload) error) (Attachment, error) {
|
|
var a Attachment
|
|
tx, err := s.db.Begin(ctx)
|
|
if err != nil {
|
|
return a, err
|
|
}
|
|
defer tx.Rollback(context.Background())
|
|
u, err := scanDirect(tx.QueryRow(ctx, `SELECT `+directColumns+` FROM direct_uploads d JOIN chat_members cm ON cm.chat_id=d.chat_id AND cm.user_id=$3 WHERE d.id=$1 AND d.chat_id=$2 AND d.owner_id=$3 FOR UPDATE OF d`, id, chat, user))
|
|
if err != nil {
|
|
return a, err
|
|
}
|
|
if u.StagingKey != "staging/direct/"+u.ID || u.FinalKey != "originals/"+u.AttachmentID {
|
|
return a, errors.New("invalid direct upload object keys")
|
|
}
|
|
if u.State == "ready" {
|
|
return s.GetForMember(ctx, u.AttachmentID, user)
|
|
}
|
|
if u.State == "rejected" && u.ErrorCode != nil {
|
|
return a, DirectError(*u.ErrorCode)
|
|
}
|
|
var expired bool
|
|
if err = tx.QueryRow(ctx, `SELECT clock_timestamp()>=$1`, u.CompleteBefore).Scan(&expired); err != nil {
|
|
return a, err
|
|
}
|
|
if expired || u.State == "expired" {
|
|
return a, DirectError("upload_expired")
|
|
}
|
|
grace, err := UploadCleanupGrace()
|
|
if err != nil {
|
|
return a, err
|
|
}
|
|
// ON CONFLICT handles retry after an interrupted COPY without losing tracking.
|
|
_, err = s.db.Exec(ctx, `INSERT INTO upload_attempts(id,object_key,cleanup_after) VALUES($1,$2,clock_timestamp()+$3*interval '1 second') ON CONFLICT(id) DO UPDATE SET cleanup_after=GREATEST(upload_attempts.cleanup_after,EXCLUDED.cleanup_after) WHERE upload_attempts.object_key=EXCLUDED.object_key`, u.AttachmentID, u.FinalKey, grace.Seconds())
|
|
if err != nil {
|
|
return a, err
|
|
}
|
|
var key string
|
|
if err = tx.QueryRow(ctx, `SELECT object_key FROM upload_attempts WHERE id=$1 AND cleanup_after>clock_timestamp() FOR UPDATE`, u.AttachmentID).Scan(&key); err != nil {
|
|
return a, err
|
|
}
|
|
if key != u.FinalKey {
|
|
return a, errors.New("direct upload reservation mismatch")
|
|
}
|
|
if err = validate(ctx, u); err != nil {
|
|
var invalid UploadError
|
|
if errors.As(err, &invalid) && (invalid.Status == 400 || invalid.Status == 413 || invalid.Status == 415) {
|
|
_, saveErr := tx.Exec(ctx, `UPDATE direct_uploads SET state='rejected',error_code=$2,cleanup_after=clock_timestamp(),purge_after=clock_timestamp()+interval '24 hours' WHERE id=$1`, id, invalid.Code)
|
|
if saveErr != nil {
|
|
return a, saveErr
|
|
}
|
|
if saveErr = tx.Commit(ctx); saveErr != nil {
|
|
return a, saveErr
|
|
}
|
|
}
|
|
return a, err
|
|
}
|
|
now := time.Now().UTC().Truncate(time.Microsecond)
|
|
a = Attachment{ID: u.AttachmentID, ChatID: u.ChatID, OwnerID: u.OwnerID, Filename: u.Filename, ContentType: u.ContentType, SizeBytes: u.SizeBytes, SHA256: u.SHA256, ObjectKey: u.FinalKey, Status: "queued", Variants: []any{}, CreatedAt: now, UpdatedAt: now}
|
|
_, err = tx.Exec(ctx, `INSERT INTO attachments(id,chat_id,owner_id,filename,object_key,content_type,size_bytes,sha256,created_at,updated_at) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)`, a.ID, a.ChatID, a.OwnerID, a.Filename, a.ObjectKey, a.ContentType, a.SizeBytes, a.SHA256, a.CreatedAt, a.UpdatedAt)
|
|
if err != nil {
|
|
return Attachment{}, err
|
|
}
|
|
if err = enqueueJob(ctx, tx, a, a.ObjectKey); err != nil {
|
|
return Attachment{}, err
|
|
}
|
|
if _, err = tx.Exec(ctx, `UPDATE direct_uploads SET state='ready',cleanup_after=clock_timestamp(),purge_after=clock_timestamp()+interval '24 hours' WHERE id=$1`, id); err != nil {
|
|
return Attachment{}, err
|
|
}
|
|
if _, err = tx.Exec(ctx, `DELETE FROM upload_attempts WHERE id=$1`, a.ID); err != nil {
|
|
return Attachment{}, err
|
|
}
|
|
if err = tx.Commit(ctx); err != nil {
|
|
return Attachment{}, err
|
|
}
|
|
return a, nil
|
|
}
|