feat(storage): lab5 implement job claim, complete and variants upsert
This commit is contained in:
@@ -3,6 +3,7 @@ package postgres
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
@@ -216,4 +217,62 @@ 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) {
|
||||
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
|
||||
`
|
||||
var a domain.Attachment
|
||||
err := r.pool.QueryRow(ctx, q, id, lease).Scan(&a.ID, &a.ChatID, &a.StagingKey, &a.PipelineVersion)
|
||||
if err != nil {
|
||||
if err == pgx.ErrNoRows {
|
||||
return nil, nil // Задача уже взята или выполнена
|
||||
}
|
||||
return nil, mapError(err)
|
||||
}
|
||||
return &a, nil
|
||||
}
|
||||
|
||||
func (r *AttachmentRepo) CompleteJob(ctx context.Context, id string, pipelineVersion int, variants []domain.AttachmentVariant) (bool, error) {
|
||||
tx, err := r.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return false, mapError(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
|
||||
const q = `
|
||||
UPDATE attachments
|
||||
SET status = 'ready', locked_until = NULL, updated_at = now()
|
||||
WHERE id = $1::uuid AND pipeline_version = $2 AND status = 'processing'
|
||||
`
|
||||
tag, err := tx.Exec(ctx, q, id, pipelineVersion)
|
||||
if err != nil {
|
||||
return false, mapError(err)
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
variantRepo := NewAttachmentVariantRepo(r.pool)
|
||||
for _, v := range variants {
|
||||
if err := variantRepo.Upsert(ctx, &pgxTx{tx: tx}, &v); err != nil {
|
||||
return false, err
|
||||
}
|
||||
}
|
||||
|
||||
return true, mapError(tx.Commit(ctx))
|
||||
}
|
||||
|
||||
func (r *AttachmentRepo) FailJob(ctx context.Context, id string, errorCode string) error {
|
||||
const q = `
|
||||
UPDATE attachments
|
||||
SET status = 'failed', error_code = $2, locked_until = NULL, updated_at = now()
|
||||
WHERE id = $1::uuid AND status = 'processing'
|
||||
`
|
||||
_, err := r.pool.Exec(ctx, q, id, errorCode)
|
||||
return mapError(err)
|
||||
}
|
||||
|
||||
var _ domain.AttachmentRepository = (*AttachmentRepo)(nil)
|
||||
|
||||
Reference in New Issue
Block a user