Compare commits
10
Commits
9b28579031
...
19ddbfd16a
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
19ddbfd16a | ||
|
|
20fdd31c12 | ||
|
|
d40b339906 | ||
|
|
f748c09e10 | ||
|
|
dce767a156 | ||
|
|
996e305ea4 | ||
|
|
8fb191fc78 | ||
|
|
d27a779c20 | ||
|
|
b022f8f7fc | ||
|
|
295371c326 |
@@ -103,6 +103,7 @@ func main() {
|
||||
store.Chats(),
|
||||
objectStorage,
|
||||
store.Outbox(),
|
||||
store.FailedJobs(),
|
||||
store,
|
||||
cfg.MaxUploadBytes,
|
||||
cfg.MaxImagePixels,
|
||||
@@ -139,6 +140,7 @@ func main() {
|
||||
reconciler := service.NewReconciler(
|
||||
store.Attachments(),
|
||||
objectStorage,
|
||||
store.Outbox(),
|
||||
pool,
|
||||
cfg.ReconcilerGracePeriod,
|
||||
)
|
||||
|
||||
@@ -44,7 +44,7 @@ func main() {
|
||||
log.Fatalf("S3: %v", err)
|
||||
}
|
||||
|
||||
pipeline := worker.NewPipeline(store.Attachments(), objectStorage, store.Variants())
|
||||
pipeline := worker.NewPipeline(store.Attachments(), objectStorage, store.Variants(), store.FailedJobs(), store.Outbox())
|
||||
|
||||
conn, err := amqp.Dial(cfg.RabbitMQURL)
|
||||
if err != nil {
|
||||
@@ -58,7 +58,7 @@ func main() {
|
||||
}
|
||||
defer ch.Close()
|
||||
|
||||
// Prefetch: сколько сообщений worker берет разом (защита от перегрузки)
|
||||
// Сколько сообщений worker берет разом (защита от перегрузки)
|
||||
ch.Qos(2, 0, false)
|
||||
|
||||
q, err := ch.QueueDeclare("attachments.process", true, false, false, false, nil)
|
||||
@@ -86,9 +86,9 @@ func main() {
|
||||
continue
|
||||
}
|
||||
|
||||
if err := pipeline.Process(ctx, msg.AttachmentID); err != nil {
|
||||
if err := pipeline.Process(ctx, msg.AttachmentID, msg.PipelineVersion); err != nil {
|
||||
log.Printf("worker: ошибка %s: %v", msg.AttachmentID, err)
|
||||
_ = d.Nack(false, true) // requeue
|
||||
_ = d.Nack(false, true)
|
||||
} else {
|
||||
_ = d.Ack(false)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
package domain
|
||||
|
||||
import "time"
|
||||
|
||||
// FailedJob — реестр окончательно проваленных задач (DLQ-сторона).
|
||||
// Заполняется worker'ом после исчерпания retry или при permanent-ошибке.
|
||||
// Читается для операторского просмотра и для явного replay (Этап 5).
|
||||
type FailedJob struct {
|
||||
ID string
|
||||
AttachmentID string
|
||||
ReasonCode string // из jobcodes.go
|
||||
Attempts int
|
||||
LastErrorAt time.Time
|
||||
ResolvedAt *time.Time // nil = не разобрана
|
||||
Resolution string // "replayed", "manual_fix", ...
|
||||
CreatedAt time.Time
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package domain
|
||||
|
||||
const (
|
||||
JobErrorDecodeFailed = "decode_failed"
|
||||
JobErrorTooLarge = "too_large"
|
||||
JobErrorUnsupportedFormat = "unsupported_format"
|
||||
JobErrorStorage = "storage_error"
|
||||
JobErrorInternal = "internal_error"
|
||||
JobErrorRetryExhausted = "retry_exhausted"
|
||||
)
|
||||
@@ -41,25 +41,37 @@ type AttachmentRepository interface {
|
||||
GetByID(ctx context.Context, id string) (*Attachment, error)
|
||||
MarkReady(ctx context.Context, id string) error
|
||||
MarkFailed(ctx context.Context, id string, errorCode string) error
|
||||
ListStalePending(ctx context.Context, olderThan time.Time, limit int) ([]Attachment, error)
|
||||
ExistingKeys(ctx context.Context, keys []string) ([]string, error)
|
||||
DeletePending(ctx context.Context, id string) error
|
||||
CreateInTx(ctx context.Context, tx Tx, a *Attachment) error
|
||||
ResetForReplay(ctx context.Context, tx Tx, id string) error
|
||||
|
||||
ListExpiredLeases(ctx context.Context, limit int) ([]Attachment, error)
|
||||
ResetLease(ctx context.Context, id string) error
|
||||
ListStagingToCleanup(ctx context.Context, limit int) ([]Attachment, error)
|
||||
ClearStagingKey(ctx context.Context, id string) error
|
||||
}
|
||||
|
||||
type OutboxRepository interface {
|
||||
Enqueue(ctx context.Context, tx Tx, e *OutboxEntry) error
|
||||
ClaimBatch(ctx context.Context, limit int) ([]OutboxEntry, error)
|
||||
MarkPublished(ctx context.Context, ids []string) error
|
||||
EnqueueDirect(ctx context.Context, e *OutboxEntry) error
|
||||
}
|
||||
|
||||
type AttachmentJobRepository interface {
|
||||
ClaimForProcessing(ctx context.Context, id string, lease time.Duration) (*Attachment, error)
|
||||
ClaimForProcessing(ctx context.Context, id string, version int, lease time.Duration) (*Attachment, error)
|
||||
CompleteJob(ctx context.Context, id string, pipelineVersion int, variants []AttachmentVariant) (bool, error)
|
||||
FailJob(ctx context.Context, id string, errorCode string) error
|
||||
ScheduleRetry(ctx context.Context, id string, nextAttemptAt time.Time, errorCode string) error
|
||||
}
|
||||
|
||||
type AttachmentVariantRepository interface {
|
||||
Upsert(ctx context.Context, tx Tx, v *AttachmentVariant) error
|
||||
ListByAttachment(ctx context.Context, id string) ([]AttachmentVariant, error)
|
||||
}
|
||||
|
||||
type FailedJobRepository interface {
|
||||
Record(ctx context.Context, f *FailedJob) error
|
||||
Resolve(ctx context.Context, attachmentID string, resolution string) error
|
||||
ResolveInTx(ctx context.Context, tx Tx, id string) error
|
||||
}
|
||||
|
||||
@@ -92,3 +92,20 @@ func (h *AttachmentHandler) Content(c *gin.Context) {
|
||||
|
||||
c.DataFromReader(http.StatusOK, size, contentType, rc, nil)
|
||||
}
|
||||
|
||||
func (h *AttachmentHandler) Replay(c *gin.Context) {
|
||||
me := middleware.CurrentUser(c)
|
||||
|
||||
attachmentID, err := parseUUIDPathParam(c, "attachment_id")
|
||||
if err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.svc.Replay(c.Request.Context(), me.ID, attachmentID); err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.Status(http.StatusAccepted)
|
||||
}
|
||||
|
||||
@@ -50,6 +50,7 @@ func NewRouter(h Handlers, auth gin.HandlerFunc) *gin.Engine {
|
||||
protected.POST("/chats/:chat_id/attachments", h.Attachment.Upload)
|
||||
protected.GET("/attachments/:attachment_id", h.Attachment.Get)
|
||||
protected.GET("/attachments/:attachment_id/content", h.Attachment.Content)
|
||||
protected.POST("/attachments/:attachment_id/replay", h.Attachment.Replay)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -29,6 +29,7 @@ type AttachmentService struct {
|
||||
chats domain.ChatRepository
|
||||
storage domain.ObjectStorage
|
||||
outbox domain.OutboxRepository
|
||||
failedJobs domain.FailedJobRepository
|
||||
tx txRunner
|
||||
maxBytes int64
|
||||
maxPixels int64
|
||||
@@ -39,6 +40,7 @@ func NewAttachmentService(
|
||||
chats domain.ChatRepository,
|
||||
storage domain.ObjectStorage,
|
||||
outbox domain.OutboxRepository,
|
||||
failedJobs domain.FailedJobRepository,
|
||||
tx txRunner,
|
||||
maxBytes, maxPixels int64,
|
||||
) *AttachmentService {
|
||||
@@ -47,6 +49,7 @@ func NewAttachmentService(
|
||||
chats: chats,
|
||||
storage: storage,
|
||||
outbox: outbox,
|
||||
failedJobs: failedJobs,
|
||||
tx: tx,
|
||||
maxBytes: maxBytes,
|
||||
maxPixels: maxPixels,
|
||||
@@ -190,6 +193,49 @@ func (s *AttachmentService) Download(
|
||||
return nil, 0, "", &domain.NotFoundError{Entity: "variant", ID: variantName}
|
||||
}
|
||||
|
||||
// Replay позволяет оператору перезапустить упавшую задачу.
|
||||
func (s *AttachmentService) Replay(ctx context.Context, userID, attachmentID string) error {
|
||||
a, err := s.Get(ctx, userID, attachmentID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if a.Status != domain.AttachmentStatusFailed {
|
||||
return &domain.ConflictError{Reason: "перезапустить можно только failed-вложение"}
|
||||
}
|
||||
|
||||
// Формируем новое сообщение
|
||||
payload, err := json.Marshal(domain.JobMessage{
|
||||
AttachmentID: a.ID,
|
||||
PipelineVersion: a.PipelineVersion,
|
||||
Attempt: 1, // Сбрасываем счетчик попыток
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = s.tx.WithTx(ctx, func(tx domain.Tx) error {
|
||||
if err := s.attachments.ResetForReplay(ctx, tx, a.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
// Помечаем в реестре упавших задач (внутри транзакции)
|
||||
if err := s.failedJobs.ResolveInTx(ctx, tx, a.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.outbox.Enqueue(ctx, tx, &domain.OutboxEntry{
|
||||
AggregateType: domain.OutboxAggregateAttachment,
|
||||
AggregateID: a.ID,
|
||||
EventType: domain.OutboxEventProcess,
|
||||
Payload: payload,
|
||||
})
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *AttachmentService) ensureMember(ctx context.Context, userID, chatID string) error {
|
||||
c, err := s.chats.GetByID(ctx, chatID)
|
||||
if err != nil {
|
||||
|
||||
@@ -2,6 +2,7 @@ package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
@@ -15,6 +16,7 @@ const advisoryLockKey int64 = 0x4D5455534904
|
||||
type Reconciler struct {
|
||||
attachments domain.AttachmentRepository
|
||||
storage domain.ObjectStorage
|
||||
outbox domain.OutboxRepository
|
||||
pool *pgxpool.Pool
|
||||
gracePeriod time.Duration
|
||||
batchSize int
|
||||
@@ -23,6 +25,7 @@ type Reconciler struct {
|
||||
func NewReconciler(
|
||||
attachments domain.AttachmentRepository,
|
||||
storage domain.ObjectStorage,
|
||||
outbox domain.OutboxRepository,
|
||||
pool *pgxpool.Pool,
|
||||
gracePeriod time.Duration,
|
||||
) *Reconciler {
|
||||
@@ -32,6 +35,7 @@ func NewReconciler(
|
||||
return &Reconciler{
|
||||
attachments: attachments,
|
||||
storage: storage,
|
||||
outbox: outbox,
|
||||
pool: pool,
|
||||
gracePeriod: gracePeriod,
|
||||
batchSize: 100,
|
||||
@@ -45,14 +49,13 @@ func (r *Reconciler) Run(ctx context.Context, interval time.Duration) {
|
||||
ticker := time.NewTicker(interval)
|
||||
defer ticker.Stop()
|
||||
|
||||
log.Printf("reconciler: started, interval=%s grace=%s", interval, r.gracePeriod)
|
||||
|
||||
log.Printf("reconciler: запущен (interval=%s, grace=%s)", interval, r.gracePeriod)
|
||||
r.tick(ctx)
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
log.Println("reconciler: stopped")
|
||||
log.Println("reconciler: остановлен")
|
||||
return
|
||||
case <-ticker.C:
|
||||
r.tick(ctx)
|
||||
@@ -63,7 +66,7 @@ func (r *Reconciler) Run(ctx context.Context, interval time.Duration) {
|
||||
func (r *Reconciler) tick(ctx context.Context) {
|
||||
acquired, release, err := r.acquireLock(ctx)
|
||||
if err != nil {
|
||||
log.Printf("reconciler: acquire lock: %v", err)
|
||||
log.Printf("reconciler: ошибка получения блокировки: %v", err)
|
||||
return
|
||||
}
|
||||
if !acquired {
|
||||
@@ -71,11 +74,12 @@ func (r *Reconciler) tick(ctx context.Context) {
|
||||
}
|
||||
defer release()
|
||||
|
||||
pendingDeleted := r.sweepPending(ctx)
|
||||
leasesReset := r.sweepExpiredLeases(ctx)
|
||||
stagingDeleted := r.sweepStaging(ctx)
|
||||
orphansDeleted := r.sweepOrphans(ctx)
|
||||
|
||||
if pendingDeleted > 0 || orphansDeleted > 0 {
|
||||
log.Printf("reconciler: sweep done pending=%d orphans=%d", pendingDeleted, orphansDeleted)
|
||||
if leasesReset > 0 || stagingDeleted > 0 || orphansDeleted > 0 {
|
||||
log.Printf("reconciler: очистка завершена (восстановлено_задач=%d, удалено_staging=%d, удалено_сирот=%d)", leasesReset, stagingDeleted, orphansDeleted)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -99,29 +103,64 @@ func (r *Reconciler) acquireLock(ctx context.Context) (bool, func(), error) {
|
||||
unlockCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
if _, err := conn.Exec(unlockCtx, `SELECT pg_advisory_unlock($1)`, advisoryLockKey); err != nil {
|
||||
log.Printf("reconciler: unlock: %v", err)
|
||||
log.Printf("reconciler: ошибка снятия блокировки: %v", err)
|
||||
}
|
||||
conn.Release()
|
||||
}
|
||||
return true, release, nil
|
||||
}
|
||||
|
||||
func (r *Reconciler) sweepPending(ctx context.Context) int {
|
||||
cutoff := time.Now().UTC().Add(-r.gracePeriod)
|
||||
stale, err := r.attachments.ListStalePending(ctx, cutoff, r.batchSize)
|
||||
func (r *Reconciler) sweepExpiredLeases(ctx context.Context) int {
|
||||
expired, err := r.attachments.ListExpiredLeases(ctx, r.batchSize)
|
||||
if err != nil {
|
||||
log.Printf("reconciler: list stale pending: %v", err)
|
||||
log.Printf("reconciler: ошибка получения истёкших аренд: %v", err)
|
||||
return 0
|
||||
}
|
||||
|
||||
recovered := 0
|
||||
for _, a := range expired {
|
||||
if err := r.attachments.ResetLease(ctx, a.ID); err != nil {
|
||||
log.Printf("reconciler: ошибка сброса аренды для %s: %v", a.ID, err)
|
||||
continue
|
||||
}
|
||||
|
||||
payload, _ := json.Marshal(domain.JobMessage{
|
||||
AttachmentID: a.ID,
|
||||
PipelineVersion: a.PipelineVersion,
|
||||
Attempt: a.Attempts + 1,
|
||||
})
|
||||
err := r.outbox.EnqueueDirect(ctx, &domain.OutboxEntry{
|
||||
AggregateType: domain.OutboxAggregateAttachment,
|
||||
AggregateID: a.ID,
|
||||
EventType: domain.OutboxEventProcess,
|
||||
Payload: payload,
|
||||
CreatedAt: time.Now().UTC(),
|
||||
})
|
||||
if err != nil {
|
||||
log.Printf("reconciler: ошибка постановки в очередь восстановленной задачи %s: %v", a.ID, err)
|
||||
continue
|
||||
}
|
||||
recovered++
|
||||
}
|
||||
return recovered
|
||||
}
|
||||
|
||||
// Чистим staging в S3 для готовых задач
|
||||
func (r *Reconciler) sweepStaging(ctx context.Context) int {
|
||||
toCleanup, err := r.attachments.ListStagingToCleanup(ctx, r.batchSize)
|
||||
if err != nil {
|
||||
log.Printf("reconciler: ошибка получения списка staging для очистки: %v", err)
|
||||
return 0
|
||||
}
|
||||
|
||||
deleted := 0
|
||||
for _, a := range stale {
|
||||
if err := r.storage.Delete(ctx, a.ObjectKey); err != nil {
|
||||
log.Printf("reconciler: delete object %s: %v", a.ObjectKey, err)
|
||||
for _, a := range toCleanup {
|
||||
if err := r.storage.Delete(ctx, a.StagingKey); err != nil {
|
||||
log.Printf("reconciler: ошибка удаления объекта staging %s: %v", a.StagingKey, err)
|
||||
continue
|
||||
}
|
||||
if err := r.attachments.DeletePending(ctx, a.ID); err != nil {
|
||||
log.Printf("reconciler: delete pending row %s: %v", a.ID, err)
|
||||
if err := r.attachments.ClearStagingKey(ctx, a.ID); err != nil {
|
||||
log.Printf("reconciler: ошибка очистки ключа staging %s: %v", a.ID, err)
|
||||
continue
|
||||
}
|
||||
deleted++
|
||||
@@ -129,10 +168,11 @@ func (r *Reconciler) sweepPending(ctx context.Context) int {
|
||||
return deleted
|
||||
}
|
||||
|
||||
// Удаляем старые сиротские объекты (без записи в БД)
|
||||
func (r *Reconciler) sweepOrphans(ctx context.Context) int {
|
||||
objects, err := r.storage.List(ctx, "chats/")
|
||||
if err != nil {
|
||||
log.Printf("reconciler: list objects: %v", err)
|
||||
log.Printf("reconciler: ошибка получения списка объектов: %v", err)
|
||||
return 0
|
||||
}
|
||||
if len(objects) == 0 {
|
||||
@@ -152,7 +192,7 @@ func (r *Reconciler) sweepOrphans(ctx context.Context) int {
|
||||
|
||||
existing, err := r.attachments.ExistingKeys(ctx, keys)
|
||||
if err != nil {
|
||||
log.Printf("reconciler: existing keys: %v", err)
|
||||
log.Printf("reconciler: ошибка получения существующих ключей: %v", err)
|
||||
return 0
|
||||
}
|
||||
|
||||
@@ -167,7 +207,7 @@ func (r *Reconciler) sweepOrphans(ctx context.Context) int {
|
||||
continue
|
||||
}
|
||||
if err := r.storage.Delete(ctx, k); err != nil {
|
||||
log.Printf("reconciler: delete orphan %s: %v", k, err)
|
||||
log.Printf("reconciler: ошибка удаления сиротского объекта %s: %v", k, err)
|
||||
continue
|
||||
}
|
||||
deleted++
|
||||
|
||||
@@ -173,47 +173,6 @@ func (r *AttachmentRepo) MarkFailed(ctx context.Context, id, errorCode string) e
|
||||
}
|
||||
}
|
||||
|
||||
func (r *AttachmentRepo) ListStalePending(ctx context.Context, olderThan time.Time, limit int) ([]domain.Attachment, error) {
|
||||
if limit <= 0 {
|
||||
return []domain.Attachment{}, nil
|
||||
}
|
||||
const q = `
|
||||
SELECT id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
|
||||
object_key, status, error_code, created_at, updated_at
|
||||
FROM attachments
|
||||
WHERE status = 'pending' AND created_at < $1
|
||||
ORDER BY created_at
|
||||
LIMIT $2
|
||||
`
|
||||
rows, err := r.pool.Query(ctx, q, olderThan, limit)
|
||||
if err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
out := make([]domain.Attachment, 0, limit)
|
||||
for rows.Next() {
|
||||
var a domain.Attachment
|
||||
var status string
|
||||
if err := rows.Scan(&a.ID, &a.ChatID, &a.OwnerID, &a.Filename,
|
||||
&a.ContentType, &a.SizeBytes, &a.SHA256, &a.ObjectKey,
|
||||
&status, &a.ErrorCode, &a.CreatedAt, &a.UpdatedAt); err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
a.Status = domain.AttachmentStatus(status)
|
||||
out = append(out, a)
|
||||
}
|
||||
return out, mapError(rows.Err())
|
||||
}
|
||||
|
||||
func (r *AttachmentRepo) DeletePending(ctx context.Context, id string) error {
|
||||
const q = `DELETE FROM attachments WHERE id = $1::uuid AND status = 'pending'`
|
||||
if _, err := r.pool.Exec(ctx, q, id); err != nil {
|
||||
return mapError(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *AttachmentRepo) ExistingKeys(ctx context.Context, keys []string) ([]string, error) {
|
||||
if len(keys) == 0 {
|
||||
return []string{}, nil
|
||||
@@ -236,15 +195,15 @@ func (r *AttachmentRepo) ExistingKeys(ctx context.Context, keys []string) ([]str
|
||||
return out, mapError(rows.Err())
|
||||
}
|
||||
|
||||
func (r *AttachmentRepo) ClaimForProcessing(ctx context.Context, id string, lease time.Duration) (*domain.Attachment, error) {
|
||||
func (r *AttachmentRepo) ClaimForProcessing(ctx context.Context, id string, version int, lease time.Duration) (*domain.Attachment, error) {
|
||||
const q = `
|
||||
UPDATE attachments
|
||||
SET status = 'processing', locked_until = now() + $2, updated_at = now()
|
||||
WHERE id = $1::uuid AND status = 'queued'
|
||||
RETURNING id, chat_id, staging_key, pipeline_version, object_key, content_type
|
||||
SET status = 'processing', locked_until = now() + $2, updated_at = now(), attempts = attempts + 1
|
||||
WHERE id = $1::uuid AND status = 'queued' AND pipeline_version = $3
|
||||
RETURNING id, chat_id, staging_key, pipeline_version, object_key, content_type, attempts
|
||||
`
|
||||
var a domain.Attachment
|
||||
err := r.pool.QueryRow(ctx, q, id, lease).Scan(&a.ID, &a.ChatID, &a.StagingKey, &a.PipelineVersion, &a.ObjectKey, &a.ContentType)
|
||||
err := r.pool.QueryRow(ctx, q, id, lease, version).Scan(&a.ID, &a.ChatID, &a.StagingKey, &a.PipelineVersion, &a.ObjectKey, &a.ContentType, &a.Attempts)
|
||||
if err != nil {
|
||||
if err == pgx.ErrNoRows {
|
||||
return nil, nil
|
||||
@@ -297,4 +256,97 @@ func (r *AttachmentRepo) FailJob(ctx context.Context, id string, errorCode strin
|
||||
return mapError(err)
|
||||
}
|
||||
|
||||
func (r *AttachmentRepo) ScheduleRetry(ctx context.Context, id string, nextAttemptAt time.Time, errorCode string) error {
|
||||
const q = `
|
||||
UPDATE attachments
|
||||
SET status = 'queued', error_code = NULL, next_attempt_at = $2, locked_until = NULL, updated_at = now()
|
||||
WHERE id = $1::uuid AND status = 'processing'
|
||||
`
|
||||
_, err := r.pool.Exec(ctx, q, id, nextAttemptAt)
|
||||
return mapError(err)
|
||||
}
|
||||
|
||||
func (r *AttachmentRepo) ResetForReplay(ctx context.Context, tx domain.Tx, id string) error {
|
||||
const q = `
|
||||
UPDATE attachments
|
||||
SET status = 'queued', attempts = 0, error_code = NULL, locked_until = NULL, next_attempt_at = NULL, updated_at = now()
|
||||
WHERE id = $1::uuid AND status = 'failed'
|
||||
`
|
||||
return tx.Exec(ctx, q, id)
|
||||
}
|
||||
|
||||
// для сверщика.
|
||||
func (r *AttachmentRepo) ListExpiredLeases(ctx context.Context, limit int) ([]domain.Attachment, error) {
|
||||
const q = `
|
||||
SELECT id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
|
||||
object_key, status, error_code, created_at, updated_at,
|
||||
attempts, next_attempt_at, locked_until, pipeline_version, staging_key
|
||||
FROM attachments
|
||||
WHERE status = 'processing' AND locked_until < now()
|
||||
ORDER BY locked_until
|
||||
LIMIT $1
|
||||
`
|
||||
rows, err := r.pool.Query(ctx, q, limit)
|
||||
if err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var out []domain.Attachment
|
||||
for rows.Next() {
|
||||
var a domain.Attachment
|
||||
var status string
|
||||
err := rows.Scan(&a.ID, &a.ChatID, &a.OwnerID, &a.Filename, &a.ContentType,
|
||||
&a.SizeBytes, &a.SHA256, &a.ObjectKey, &status, &a.ErrorCode,
|
||||
&a.CreatedAt, &a.UpdatedAt, &a.Attempts, &a.NextAttemptAt, &a.LockedUntil,
|
||||
&a.PipelineVersion, &a.StagingKey)
|
||||
if err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
a.Status = domain.AttachmentStatus(status)
|
||||
out = append(out, a)
|
||||
}
|
||||
return out, mapError(rows.Err())
|
||||
}
|
||||
|
||||
func (r *AttachmentRepo) ResetLease(ctx context.Context, id string) error {
|
||||
const q = `
|
||||
UPDATE attachments
|
||||
SET status = 'queued', locked_until = NULL, updated_at = now()
|
||||
WHERE id = $1::uuid AND status = 'processing' AND locked_until < now()
|
||||
`
|
||||
_, err := r.pool.Exec(ctx, q, id)
|
||||
return mapError(err)
|
||||
}
|
||||
|
||||
func (r *AttachmentRepo) ListStagingToCleanup(ctx context.Context, limit int) ([]domain.Attachment, error) {
|
||||
const q = `
|
||||
SELECT id, staging_key
|
||||
FROM attachments
|
||||
WHERE status = 'ready' AND staging_key IS NOT NULL
|
||||
LIMIT $1
|
||||
`
|
||||
rows, err := r.pool.Query(ctx, q, limit)
|
||||
if err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var out []domain.Attachment
|
||||
for rows.Next() {
|
||||
var a domain.Attachment
|
||||
if err := rows.Scan(&a.ID, &a.StagingKey); err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
out = append(out, a)
|
||||
}
|
||||
return out, mapError(rows.Err())
|
||||
}
|
||||
|
||||
func (r *AttachmentRepo) ClearStagingKey(ctx context.Context, id string) error {
|
||||
const q = `UPDATE attachments SET staging_key = NULL WHERE id = $1::uuid`
|
||||
_, err := r.pool.Exec(ctx, q, id)
|
||||
return mapError(err)
|
||||
}
|
||||
|
||||
var _ domain.AttachmentRepository = (*AttachmentRepo)(nil)
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
type FailedJobRepo struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewFailedJobRepo(pool *pgxpool.Pool) *FailedJobRepo {
|
||||
return &FailedJobRepo{pool: pool}
|
||||
}
|
||||
|
||||
func (r *FailedJobRepo) Record(ctx context.Context, f *domain.FailedJob) error {
|
||||
if f.ID == "" {
|
||||
f.ID = uuid.NewString()
|
||||
}
|
||||
if f.LastErrorAt.IsZero() {
|
||||
f.LastErrorAt = time.Now().UTC()
|
||||
}
|
||||
const q = `
|
||||
INSERT INTO failed_jobs (id, attachment_id, reason_code, attempts, last_error_at, created_at)
|
||||
VALUES ($1::uuid, $2::uuid, $3, $4, $5, $5)
|
||||
`
|
||||
_, err := r.pool.Exec(ctx, q, f.ID, f.AttachmentID, f.ReasonCode, f.Attempts, f.LastErrorAt)
|
||||
return mapError(err)
|
||||
}
|
||||
|
||||
func (r *FailedJobRepo) Resolve(ctx context.Context, attachmentID string, resolution string) error {
|
||||
const q = `UPDATE failed_jobs SET resolved_at = now(), resolution = $2 WHERE attachment_id = $1::uuid AND resolved_at IS NULL`
|
||||
_, err := r.pool.Exec(ctx, q, attachmentID, resolution)
|
||||
return mapError(err)
|
||||
}
|
||||
|
||||
func (r *FailedJobRepo) ResolveInTx(ctx context.Context, tx domain.Tx, id string) error {
|
||||
const q = `
|
||||
UPDATE failed_jobs
|
||||
SET resolved_at = now(), resolution = 'manual_replay'
|
||||
WHERE attachment_id = $1::uuid AND resolved_at IS NULL
|
||||
`
|
||||
return tx.Exec(ctx, q, id)
|
||||
}
|
||||
|
||||
var _ domain.FailedJobRepository = (*FailedJobRepo)(nil)
|
||||
@@ -57,7 +57,7 @@ func (r *OutboxRepo) ClaimBatch(ctx context.Context, limit int) ([]domain.Outbox
|
||||
const q = `
|
||||
WITH claimed AS (
|
||||
SELECT id FROM outbox
|
||||
WHERE published_at IS NULL
|
||||
WHERE published_at IS NULL AND created_at <= now()
|
||||
ORDER BY created_at
|
||||
LIMIT $1
|
||||
FOR UPDATE SKIP LOCKED
|
||||
@@ -88,6 +88,22 @@ func (r *OutboxRepo) ClaimBatch(ctx context.Context, limit int) ([]domain.Outbox
|
||||
return entries, mapError(rows.Err())
|
||||
}
|
||||
|
||||
func (r *OutboxRepo) EnqueueDirect(ctx context.Context, e *domain.OutboxEntry) error {
|
||||
if e.ID == "" {
|
||||
e.ID = uuid.NewString()
|
||||
}
|
||||
const q = `
|
||||
INSERT INTO outbox
|
||||
(id, aggregate_type, aggregate_id, event_type, payload, attempts, created_at, published_at)
|
||||
VALUES ($1::uuid, $2, $3::uuid, $4, $5::jsonb, $6, $7, $8)
|
||||
`
|
||||
_, err := r.pool.Exec(ctx, q,
|
||||
e.ID, e.AggregateType, e.AggregateID, e.EventType,
|
||||
string(e.Payload), e.Attempts, e.CreatedAt, e.PublishedAt,
|
||||
)
|
||||
return mapError(err)
|
||||
}
|
||||
|
||||
func (r *OutboxRepo) MarkPublished(ctx context.Context, ids []string) error {
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
|
||||
@@ -19,3 +19,4 @@ func (s *Storage) Sessions() *SessionRepo { return &SessionRepo{pool:
|
||||
func (s *Storage) Attachments() *AttachmentRepo { return &AttachmentRepo{pool: s.pool} }
|
||||
func (s *Storage) Outbox() *OutboxRepo { return &OutboxRepo{pool: s.pool} }
|
||||
func (s *Storage) Variants() *AttachmentVariantRepo { return &AttachmentVariantRepo{pool: s.pool} }
|
||||
func (s *Storage) FailedJobs() *FailedJobRepo { return &FailedJobRepo{pool: s.pool} }
|
||||
|
||||
@@ -3,9 +3,11 @@ package worker
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"math/rand"
|
||||
"time"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
@@ -13,73 +15,110 @@ import (
|
||||
)
|
||||
|
||||
type Pipeline struct {
|
||||
jobs domain.AttachmentJobRepository
|
||||
store domain.ObjectStorage
|
||||
variants domain.AttachmentVariantRepository
|
||||
lease time.Duration
|
||||
jobs domain.AttachmentJobRepository
|
||||
store domain.ObjectStorage
|
||||
variants domain.AttachmentVariantRepository
|
||||
failedJobs domain.FailedJobRepository
|
||||
outbox domain.OutboxRepository
|
||||
lease time.Duration
|
||||
maxRetries int
|
||||
}
|
||||
|
||||
func NewPipeline(jobs domain.AttachmentJobRepository, store domain.ObjectStorage, variants domain.AttachmentVariantRepository) *Pipeline {
|
||||
func NewPipeline(
|
||||
jobs domain.AttachmentJobRepository,
|
||||
store domain.ObjectStorage,
|
||||
variants domain.AttachmentVariantRepository,
|
||||
failedJobs domain.FailedJobRepository,
|
||||
outbox domain.OutboxRepository,
|
||||
) *Pipeline {
|
||||
return &Pipeline{
|
||||
jobs: jobs,
|
||||
store: store,
|
||||
variants: variants,
|
||||
lease: 5 * time.Minute, // Lease на 5 минут, чтобы избежать дублей
|
||||
jobs: jobs,
|
||||
store: store,
|
||||
variants: variants,
|
||||
failedJobs: failedJobs,
|
||||
outbox: outbox,
|
||||
lease: 5 * time.Minute,
|
||||
maxRetries: 5,
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Pipeline) Process(ctx context.Context, attachmentID string) error {
|
||||
log.Printf("worker: начало обработки %s", attachmentID)
|
||||
func (p *Pipeline) Process(ctx context.Context, attachmentID string, pipelineVersion int) error {
|
||||
log.Printf("worker: начало обработки %s (версия пайплайна %d)", attachmentID, pipelineVersion)
|
||||
|
||||
// 1. Забираем задачу (защита от дублей). Если уже взята или готова — nil.
|
||||
a, err := p.jobs.ClaimForProcessing(ctx, attachmentID, p.lease)
|
||||
jobCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// 1. Забираем задачу с проверкой версии
|
||||
a, err := p.jobs.ClaimForProcessing(jobCtx, attachmentID, pipelineVersion, p.lease)
|
||||
if err != nil {
|
||||
return fmt.Errorf("захват задачи: %w", err)
|
||||
}
|
||||
if a == nil {
|
||||
log.Printf("worker: задача %s уже взята или выполнена", attachmentID)
|
||||
log.Printf("worker: задача %s уже взята, выполнена или версия устарела", attachmentID)
|
||||
return nil // no-op
|
||||
}
|
||||
|
||||
// 2. Скачиваем оригинал из staging (куда его положил API)
|
||||
rc, _, _, err := p.store.Get(ctx, a.StagingKey)
|
||||
// 2. Скачиваем оригинал из staging
|
||||
rc, _, _, err := p.store.Get(jobCtx, a.StagingKey)
|
||||
if err != nil {
|
||||
_ = p.jobs.FailJob(ctx, a.ID, "storage_error")
|
||||
return fmt.Errorf("скачивание staging: %w", err)
|
||||
return p.handleFailure(a, fmt.Errorf("скачивание staging: %w", err), false)
|
||||
}
|
||||
defer rc.Close()
|
||||
|
||||
buf, err := io.ReadAll(rc)
|
||||
if err != nil {
|
||||
_ = p.jobs.FailJob(ctx, a.ID, "storage_error")
|
||||
return fmt.Errorf("чтение staging: %w", err)
|
||||
return p.handleFailure(a, fmt.Errorf("чтение staging: %w", err), false)
|
||||
}
|
||||
|
||||
// 3. Генерируем thumbnail
|
||||
// 3. Генерируем все варианты (Thumbnail, Crop, Optimized)
|
||||
log.Printf("worker: генерация вариантов для %s", a.ID)
|
||||
thumbMeta, thumbData, err := imaging.Thumbnail(a.ID, buf)
|
||||
if err != nil {
|
||||
_ = p.jobs.FailJob(ctx, a.ID, "decode_failed")
|
||||
return fmt.Errorf("генерация thumbnail: %w", err)
|
||||
return p.handleFailure(a, fmt.Errorf("генерация thumbnail: %w", err), true)
|
||||
}
|
||||
|
||||
cropMeta, cropData, err := imaging.Crop(a.ID, buf)
|
||||
if err != nil {
|
||||
return p.handleFailure(a, fmt.Errorf("генерация crop: %w", err), true)
|
||||
}
|
||||
|
||||
webpMeta, webpData, err := imaging.Optimized(a.ID, buf)
|
||||
if err != nil {
|
||||
return p.handleFailure(a, fmt.Errorf("генерация webp: %w", err), true)
|
||||
}
|
||||
|
||||
// 4. Сохраняем оригинал в финальный prefix (chats/...)
|
||||
if err := p.store.Put(ctx, a.ObjectKey, bytes.NewReader(buf), int64(len(buf)), a.ContentType); err != nil {
|
||||
_ = p.jobs.FailJob(ctx, a.ID, "storage_error")
|
||||
return fmt.Errorf("загрузка оригинала: %w", err)
|
||||
if err := p.store.Put(jobCtx, a.ObjectKey, bytes.NewReader(buf), int64(len(buf)), a.ContentType); err != nil {
|
||||
return p.handleFailure(a, fmt.Errorf("загрузка оригинала: %w", err), false)
|
||||
}
|
||||
|
||||
// 5. Сохраняем thumbnail в S3
|
||||
thumbKey := fmt.Sprintf("%s/thumbnail", a.ObjectKey)
|
||||
if err := p.store.Put(ctx, thumbKey, bytes.NewReader(thumbData), thumbMeta.SizeBytes, thumbMeta.ContentType); err != nil {
|
||||
_ = p.jobs.FailJob(ctx, a.ID, "storage_error")
|
||||
return fmt.Errorf("загрузка thumbnail: %w", err)
|
||||
// 5. Загружаем все сгенерированные варианты в S3
|
||||
variants := []domain.AttachmentVariant{*thumbMeta, *cropMeta, *webpMeta}
|
||||
|
||||
for i := range variants {
|
||||
v := &variants[i]
|
||||
key := fmt.Sprintf("%s/%s", a.ObjectKey, v.Name)
|
||||
|
||||
var data []byte
|
||||
switch v.Name {
|
||||
case domain.VariantThumbnail:
|
||||
data = thumbData
|
||||
case domain.VariantCrop:
|
||||
data = cropData
|
||||
case domain.VariantOptimized:
|
||||
data = webpData
|
||||
}
|
||||
|
||||
if err := p.store.Put(jobCtx, key, bytes.NewReader(data), v.SizeBytes, v.ContentType); err != nil {
|
||||
return p.handleFailure(a, fmt.Errorf("загрузка варианта %s: %w", v.Name, err), false)
|
||||
}
|
||||
v.ObjectKey = key
|
||||
}
|
||||
thumbMeta.ObjectKey = thumbKey
|
||||
|
||||
// 6. Фиксируем результат в БД (переводим в ready)
|
||||
ok, err := p.jobs.CompleteJob(ctx, a.ID, a.PipelineVersion, []domain.AttachmentVariant{*thumbMeta})
|
||||
ok, err := p.jobs.CompleteJob(jobCtx, a.ID, a.PipelineVersion, variants)
|
||||
if err != nil {
|
||||
return fmt.Errorf("фиксация в БД: %w", err)
|
||||
return p.handleFailure(a, fmt.Errorf("фиксация в БД: %w", err), false)
|
||||
}
|
||||
if !ok {
|
||||
log.Printf("worker: версия устарела или статус изменился, пропускаем %s", a.ID)
|
||||
@@ -89,3 +128,52 @@ func (p *Pipeline) Process(ctx context.Context, attachmentID string) error {
|
||||
log.Printf("worker: успешно завершено %s", a.ID)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Pipeline) handleFailure(a *domain.Attachment, err error, isPermanent bool) error {
|
||||
// Если исчерпаны попытки или ошибка постоянная (например, битый файл)
|
||||
if isPermanent || a.Attempts >= p.maxRetries {
|
||||
reason := domain.JobErrorInternal
|
||||
if a.Attempts >= p.maxRetries {
|
||||
reason = domain.JobErrorRetryExhausted
|
||||
} else if isPermanent {
|
||||
reason = domain.JobErrorDecodeFailed
|
||||
}
|
||||
|
||||
log.Printf("worker: финальная ошибка для %s (попытка %d): %v", a.ID, a.Attempts, err)
|
||||
|
||||
// Используем context.Background(), чтобы запись в БД прошла даже при истекшем jobCtx
|
||||
_ = p.jobs.FailJob(context.Background(), a.ID, reason)
|
||||
_ = p.failedJobs.Record(context.Background(), &domain.FailedJob{
|
||||
AttachmentID: a.ID,
|
||||
ReasonCode: reason,
|
||||
Attempts: a.Attempts,
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
// Временная ошибка - делаем Retry с backoff
|
||||
log.Printf("worker: временная ошибка для %s, попытка %d: %v", a.ID, a.Attempts, err)
|
||||
|
||||
// Экспоненциальный backoff: 2^attempts секунд + случайный jitter (0-1000 мс)
|
||||
backoff := time.Duration(1<<uint(a.Attempts)) * time.Second
|
||||
jitter := time.Duration(rand.Intn(1000)) * time.Millisecond
|
||||
nextAt := time.Now().UTC().Add(backoff + jitter)
|
||||
|
||||
_ = p.jobs.ScheduleRetry(context.Background(), a.ID, nextAt, "")
|
||||
|
||||
// Кладем в Outbox отложенное сообщение
|
||||
payload, _ := json.Marshal(domain.JobMessage{
|
||||
AttachmentID: a.ID,
|
||||
PipelineVersion: a.PipelineVersion,
|
||||
Attempt: a.Attempts + 1,
|
||||
})
|
||||
_ = p.outbox.EnqueueDirect(context.Background(), &domain.OutboxEntry{
|
||||
AggregateType: domain.OutboxAggregateAttachment,
|
||||
AggregateID: a.ID,
|
||||
EventType: domain.OutboxEventProcess,
|
||||
Payload: payload,
|
||||
CreatedAt: nextAt,
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
-- +goose Up
|
||||
-- +goose StatementBegin
|
||||
|
||||
CREATE TABLE failed_jobs (
|
||||
id UUID PRIMARY KEY,
|
||||
attachment_id UUID NOT NULL REFERENCES attachments(id) ON DELETE CASCADE,
|
||||
reason_code TEXT NOT NULL,
|
||||
attempts INT NOT NULL,
|
||||
last_error_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
resolved_at TIMESTAMPTZ,
|
||||
resolution TEXT,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
|
||||
CONSTRAINT failed_jobs_reason_len CHECK (char_length(reason_code) BETWEEN 1 AND 64),
|
||||
CONSTRAINT failed_jobs_attempts_pos CHECK (attempts > 0)
|
||||
);
|
||||
|
||||
CREATE INDEX failed_jobs_unresolved_idx ON failed_jobs (created_at) WHERE resolved_at IS NULL;
|
||||
|
||||
-- +goose StatementEnd
|
||||
|
||||
-- +goose Down
|
||||
-- +goose StatementBegin
|
||||
DROP TABLE IF EXISTS failed_jobs;
|
||||
-- +goose StatementEnd
|
||||
@@ -26,6 +26,8 @@ services:
|
||||
timeout: 3s
|
||||
retries: 10
|
||||
start_period: 5s
|
||||
ports:
|
||||
- "5432:5432"
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
@@ -74,6 +76,7 @@ services:
|
||||
- rabbitmq_data:/var/lib/rabbitmq
|
||||
ports:
|
||||
- "15672:15672"
|
||||
- "5672:5672"
|
||||
healthcheck:
|
||||
test: ["CMD", "rabbitmq-diagnostics", "-q", "ping"]
|
||||
interval: 5s
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
#!/usr/bin/env python3
|
||||
import sys
|
||||
import time
|
||||
import json
|
||||
import pika
|
||||
import psycopg2
|
||||
from pathlib import Path
|
||||
|
||||
RABBITMQ_URL = "amqp://messenger:sdsdjhkjshdjkhsdkjhkjsdh@localhost:5672/"
|
||||
DB_URL = "postgresql://messenger:1de200d38ea7d870f772acfbf1887572@localhost:5432/messenger"
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
def get_db():
|
||||
return psycopg2.connect(DB_URL)
|
||||
|
||||
def publish_duplicate(attachment_id: str, pipeline_version: int):
|
||||
connection = pika.BlockingConnection(pika.URLParameters(RABBITMQ_URL))
|
||||
channel = connection.channel()
|
||||
|
||||
payload = json.dumps({
|
||||
"attachment_id": attachment_id,
|
||||
"pipeline_version": pipeline_version,
|
||||
"attempt": 1
|
||||
})
|
||||
|
||||
channel.basic_publish(
|
||||
exchange='attachments',
|
||||
routing_key='process',
|
||||
body=payload.encode(),
|
||||
properties=pika.BasicProperties(delivery_mode=2)
|
||||
)
|
||||
connection.close()
|
||||
|
||||
def main():
|
||||
args = arguments('Fault Injection (Track 2)')
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
|
||||
print("=== ТЕСТ 1: Идемпотентность при дублировании сообщений ===")
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
|
||||
att, content = c.attachment(alice, chat)
|
||||
att_id = att['id']
|
||||
print(f"Загружено вложение: {att_id}")
|
||||
|
||||
ready_att = c.wait_ready(bob, att)
|
||||
print("Первая обработка успешна. Статус: ready.")
|
||||
|
||||
with get_db() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("SELECT COUNT(*) FROM attachment_variants WHERE attachment_id = %s", (att_id,))
|
||||
count_before = cur.fetchone()[0]
|
||||
|
||||
print(f"Вариантов в БД до дубля: {count_before}")
|
||||
check(count_before == 3, "Ожидалось 3 варианта (thumbnail, crop, optimized)")
|
||||
|
||||
print("Публикуем дубликат сообщения в RabbitMQ...")
|
||||
publish_duplicate(att_id, 1)
|
||||
time.sleep(2)
|
||||
|
||||
with get_db() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("SELECT COUNT(*) FROM attachment_variants WHERE attachment_id = %s", (att_id,))
|
||||
count_after = cur.fetchone()[0]
|
||||
|
||||
check(count_after == count_before, "Дубликат сообщения создал лишние варианты (НАРУШЕНИЕ ИДЕМПОТЕНТНОСТИ)")
|
||||
print("PASS: Дубликат проигнорирован, лишних вариантов не создано.")
|
||||
|
||||
print("\n=== ТЕСТ 2: Защита от устаревшей версии (Versioned Pipeline) ===")
|
||||
att2, _ = c.attachment(alice, chat)
|
||||
att2_id = att2['id']
|
||||
print(f"Загружено вложение 2: {att2_id}")
|
||||
|
||||
with get_db() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("UPDATE attachments SET pipeline_version = 2, status = 'queued' WHERE id = %s", (att2_id,))
|
||||
conn.commit()
|
||||
|
||||
print("Мы вручную поменяли версию на 2.")
|
||||
print("Публикуем сообщение со СТАРОЙ версией (1)...")
|
||||
publish_duplicate(att2_id, 1)
|
||||
time.sleep(2)
|
||||
|
||||
with get_db() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("SELECT status FROM attachments WHERE id = %s", (att2_id,))
|
||||
status = cur.fetchone()[0]
|
||||
|
||||
check(status == 'queued', f"Старый воркер перезаписал статус! Текущий статус: {status}")
|
||||
print("PASS: Задача со старой версией проигнорирована. Статус остался 'queued'.")
|
||||
print("\nВСЕ ТЕСТЫ FAULT INJECTION ПРОЙДЕНЫ!")
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
Reference in New Issue
Block a user