fix: неопределённый исход MarkReady не удаляет объект; 503 вместо 415 при отказе S3

This commit is contained in:
2026-11-04 20:54:28 +03:00
parent 3ffd41cf3c
commit 5119d0b5fd
3 changed files with 158 additions and 13 deletions
+49 -7
View File
@@ -78,9 +78,14 @@ func declaredType(h string) (string, bool) {
//
// Порядок: намерение в PostgreSQL (uploading) → потоковый PUT в S3, параллельно
// SHA-256 и структурная проверка изображения → status=ready. 201 возвращается
// только после того, как и объект, и метаданные сохранены. Любая ошибка после
// записи намерения компенсируется (удаление объекта и намерения); если компенсация
// не удалась (упали БД/S3/процесс), остаток убирает reconciler после grace period.
// только после того, как и объект, и метаданные сохранены.
//
// Ошибка до MarkReady (проверка, PUT, обрыв клиента) компенсируется сразу:
// удаляются объект и намерение. Ошибка самого MarkReady — неопределённый исход:
// UPDATE мог дойти до PostgreSQL и закоммититься позже (так и было в тесте с
// паузой БД). Поэтому объект НЕ удаляется: остаётся либо ready+объект
// (согласовано), либо uploading+объект — это reconciler уберёт после grace.
// Состояние «ready без объекта» таким образом исключено.
func (s *AttachmentService) Upload(ctx context.Context, ownerID, chatID, filename, contentType string, body io.Reader, contentLength int64) (*domain.Attachment, error) {
parsed, err := uuid.Parse(chatID)
if err != nil {
@@ -160,9 +165,11 @@ func (s *AttachmentService) Upload(ctx context.Context, ownerID, chatID, filenam
a.SizeBytes = size
a.SHA256 = sum
a.UpdatedAt = nowUTC()
if err := s.repo.MarkReady(ctx, a); err != nil {
// S3 записан, а БД — нет: объект удаляем, намерение — по возможности.
s.compensate(ctx, a, err)
// Байты уже сохранены: доводим учёт до конца, даже если клиент отвалился.
mctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second)
defer cancel()
if err := s.repo.MarkReady(mctx, a); err != nil {
s.markReadyFailed(ctx, a, err)
return nil, ErrUnavailable
}
return a, nil
@@ -170,6 +177,20 @@ func (s *AttachmentService) Upload(ctx context.Context, ownerID, chatID, filenam
var errClientBody = errors.New("request body read failed")
// trackingReader запоминает ошибку чтения, отличную от EOF.
type trackingReader struct {
r io.Reader
err error
}
func (t *trackingReader) Read(p []byte) (int, error) {
n, err := t.r.Read(p)
if err != nil && err != io.EOF {
t.err = err
}
return n, err
}
type bodyReader struct{ r io.Reader }
func (b bodyReader) Read(p []byte) (int, error) {
@@ -186,7 +207,14 @@ func (s *AttachmentService) putValidated(ctx context.Context, key string, body i
pr, pw := io.Pipe()
valErr := make(chan error, 1)
go func() {
_, err := imagecheck.Validate(pr, format, s.maxPixels)
tr := &trackingReader{r: pr}
_, err := imagecheck.Validate(tr, format, s.maxPixels)
if tr.err != nil {
// Поток оборвали снаружи (PUT в S3 упал или клиент отвалился):
// изображение тут ни при чём, причину определит putErr.
valErr <- nil
return
}
if err != nil {
pr.CloseWithError(err) // прерывает PUT: дальше писать некуда
}
@@ -219,6 +247,20 @@ func (s *AttachmentService) putValidated(ctx context.Context, key string, body i
return hex.EncodeToString(h.Sum(nil)), nil
}
// markReadyFailed: исход UPDATE неизвестен — объект оставляем. Пробуем убрать
// намерение (DELETE ... WHERE status='uploading' безопасен при любом исходе:
// если UPDATE уже закоммичен, он ничего не удалит). Если и это не удалось —
// uploading+объект уберёт reconciler после grace period.
func (s *AttachmentService) markReadyFailed(ctx context.Context, a *domain.Attachment, cause error) {
cctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second)
defer cancel()
if err := s.repo.DeleteIntent(cctx, a.ID); err != nil {
slog.Warn("mark ready failed, intent left for reconciler", "attachment_id", a.ID, "cause", cause.Error(), "err", err)
return
}
slog.Warn("mark ready failed, object left for reconciler", "attachment_id", a.ID, "cause", cause.Error())
}
// compensate убирает следы неудачной загрузки. Работает и после обрыва клиента
// (контекст запроса отменён), поэтому использует отдельный контекст.
func (s *AttachmentService) compensate(ctx context.Context, a *domain.Attachment, cause error) {