This commit is contained in:
@@ -0,0 +1,906 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab7/internal/domain"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
const attachmentJobColumns = `
|
||||
schema_version, job_id::text, job_type, attachment_id::text,
|
||||
pipeline_version, attempt, max_attempts, status, error_code,
|
||||
available_at, lease_until, leased_by, replay_count, created_at, updated_at,
|
||||
COALESCE(traceparent, ''), COALESCE(tracestate, '')
|
||||
`
|
||||
|
||||
type scanner interface {
|
||||
Scan(dest ...any) error
|
||||
}
|
||||
|
||||
func scanAttachmentJob(row scanner, job *domain.AttachmentJob) error {
|
||||
return row.Scan(
|
||||
&job.SchemaVersion,
|
||||
&job.JobID,
|
||||
&job.Type,
|
||||
&job.AttachmentID,
|
||||
&job.PipelineVersion,
|
||||
&job.Attempt,
|
||||
&job.MaxAttempts,
|
||||
&job.Status,
|
||||
&job.ErrorCode,
|
||||
&job.AvailableAt,
|
||||
&job.LeaseUntil,
|
||||
&job.LeasedBy,
|
||||
&job.ReplayCount,
|
||||
&job.CreatedAt,
|
||||
&job.UpdatedAt,
|
||||
&job.TraceParent,
|
||||
&job.TraceState,
|
||||
)
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) CreateQueuedAttachment(ctx context.Context, attachment domain.Attachment, job domain.AttachmentJob) (domain.Attachment, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
tx, err := s.pool.Begin(queryContext)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("begin queued attachment transaction: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(queryContext) }()
|
||||
|
||||
err = tx.QueryRow(queryContext, `
|
||||
INSERT INTO attachments (
|
||||
id, chat_id, owner_id, object_key, staging_key, filename, content_type,
|
||||
size_bytes, sha256, width, height, pipeline_version, status, error_code,
|
||||
created_at, updated_at
|
||||
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,decode($9,'hex'),$10,$11,$12,$13,NULL,$14,$15)
|
||||
RETURNING created_at, updated_at
|
||||
`, attachment.ID, attachment.ChatID, attachment.OwnerID, attachment.ObjectKey,
|
||||
attachment.StagingKey, attachment.Filename, attachment.ContentType, attachment.SizeBytes,
|
||||
attachment.SHA256, attachment.Width, attachment.Height, attachment.PipelineVersion,
|
||||
attachment.Status, attachment.CreatedAt, attachment.UpdatedAt,
|
||||
).Scan(&attachment.CreatedAt, &attachment.UpdatedAt)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("insert queued attachment: %w", err)
|
||||
}
|
||||
if job.AvailableAt.IsZero() {
|
||||
job.AvailableAt = job.CreatedAt
|
||||
}
|
||||
_, err = tx.Exec(queryContext, `
|
||||
INSERT INTO attachment_jobs (
|
||||
job_id, attachment_id, schema_version, job_type, pipeline_version,
|
||||
attempt, max_attempts, status, available_at, created_at, updated_at,
|
||||
traceparent, tracestate
|
||||
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)
|
||||
`, job.JobID, job.AttachmentID, job.SchemaVersion, job.Type, job.PipelineVersion,
|
||||
job.Attempt, job.MaxAttempts, job.Status, job.AvailableAt, job.CreatedAt, job.UpdatedAt,
|
||||
job.TraceParent, job.TraceState)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("insert attachment job: %w", err)
|
||||
}
|
||||
if err = tx.Commit(queryContext); err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("commit queued attachment: %w", err)
|
||||
}
|
||||
attachment.Variants = make([]domain.AttachmentVariant, 0)
|
||||
return attachment, nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) ListUnpublishedAttachmentJobs(ctx context.Context, limit int) ([]domain.AttachmentJob, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
rows, err := s.pool.Query(queryContext, `
|
||||
SELECT `+attachmentJobColumns+`
|
||||
FROM attachment_jobs
|
||||
WHERE status = 'queued' AND published_at IS NULL
|
||||
AND available_at <= CURRENT_TIMESTAMP
|
||||
ORDER BY available_at, created_at, job_id
|
||||
LIMIT $1
|
||||
`, limit)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list unpublished attachment jobs: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
jobs := make([]domain.AttachmentJob, 0)
|
||||
for rows.Next() {
|
||||
var job domain.AttachmentJob
|
||||
if err = scanAttachmentJob(rows, &job); err != nil {
|
||||
return nil, fmt.Errorf("scan unpublished attachment job: %w", err)
|
||||
}
|
||||
jobs = append(jobs, job)
|
||||
}
|
||||
return jobs, rows.Err()
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) MarkAttachmentJobPublished(ctx context.Context, jobID string, attempt int, publishedAt time.Time) error {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
_, err := s.pool.Exec(queryContext, `
|
||||
UPDATE attachment_jobs SET published_at = $3, updated_at = $3
|
||||
WHERE job_id = $1 AND attempt = $2 AND status = 'queued'
|
||||
`, jobID, attempt, publishedAt)
|
||||
if err != nil {
|
||||
return fmt.Errorf("mark attachment job published: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) ClaimAttachmentJob(
|
||||
ctx context.Context,
|
||||
message domain.AttachmentJobMessage,
|
||||
workerID string,
|
||||
leaseUntil time.Time,
|
||||
) (domain.AttachmentJob, bool, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
tx, err := s.pool.Begin(queryContext)
|
||||
if err != nil {
|
||||
return domain.AttachmentJob{}, false, fmt.Errorf("begin claim attachment job: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(queryContext) }()
|
||||
|
||||
var job domain.AttachmentJob
|
||||
err = scanAttachmentJob(tx.QueryRow(queryContext, `
|
||||
UPDATE attachment_jobs
|
||||
SET status = 'processing', lease_until = $5, leased_by = $6,
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
WHERE job_id = $1 AND attachment_id = $2 AND pipeline_version = $3
|
||||
AND attempt = $4 AND status = 'queued'
|
||||
AND available_at <= CURRENT_TIMESTAMP
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM attachments a
|
||||
WHERE a.id = attachment_jobs.attachment_id
|
||||
AND a.pipeline_version = attachment_jobs.pipeline_version
|
||||
AND a.status = 'queued'
|
||||
)
|
||||
RETURNING `+attachmentJobColumns+`
|
||||
`, message.JobID, message.AttachmentID, message.PipelineVersion, message.Attempt,
|
||||
leaseUntil, workerID), &job)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
var status domain.AttachmentJobStatus
|
||||
var attachmentStatus domain.AttachmentStatus
|
||||
var attempt, activeVersion, jobVersion int
|
||||
lookupErr := tx.QueryRow(queryContext, `
|
||||
SELECT j.status, j.attempt, a.status, a.pipeline_version, j.pipeline_version
|
||||
FROM attachment_jobs j
|
||||
JOIN attachments a ON a.id=j.attachment_id
|
||||
WHERE j.job_id=$1
|
||||
FOR UPDATE OF a,j
|
||||
`, message.JobID).Scan(
|
||||
&status,
|
||||
&attempt,
|
||||
&attachmentStatus,
|
||||
&activeVersion,
|
||||
&jobVersion,
|
||||
)
|
||||
if errors.Is(lookupErr, pgx.ErrNoRows) {
|
||||
return domain.AttachmentJob{}, false, ErrNotFound
|
||||
}
|
||||
if lookupErr != nil {
|
||||
return domain.AttachmentJob{}, false, fmt.Errorf("inspect unclaimed attachment job: %w", lookupErr)
|
||||
}
|
||||
err = nil
|
||||
switch {
|
||||
case status == domain.AttachmentJobQueued &&
|
||||
activeVersion == jobVersion &&
|
||||
attachmentStatus == domain.AttachmentStatusReady:
|
||||
_, err = tx.Exec(queryContext, `
|
||||
UPDATE attachment_jobs
|
||||
SET status='succeeded', error_code=NULL, published_at=COALESCE(published_at,CURRENT_TIMESTAMP),
|
||||
lease_until=NULL, leased_by=NULL, updated_at=CURRENT_TIMESTAMP
|
||||
WHERE job_id=$1
|
||||
`, message.JobID)
|
||||
status = domain.AttachmentJobSucceeded
|
||||
case status == domain.AttachmentJobQueued && activeVersion != jobVersion:
|
||||
_, err = tx.Exec(queryContext, `
|
||||
UPDATE attachment_jobs
|
||||
SET status='superseded', error_code='superseded_pipeline',
|
||||
lease_until=NULL, leased_by=NULL, updated_at=CURRENT_TIMESTAMP
|
||||
WHERE job_id=$1
|
||||
`, message.JobID)
|
||||
status = domain.AttachmentJobSuperseded
|
||||
}
|
||||
if err != nil {
|
||||
return domain.AttachmentJob{}, false, fmt.Errorf("normalize unclaimed attachment job: %w", err)
|
||||
}
|
||||
if err = tx.Commit(queryContext); err != nil {
|
||||
return domain.AttachmentJob{}, false, fmt.Errorf("commit unclaimed attachment job: %w", err)
|
||||
}
|
||||
return domain.AttachmentJob{JobID: message.JobID, Status: status, Attempt: attempt}, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return domain.AttachmentJob{}, false, fmt.Errorf("claim attachment job: %w", err)
|
||||
}
|
||||
_, err = tx.Exec(queryContext, `
|
||||
UPDATE attachments SET status = 'processing', updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = $1 AND pipeline_version = $2 AND status = 'queued'
|
||||
`, message.AttachmentID, message.PipelineVersion)
|
||||
if err != nil {
|
||||
return domain.AttachmentJob{}, false, fmt.Errorf("mark attachment processing: %w", err)
|
||||
}
|
||||
if err = tx.Commit(queryContext); err != nil {
|
||||
return domain.AttachmentJob{}, false, fmt.Errorf("commit claimed attachment job: %w", err)
|
||||
}
|
||||
return job, true, nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) GetAttachmentForProcessing(ctx context.Context, attachmentID string) (domain.Attachment, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
var attachment domain.Attachment
|
||||
var digest []byte
|
||||
var stagingKey *string
|
||||
err := s.pool.QueryRow(queryContext, `
|
||||
SELECT id::text, chat_id::text, owner_id::text, object_key, staging_key,
|
||||
filename, content_type, size_bytes, sha256, width, height,
|
||||
pipeline_version, status, error_code, created_at, updated_at
|
||||
FROM attachments WHERE id = $1
|
||||
`, attachmentID).Scan(&attachment.ID, &attachment.ChatID, &attachment.OwnerID,
|
||||
&attachment.ObjectKey, &stagingKey, &attachment.Filename,
|
||||
&attachment.ContentType, &attachment.SizeBytes, &digest, &attachment.Width,
|
||||
&attachment.Height, &attachment.PipelineVersion, &attachment.Status,
|
||||
&attachment.ErrorCode, &attachment.CreatedAt, &attachment.UpdatedAt)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.Attachment{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("get attachment for processing: %w", err)
|
||||
}
|
||||
attachment.SHA256 = fmt.Sprintf("%x", digest)
|
||||
if stagingKey != nil {
|
||||
attachment.StagingKey = *stagingKey
|
||||
}
|
||||
return attachment, nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) CompleteAttachmentJob(
|
||||
ctx context.Context,
|
||||
job domain.AttachmentJob,
|
||||
variants []domain.AttachmentVariant,
|
||||
updatedAt time.Time,
|
||||
) (bool, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
tx, err := s.pool.Begin(queryContext)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("begin complete attachment job: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(queryContext) }()
|
||||
|
||||
var attachmentStatus domain.AttachmentStatus
|
||||
var pipelineVersion int
|
||||
var jobStatus domain.AttachmentJobStatus
|
||||
err = tx.QueryRow(queryContext, `
|
||||
SELECT a.status, a.pipeline_version, j.status
|
||||
FROM attachments a
|
||||
JOIN attachment_jobs j ON j.attachment_id = a.id
|
||||
WHERE a.id = $1 AND j.job_id = $2
|
||||
FOR UPDATE OF a, j
|
||||
`, job.AttachmentID, job.JobID).Scan(&attachmentStatus, &pipelineVersion, &jobStatus)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("lock attachment completion: %w", err)
|
||||
}
|
||||
if pipelineVersion != job.PipelineVersion || jobStatus == domain.AttachmentJobSuperseded {
|
||||
if jobStatus != domain.AttachmentJobSuperseded {
|
||||
_, err = tx.Exec(queryContext, `
|
||||
UPDATE attachment_jobs
|
||||
SET status='superseded', error_code='superseded_pipeline',
|
||||
lease_until=NULL, leased_by=NULL, updated_at=$2
|
||||
WHERE job_id=$1
|
||||
`, job.JobID, updatedAt)
|
||||
if err == nil {
|
||||
_, err = tx.Exec(queryContext, `
|
||||
INSERT INTO attachment_job_events
|
||||
(job_id, event_type, previous_status, new_status, attempt, error_code, created_at)
|
||||
VALUES ($1, 'superseded', $2, 'superseded', $3, 'superseded_pipeline', $4)
|
||||
`, job.JobID, jobStatus, job.Attempt, updatedAt)
|
||||
}
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("supersede stale pipeline completion: %w", err)
|
||||
}
|
||||
}
|
||||
if err = tx.Commit(queryContext); err != nil {
|
||||
return false, fmt.Errorf("commit stale pipeline completion: %w", err)
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
if attachmentStatus == domain.AttachmentStatusReady || jobStatus == domain.AttachmentJobSucceeded {
|
||||
_, err = tx.Exec(queryContext, `
|
||||
UPDATE attachment_jobs
|
||||
SET status='succeeded', error_code=NULL, lease_until=NULL, leased_by=NULL, updated_at=$2
|
||||
WHERE job_id=$1
|
||||
`, job.JobID, updatedAt)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("normalize completed job: %w", err)
|
||||
}
|
||||
if err = tx.Commit(queryContext); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
if len(variants) != 3 {
|
||||
return false, fmt.Errorf("complete attachment requires three variants: %w", ErrConflict)
|
||||
}
|
||||
for _, variant := range variants {
|
||||
_, err = tx.Exec(queryContext, `
|
||||
INSERT INTO attachment_variants (
|
||||
attachment_id, pipeline_version, name, object_key, content_type,
|
||||
size_bytes, width, height, sha256, created_at
|
||||
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,decode($9,'hex'),$10)
|
||||
ON CONFLICT (attachment_id, pipeline_version, name) DO UPDATE SET
|
||||
object_key = EXCLUDED.object_key, content_type = EXCLUDED.content_type,
|
||||
size_bytes = EXCLUDED.size_bytes, width = EXCLUDED.width,
|
||||
height = EXCLUDED.height, sha256 = EXCLUDED.sha256
|
||||
`, job.AttachmentID, job.PipelineVersion, variant.Name, variant.ObjectKey,
|
||||
variant.ContentType, variant.SizeBytes, variant.Width, variant.Height,
|
||||
variant.SHA256, updatedAt)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("upsert attachment variant %s: %w", variant.Name, err)
|
||||
}
|
||||
}
|
||||
tag, err := tx.Exec(queryContext, `
|
||||
UPDATE attachments SET status = 'ready', error_code = NULL, updated_at = $3
|
||||
WHERE id = $1 AND pipeline_version = $2 AND status IN ('queued','processing')
|
||||
`, job.AttachmentID, job.PipelineVersion, updatedAt)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("mark attachment ready: %w", err)
|
||||
}
|
||||
if tag.RowsAffected() != 1 {
|
||||
return false, fmt.Errorf("active pipeline changed during completion: %w", ErrConflict)
|
||||
}
|
||||
_, err = tx.Exec(queryContext, `
|
||||
UPDATE attachment_jobs
|
||||
SET status = 'succeeded', error_code = NULL, lease_until = NULL,
|
||||
leased_by = NULL, updated_at = $2
|
||||
WHERE job_id = $1
|
||||
`, job.JobID, updatedAt)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("mark attachment job succeeded: %w", err)
|
||||
}
|
||||
_, err = tx.Exec(queryContext, `
|
||||
INSERT INTO attachment_job_events
|
||||
(job_id, event_type, previous_status, new_status, attempt, created_at)
|
||||
VALUES ($1, 'completed', $2, 'succeeded', $3, $4)
|
||||
`, job.JobID, jobStatus, job.Attempt, updatedAt)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("record attachment completion: %w", err)
|
||||
}
|
||||
if err = tx.Commit(queryContext); err != nil {
|
||||
return false, fmt.Errorf("commit completed attachment job: %w", err)
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) RetryAttachmentJob(
|
||||
ctx context.Context,
|
||||
jobID string,
|
||||
errorCode string,
|
||||
availableAt time.Time,
|
||||
updatedAt time.Time,
|
||||
eventType string,
|
||||
) (domain.AttachmentJob, bool, error) {
|
||||
if eventType != "retry_scheduled" && eventType != "lease_recovered" {
|
||||
return domain.AttachmentJob{}, false, fmt.Errorf("unsupported retry event type")
|
||||
}
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
tx, err := s.pool.Begin(queryContext)
|
||||
if err != nil {
|
||||
return domain.AttachmentJob{}, false, fmt.Errorf("begin retry attachment job: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(queryContext) }()
|
||||
|
||||
var job domain.AttachmentJob
|
||||
err = scanAttachmentJob(tx.QueryRow(queryContext, `
|
||||
SELECT `+attachmentJobColumns+`
|
||||
FROM attachment_jobs WHERE job_id = $1 FOR UPDATE
|
||||
`, jobID), &job)
|
||||
if err != nil {
|
||||
return domain.AttachmentJob{}, false, fmt.Errorf("lock attachment job for retry: %w", err)
|
||||
}
|
||||
var attachmentStatus domain.AttachmentStatus
|
||||
var activePipelineVersion int
|
||||
if err = tx.QueryRow(queryContext,
|
||||
`SELECT status, pipeline_version FROM attachments WHERE id = $1 FOR UPDATE`,
|
||||
job.AttachmentID,
|
||||
).Scan(&attachmentStatus, &activePipelineVersion); err != nil {
|
||||
return domain.AttachmentJob{}, false, fmt.Errorf("lock attachment for retry: %w", err)
|
||||
}
|
||||
if activePipelineVersion != job.PipelineVersion || job.Status == domain.AttachmentJobSuperseded {
|
||||
previousStatus := job.Status
|
||||
if job.Status != domain.AttachmentJobSuperseded {
|
||||
_, err = tx.Exec(queryContext, `
|
||||
UPDATE attachment_jobs
|
||||
SET status='superseded', error_code='superseded_pipeline',
|
||||
lease_until=NULL, leased_by=NULL, updated_at=$2
|
||||
WHERE job_id=$1
|
||||
`, jobID, updatedAt)
|
||||
if err == nil {
|
||||
_, err = tx.Exec(queryContext, `
|
||||
INSERT INTO attachment_job_events
|
||||
(job_id, event_type, previous_status, new_status, attempt, error_code, created_at)
|
||||
VALUES ($1, 'superseded', $2, 'superseded', $3, 'superseded_pipeline', $4)
|
||||
`, jobID, previousStatus, job.Attempt, updatedAt)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return domain.AttachmentJob{}, false, err
|
||||
}
|
||||
if err = tx.Commit(queryContext); err != nil {
|
||||
return domain.AttachmentJob{}, false, err
|
||||
}
|
||||
job.Status = domain.AttachmentJobSuperseded
|
||||
job.ErrorCode = stringPointer("superseded_pipeline")
|
||||
job.LeaseUntil = nil
|
||||
job.LeasedBy = nil
|
||||
return job, true, nil
|
||||
}
|
||||
if attachmentStatus == domain.AttachmentStatusReady || job.Status == domain.AttachmentJobSucceeded {
|
||||
_, err = tx.Exec(queryContext, `
|
||||
UPDATE attachment_jobs
|
||||
SET status='succeeded', error_code=NULL, lease_until=NULL, leased_by=NULL, updated_at=$2
|
||||
WHERE job_id=$1
|
||||
`, jobID, updatedAt)
|
||||
if err != nil {
|
||||
return domain.AttachmentJob{}, false, err
|
||||
}
|
||||
if err = tx.Commit(queryContext); err != nil {
|
||||
return domain.AttachmentJob{}, false, err
|
||||
}
|
||||
job.Status = domain.AttachmentJobSucceeded
|
||||
return job, true, nil
|
||||
}
|
||||
if job.Status != domain.AttachmentJobProcessing {
|
||||
if err = tx.Commit(queryContext); err != nil {
|
||||
return domain.AttachmentJob{}, false, err
|
||||
}
|
||||
return job, job.Status == domain.AttachmentJobFailed || job.Status == domain.AttachmentJobSuperseded, nil
|
||||
}
|
||||
if job.Attempt >= job.MaxAttempts {
|
||||
_, err = tx.Exec(queryContext, `
|
||||
UPDATE attachment_jobs
|
||||
SET status='failed', error_code=$2, lease_until=NULL, leased_by=NULL, updated_at=$3
|
||||
WHERE job_id=$1
|
||||
`, jobID, errorCode, updatedAt)
|
||||
if err == nil {
|
||||
_, err = tx.Exec(queryContext, `
|
||||
UPDATE attachments
|
||||
SET status='failed', error_code='retry_exhausted', updated_at=$3
|
||||
WHERE id=$1 AND pipeline_version=$2 AND status <> 'ready'
|
||||
`, job.AttachmentID, job.PipelineVersion, updatedAt)
|
||||
}
|
||||
if err == nil {
|
||||
_, err = tx.Exec(queryContext, `
|
||||
INSERT INTO attachment_job_events
|
||||
(job_id, event_type, previous_status, new_status, attempt, error_code, created_at)
|
||||
VALUES ($1, 'permanent_failure', 'processing', 'failed', $2, $3, $4)
|
||||
`, jobID, job.Attempt, errorCode, updatedAt)
|
||||
}
|
||||
if err != nil {
|
||||
return domain.AttachmentJob{}, false, err
|
||||
}
|
||||
if err = tx.Commit(queryContext); err != nil {
|
||||
return domain.AttachmentJob{}, false, err
|
||||
}
|
||||
job.Status = domain.AttachmentJobFailed
|
||||
job.ErrorCode = &errorCode
|
||||
job.LeaseUntil = nil
|
||||
job.LeasedBy = nil
|
||||
return job, true, nil
|
||||
}
|
||||
|
||||
job.Attempt++
|
||||
_, err = tx.Exec(queryContext, `
|
||||
UPDATE attachment_jobs
|
||||
SET attempt=$2, status='queued', error_code=$3, available_at=$4,
|
||||
published_at=NULL, lease_until=NULL, leased_by=NULL, updated_at=$5
|
||||
WHERE job_id=$1
|
||||
`, jobID, job.Attempt, errorCode, availableAt, updatedAt)
|
||||
if err == nil {
|
||||
_, err = tx.Exec(queryContext, `
|
||||
UPDATE attachments
|
||||
SET status='queued', error_code=NULL, updated_at=$3
|
||||
WHERE id=$1 AND pipeline_version=$2 AND status <> 'ready'
|
||||
`, job.AttachmentID, job.PipelineVersion, updatedAt)
|
||||
}
|
||||
if err == nil {
|
||||
_, err = tx.Exec(queryContext, `
|
||||
INSERT INTO attachment_job_events
|
||||
(job_id, event_type, previous_status, new_status, attempt, error_code, created_at)
|
||||
VALUES ($1, $2, 'processing', 'queued', $3, $4, $5)
|
||||
`, jobID, eventType, job.Attempt, errorCode, updatedAt)
|
||||
}
|
||||
if err != nil {
|
||||
return domain.AttachmentJob{}, false, err
|
||||
}
|
||||
if err = tx.Commit(queryContext); err != nil {
|
||||
return domain.AttachmentJob{}, false, err
|
||||
}
|
||||
job.Status = domain.AttachmentJobQueued
|
||||
job.ErrorCode = &errorCode
|
||||
job.AvailableAt = availableAt
|
||||
job.LeaseUntil = nil
|
||||
job.LeasedBy = nil
|
||||
job.UpdatedAt = updatedAt
|
||||
return job, false, nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) FailAttachmentJob(ctx context.Context, jobID, errorCode string, updatedAt time.Time) error {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
tx, err := s.pool.Begin(queryContext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = tx.Rollback(queryContext) }()
|
||||
|
||||
var attachmentID string
|
||||
var attachmentStatus domain.AttachmentStatus
|
||||
var activePipelineVersion, jobPipelineVersion, attempt int
|
||||
var jobStatus domain.AttachmentJobStatus
|
||||
err = tx.QueryRow(queryContext, `
|
||||
SELECT a.id::text, a.status, a.pipeline_version, j.pipeline_version, j.status, j.attempt
|
||||
FROM attachment_jobs j
|
||||
JOIN attachments a ON a.id=j.attachment_id
|
||||
WHERE j.job_id=$1 FOR UPDATE OF a,j
|
||||
`, jobID).Scan(
|
||||
&attachmentID,
|
||||
&attachmentStatus,
|
||||
&activePipelineVersion,
|
||||
&jobPipelineVersion,
|
||||
&jobStatus,
|
||||
&attempt,
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if activePipelineVersion != jobPipelineVersion || jobStatus == domain.AttachmentJobSuperseded {
|
||||
if jobStatus != domain.AttachmentJobSuperseded {
|
||||
_, err = tx.Exec(queryContext, `
|
||||
UPDATE attachment_jobs
|
||||
SET status='superseded', error_code='superseded_pipeline',
|
||||
lease_until=NULL, leased_by=NULL, updated_at=$2
|
||||
WHERE job_id=$1
|
||||
`, jobID, updatedAt)
|
||||
if err == nil {
|
||||
_, err = tx.Exec(queryContext, `
|
||||
INSERT INTO attachment_job_events
|
||||
(job_id, event_type, previous_status, new_status, attempt, error_code, created_at)
|
||||
VALUES ($1, 'superseded', $2, 'superseded', $3, 'superseded_pipeline', $4)
|
||||
`, jobID, jobStatus, attempt, updatedAt)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit(queryContext)
|
||||
}
|
||||
if attachmentStatus == domain.AttachmentStatusReady || jobStatus == domain.AttachmentJobSucceeded {
|
||||
_, err = tx.Exec(queryContext, `
|
||||
UPDATE attachment_jobs
|
||||
SET status='succeeded', error_code=NULL, lease_until=NULL, leased_by=NULL, updated_at=$2
|
||||
WHERE job_id=$1
|
||||
`, jobID, updatedAt)
|
||||
} else {
|
||||
_, err = tx.Exec(queryContext, `
|
||||
UPDATE attachment_jobs
|
||||
SET status='failed', error_code=$2, lease_until=NULL, leased_by=NULL, updated_at=$3
|
||||
WHERE job_id=$1
|
||||
`, jobID, errorCode, updatedAt)
|
||||
if err == nil {
|
||||
_, err = tx.Exec(queryContext, `
|
||||
UPDATE attachments
|
||||
SET status='failed', error_code=$3, updated_at=$4
|
||||
WHERE id=$1 AND pipeline_version=$2
|
||||
`, attachmentID, jobPipelineVersion, errorCode, updatedAt)
|
||||
}
|
||||
if err == nil {
|
||||
_, err = tx.Exec(queryContext, `
|
||||
INSERT INTO attachment_job_events
|
||||
(job_id, event_type, previous_status, new_status, attempt, error_code, created_at)
|
||||
VALUES ($1, 'permanent_failure', $2, 'failed', $3, $4, $5)
|
||||
`, jobID, jobStatus, attempt, errorCode, updatedAt)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit(queryContext)
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) ListExpiredAttachmentJobs(ctx context.Context, now time.Time, limit int) ([]domain.AttachmentJob, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
rows, err := s.pool.Query(queryContext, `
|
||||
SELECT `+attachmentJobColumns+`
|
||||
FROM attachment_jobs
|
||||
WHERE status='processing' AND lease_until <= $1
|
||||
ORDER BY lease_until, job_id
|
||||
LIMIT $2
|
||||
`, now, limit)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list expired attachment jobs: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
jobs := make([]domain.AttachmentJob, 0)
|
||||
for rows.Next() {
|
||||
var job domain.AttachmentJob
|
||||
if err = scanAttachmentJob(rows, &job); err != nil {
|
||||
return nil, fmt.Errorf("scan expired attachment job: %w", err)
|
||||
}
|
||||
jobs = append(jobs, job)
|
||||
}
|
||||
return jobs, rows.Err()
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) ReplayFailedAttachmentJob(ctx context.Context, jobID string, replayedAt time.Time) (domain.AttachmentJob, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
tx, err := s.pool.Begin(queryContext)
|
||||
if err != nil {
|
||||
return domain.AttachmentJob{}, fmt.Errorf("begin attachment replay: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(queryContext) }()
|
||||
|
||||
var job domain.AttachmentJob
|
||||
err = scanAttachmentJob(tx.QueryRow(queryContext, `
|
||||
SELECT `+attachmentJobColumns+`
|
||||
FROM attachment_jobs WHERE job_id=$1 FOR UPDATE
|
||||
`, jobID), &job)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.AttachmentJob{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return domain.AttachmentJob{}, fmt.Errorf("lock failed job for replay: %w", err)
|
||||
}
|
||||
var attachmentStatus domain.AttachmentStatus
|
||||
var activePipelineVersion int
|
||||
var stagingKey *string
|
||||
if err = tx.QueryRow(queryContext, `
|
||||
SELECT status, staging_key, pipeline_version FROM attachments WHERE id=$1 FOR UPDATE
|
||||
`, job.AttachmentID).Scan(&attachmentStatus, &stagingKey, &activePipelineVersion); err != nil {
|
||||
return domain.AttachmentJob{}, err
|
||||
}
|
||||
if job.Status != domain.AttachmentJobFailed ||
|
||||
attachmentStatus != domain.AttachmentStatusFailed ||
|
||||
activePipelineVersion != job.PipelineVersion {
|
||||
return domain.AttachmentJob{}, fmt.Errorf("only the active failed pipeline can be replayed: %w", ErrConflict)
|
||||
}
|
||||
if stagingKey == nil || *stagingKey == "" {
|
||||
return domain.AttachmentJob{}, fmt.Errorf("failed job staging is no longer retained: %w", ErrConflict)
|
||||
}
|
||||
_, err = tx.Exec(queryContext, `
|
||||
UPDATE attachment_jobs
|
||||
SET attempt=1, status='queued', error_code=NULL, available_at=$2,
|
||||
published_at=NULL, lease_until=NULL, leased_by=NULL,
|
||||
replay_count=replay_count+1, updated_at=$2
|
||||
WHERE job_id=$1
|
||||
`, jobID, replayedAt)
|
||||
if err == nil {
|
||||
_, err = tx.Exec(queryContext, `
|
||||
UPDATE attachments SET status='queued', error_code=NULL, updated_at=$2 WHERE id=$1
|
||||
`, job.AttachmentID, replayedAt)
|
||||
}
|
||||
if err == nil {
|
||||
_, err = tx.Exec(queryContext, `
|
||||
INSERT INTO attachment_job_events
|
||||
(job_id, event_type, previous_status, new_status, attempt, created_at)
|
||||
VALUES ($1, 'operator_replay', 'failed', 'queued', 1, $2)
|
||||
`, jobID, replayedAt)
|
||||
}
|
||||
if err != nil {
|
||||
return domain.AttachmentJob{}, fmt.Errorf("replay failed job: %w", err)
|
||||
}
|
||||
if err = tx.Commit(queryContext); err != nil {
|
||||
return domain.AttachmentJob{}, fmt.Errorf("commit attachment replay: %w", err)
|
||||
}
|
||||
job.Attempt = 1
|
||||
job.Status = domain.AttachmentJobQueued
|
||||
job.ErrorCode = nil
|
||||
job.AvailableAt = replayedAt
|
||||
job.ReplayCount++
|
||||
job.UpdatedAt = replayedAt
|
||||
return job, nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) ListFailedAttachmentJobs(ctx context.Context, limit int) ([]domain.AttachmentJob, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
rows, err := s.pool.Query(queryContext, `
|
||||
SELECT `+attachmentJobColumns+`
|
||||
FROM attachment_jobs
|
||||
WHERE status='failed'
|
||||
ORDER BY updated_at, job_id
|
||||
LIMIT $1
|
||||
`, limit)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list failed attachment jobs: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
jobs := make([]domain.AttachmentJob, 0)
|
||||
for rows.Next() {
|
||||
var job domain.AttachmentJob
|
||||
if err = scanAttachmentJob(rows, &job); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
jobs = append(jobs, job)
|
||||
}
|
||||
return jobs, rows.Err()
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) LookupAttachmentByStagingKey(
|
||||
ctx context.Context,
|
||||
stagingKey string,
|
||||
) (string, domain.AttachmentStatus, time.Time, bool, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
var attachmentID string
|
||||
var status domain.AttachmentStatus
|
||||
var updatedAt time.Time
|
||||
err := s.pool.QueryRow(queryContext, `
|
||||
SELECT id::text, status, updated_at FROM attachments WHERE staging_key=$1
|
||||
`, stagingKey).Scan(&attachmentID, &status, &updatedAt)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return "", "", time.Time{}, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return "", "", time.Time{}, false, err
|
||||
}
|
||||
return attachmentID, status, updatedAt, true, nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) ClearAttachmentStagingKey(ctx context.Context, attachmentID, stagingKey string) error {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
_, err := s.pool.Exec(queryContext, `
|
||||
UPDATE attachments SET staging_key=NULL
|
||||
WHERE id=$1 AND staging_key=$2 AND status IN ('ready','failed')
|
||||
`, attachmentID, stagingKey)
|
||||
if err != nil {
|
||||
return fmt.Errorf("clear attachment staging key: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) ListReadyStagingKeys(
|
||||
ctx context.Context,
|
||||
limit int,
|
||||
) (map[string]string, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
rows, err := s.pool.Query(queryContext, `
|
||||
SELECT staging_key, id::text
|
||||
FROM attachments
|
||||
WHERE status='ready' AND staging_key IS NOT NULL
|
||||
ORDER BY updated_at, id
|
||||
LIMIT $1
|
||||
`, limit)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list ready staging keys: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
keys := make(map[string]string)
|
||||
for rows.Next() {
|
||||
var key, attachmentID string
|
||||
if err = rows.Scan(&key, &attachmentID); err != nil {
|
||||
return nil, fmt.Errorf("scan ready staging key: %w", err)
|
||||
}
|
||||
keys[key] = attachmentID
|
||||
}
|
||||
return keys, rows.Err()
|
||||
}
|
||||
|
||||
func stringPointer(value string) *string { return &value }
|
||||
|
||||
func (s *PostgreSQLStore) GetAttachmentJob(ctx context.Context, jobID string) (domain.AttachmentJob, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
var job domain.AttachmentJob
|
||||
err := scanAttachmentJob(s.pool.QueryRow(queryContext, `
|
||||
SELECT `+attachmentJobColumns+`
|
||||
FROM attachment_jobs WHERE job_id=$1
|
||||
`, jobID), &job)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.AttachmentJob{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return domain.AttachmentJob{}, fmt.Errorf("get attachment job: %w", err)
|
||||
}
|
||||
return job, nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) UpgradeAttachmentPipeline(
|
||||
ctx context.Context,
|
||||
attachmentID string,
|
||||
targetVersion int,
|
||||
stagingKey string,
|
||||
job domain.AttachmentJob,
|
||||
upgradedAt time.Time,
|
||||
) (domain.AttachmentJob, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
tx, err := s.pool.Begin(queryContext)
|
||||
if err != nil {
|
||||
return domain.AttachmentJob{}, fmt.Errorf("begin pipeline upgrade: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(queryContext) }()
|
||||
|
||||
var status domain.AttachmentStatus
|
||||
var currentVersion int
|
||||
err = tx.QueryRow(queryContext, `
|
||||
SELECT status, pipeline_version
|
||||
FROM attachments WHERE id=$1 FOR UPDATE
|
||||
`, attachmentID).Scan(&status, ¤tVersion)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.AttachmentJob{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return domain.AttachmentJob{}, fmt.Errorf("lock attachment for pipeline upgrade: %w", err)
|
||||
}
|
||||
if targetVersion != currentVersion+1 ||
|
||||
(status != domain.AttachmentStatusReady && status != domain.AttachmentStatusProcessing) {
|
||||
return domain.AttachmentJob{}, fmt.Errorf("pipeline upgrade requires ready/processing current version and next target version: %w", ErrConflict)
|
||||
}
|
||||
|
||||
_, err = tx.Exec(queryContext, `
|
||||
INSERT INTO attachment_job_events
|
||||
(job_id, event_type, previous_status, new_status, attempt, error_code, created_at)
|
||||
SELECT job_id, 'superseded', status, 'superseded', attempt, 'superseded_pipeline', $3
|
||||
FROM attachment_jobs
|
||||
WHERE attachment_id=$1 AND pipeline_version < $2
|
||||
AND status IN ('queued','processing')
|
||||
`, attachmentID, targetVersion, upgradedAt)
|
||||
if err == nil {
|
||||
_, err = tx.Exec(queryContext, `
|
||||
UPDATE attachment_jobs
|
||||
SET status='superseded', error_code='superseded_pipeline',
|
||||
lease_until=NULL, leased_by=NULL, updated_at=$3
|
||||
WHERE attachment_id=$1 AND pipeline_version < $2
|
||||
AND status IN ('queued','processing')
|
||||
`, attachmentID, targetVersion, upgradedAt)
|
||||
}
|
||||
if err == nil {
|
||||
_, err = tx.Exec(queryContext, `
|
||||
UPDATE attachments
|
||||
SET pipeline_version=$2, staging_key=$3, status='queued',
|
||||
error_code=NULL, updated_at=$4
|
||||
WHERE id=$1
|
||||
`, attachmentID, targetVersion, stagingKey, upgradedAt)
|
||||
}
|
||||
if job.AvailableAt.IsZero() {
|
||||
job.AvailableAt = upgradedAt
|
||||
}
|
||||
if err == nil {
|
||||
_, err = tx.Exec(queryContext, `
|
||||
INSERT INTO attachment_jobs (
|
||||
job_id, attachment_id, schema_version, job_type, pipeline_version,
|
||||
attempt, max_attempts, status, available_at, created_at, updated_at,
|
||||
traceparent, tracestate
|
||||
) VALUES ($1,$2,$3,$4,$5,$6,$7,'queued',$8,$9,$10,$11,$12)
|
||||
`, job.JobID, attachmentID, job.SchemaVersion, job.Type, targetVersion,
|
||||
job.Attempt, job.MaxAttempts, job.AvailableAt, job.CreatedAt, job.UpdatedAt,
|
||||
job.TraceParent, job.TraceState)
|
||||
}
|
||||
if err == nil {
|
||||
_, err = tx.Exec(queryContext, `
|
||||
INSERT INTO attachment_job_events
|
||||
(job_id, event_type, previous_status, new_status, attempt, created_at)
|
||||
VALUES ($1, 'version_upgrade', 'queued', 'queued', $2, $3)
|
||||
`, job.JobID, job.Attempt, upgradedAt)
|
||||
}
|
||||
if err != nil {
|
||||
return domain.AttachmentJob{}, fmt.Errorf("apply pipeline upgrade: %w", err)
|
||||
}
|
||||
if err = tx.Commit(queryContext); err != nil {
|
||||
return domain.AttachmentJob{}, fmt.Errorf("commit pipeline upgrade: %w", err)
|
||||
}
|
||||
job.Status = domain.AttachmentJobQueued
|
||||
job.PipelineVersion = targetVersion
|
||||
job.AvailableAt = upgradedAt
|
||||
job.UpdatedAt = upgradedAt
|
||||
return job, nil
|
||||
}
|
||||
@@ -0,0 +1,372 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab7/internal/domain"
|
||||
"mtusi2026lab7/internal/reconcile"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func (s *PostgreSQLStore) CreateAttachment(
|
||||
ctx context.Context,
|
||||
attachment domain.Attachment,
|
||||
) (domain.Attachment, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
err := s.pool.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
INSERT INTO attachments (
|
||||
id, chat_id, owner_id, object_key, filename, content_type,
|
||||
size_bytes, sha256, width, height, status, error_code,
|
||||
created_at, updated_at
|
||||
)
|
||||
VALUES (
|
||||
$1, $2, $3, $4, $5, $6,
|
||||
$7, decode($8, 'hex'), $9, $10, $11, $12,
|
||||
$13, $14
|
||||
)
|
||||
RETURNING created_at, updated_at
|
||||
`,
|
||||
attachment.ID,
|
||||
attachment.ChatID,
|
||||
attachment.OwnerID,
|
||||
attachment.ObjectKey,
|
||||
attachment.Filename,
|
||||
attachment.ContentType,
|
||||
attachment.SizeBytes,
|
||||
attachment.SHA256,
|
||||
attachment.Width,
|
||||
attachment.Height,
|
||||
attachment.Status,
|
||||
attachment.ErrorCode,
|
||||
attachment.CreatedAt,
|
||||
attachment.UpdatedAt,
|
||||
).Scan(&attachment.CreatedAt, &attachment.UpdatedAt)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("insert attachment metadata: %w", err)
|
||||
}
|
||||
if attachment.Variants == nil {
|
||||
attachment.Variants = make([]domain.AttachmentVariant, 0)
|
||||
}
|
||||
return attachment, nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) MarkAttachmentReady(
|
||||
ctx context.Context,
|
||||
attachmentID string,
|
||||
updatedAt time.Time,
|
||||
) (domain.Attachment, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
var attachment domain.Attachment
|
||||
var sha256Bytes []byte
|
||||
err := s.pool.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
UPDATE attachments
|
||||
SET status = 'ready', error_code = NULL, updated_at = $2
|
||||
WHERE id = $1 AND status IN ('queued', 'processing')
|
||||
RETURNING
|
||||
id::text, chat_id::text, owner_id::text, object_key,
|
||||
filename, content_type, size_bytes, sha256, width, height,
|
||||
pipeline_version, status, error_code, created_at, updated_at
|
||||
`,
|
||||
attachmentID,
|
||||
updatedAt,
|
||||
).Scan(
|
||||
&attachment.ID,
|
||||
&attachment.ChatID,
|
||||
&attachment.OwnerID,
|
||||
&attachment.ObjectKey,
|
||||
&attachment.Filename,
|
||||
&attachment.ContentType,
|
||||
&attachment.SizeBytes,
|
||||
&sha256Bytes,
|
||||
&attachment.Width,
|
||||
&attachment.Height,
|
||||
&attachment.PipelineVersion,
|
||||
&attachment.Status,
|
||||
&attachment.ErrorCode,
|
||||
&attachment.CreatedAt,
|
||||
&attachment.UpdatedAt,
|
||||
)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.Attachment{}, ErrConflict
|
||||
}
|
||||
if err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("mark attachment ready: %w", err)
|
||||
}
|
||||
attachment.SHA256 = fmt.Sprintf("%x", sha256Bytes)
|
||||
attachment.Variants, err = s.listAttachmentVariants(queryContext, attachment.ID, attachment.PipelineVersion)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
return attachment, nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) MarkAttachmentFailed(
|
||||
ctx context.Context,
|
||||
attachmentID string,
|
||||
errorCode string,
|
||||
updatedAt time.Time,
|
||||
) error {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
commandTag, err := s.pool.Exec(
|
||||
queryContext,
|
||||
`
|
||||
UPDATE attachments
|
||||
SET status = 'failed', error_code = $2, updated_at = $3
|
||||
WHERE id = $1 AND status IN ('queued', 'processing')
|
||||
`,
|
||||
attachmentID,
|
||||
errorCode,
|
||||
updatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("mark attachment failed: %w", err)
|
||||
}
|
||||
if commandTag.RowsAffected() != 1 {
|
||||
return ErrConflict
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) GetAttachment(
|
||||
ctx context.Context,
|
||||
attachmentID string,
|
||||
callerID string,
|
||||
) (domain.Attachment, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
var attachment domain.Attachment
|
||||
var sha256Bytes []byte
|
||||
err := s.pool.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
SELECT
|
||||
a.id::text, a.chat_id::text, a.owner_id::text, a.object_key,
|
||||
a.filename, a.content_type, a.size_bytes, a.sha256,
|
||||
a.width, a.height, a.pipeline_version, a.status, a.error_code,
|
||||
a.created_at, a.updated_at
|
||||
FROM attachments AS a
|
||||
JOIN chat_members AS cm
|
||||
ON cm.chat_id = a.chat_id AND cm.user_id = $2
|
||||
WHERE a.id = $1
|
||||
`,
|
||||
attachmentID,
|
||||
callerID,
|
||||
).Scan(
|
||||
&attachment.ID,
|
||||
&attachment.ChatID,
|
||||
&attachment.OwnerID,
|
||||
&attachment.ObjectKey,
|
||||
&attachment.Filename,
|
||||
&attachment.ContentType,
|
||||
&attachment.SizeBytes,
|
||||
&sha256Bytes,
|
||||
&attachment.Width,
|
||||
&attachment.Height,
|
||||
&attachment.PipelineVersion,
|
||||
&attachment.Status,
|
||||
&attachment.ErrorCode,
|
||||
&attachment.CreatedAt,
|
||||
&attachment.UpdatedAt,
|
||||
)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.Attachment{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("get attachment metadata: %w", err)
|
||||
}
|
||||
attachment.SHA256 = fmt.Sprintf("%x", sha256Bytes)
|
||||
attachment.Variants, err = s.listAttachmentVariants(queryContext, attachment.ID, attachment.PipelineVersion)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
return attachment, nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) ListAttachmentInventory(
|
||||
ctx context.Context,
|
||||
) ([]reconcile.AttachmentRecord, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
rows, err := s.pool.Query(
|
||||
queryContext,
|
||||
`
|
||||
SELECT
|
||||
a.id::text,
|
||||
a.object_key,
|
||||
a.status,
|
||||
a.updated_at,
|
||||
EXISTS (
|
||||
SELECT 1
|
||||
FROM message_attachments AS ma
|
||||
WHERE ma.attachment_id = a.id
|
||||
) AS referenced,
|
||||
COALESCE(a.staging_key, ''),
|
||||
COALESCE(av.object_key, '')
|
||||
FROM attachments AS a
|
||||
LEFT JOIN attachment_variants AS av ON av.attachment_id = a.id
|
||||
ORDER BY a.id, av.pipeline_version, av.name
|
||||
`,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("query attachment inventory: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
records := make([]reconcile.AttachmentRecord, 0)
|
||||
recordIndexes := make(map[string]int)
|
||||
for rows.Next() {
|
||||
var record reconcile.AttachmentRecord
|
||||
var stagingKey string
|
||||
var variantKey string
|
||||
if err = rows.Scan(
|
||||
&record.ID,
|
||||
&record.ObjectKey,
|
||||
&record.Status,
|
||||
&record.UpdatedAt,
|
||||
&record.Referenced,
|
||||
&stagingKey,
|
||||
&variantKey,
|
||||
); err != nil {
|
||||
return nil, fmt.Errorf("scan attachment inventory: %w", err)
|
||||
}
|
||||
if recordIndex, exists := recordIndexes[record.ID]; exists {
|
||||
if variantKey != "" {
|
||||
records[recordIndex].AdditionalObjectKeys = append(
|
||||
records[recordIndex].AdditionalObjectKeys,
|
||||
variantKey,
|
||||
)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if stagingKey != "" {
|
||||
record.AdditionalObjectKeys = append(record.AdditionalObjectKeys, stagingKey)
|
||||
}
|
||||
if variantKey != "" {
|
||||
record.AdditionalObjectKeys = append(record.AdditionalObjectKeys, variantKey)
|
||||
}
|
||||
recordIndexes[record.ID] = len(records)
|
||||
records = append(records, record)
|
||||
}
|
||||
if err = rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("iterate attachment inventory: %w", err)
|
||||
}
|
||||
return records, nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) MarkAttachmentFailedIfUnreferenced(
|
||||
ctx context.Context,
|
||||
attachmentID string,
|
||||
expectedStatus domain.AttachmentStatus,
|
||||
updatedBefore time.Time,
|
||||
errorCode string,
|
||||
updatedAt time.Time,
|
||||
) (bool, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
transaction, err := s.pool.BeginTx(queryContext, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("begin attachment reconciliation transaction: %w", err)
|
||||
}
|
||||
defer func() { _ = transaction.Rollback(queryContext) }()
|
||||
|
||||
var lockedAttachmentID string
|
||||
err = transaction.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
SELECT id::text
|
||||
FROM attachments
|
||||
WHERE id = $1
|
||||
FOR UPDATE
|
||||
`,
|
||||
attachmentID,
|
||||
).Scan(&lockedAttachmentID)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("lock attachment during reconciliation: %w", err)
|
||||
}
|
||||
|
||||
// This is deliberately a second statement. Under READ COMMITTED it gets a
|
||||
// fresh snapshot after the row lock was acquired, so a message transaction
|
||||
// that linked this attachment while we waited is visible to NOT EXISTS.
|
||||
commandTag, err := transaction.Exec(
|
||||
queryContext,
|
||||
`
|
||||
UPDATE attachments AS a
|
||||
SET status = 'failed', error_code = $4, updated_at = $5
|
||||
WHERE a.id = $1
|
||||
AND a.status = $2
|
||||
AND a.updated_at <= $3
|
||||
AND NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM message_attachments AS ma
|
||||
WHERE ma.attachment_id = a.id
|
||||
)
|
||||
`,
|
||||
attachmentID,
|
||||
expectedStatus,
|
||||
updatedBefore,
|
||||
errorCode,
|
||||
updatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("mark attachment failed during reconciliation: %w", err)
|
||||
}
|
||||
if err = transaction.Commit(queryContext); err != nil {
|
||||
return false, fmt.Errorf("commit attachment reconciliation: %w", err)
|
||||
}
|
||||
return commandTag.RowsAffected() == 1, nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) listAttachmentVariants(
|
||||
ctx context.Context,
|
||||
attachmentID string,
|
||||
pipelineVersion int,
|
||||
) ([]domain.AttachmentVariant, error) {
|
||||
if pipelineVersion < 1 {
|
||||
pipelineVersion = 1
|
||||
}
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT name, object_key, content_type, size_bytes, width, height, sha256, pipeline_version
|
||||
FROM attachment_variants
|
||||
WHERE attachment_id = $1 AND pipeline_version = $2
|
||||
ORDER BY name
|
||||
`, attachmentID, pipelineVersion)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("query attachment variants: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
variants := make([]domain.AttachmentVariant, 0)
|
||||
for rows.Next() {
|
||||
var variant domain.AttachmentVariant
|
||||
var digest []byte
|
||||
if err = rows.Scan(&variant.Name, &variant.ObjectKey, &variant.ContentType, &variant.SizeBytes, &variant.Width, &variant.Height, &digest, &variant.PipelineVersion); err != nil {
|
||||
return nil, fmt.Errorf("scan attachment variant: %w", err)
|
||||
}
|
||||
variant.SHA256 = fmt.Sprintf("%x", digest)
|
||||
variants = append(variants, variant)
|
||||
}
|
||||
if err = rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("iterate attachment variants: %w", err)
|
||||
}
|
||||
return variants, nil
|
||||
}
|
||||
|
||||
var _ reconcile.MetadataStore = (*PostgreSQLStore)(nil)
|
||||
@@ -0,0 +1,278 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"mtusi2026lab7/internal/domain"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func (s *PostgreSQLStore) CreateChat(
|
||||
ctx context.Context,
|
||||
title string,
|
||||
memberIDs []string,
|
||||
) (domain.Chat, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
transaction, err := s.pool.Begin(queryContext)
|
||||
if err != nil {
|
||||
return domain.Chat{}, fmt.Errorf(
|
||||
"begin create chat transaction: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
_ = transaction.Rollback(queryContext)
|
||||
}()
|
||||
|
||||
chat := domain.Chat{
|
||||
ID: uuid.NewString(),
|
||||
Title: title,
|
||||
MemberIDs: append([]string(nil), memberIDs...),
|
||||
}
|
||||
|
||||
err = transaction.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
INSERT INTO chats (
|
||||
id,
|
||||
title
|
||||
)
|
||||
VALUES ($1, $2)
|
||||
RETURNING created_at
|
||||
`,
|
||||
chat.ID,
|
||||
chat.Title,
|
||||
).Scan(&chat.CreatedAt)
|
||||
if err != nil {
|
||||
return domain.Chat{}, fmt.Errorf("insert chat: %w", err)
|
||||
}
|
||||
|
||||
for position, memberID := range memberIDs {
|
||||
commandTag, insertErr := transaction.Exec(
|
||||
queryContext,
|
||||
`
|
||||
INSERT INTO chat_members (
|
||||
chat_id,
|
||||
user_id,
|
||||
position
|
||||
)
|
||||
SELECT
|
||||
$1,
|
||||
id,
|
||||
$3
|
||||
FROM users
|
||||
WHERE id = $2
|
||||
`,
|
||||
chat.ID,
|
||||
memberID,
|
||||
position,
|
||||
)
|
||||
if insertErr != nil {
|
||||
return domain.Chat{}, fmt.Errorf(
|
||||
"insert chat member %s: %w",
|
||||
memberID,
|
||||
insertErr,
|
||||
)
|
||||
}
|
||||
|
||||
// INSERT ... SELECT не вставляет строку, если пользователя нет.
|
||||
// Возврат из функции активирует deferred Rollback: уже созданные
|
||||
// chat и предыдущие membership-строки не останутся в базе.
|
||||
if commandTag.RowsAffected() != 1 {
|
||||
return domain.Chat{}, fmt.Errorf(
|
||||
"%w: member %s",
|
||||
ErrNotFound,
|
||||
memberID,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if err = transaction.Commit(queryContext); err != nil {
|
||||
return domain.Chat{}, fmt.Errorf(
|
||||
"commit create chat transaction: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) GetChatByID(
|
||||
ctx context.Context,
|
||||
chatID string,
|
||||
callerID string,
|
||||
) (domain.Chat, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
var chat domain.Chat
|
||||
|
||||
err := s.pool.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
SELECT
|
||||
chat.id::text,
|
||||
chat.title,
|
||||
chat.created_at,
|
||||
array_agg(
|
||||
member.user_id::text
|
||||
ORDER BY member.position
|
||||
)
|
||||
FROM chats AS chat
|
||||
JOIN chat_members AS caller
|
||||
ON caller.chat_id = chat.id
|
||||
AND caller.user_id = $2
|
||||
JOIN chat_members AS member
|
||||
ON member.chat_id = chat.id
|
||||
WHERE chat.id = $1
|
||||
GROUP BY
|
||||
chat.id,
|
||||
chat.title,
|
||||
chat.created_at
|
||||
`,
|
||||
chatID,
|
||||
callerID,
|
||||
).Scan(
|
||||
&chat.ID,
|
||||
&chat.Title,
|
||||
&chat.CreatedAt,
|
||||
&chat.MemberIDs,
|
||||
)
|
||||
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.Chat{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return domain.Chat{}, fmt.Errorf("select chat by id: %w", err)
|
||||
}
|
||||
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) GetChatsForUser(
|
||||
ctx context.Context,
|
||||
userID string,
|
||||
limit int,
|
||||
cursor *domain.ChatCursor,
|
||||
) ([]domain.Chat, bool, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
var (
|
||||
rows pgx.Rows
|
||||
err error
|
||||
)
|
||||
|
||||
if cursor == nil {
|
||||
rows, err = s.pool.Query(
|
||||
queryContext,
|
||||
`
|
||||
SELECT
|
||||
chat.id::text,
|
||||
chat.title,
|
||||
chat.created_at,
|
||||
array_agg(
|
||||
member.user_id::text
|
||||
ORDER BY member.position
|
||||
)
|
||||
FROM chat_members AS own_membership
|
||||
JOIN chats AS chat
|
||||
ON chat.id = own_membership.chat_id
|
||||
JOIN chat_members AS member
|
||||
ON member.chat_id = chat.id
|
||||
WHERE own_membership.user_id = $1
|
||||
GROUP BY
|
||||
chat.id,
|
||||
chat.title,
|
||||
chat.created_at
|
||||
ORDER BY
|
||||
chat.created_at,
|
||||
chat.id
|
||||
LIMIT $2
|
||||
`,
|
||||
userID,
|
||||
limit+1,
|
||||
)
|
||||
} else {
|
||||
rows, err = s.pool.Query(
|
||||
queryContext,
|
||||
`
|
||||
SELECT
|
||||
chat.id::text,
|
||||
chat.title,
|
||||
chat.created_at,
|
||||
array_agg(
|
||||
member.user_id::text
|
||||
ORDER BY member.position
|
||||
)
|
||||
FROM chat_members AS own_membership
|
||||
JOIN chats AS chat
|
||||
ON chat.id = own_membership.chat_id
|
||||
JOIN chat_members AS member
|
||||
ON member.chat_id = chat.id
|
||||
WHERE own_membership.user_id = $1
|
||||
AND (chat.created_at, chat.id) > ($2, $3)
|
||||
GROUP BY
|
||||
chat.id,
|
||||
chat.title,
|
||||
chat.created_at
|
||||
ORDER BY
|
||||
chat.created_at,
|
||||
chat.id
|
||||
LIMIT $4
|
||||
`,
|
||||
userID,
|
||||
cursor.CreatedAt,
|
||||
cursor.ChatID,
|
||||
limit+1,
|
||||
)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf(
|
||||
"query chats for user: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
items := make([]domain.Chat, 0, limit+1)
|
||||
|
||||
for rows.Next() {
|
||||
var chat domain.Chat
|
||||
|
||||
if err := rows.Scan(
|
||||
&chat.ID,
|
||||
&chat.Title,
|
||||
&chat.CreatedAt,
|
||||
&chat.MemberIDs,
|
||||
); err != nil {
|
||||
return nil, false, fmt.Errorf(
|
||||
"scan chat page: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
items = append(items, chat)
|
||||
}
|
||||
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, false, fmt.Errorf(
|
||||
"iterate chat page: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
hasMore := len(items) > limit
|
||||
if hasMore {
|
||||
items = items[:limit]
|
||||
}
|
||||
return items, hasMore, nil
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package postgres
|
||||
|
||||
import "mtusi2026lab7/internal/application"
|
||||
|
||||
var _ application.Repository = (*PostgreSQLStore)(nil)
|
||||
@@ -0,0 +1,8 @@
|
||||
package postgres
|
||||
|
||||
import "mtusi2026lab7/internal/domain"
|
||||
|
||||
var (
|
||||
ErrNotFound = domain.ErrNotFound
|
||||
ErrConflict = domain.ErrConflict
|
||||
)
|
||||
@@ -0,0 +1,75 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
func (s *PostgreSQLStore) AllowLoginAttempt(
|
||||
ctx context.Context,
|
||||
identifierHash [32]byte,
|
||||
now time.Time,
|
||||
window time.Duration,
|
||||
limit int,
|
||||
) (bool, time.Duration, error) {
|
||||
if err := s.maybePruneExpiredState(ctx, now); err != nil {
|
||||
return false, 0, err
|
||||
}
|
||||
if err := s.maybePruneExpiredLoginRateState(ctx, now, window); err != nil {
|
||||
return false, 0, err
|
||||
}
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
var attempts int
|
||||
var windowStartedAt time.Time
|
||||
err := s.pool.QueryRow(queryContext, `
|
||||
INSERT INTO login_rate_limits (
|
||||
identifier_hash, window_started_at, attempts
|
||||
)
|
||||
VALUES ($1, $2, 1)
|
||||
ON CONFLICT (identifier_hash) DO UPDATE
|
||||
SET
|
||||
window_started_at = CASE
|
||||
WHEN login_rate_limits.window_started_at <= $3
|
||||
THEN EXCLUDED.window_started_at
|
||||
ELSE login_rate_limits.window_started_at
|
||||
END,
|
||||
attempts = CASE
|
||||
WHEN login_rate_limits.window_started_at <= $3 THEN 1
|
||||
ELSE login_rate_limits.attempts + 1
|
||||
END
|
||||
RETURNING attempts, window_started_at
|
||||
`, identifierHash[:], now.UTC(), now.UTC().Add(-window)).Scan(
|
||||
&attempts,
|
||||
&windowStartedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return false, 0, fmt.Errorf("update login rate limit: %w", err)
|
||||
}
|
||||
if attempts <= limit {
|
||||
return true, 0, nil
|
||||
}
|
||||
retryAfter := windowStartedAt.Add(window).Sub(now.UTC())
|
||||
if retryAfter < time.Second {
|
||||
retryAfter = time.Second
|
||||
}
|
||||
return false, retryAfter, nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) ResetLoginAttempts(
|
||||
ctx context.Context,
|
||||
identifierHash [32]byte,
|
||||
) error {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
if _, err := s.pool.Exec(
|
||||
queryContext,
|
||||
`DELETE FROM login_rate_limits WHERE identifier_hash = $1`,
|
||||
identifierHash[:],
|
||||
); err != nil {
|
||||
return fmt.Errorf("reset login rate limit: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
expiredStatePruneEvery = 128
|
||||
expiredStatePruneBatch = 256
|
||||
)
|
||||
|
||||
// maybePruneExpiredState bounds session/idempotency table growth without adding
|
||||
// a cleanup round trip to every request. The first operation after process
|
||||
// start prunes immediately; later operations amortize one bounded indexed
|
||||
// delete per expiredStatePruneEvery writes.
|
||||
func (s *PostgreSQLStore) maybePruneExpiredState(ctx context.Context, now time.Time) error {
|
||||
iteration := s.expiredStatePruneCounter.Add(1)
|
||||
if iteration != 1 && iteration%expiredStatePruneEvery != 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
_, err := s.pool.Exec(queryContext, `
|
||||
WITH stale_sessions AS (
|
||||
SELECT token_hash
|
||||
FROM sessions
|
||||
WHERE expires_at <= $1
|
||||
ORDER BY expires_at
|
||||
LIMIT $2
|
||||
FOR UPDATE SKIP LOCKED
|
||||
), deleted_sessions AS (
|
||||
DELETE FROM sessions AS target
|
||||
USING stale_sessions AS stale
|
||||
WHERE target.token_hash = stale.token_hash
|
||||
RETURNING 1
|
||||
), stale_idempotency AS (
|
||||
SELECT user_id, method, canonical_path, idempotency_key
|
||||
FROM message_idempotency
|
||||
WHERE expires_at <= $1
|
||||
ORDER BY expires_at
|
||||
LIMIT $2
|
||||
FOR UPDATE SKIP LOCKED
|
||||
), deleted_idempotency AS (
|
||||
DELETE FROM message_idempotency AS target
|
||||
USING stale_idempotency AS stale
|
||||
WHERE target.user_id = stale.user_id
|
||||
AND target.method = stale.method
|
||||
AND target.canonical_path = stale.canonical_path
|
||||
AND target.idempotency_key = stale.idempotency_key
|
||||
RETURNING 1
|
||||
)
|
||||
SELECT
|
||||
(SELECT count(*) FROM deleted_sessions),
|
||||
(SELECT count(*) FROM deleted_idempotency)
|
||||
`, now.UTC(), expiredStatePruneBatch)
|
||||
if err != nil {
|
||||
return fmt.Errorf("prune expired auth state: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// maybePruneExpiredLoginRateState uses the configured limiter window as the
|
||||
// cutoff. Comparing with now directly would delete active windows and weaken
|
||||
// the limiter whenever maintenance runs.
|
||||
func (s *PostgreSQLStore) maybePruneExpiredLoginRateState(
|
||||
ctx context.Context,
|
||||
now time.Time,
|
||||
window time.Duration,
|
||||
) error {
|
||||
iteration := s.loginRatePruneCounter.Add(1)
|
||||
if iteration != 1 && iteration%expiredStatePruneEvery != 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
_, err := s.pool.Exec(queryContext, `
|
||||
WITH stale_login_limits AS (
|
||||
SELECT identifier_hash
|
||||
FROM login_rate_limits
|
||||
WHERE window_started_at <= $1
|
||||
ORDER BY window_started_at
|
||||
LIMIT $2
|
||||
FOR UPDATE SKIP LOCKED
|
||||
)
|
||||
DELETE FROM login_rate_limits AS target
|
||||
USING stale_login_limits AS stale
|
||||
WHERE target.identifier_hash = stale.identifier_hash
|
||||
`, now.UTC().Add(-window), expiredStatePruneBatch)
|
||||
if err != nil {
|
||||
return fmt.Errorf("prune expired login rate state: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,426 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab7/internal/application"
|
||||
"mtusi2026lab7/internal/domain"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func (s *PostgreSQLStore) CreateMessageIdempotently(
|
||||
ctx context.Context,
|
||||
write application.IdempotentMessageWrite,
|
||||
) (domain.Message, error) {
|
||||
if err := s.maybePruneExpiredState(ctx, time.Now()); err != nil {
|
||||
return domain.Message{}, err
|
||||
}
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
transaction, err := s.pool.BeginTx(queryContext, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return domain.Message{}, fmt.Errorf("begin idempotent message transaction: %w", err)
|
||||
}
|
||||
defer func() { _ = transaction.Rollback(queryContext) }()
|
||||
|
||||
var isMember bool
|
||||
err = transaction.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
SELECT EXISTS (
|
||||
SELECT 1
|
||||
FROM chat_members
|
||||
WHERE chat_id = $1
|
||||
AND user_id = $2
|
||||
)
|
||||
`,
|
||||
write.ChatID,
|
||||
write.ActorID,
|
||||
).Scan(&isMember)
|
||||
if err != nil {
|
||||
return domain.Message{}, fmt.Errorf("check chat membership: %w", err)
|
||||
}
|
||||
if !isMember {
|
||||
return domain.Message{}, ErrNotFound
|
||||
}
|
||||
|
||||
attachmentUUIDs := make([]uuid.UUID, len(write.AttachmentIDs))
|
||||
for index, attachmentID := range write.AttachmentIDs {
|
||||
parsedID, parseErr := uuid.Parse(attachmentID)
|
||||
if parseErr != nil {
|
||||
return domain.Message{}, fmt.Errorf("parse validated attachment id: %w", parseErr)
|
||||
}
|
||||
attachmentUUIDs[index] = parsedID
|
||||
}
|
||||
|
||||
if len(attachmentUUIDs) > 0 {
|
||||
rows, queryError := transaction.Query(
|
||||
queryContext,
|
||||
`
|
||||
SELECT id::text, status
|
||||
FROM attachments
|
||||
WHERE chat_id = $1
|
||||
AND id = ANY($2::uuid[])
|
||||
ORDER BY id
|
||||
FOR UPDATE
|
||||
`,
|
||||
write.ChatID,
|
||||
attachmentUUIDs,
|
||||
)
|
||||
if queryError != nil {
|
||||
return domain.Message{}, fmt.Errorf("lock message attachments: %w", queryError)
|
||||
}
|
||||
availableCount := 0
|
||||
eligibleCount := 0
|
||||
for rows.Next() {
|
||||
var attachmentID string
|
||||
var status domain.AttachmentStatus
|
||||
if queryError = rows.Scan(&attachmentID, &status); queryError != nil {
|
||||
rows.Close()
|
||||
return domain.Message{}, fmt.Errorf("scan locked message attachment: %w", queryError)
|
||||
}
|
||||
availableCount++
|
||||
if status != domain.AttachmentStatusFailed {
|
||||
eligibleCount++
|
||||
}
|
||||
}
|
||||
queryError = rows.Err()
|
||||
rows.Close()
|
||||
if queryError != nil {
|
||||
return domain.Message{}, fmt.Errorf("iterate locked message attachments: %w", queryError)
|
||||
}
|
||||
if availableCount != len(attachmentUUIDs) {
|
||||
return domain.Message{}, ErrNotFound
|
||||
}
|
||||
if eligibleCount != len(attachmentUUIDs) {
|
||||
return domain.Message{}, application.ErrAttachmentNotReady
|
||||
}
|
||||
}
|
||||
|
||||
_, err = transaction.Exec(
|
||||
queryContext,
|
||||
`
|
||||
DELETE FROM message_idempotency
|
||||
WHERE user_id = $1
|
||||
AND method = $2
|
||||
AND canonical_path = $3
|
||||
AND idempotency_key = $4
|
||||
AND expires_at <= CURRENT_TIMESTAMP
|
||||
`,
|
||||
write.ActorID,
|
||||
write.Method,
|
||||
write.CanonicalPath,
|
||||
write.Key,
|
||||
)
|
||||
if err != nil {
|
||||
return domain.Message{}, fmt.Errorf("delete expired idempotency key: %w", err)
|
||||
}
|
||||
|
||||
message := domain.Message{
|
||||
ID: uuid.NewString(),
|
||||
ChatID: write.ChatID,
|
||||
SenderID: write.ActorID,
|
||||
Text: write.Text,
|
||||
AttachmentIDs: append([]string(nil), write.AttachmentIDs...),
|
||||
}
|
||||
|
||||
var storedHash []byte
|
||||
var storedMessageID string
|
||||
err = transaction.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
INSERT INTO message_idempotency (
|
||||
user_id,
|
||||
method,
|
||||
canonical_path,
|
||||
idempotency_key,
|
||||
request_hash,
|
||||
message_id,
|
||||
expires_at
|
||||
)
|
||||
VALUES (
|
||||
$1,
|
||||
$2,
|
||||
$3,
|
||||
$4,
|
||||
$5,
|
||||
$6,
|
||||
CURRENT_TIMESTAMP + $7 * INTERVAL '1 second'
|
||||
)
|
||||
ON CONFLICT DO NOTHING
|
||||
RETURNING request_hash, message_id::text
|
||||
`,
|
||||
write.ActorID,
|
||||
write.Method,
|
||||
write.CanonicalPath,
|
||||
write.Key,
|
||||
write.RequestHash[:],
|
||||
message.ID,
|
||||
int64(write.TTL/time.Second),
|
||||
).Scan(&storedHash, &storedMessageID)
|
||||
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
err = transaction.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
SELECT request_hash, message_id::text
|
||||
FROM message_idempotency
|
||||
WHERE user_id = $1
|
||||
AND method = $2
|
||||
AND canonical_path = $3
|
||||
AND idempotency_key = $4
|
||||
`,
|
||||
write.ActorID,
|
||||
write.Method,
|
||||
write.CanonicalPath,
|
||||
write.Key,
|
||||
).Scan(&storedHash, &storedMessageID)
|
||||
if err != nil {
|
||||
return domain.Message{}, fmt.Errorf("read idempotency result: %w", err)
|
||||
}
|
||||
|
||||
if !bytes.Equal(storedHash, write.RequestHash[:]) {
|
||||
return domain.Message{}, application.ErrIdempotencyConflict
|
||||
}
|
||||
|
||||
err = transaction.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
SELECT
|
||||
id::text,
|
||||
chat_id::text,
|
||||
sender_id::text,
|
||||
text,
|
||||
created_at,
|
||||
COALESCE(
|
||||
ARRAY(
|
||||
SELECT attachment_id::text
|
||||
FROM message_attachments
|
||||
WHERE message_id = messages.id
|
||||
ORDER BY position
|
||||
), ARRAY[]::text[]
|
||||
)
|
||||
FROM messages
|
||||
WHERE id = $1
|
||||
`,
|
||||
storedMessageID,
|
||||
).Scan(
|
||||
&message.ID,
|
||||
&message.ChatID,
|
||||
&message.SenderID,
|
||||
&message.Text,
|
||||
&message.CreatedAt,
|
||||
&message.AttachmentIDs,
|
||||
)
|
||||
if err != nil {
|
||||
return domain.Message{}, fmt.Errorf("read idempotent message: %w", err)
|
||||
}
|
||||
|
||||
if err = transaction.Commit(queryContext); err != nil {
|
||||
return domain.Message{}, fmt.Errorf("commit idempotency replay: %w", err)
|
||||
}
|
||||
return message, nil
|
||||
}
|
||||
if err != nil {
|
||||
return domain.Message{}, fmt.Errorf("claim idempotency key: %w", err)
|
||||
}
|
||||
|
||||
err = transaction.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
INSERT INTO messages (
|
||||
id,
|
||||
chat_id,
|
||||
sender_id,
|
||||
text
|
||||
)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING created_at
|
||||
`,
|
||||
message.ID,
|
||||
message.ChatID,
|
||||
message.SenderID,
|
||||
message.Text,
|
||||
).Scan(&message.CreatedAt)
|
||||
if err != nil {
|
||||
return domain.Message{}, fmt.Errorf("insert message: %w", err)
|
||||
}
|
||||
|
||||
if len(attachmentUUIDs) > 0 {
|
||||
_, err = transaction.Exec(
|
||||
queryContext,
|
||||
`
|
||||
INSERT INTO message_attachments (
|
||||
message_id,
|
||||
chat_id,
|
||||
attachment_id,
|
||||
position
|
||||
)
|
||||
SELECT $1, $2, attachment_id, (ordinality - 1)::smallint
|
||||
FROM unnest($3::uuid[]) WITH ORDINALITY AS input(attachment_id, ordinality)
|
||||
`,
|
||||
message.ID,
|
||||
message.ChatID,
|
||||
attachmentUUIDs,
|
||||
)
|
||||
if err != nil {
|
||||
return domain.Message{}, fmt.Errorf("link message attachments: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if err = transaction.Commit(queryContext); err != nil {
|
||||
return domain.Message{}, fmt.Errorf("commit idempotent message: %w", err)
|
||||
}
|
||||
|
||||
return message, nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) GetMessages(
|
||||
ctx context.Context,
|
||||
chatID string,
|
||||
callerID string,
|
||||
limit int,
|
||||
cursor *domain.MessageCursor,
|
||||
) ([]domain.Message, bool, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
var isMember bool
|
||||
|
||||
err := s.pool.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
SELECT EXISTS (
|
||||
SELECT 1
|
||||
FROM chat_members
|
||||
WHERE chat_id = $1
|
||||
AND user_id = $2
|
||||
)
|
||||
`,
|
||||
chatID,
|
||||
callerID,
|
||||
).Scan(&isMember)
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf(
|
||||
"check chat membership: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
if !isMember {
|
||||
return nil, false, ErrNotFound
|
||||
}
|
||||
|
||||
var rows pgx.Rows
|
||||
|
||||
if cursor == nil {
|
||||
rows, err = s.pool.Query(
|
||||
queryContext,
|
||||
`
|
||||
SELECT
|
||||
id::text,
|
||||
chat_id::text,
|
||||
sender_id::text,
|
||||
text,
|
||||
created_at,
|
||||
COALESCE(
|
||||
ARRAY(
|
||||
SELECT attachment_id::text
|
||||
FROM message_attachments
|
||||
WHERE message_id = messages.id
|
||||
ORDER BY position
|
||||
), ARRAY[]::text[]
|
||||
)
|
||||
FROM messages
|
||||
WHERE chat_id = $1
|
||||
ORDER BY
|
||||
created_at,
|
||||
id
|
||||
LIMIT $2
|
||||
`,
|
||||
chatID,
|
||||
limit+1,
|
||||
)
|
||||
} else {
|
||||
rows, err = s.pool.Query(
|
||||
queryContext,
|
||||
`
|
||||
SELECT
|
||||
id::text,
|
||||
chat_id::text,
|
||||
sender_id::text,
|
||||
text,
|
||||
created_at,
|
||||
COALESCE(
|
||||
ARRAY(
|
||||
SELECT attachment_id::text
|
||||
FROM message_attachments
|
||||
WHERE message_id = messages.id
|
||||
ORDER BY position
|
||||
), ARRAY[]::text[]
|
||||
)
|
||||
FROM messages
|
||||
WHERE chat_id = $1
|
||||
AND (created_at, id) > ($2, $3)
|
||||
ORDER BY
|
||||
created_at,
|
||||
id
|
||||
LIMIT $4
|
||||
`,
|
||||
chatID,
|
||||
cursor.CreatedAt,
|
||||
cursor.MessageID,
|
||||
limit+1,
|
||||
)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf(
|
||||
"query messages: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
items := make([]domain.Message, 0, limit+1)
|
||||
|
||||
for rows.Next() {
|
||||
var message domain.Message
|
||||
|
||||
if err := rows.Scan(
|
||||
&message.ID,
|
||||
&message.ChatID,
|
||||
&message.SenderID,
|
||||
&message.Text,
|
||||
&message.CreatedAt,
|
||||
&message.AttachmentIDs,
|
||||
); err != nil {
|
||||
return nil, false, fmt.Errorf(
|
||||
"scan message page: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
items = append(items, message)
|
||||
}
|
||||
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, false, fmt.Errorf(
|
||||
"iterate message page: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
hasMore := len(items) > limit
|
||||
if hasMore {
|
||||
items = items[:limit]
|
||||
}
|
||||
return items, hasMore, nil
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
func (s *PostgreSQLStore) AttachmentQueueStats(
|
||||
ctx context.Context,
|
||||
now time.Time,
|
||||
) (int64, float64, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
var depth int64
|
||||
var oldestAge float64
|
||||
err := s.pool.QueryRow(queryContext, `
|
||||
SELECT
|
||||
COUNT(*),
|
||||
COALESCE(EXTRACT(EPOCH FROM ($1::timestamptz - MIN(created_at))), 0)
|
||||
FROM attachment_jobs
|
||||
WHERE status = 'queued'
|
||||
`, now).Scan(&depth, &oldestAge)
|
||||
if err != nil {
|
||||
return 0, 0, fmt.Errorf("read attachment queue stats: %w", err)
|
||||
}
|
||||
if oldestAge < 0 {
|
||||
oldestAge = 0
|
||||
}
|
||||
return depth, oldestAge, nil
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab7/internal/domain"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func (s *PostgreSQLStore) CreateSession(
|
||||
ctx context.Context,
|
||||
tokenHash []byte,
|
||||
userID string,
|
||||
expiresAt time.Time,
|
||||
) error {
|
||||
if err := s.maybePruneExpiredState(ctx, time.Now()); err != nil {
|
||||
return err
|
||||
}
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
_, err := s.pool.Exec(
|
||||
queryContext,
|
||||
`
|
||||
INSERT INTO sessions (
|
||||
token_hash,
|
||||
user_id,
|
||||
expires_at
|
||||
)
|
||||
VALUES ($1, $2, $3)
|
||||
`,
|
||||
tokenHash,
|
||||
userID,
|
||||
expiresAt,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("insert session: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) GetUserBySession(
|
||||
ctx context.Context,
|
||||
tokenHash []byte,
|
||||
) (domain.User, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
var user domain.User
|
||||
|
||||
err := s.pool.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
SELECT
|
||||
app_user.id::text,
|
||||
app_user.username,
|
||||
app_user.display_name,
|
||||
app_user.created_at
|
||||
FROM sessions AS session
|
||||
JOIN users AS app_user
|
||||
ON app_user.id = session.user_id
|
||||
WHERE session.token_hash = $1
|
||||
AND session.expires_at > CURRENT_TIMESTAMP
|
||||
`,
|
||||
tokenHash,
|
||||
).Scan(
|
||||
&user.ID,
|
||||
&user.Username,
|
||||
&user.DisplayName,
|
||||
&user.CreatedAt,
|
||||
)
|
||||
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.User{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return domain.User{}, fmt.Errorf(
|
||||
"select user by session: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) DeleteSession(
|
||||
ctx context.Context,
|
||||
tokenHash []byte,
|
||||
) error {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
_, err := s.pool.Exec(
|
||||
queryContext,
|
||||
`
|
||||
DELETE FROM sessions
|
||||
WHERE token_hash = $1
|
||||
`,
|
||||
tokenHash,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("delete session: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type PostgreSQLStore struct {
|
||||
pool *pgxpool.Pool
|
||||
queryTimeout time.Duration
|
||||
expiredStatePruneCounter atomic.Uint64
|
||||
loginRatePruneCounter atomic.Uint64
|
||||
}
|
||||
|
||||
func NewPostgreSQLStore(
|
||||
pool *pgxpool.Pool,
|
||||
queryTimeout time.Duration,
|
||||
) *PostgreSQLStore {
|
||||
return &PostgreSQLStore{
|
||||
pool: pool,
|
||||
queryTimeout: queryTimeout,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) Ping(ctx context.Context) error {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
return s.pool.Ping(queryContext)
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) Close() {
|
||||
s.pool.Close()
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) withTimeout(
|
||||
ctx context.Context,
|
||||
) (context.Context, context.CancelFunc) {
|
||||
return context.WithTimeout(ctx, s.queryTimeout)
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"mtusi2026lab7/internal/domain"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
)
|
||||
|
||||
func (s *PostgreSQLStore) CreateUser(
|
||||
ctx context.Context,
|
||||
username string,
|
||||
displayName string,
|
||||
passwordHash string,
|
||||
) (domain.User, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
user := domain.User{
|
||||
ID: uuid.NewString(),
|
||||
Username: username,
|
||||
DisplayName: displayName,
|
||||
}
|
||||
|
||||
err := s.pool.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
INSERT INTO users (
|
||||
id,
|
||||
username,
|
||||
display_name,
|
||||
password_hash
|
||||
)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING created_at
|
||||
`,
|
||||
user.ID,
|
||||
user.Username,
|
||||
user.DisplayName,
|
||||
passwordHash,
|
||||
).Scan(&user.CreatedAt)
|
||||
|
||||
if err == nil {
|
||||
return user, nil
|
||||
}
|
||||
|
||||
var postgresError *pgconn.PgError
|
||||
if errors.As(err, &postgresError) &&
|
||||
postgresError.Code == "23505" &&
|
||||
postgresError.ConstraintName == "users_username_unique" {
|
||||
return domain.User{}, ErrConflict
|
||||
}
|
||||
|
||||
return domain.User{}, fmt.Errorf("insert user: %w", err)
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) GetUserByID(
|
||||
ctx context.Context,
|
||||
userID string,
|
||||
) (domain.User, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
var user domain.User
|
||||
|
||||
err := s.pool.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
SELECT
|
||||
id::text,
|
||||
username,
|
||||
display_name,
|
||||
created_at
|
||||
FROM users
|
||||
WHERE id = $1
|
||||
`,
|
||||
userID,
|
||||
).Scan(
|
||||
&user.ID,
|
||||
&user.Username,
|
||||
&user.DisplayName,
|
||||
&user.CreatedAt,
|
||||
)
|
||||
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.User{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return domain.User{}, fmt.Errorf("select user by id: %w", err)
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) GetUserByUsername(
|
||||
ctx context.Context,
|
||||
username string,
|
||||
) (domain.User, string, error) {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
var (
|
||||
user domain.User
|
||||
passwordHash string
|
||||
)
|
||||
|
||||
err := s.pool.QueryRow(
|
||||
queryContext,
|
||||
`
|
||||
SELECT
|
||||
id::text,
|
||||
username,
|
||||
display_name,
|
||||
created_at,
|
||||
password_hash
|
||||
FROM users
|
||||
WHERE username = $1
|
||||
`,
|
||||
username,
|
||||
).Scan(
|
||||
&user.ID,
|
||||
&user.Username,
|
||||
&user.DisplayName,
|
||||
&user.CreatedAt,
|
||||
&passwordHash,
|
||||
)
|
||||
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.User{}, "", ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return domain.User{}, "", fmt.Errorf(
|
||||
"select user by username: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
return user, passwordHash, nil
|
||||
}
|
||||
|
||||
func (s *PostgreSQLStore) UpdatePasswordHash(
|
||||
ctx context.Context,
|
||||
userID string,
|
||||
previousHash string,
|
||||
newHash string,
|
||||
) error {
|
||||
queryContext, cancel := s.withTimeout(ctx)
|
||||
defer cancel()
|
||||
_, err := s.pool.Exec(
|
||||
queryContext,
|
||||
`UPDATE users SET password_hash = $1 WHERE id = $2 AND password_hash = $3`,
|
||||
newHash,
|
||||
userID,
|
||||
previousHash,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("update password hash: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user