forked from mtusi2026/mtusi2026lab6
chore: import lab5 baseline
This commit is contained in:
@@ -0,0 +1,563 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/model"
|
||||
)
|
||||
|
||||
const attachmentJobTopic = "attachment.jobs"
|
||||
|
||||
const attachmentJobColumns = `
|
||||
id, attachment_id, pipeline_version, attempt, status, available_at,
|
||||
lease_token, lease_owner, lease_until, error_code, created_at, updated_at`
|
||||
|
||||
func (s *Store) QueueAttachmentWithJobAndOutbox(
|
||||
ctx context.Context,
|
||||
attachmentID string,
|
||||
stagingKey string,
|
||||
job model.AttachmentJob,
|
||||
traceparent string,
|
||||
tracestate string,
|
||||
) (model.Attachment, error) {
|
||||
if job.ID == "" || job.PipelineVersion < 1 {
|
||||
return model.Attachment{}, model.ErrInvalidInput
|
||||
}
|
||||
if job.Attempt == 0 {
|
||||
job.Attempt = 1
|
||||
}
|
||||
if job.Attempt != 1 {
|
||||
return model.Attachment{}, model.ErrInvalidInput
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
if job.CreatedAt.IsZero() {
|
||||
job.CreatedAt = now
|
||||
}
|
||||
if job.AvailableAt.IsZero() {
|
||||
job.AvailableAt = now
|
||||
}
|
||||
|
||||
tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return model.Attachment{}, fmt.Errorf("begin queue attachment transaction: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(context.WithoutCancel(ctx)) }()
|
||||
|
||||
query := `
|
||||
UPDATE attachments
|
||||
SET status = 'queued', pipeline_version = $3, staging_key = $2,
|
||||
ready_at = NULL, error_code = NULL, updated_at = clock_timestamp()
|
||||
WHERE id = $1 AND object_key = $2 AND status = 'pending'
|
||||
RETURNING ` + attachmentColumns
|
||||
var attachment model.Attachment
|
||||
err = scanAttachment(tx.QueryRow(ctx, query, attachmentID, stagingKey, job.PipelineVersion), &attachment)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return s.alreadyQueuedAttachment(ctx, tx, attachmentID, stagingKey, job)
|
||||
}
|
||||
if err != nil {
|
||||
return model.Attachment{}, fmt.Errorf("queue attachment: %w", err)
|
||||
}
|
||||
|
||||
job.AttachmentID = attachmentID
|
||||
job.Status = model.AttachmentJobQueued
|
||||
job.UpdatedAt = job.CreatedAt
|
||||
if err := insertAttachmentJob(ctx, tx, job); err != nil {
|
||||
return model.Attachment{}, err
|
||||
}
|
||||
if err := insertAttachmentJobOutbox(ctx, tx, job, traceparent, tracestate); err != nil {
|
||||
return model.Attachment{}, err
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return model.Attachment{}, fmt.Errorf("commit queued attachment: %w", err)
|
||||
}
|
||||
return publicAttachment(attachment), nil
|
||||
}
|
||||
|
||||
func (s *Store) QueueAttachmentPipelineVersion(
|
||||
ctx context.Context,
|
||||
attachmentID string,
|
||||
job model.AttachmentJob,
|
||||
traceparent string,
|
||||
tracestate string,
|
||||
) (model.Attachment, error) {
|
||||
if job.ID == "" || job.PipelineVersion < 2 {
|
||||
return model.Attachment{}, model.ErrInvalidInput
|
||||
}
|
||||
job.Attempt = 1
|
||||
now := time.Now().UTC()
|
||||
job.CreatedAt = now
|
||||
job.AvailableAt = now
|
||||
|
||||
tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return model.Attachment{}, fmt.Errorf("begin queue attachment pipeline version: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(context.WithoutCancel(ctx)) }()
|
||||
|
||||
const selectAttachment = `SELECT ` + attachmentColumns + ` FROM attachments WHERE id = $1 FOR UPDATE`
|
||||
var attachment model.Attachment
|
||||
if err := scanAttachment(tx.QueryRow(ctx, selectAttachment, attachmentID), &attachment); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.Attachment{}, ErrNotFound
|
||||
}
|
||||
return model.Attachment{}, fmt.Errorf("lock attachment for pipeline update: %w", err)
|
||||
}
|
||||
if attachment.Status != model.AttachmentReady || job.PipelineVersion != attachment.PipelineVersion+1 {
|
||||
return model.Attachment{}, ErrConflict
|
||||
}
|
||||
job.AttachmentID = attachment.ID
|
||||
job.Status = model.AttachmentJobQueued
|
||||
job.UpdatedAt = now
|
||||
const queueAttachment = `
|
||||
UPDATE attachments
|
||||
SET status = 'queued', pipeline_version = $2, staging_key = object_key,
|
||||
ready_at = NULL, error_code = NULL, updated_at = clock_timestamp()
|
||||
WHERE id = $1
|
||||
RETURNING ` + attachmentColumns
|
||||
if err := scanAttachment(tx.QueryRow(ctx, queueAttachment, attachment.ID, job.PipelineVersion), &attachment); err != nil {
|
||||
return model.Attachment{}, fmt.Errorf("queue attachment pipeline version: %w", err)
|
||||
}
|
||||
if err := insertAttachmentJob(ctx, tx, job); err != nil {
|
||||
return model.Attachment{}, err
|
||||
}
|
||||
if err := insertAttachmentJobOutbox(ctx, tx, job, traceparent, tracestate); err != nil {
|
||||
return model.Attachment{}, err
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return model.Attachment{}, fmt.Errorf("commit queued attachment pipeline version: %w", err)
|
||||
}
|
||||
return publicAttachment(attachment), nil
|
||||
}
|
||||
|
||||
func (s *Store) alreadyQueuedAttachment(
|
||||
ctx context.Context,
|
||||
tx pgx.Tx,
|
||||
attachmentID string,
|
||||
stagingKey string,
|
||||
job model.AttachmentJob,
|
||||
) (model.Attachment, error) {
|
||||
query := `
|
||||
SELECT ` + attachmentColumnsWithAlias("a") + `
|
||||
FROM attachments a
|
||||
JOIN attachment_jobs j
|
||||
ON j.attachment_id = a.id AND j.pipeline_version = a.pipeline_version
|
||||
WHERE a.id = $1 AND a.staging_key = $2 AND a.status IN ('queued', 'processing', 'ready')
|
||||
AND j.id = $3 AND j.pipeline_version = $4`
|
||||
var attachment model.Attachment
|
||||
if err := scanAttachment(tx.QueryRow(ctx, query, attachmentID, stagingKey, job.ID, job.PipelineVersion), &attachment); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.Attachment{}, ErrConflict
|
||||
}
|
||||
return model.Attachment{}, fmt.Errorf("find queued attachment: %w", err)
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return model.Attachment{}, fmt.Errorf("commit repeated queue attachment: %w", err)
|
||||
}
|
||||
return publicAttachment(attachment), nil
|
||||
}
|
||||
|
||||
func insertAttachmentJob(ctx context.Context, tx pgx.Tx, job model.AttachmentJob) error {
|
||||
const query = `
|
||||
INSERT INTO attachment_jobs (
|
||||
id, attachment_id, pipeline_version, attempt, status, available_at, created_at, updated_at
|
||||
)
|
||||
VALUES ($1, $2, $3, $4, 'queued', $5, $6, $6)`
|
||||
if _, err := tx.Exec(
|
||||
ctx, query, job.ID, job.AttachmentID, job.PipelineVersion, job.Attempt, job.AvailableAt, job.CreatedAt,
|
||||
); err != nil {
|
||||
return fmt.Errorf("insert attachment job: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func insertAttachmentJobOutbox(
|
||||
ctx context.Context,
|
||||
tx pgx.Tx,
|
||||
job model.AttachmentJob,
|
||||
traceparent string,
|
||||
tracestate string,
|
||||
) error {
|
||||
payload, err := json.Marshal(model.AttachmentJobMessage{
|
||||
SchemaVersion: 1, JobID: job.ID, Type: "attachment.process.v1",
|
||||
AttachmentID: job.AttachmentID, PipelineVersion: job.PipelineVersion,
|
||||
Attempt: job.Attempt, CreatedAt: job.CreatedAt,
|
||||
Traceparent: traceparent, Tracestate: tracestate,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("marshal attachment job event: %w", err)
|
||||
}
|
||||
const query = `
|
||||
INSERT INTO outbox_events (
|
||||
id, topic, partition_key, payload, job_id, attempt, available_at
|
||||
)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7)`
|
||||
if _, err := tx.Exec(
|
||||
ctx, query, uuid.NewString(), attachmentJobTopic, job.AttachmentID, payload,
|
||||
job.ID, job.Attempt, job.AvailableAt,
|
||||
); err != nil {
|
||||
return fmt.Errorf("insert attachment job outbox event: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) AttachmentJob(ctx context.Context, jobID string) (model.AttachmentJob, error) {
|
||||
const query = `SELECT ` + attachmentJobColumns + ` FROM attachment_jobs WHERE id = $1`
|
||||
var job model.AttachmentJob
|
||||
if err := scanAttachmentJob(s.pool.QueryRow(ctx, query, jobID), &job); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.AttachmentJob{}, ErrNotFound
|
||||
}
|
||||
return model.AttachmentJob{}, fmt.Errorf("get attachment job: %w", err)
|
||||
}
|
||||
return job, nil
|
||||
}
|
||||
|
||||
func (s *Store) ClaimAttachmentJob(
|
||||
ctx context.Context,
|
||||
jobID string,
|
||||
attachmentID string,
|
||||
pipelineVersion int,
|
||||
attempt int,
|
||||
workerID string,
|
||||
leaseDuration time.Duration,
|
||||
) (model.AttachmentJobLease, error) {
|
||||
if leaseDuration <= 0 || workerID == "" {
|
||||
return model.AttachmentJobLease{}, model.ErrInvalidInput
|
||||
}
|
||||
tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return model.AttachmentJobLease{}, fmt.Errorf("begin claim attachment job: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(context.WithoutCancel(ctx)) }()
|
||||
|
||||
job, attachment, err := lockAttachmentJob(ctx, tx, jobID)
|
||||
if err != nil {
|
||||
return model.AttachmentJobLease{}, err
|
||||
}
|
||||
if attachment.ID != attachmentID || job.AttachmentID != attachmentID {
|
||||
return model.AttachmentJobLease{}, model.ErrInvalidInput
|
||||
}
|
||||
if attachment.PipelineVersion != pipelineVersion || job.PipelineVersion != pipelineVersion {
|
||||
return model.AttachmentJobLease{}, model.ErrStalePipeline
|
||||
}
|
||||
if job.Status == model.AttachmentJobReady || attachment.Status == model.AttachmentReady {
|
||||
return model.AttachmentJobLease{}, model.ErrJobComplete
|
||||
}
|
||||
if job.Attempt != attempt {
|
||||
return model.AttachmentJobLease{}, model.ErrStaleAttempt
|
||||
}
|
||||
if job.Status == model.AttachmentJobProcessing {
|
||||
return model.AttachmentJobLease{}, model.ErrJobBusy
|
||||
}
|
||||
if job.Status != model.AttachmentJobQueued {
|
||||
return model.AttachmentJobLease{}, ErrConflict
|
||||
}
|
||||
if job.AvailableAt.After(time.Now()) {
|
||||
return model.AttachmentJobLease{}, model.ErrJobNotDue
|
||||
}
|
||||
|
||||
job.LeaseToken = uuid.NewString()
|
||||
job.LeaseOwner = workerID
|
||||
leaseUntil := time.Now().UTC().Add(leaseDuration)
|
||||
job.LeaseUntil = &leaseUntil
|
||||
job.Status = model.AttachmentJobProcessing
|
||||
const updateJob = `
|
||||
UPDATE attachment_jobs
|
||||
SET status = 'processing', lease_token = $2, lease_owner = $3,
|
||||
lease_until = $4, error_code = NULL, updated_at = clock_timestamp()
|
||||
WHERE id = $1`
|
||||
if _, err := tx.Exec(ctx, updateJob, job.ID, job.LeaseToken, job.LeaseOwner, leaseUntil); err != nil {
|
||||
return model.AttachmentJobLease{}, fmt.Errorf("claim attachment job: %w", err)
|
||||
}
|
||||
const updateAttachment = `
|
||||
UPDATE attachments
|
||||
SET status = 'processing', error_code = NULL, updated_at = clock_timestamp()
|
||||
WHERE id = $1 AND pipeline_version = $2 AND status = 'queued'`
|
||||
result, err := tx.Exec(ctx, updateAttachment, attachment.ID, pipelineVersion)
|
||||
if err != nil {
|
||||
return model.AttachmentJobLease{}, fmt.Errorf("mark attachment processing: %w", err)
|
||||
}
|
||||
if result.RowsAffected() != 1 {
|
||||
return model.AttachmentJobLease{}, model.ErrStalePipeline
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return model.AttachmentJobLease{}, fmt.Errorf("commit attachment job claim: %w", err)
|
||||
}
|
||||
attachment.Status = model.AttachmentProcessing
|
||||
attachment.ErrorCode = nil
|
||||
return model.AttachmentJobLease{Job: job, Attachment: attachment}, nil
|
||||
}
|
||||
|
||||
func lockAttachmentJob(ctx context.Context, tx pgx.Tx, jobID string) (model.AttachmentJob, model.Attachment, error) {
|
||||
query := `
|
||||
SELECT ` + prefixedAttachmentJobColumns("j") + `, ` + attachmentColumnsWithAlias("a") + `
|
||||
FROM attachment_jobs j
|
||||
JOIN attachments a ON a.id = j.attachment_id
|
||||
WHERE j.id = $1
|
||||
FOR UPDATE OF j, a`
|
||||
var job model.AttachmentJob
|
||||
var attachment model.Attachment
|
||||
var leaseToken, leaseOwner *string
|
||||
var stagingKey *string
|
||||
err := tx.QueryRow(ctx, query, jobID).Scan(
|
||||
&job.ID, &job.AttachmentID, &job.PipelineVersion, &job.Attempt, &job.Status, &job.AvailableAt,
|
||||
&leaseToken, &leaseOwner, &job.LeaseUntil, &job.ErrorCode, &job.CreatedAt, &job.UpdatedAt,
|
||||
&attachment.ID, &attachment.ChatID, &attachment.OwnerID, &attachment.Filename,
|
||||
&attachment.ContentType, &attachment.SizeBytes, &attachment.SHA256, &attachment.ObjectKey,
|
||||
&attachment.Status, &attachment.CreatedAt, &attachment.UpdatedAt, &attachment.ReadyAt,
|
||||
&attachment.PipelineVersion, &attachment.ErrorCode, &stagingKey,
|
||||
)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.AttachmentJob{}, model.Attachment{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return model.AttachmentJob{}, model.Attachment{}, fmt.Errorf("lock attachment job: %w", err)
|
||||
}
|
||||
if leaseToken != nil {
|
||||
job.LeaseToken = *leaseToken
|
||||
}
|
||||
if leaseOwner != nil {
|
||||
job.LeaseOwner = *leaseOwner
|
||||
}
|
||||
if stagingKey != nil {
|
||||
attachment.StagingKey = *stagingKey
|
||||
}
|
||||
return job, attachment, nil
|
||||
}
|
||||
|
||||
func prefixedAttachmentJobColumns(alias string) string {
|
||||
return fmt.Sprintf(
|
||||
"%[1]s.id, %[1]s.attachment_id, %[1]s.pipeline_version, %[1]s.attempt, %[1]s.status, "+
|
||||
"%[1]s.available_at, %[1]s.lease_token, %[1]s.lease_owner, %[1]s.lease_until, "+
|
||||
"%[1]s.error_code, %[1]s.created_at, %[1]s.updated_at",
|
||||
alias,
|
||||
)
|
||||
}
|
||||
|
||||
func scanAttachmentJob(row rowScanner, job *model.AttachmentJob) error {
|
||||
var leaseToken, leaseOwner *string
|
||||
err := row.Scan(
|
||||
&job.ID, &job.AttachmentID, &job.PipelineVersion, &job.Attempt, &job.Status, &job.AvailableAt,
|
||||
&leaseToken, &leaseOwner, &job.LeaseUntil, &job.ErrorCode, &job.CreatedAt, &job.UpdatedAt,
|
||||
)
|
||||
if leaseToken != nil {
|
||||
job.LeaseToken = *leaseToken
|
||||
}
|
||||
if leaseOwner != nil {
|
||||
job.LeaseOwner = *leaseOwner
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) CompleteAttachmentJob(
|
||||
ctx context.Context,
|
||||
lease model.AttachmentJobLease,
|
||||
variants []model.Variant,
|
||||
) (model.JobMutationResult, error) {
|
||||
if !validCompletedVariants(variants, lease.Job.PipelineVersion) {
|
||||
return "", model.ErrInvalidInput
|
||||
}
|
||||
tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("begin complete attachment job: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(context.WithoutCancel(ctx)) }()
|
||||
|
||||
job, attachment, result, err := lockJobMutation(ctx, tx, lease)
|
||||
if err != nil || result != model.JobMutationApplied {
|
||||
return result, err
|
||||
}
|
||||
const deleteVariants = `
|
||||
DELETE FROM attachment_variants
|
||||
WHERE attachment_id = $1 AND pipeline_version = $2`
|
||||
if _, err := tx.Exec(ctx, deleteVariants, attachment.ID, job.PipelineVersion); err != nil {
|
||||
return "", fmt.Errorf("replace attachment variants: %w", err)
|
||||
}
|
||||
|
||||
var originalKey string
|
||||
const insertVariant = `
|
||||
INSERT INTO attachment_variants (
|
||||
attachment_id, pipeline_version, name, content_type, size_bytes,
|
||||
sha256, width, height, object_key
|
||||
)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`
|
||||
for _, variant := range variants {
|
||||
if variant.Name == "original" {
|
||||
originalKey = variant.ObjectKey
|
||||
}
|
||||
if _, err := tx.Exec(
|
||||
ctx, insertVariant, attachment.ID, job.PipelineVersion, variant.Name,
|
||||
variant.ContentType, variant.SizeBytes, variant.SHA256, variant.Width,
|
||||
variant.Height, variant.ObjectKey,
|
||||
); err != nil {
|
||||
return "", fmt.Errorf("insert attachment variant %s: %w", variant.Name, err)
|
||||
}
|
||||
}
|
||||
|
||||
const completeJob = `
|
||||
UPDATE attachment_jobs
|
||||
SET status = 'ready', lease_token = NULL, lease_owner = NULL, lease_until = NULL,
|
||||
error_code = NULL, updated_at = clock_timestamp()
|
||||
WHERE id = $1 AND lease_token = $2`
|
||||
if _, err := tx.Exec(ctx, completeJob, job.ID, lease.Job.LeaseToken); err != nil {
|
||||
return "", fmt.Errorf("complete attachment job: %w", err)
|
||||
}
|
||||
const completeAttachment = `
|
||||
UPDATE attachments
|
||||
SET status = 'ready', object_key = $3, ready_at = clock_timestamp(),
|
||||
staging_key = NULL, error_code = NULL, updated_at = clock_timestamp()
|
||||
WHERE id = $1 AND pipeline_version = $2`
|
||||
if _, err := tx.Exec(ctx, completeAttachment, attachment.ID, job.PipelineVersion, originalKey); err != nil {
|
||||
return "", fmt.Errorf("complete attachment: %w", err)
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return "", fmt.Errorf("commit completed attachment job: %w", err)
|
||||
}
|
||||
return model.JobMutationApplied, nil
|
||||
}
|
||||
|
||||
func validCompletedVariants(variants []model.Variant, pipelineVersion int) bool {
|
||||
if len(variants) != 4 || pipelineVersion < 1 {
|
||||
return false
|
||||
}
|
||||
required := map[string]struct{}{
|
||||
"original": {}, "thumbnail": {}, "crop": {}, "optimized": {},
|
||||
}
|
||||
for _, variant := range variants {
|
||||
if variant.ObjectKey == "" || variant.PipelineVersion != pipelineVersion {
|
||||
return false
|
||||
}
|
||||
if _, exists := required[variant.Name]; !exists {
|
||||
return false
|
||||
}
|
||||
delete(required, variant.Name)
|
||||
}
|
||||
return len(required) == 0
|
||||
}
|
||||
|
||||
func (s *Store) RetryAttachmentJob(
|
||||
ctx context.Context,
|
||||
lease model.AttachmentJobLease,
|
||||
errorCode string,
|
||||
nextAttemptAt time.Time,
|
||||
) (model.JobMutationResult, error) {
|
||||
if !validErrorCode(errorCode) || nextAttemptAt.IsZero() {
|
||||
return "", model.ErrInvalidInput
|
||||
}
|
||||
tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("begin retry attachment job: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(context.WithoutCancel(ctx)) }()
|
||||
|
||||
job, attachment, result, err := lockJobMutation(ctx, tx, lease)
|
||||
if err != nil || result != model.JobMutationApplied {
|
||||
return result, err
|
||||
}
|
||||
job.Attempt++
|
||||
job.Status = model.AttachmentJobQueued
|
||||
job.AvailableAt = nextAttemptAt.UTC()
|
||||
job.ErrorCode = &errorCode
|
||||
const retryJob = `
|
||||
UPDATE attachment_jobs
|
||||
SET status = 'queued', attempt = $3, available_at = $4,
|
||||
lease_token = NULL, lease_owner = NULL, lease_until = NULL,
|
||||
error_code = $5, updated_at = clock_timestamp()
|
||||
WHERE id = $1 AND lease_token = $2`
|
||||
if _, err := tx.Exec(
|
||||
ctx, retryJob, job.ID, lease.Job.LeaseToken, job.Attempt, job.AvailableAt, errorCode,
|
||||
); err != nil {
|
||||
return "", fmt.Errorf("retry attachment job: %w", err)
|
||||
}
|
||||
const queueAttachment = `
|
||||
UPDATE attachments
|
||||
SET status = 'queued', error_code = NULL, updated_at = clock_timestamp()
|
||||
WHERE id = $1 AND pipeline_version = $2`
|
||||
if _, err := tx.Exec(ctx, queueAttachment, attachment.ID, job.PipelineVersion); err != nil {
|
||||
return "", fmt.Errorf("requeue attachment: %w", err)
|
||||
}
|
||||
eventJob := job
|
||||
eventJob.CreatedAt = time.Now().UTC()
|
||||
if err := insertAttachmentJobOutbox(ctx, tx, eventJob, "", ""); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return "", fmt.Errorf("commit attachment job retry: %w", err)
|
||||
}
|
||||
return model.JobMutationApplied, nil
|
||||
}
|
||||
|
||||
func (s *Store) FailAttachmentJob(
|
||||
ctx context.Context,
|
||||
lease model.AttachmentJobLease,
|
||||
errorCode string,
|
||||
) (model.JobMutationResult, error) {
|
||||
if !validErrorCode(errorCode) {
|
||||
return "", model.ErrInvalidInput
|
||||
}
|
||||
tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("begin fail attachment job: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(context.WithoutCancel(ctx)) }()
|
||||
|
||||
job, attachment, result, err := lockJobMutation(ctx, tx, lease)
|
||||
if err != nil || result != model.JobMutationApplied {
|
||||
return result, err
|
||||
}
|
||||
const failJob = `
|
||||
UPDATE attachment_jobs
|
||||
SET status = 'failed', lease_token = NULL, lease_owner = NULL, lease_until = NULL,
|
||||
error_code = $3, updated_at = clock_timestamp()
|
||||
WHERE id = $1 AND lease_token = $2`
|
||||
if _, err := tx.Exec(ctx, failJob, job.ID, lease.Job.LeaseToken, errorCode); err != nil {
|
||||
return "", fmt.Errorf("fail attachment job: %w", err)
|
||||
}
|
||||
const failAttachment = `
|
||||
UPDATE attachments
|
||||
SET status = 'failed', error_code = $3, ready_at = NULL, updated_at = clock_timestamp()
|
||||
WHERE id = $1 AND pipeline_version = $2`
|
||||
if _, err := tx.Exec(ctx, failAttachment, attachment.ID, job.PipelineVersion, errorCode); err != nil {
|
||||
return "", fmt.Errorf("fail attachment: %w", err)
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return "", fmt.Errorf("commit failed attachment job: %w", err)
|
||||
}
|
||||
return model.JobMutationApplied, nil
|
||||
}
|
||||
|
||||
func lockJobMutation(
|
||||
ctx context.Context,
|
||||
tx pgx.Tx,
|
||||
lease model.AttachmentJobLease,
|
||||
) (model.AttachmentJob, model.Attachment, model.JobMutationResult, error) {
|
||||
job, attachment, err := lockAttachmentJob(ctx, tx, lease.Job.ID)
|
||||
if err != nil {
|
||||
return model.AttachmentJob{}, model.Attachment{}, "", err
|
||||
}
|
||||
if attachment.PipelineVersion != lease.Job.PipelineVersion || job.PipelineVersion != lease.Job.PipelineVersion {
|
||||
return job, attachment, model.JobMutationStale, nil
|
||||
}
|
||||
if job.Status == model.AttachmentJobReady && attachment.Status == model.AttachmentReady {
|
||||
return job, attachment, model.JobMutationAlreadyComplete, nil
|
||||
}
|
||||
if job.PipelineVersion != lease.Job.PipelineVersion ||
|
||||
job.Attempt != lease.Job.Attempt ||
|
||||
job.Status != model.AttachmentJobProcessing ||
|
||||
job.LeaseToken == "" || job.LeaseToken != lease.Job.LeaseToken ||
|
||||
job.LeaseUntil == nil || !job.LeaseUntil.After(time.Now()) {
|
||||
return job, attachment, model.JobMutationStale, nil
|
||||
}
|
||||
return job, attachment, model.JobMutationApplied, nil
|
||||
}
|
||||
|
||||
func validErrorCode(errorCode string) bool {
|
||||
return len(errorCode) >= 1 && len(errorCode) <= 64
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/model"
|
||||
)
|
||||
|
||||
func (s *Store) RenewAttachmentJobLease(
|
||||
ctx context.Context,
|
||||
lease model.AttachmentJobLease,
|
||||
duration time.Duration,
|
||||
) (bool, error) {
|
||||
if duration <= 0 || lease.Job.ID == "" || lease.Job.LeaseToken == "" || lease.Job.LeaseOwner == "" {
|
||||
return false, model.ErrInvalidInput
|
||||
}
|
||||
const query = `
|
||||
UPDATE attachment_jobs
|
||||
SET lease_until = clock_timestamp() + ($4::bigint * interval '1 microsecond'),
|
||||
updated_at = clock_timestamp()
|
||||
WHERE id = $1 AND lease_token = $2 AND lease_owner = $3
|
||||
AND status = 'processing' AND lease_until > clock_timestamp()`
|
||||
result, err := s.pool.Exec(
|
||||
ctx, query, lease.Job.ID, lease.Job.LeaseToken, lease.Job.LeaseOwner, duration.Microseconds(),
|
||||
)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("renew attachment job lease: %w", err)
|
||||
}
|
||||
return result.RowsAffected() == 1, nil
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/model"
|
||||
)
|
||||
|
||||
func (s *Store) RecoverExpiredAttachmentJobs(
|
||||
ctx context.Context,
|
||||
limit int,
|
||||
maxAttempts int,
|
||||
retryAt time.Time,
|
||||
) (model.RecoveryResult, error) {
|
||||
if limit < 1 || limit > 1000 || maxAttempts < 1 {
|
||||
return model.RecoveryResult{}, model.ErrInvalidInput
|
||||
}
|
||||
if retryAt.IsZero() {
|
||||
retryAt = time.Now().UTC()
|
||||
}
|
||||
tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return model.RecoveryResult{}, fmt.Errorf("begin expired job recovery: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(context.WithoutCancel(ctx)) }()
|
||||
|
||||
const selectExpired = `
|
||||
SELECT id
|
||||
FROM attachment_jobs
|
||||
WHERE status = 'processing' AND lease_until <= clock_timestamp()
|
||||
ORDER BY lease_until, id
|
||||
LIMIT $1
|
||||
FOR UPDATE SKIP LOCKED`
|
||||
rows, err := tx.Query(ctx, selectExpired, limit)
|
||||
if err != nil {
|
||||
return model.RecoveryResult{}, fmt.Errorf("select expired attachment jobs: %w", err)
|
||||
}
|
||||
jobIDs, err := pgx.CollectRows(rows, pgx.RowTo[string])
|
||||
if err != nil {
|
||||
return model.RecoveryResult{}, fmt.Errorf("scan expired attachment jobs: %w", err)
|
||||
}
|
||||
|
||||
var recovered model.RecoveryResult
|
||||
for _, jobID := range jobIDs {
|
||||
job, attachment, err := lockAttachmentJob(ctx, tx, jobID)
|
||||
if err != nil {
|
||||
return model.RecoveryResult{}, err
|
||||
}
|
||||
if job.Status != model.AttachmentJobProcessing || job.LeaseUntil == nil || job.LeaseUntil.After(time.Now()) {
|
||||
continue
|
||||
}
|
||||
if job.PipelineVersion != attachment.PipelineVersion {
|
||||
if err := markExpiredJobFailed(ctx, tx, job, attachment, "stale_pipeline", false); err != nil {
|
||||
return model.RecoveryResult{}, err
|
||||
}
|
||||
recovered.Failed++
|
||||
continue
|
||||
}
|
||||
if job.Attempt >= maxAttempts {
|
||||
if err := markExpiredJobFailed(ctx, tx, job, attachment, "retry_exhausted", true); err != nil {
|
||||
return model.RecoveryResult{}, err
|
||||
}
|
||||
recovered.Failed++
|
||||
continue
|
||||
}
|
||||
|
||||
job.Attempt++
|
||||
job.Status = model.AttachmentJobQueued
|
||||
job.AvailableAt = retryAt.UTC()
|
||||
const requeueJob = `
|
||||
UPDATE attachment_jobs
|
||||
SET status = 'queued', attempt = $2, available_at = $3,
|
||||
lease_token = NULL, lease_owner = NULL, lease_until = NULL,
|
||||
error_code = 'lease_expired', updated_at = clock_timestamp()
|
||||
WHERE id = $1`
|
||||
if _, err := tx.Exec(ctx, requeueJob, job.ID, job.Attempt, job.AvailableAt); err != nil {
|
||||
return model.RecoveryResult{}, fmt.Errorf("requeue expired attachment job: %w", err)
|
||||
}
|
||||
const requeueAttachment = `
|
||||
UPDATE attachments
|
||||
SET status = 'queued', error_code = NULL, updated_at = clock_timestamp()
|
||||
WHERE id = $1 AND pipeline_version = $2`
|
||||
if _, err := tx.Exec(ctx, requeueAttachment, attachment.ID, job.PipelineVersion); err != nil {
|
||||
return model.RecoveryResult{}, fmt.Errorf("requeue attachment after expired lease: %w", err)
|
||||
}
|
||||
eventJob := job
|
||||
eventJob.CreatedAt = time.Now().UTC()
|
||||
if err := insertAttachmentJobOutbox(ctx, tx, eventJob, "", ""); err != nil {
|
||||
return model.RecoveryResult{}, err
|
||||
}
|
||||
recovered.Requeued++
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return model.RecoveryResult{}, fmt.Errorf("commit expired attachment job recovery: %w", err)
|
||||
}
|
||||
return recovered, nil
|
||||
}
|
||||
|
||||
func markExpiredJobFailed(
|
||||
ctx context.Context,
|
||||
tx pgx.Tx,
|
||||
job model.AttachmentJob,
|
||||
attachment model.Attachment,
|
||||
errorCode string,
|
||||
failAttachment bool,
|
||||
) error {
|
||||
const failJob = `
|
||||
UPDATE attachment_jobs
|
||||
SET status = 'failed', lease_token = NULL, lease_owner = NULL, lease_until = NULL,
|
||||
error_code = $2, updated_at = clock_timestamp()
|
||||
WHERE id = $1`
|
||||
if _, err := tx.Exec(ctx, failJob, job.ID, errorCode); err != nil {
|
||||
return fmt.Errorf("fail expired attachment job: %w", err)
|
||||
}
|
||||
if !failAttachment {
|
||||
return nil
|
||||
}
|
||||
const failAttachmentQuery = `
|
||||
UPDATE attachments
|
||||
SET status = 'failed', error_code = $3, ready_at = NULL, updated_at = clock_timestamp()
|
||||
WHERE id = $1 AND pipeline_version = $2`
|
||||
if _, err := tx.Exec(ctx, failAttachmentQuery, attachment.ID, job.PipelineVersion, errorCode); err != nil {
|
||||
return fmt.Errorf("fail attachment after expired lease: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) ReplayFailedAttachment(
|
||||
ctx context.Context,
|
||||
attachmentID string,
|
||||
actor string,
|
||||
reason string,
|
||||
) (model.AttachmentJob, error) {
|
||||
if actor == "" || len(actor) > 128 || reason == "" || len(reason) > 512 {
|
||||
return model.AttachmentJob{}, model.ErrInvalidInput
|
||||
}
|
||||
tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return model.AttachmentJob{}, fmt.Errorf("begin failed attachment replay: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(context.WithoutCancel(ctx)) }()
|
||||
|
||||
const selectJob = `
|
||||
SELECT j.id
|
||||
FROM attachment_jobs j
|
||||
JOIN attachments a ON a.id = j.attachment_id AND a.pipeline_version = j.pipeline_version
|
||||
WHERE a.id = $1 AND a.status = 'failed' AND j.status = 'failed'
|
||||
FOR UPDATE OF j, a`
|
||||
var jobID string
|
||||
if err := tx.QueryRow(ctx, selectJob, attachmentID).Scan(&jobID); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.AttachmentJob{}, ErrConflict
|
||||
}
|
||||
return model.AttachmentJob{}, fmt.Errorf("select failed attachment job: %w", err)
|
||||
}
|
||||
job, attachment, err := lockAttachmentJob(ctx, tx, jobID)
|
||||
if err != nil {
|
||||
return model.AttachmentJob{}, err
|
||||
}
|
||||
previousAttempt := job.Attempt
|
||||
job.Attempt++
|
||||
job.Status = model.AttachmentJobQueued
|
||||
job.AvailableAt = time.Now().UTC()
|
||||
job.ErrorCode = nil
|
||||
job.LeaseToken = ""
|
||||
job.LeaseOwner = ""
|
||||
job.LeaseUntil = nil
|
||||
const replayJob = `
|
||||
UPDATE attachment_jobs
|
||||
SET status = 'queued', attempt = $2, available_at = $3,
|
||||
lease_token = NULL, lease_owner = NULL, lease_until = NULL,
|
||||
error_code = NULL, updated_at = clock_timestamp()
|
||||
WHERE id = $1`
|
||||
if _, err := tx.Exec(ctx, replayJob, job.ID, job.Attempt, job.AvailableAt); err != nil {
|
||||
return model.AttachmentJob{}, fmt.Errorf("replay attachment job: %w", err)
|
||||
}
|
||||
const replayAttachment = `
|
||||
UPDATE attachments
|
||||
SET status = 'queued', error_code = NULL, updated_at = clock_timestamp()
|
||||
WHERE id = $1 AND pipeline_version = $2`
|
||||
if _, err := tx.Exec(ctx, replayAttachment, attachment.ID, job.PipelineVersion); err != nil {
|
||||
return model.AttachmentJob{}, fmt.Errorf("replay failed attachment: %w", err)
|
||||
}
|
||||
const insertAudit = `
|
||||
INSERT INTO attachment_replay_audit (
|
||||
id, job_id, attachment_id, previous_attempt, new_attempt, actor, reason
|
||||
)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7)`
|
||||
if _, err := tx.Exec(
|
||||
ctx, insertAudit, uuid.NewString(), job.ID, attachment.ID,
|
||||
previousAttempt, job.Attempt, actor, reason,
|
||||
); err != nil {
|
||||
return model.AttachmentJob{}, fmt.Errorf("audit attachment replay: %w", err)
|
||||
}
|
||||
eventJob := job
|
||||
eventJob.CreatedAt = time.Now().UTC()
|
||||
if err := insertAttachmentJobOutbox(ctx, tx, eventJob, "", ""); err != nil {
|
||||
return model.AttachmentJob{}, err
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return model.AttachmentJob{}, fmt.Errorf("commit failed attachment replay: %w", err)
|
||||
}
|
||||
return job, nil
|
||||
}
|
||||
@@ -0,0 +1,393 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/model"
|
||||
)
|
||||
|
||||
const attachmentColumns = `
|
||||
id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
|
||||
object_key, status, created_at, updated_at, ready_at, pipeline_version, error_code, staging_key`
|
||||
|
||||
type rowScanner interface {
|
||||
Scan(...any) error
|
||||
}
|
||||
|
||||
func (s *Store) CreatePendingAttachment(ctx context.Context, attachment model.Attachment) (model.Attachment, error) {
|
||||
query := `
|
||||
INSERT INTO attachments (
|
||||
id, chat_id, owner_id, filename, content_type, size_bytes, sha256, object_key, status, ready_at
|
||||
)
|
||||
SELECT $1, $2, $3, $4, $5, $6, $7, $8, 'pending', NULL
|
||||
WHERE EXISTS (
|
||||
SELECT 1 FROM chat_members WHERE chat_id = $2 AND user_id = $3
|
||||
)
|
||||
RETURNING ` + attachmentColumns
|
||||
|
||||
err := scanAttachment(s.pool.QueryRow(
|
||||
ctx, query, attachment.ID, attachment.ChatID, attachment.OwnerID, attachment.Filename,
|
||||
attachment.ContentType, attachment.SizeBytes, attachment.SHA256, attachment.ObjectKey,
|
||||
), &attachment)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.Attachment{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return model.Attachment{}, fmt.Errorf("create pending attachment: %w", err)
|
||||
}
|
||||
return publicAttachment(attachment), nil
|
||||
}
|
||||
|
||||
func (s *Store) MarkAttachmentReady(ctx context.Context, attachmentID, objectKey string) (model.Attachment, error) {
|
||||
query := `
|
||||
UPDATE attachments
|
||||
SET status = 'ready', ready_at = clock_timestamp(), updated_at = clock_timestamp()
|
||||
WHERE id = $1 AND object_key = $2 AND status = 'pending'
|
||||
RETURNING ` + attachmentColumns
|
||||
|
||||
var attachment model.Attachment
|
||||
err := scanAttachment(s.pool.QueryRow(ctx, query, attachmentID, objectKey), &attachment)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.Attachment{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return model.Attachment{}, fmt.Errorf("mark attachment ready: %w", err)
|
||||
}
|
||||
return publicAttachment(attachment), nil
|
||||
}
|
||||
|
||||
func (s *Store) DeletePendingAttachment(ctx context.Context, attachmentID, objectKey string) error {
|
||||
const query = `DELETE FROM attachments WHERE id = $1 AND object_key = $2 AND status = 'pending'`
|
||||
if _, err := s.pool.Exec(ctx, query, attachmentID, objectKey); err != nil {
|
||||
return fmt.Errorf("delete pending attachment: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) AttachmentForUser(ctx context.Context, attachmentID, userID string) (model.Attachment, error) {
|
||||
query := `
|
||||
SELECT ` + attachmentColumnsWithAlias("a") + `
|
||||
FROM attachments a
|
||||
JOIN chat_members member ON member.chat_id = a.chat_id AND member.user_id = $2
|
||||
WHERE a.id = $1 AND a.status IN ('queued', 'processing', 'ready', 'failed')`
|
||||
|
||||
var attachment model.Attachment
|
||||
err := scanAttachment(s.pool.QueryRow(ctx, query, attachmentID, userID), &attachment)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.Attachment{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return model.Attachment{}, fmt.Errorf("get attachment for user: %w", err)
|
||||
}
|
||||
if attachment.Status == model.AttachmentReady {
|
||||
attachment.Variants, err = s.attachmentVariants(ctx, attachment.ID, attachment.PipelineVersion)
|
||||
if err != nil {
|
||||
return model.Attachment{}, err
|
||||
}
|
||||
}
|
||||
return publicAttachment(attachment), nil
|
||||
}
|
||||
|
||||
func (s *Store) AttachmentVariantForUser(
|
||||
ctx context.Context,
|
||||
attachmentID string,
|
||||
userID string,
|
||||
variantName string,
|
||||
) (model.Attachment, model.Variant, error) {
|
||||
attachment, err := s.AttachmentForUser(ctx, attachmentID, userID)
|
||||
if err != nil {
|
||||
return model.Attachment{}, model.Variant{}, err
|
||||
}
|
||||
if attachment.Status != model.AttachmentReady {
|
||||
return model.Attachment{}, model.Variant{}, ErrConflict
|
||||
}
|
||||
for _, variant := range attachment.Variants {
|
||||
if variant.Name == variantName {
|
||||
return attachment, variant, nil
|
||||
}
|
||||
}
|
||||
if variantName == "original" && attachment.ObjectKey != "" {
|
||||
return attachment, model.Variant{
|
||||
Name: "original", ContentType: attachment.ContentType, SizeBytes: attachment.SizeBytes,
|
||||
SHA256: attachment.SHA256, ObjectKey: attachment.ObjectKey,
|
||||
PipelineVersion: attachment.PipelineVersion,
|
||||
}, nil
|
||||
}
|
||||
return model.Attachment{}, model.Variant{}, ErrNotFound
|
||||
}
|
||||
|
||||
func (s *Store) attachmentVariants(ctx context.Context, attachmentID string, pipelineVersion int) ([]model.Variant, error) {
|
||||
const query = `
|
||||
SELECT name, content_type, size_bytes, sha256, width, height, object_key, pipeline_version
|
||||
FROM attachment_variants
|
||||
WHERE attachment_id = $1 AND pipeline_version = $2
|
||||
ORDER BY CASE name
|
||||
WHEN 'original' THEN 0
|
||||
WHEN 'thumbnail' THEN 1
|
||||
WHEN 'crop' THEN 2
|
||||
WHEN 'optimized' THEN 3
|
||||
ELSE 4
|
||||
END`
|
||||
rows, err := s.pool.Query(ctx, query, attachmentID, pipelineVersion)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list attachment variants: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
variants, err := pgx.CollectRows(rows, pgx.RowToStructByPos[model.Variant])
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("scan attachment variants: %w", err)
|
||||
}
|
||||
return variants, nil
|
||||
}
|
||||
|
||||
func (s *Store) AttachmentByStorage(ctx context.Context, attachmentID, objectKey string) (model.Attachment, error) {
|
||||
const query = `SELECT ` + attachmentColumns + ` FROM attachments WHERE id = $1 AND object_key = $2`
|
||||
|
||||
var attachment model.Attachment
|
||||
err := scanAttachment(s.pool.QueryRow(ctx, query, attachmentID, objectKey), &attachment)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.Attachment{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return model.Attachment{}, fmt.Errorf("get attachment by storage: %w", err)
|
||||
}
|
||||
return publicAttachment(attachment), nil
|
||||
}
|
||||
|
||||
func (s *Store) AttachmentExistsByObjectKey(ctx context.Context, objectKey string) (bool, error) {
|
||||
const query = `
|
||||
SELECT EXISTS (
|
||||
SELECT 1 FROM attachments WHERE object_key = $1 OR staging_key = $1
|
||||
UNION ALL
|
||||
SELECT 1 FROM attachment_variants WHERE object_key = $1
|
||||
)`
|
||||
var exists bool
|
||||
if err := s.pool.QueryRow(ctx, query, objectKey).Scan(&exists); err != nil {
|
||||
return false, fmt.Errorf("check attachment by object key: %w", err)
|
||||
}
|
||||
return exists, nil
|
||||
}
|
||||
|
||||
func (s *Store) AttachmentObjectKeys(ctx context.Context, attachmentID string) ([]string, error) {
|
||||
const query = `
|
||||
SELECT object_key
|
||||
FROM (
|
||||
SELECT object_key
|
||||
FROM attachments
|
||||
WHERE id = $1 AND object_key <> ''
|
||||
UNION
|
||||
SELECT object_key
|
||||
FROM attachment_variants
|
||||
WHERE attachment_id = $1
|
||||
) objects
|
||||
ORDER BY object_key`
|
||||
rows, err := s.pool.Query(ctx, query, attachmentID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list attachment object keys: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
keys, err := pgx.CollectRows(rows, pgx.RowTo[string])
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("scan attachment object keys: %w", err)
|
||||
}
|
||||
return keys, nil
|
||||
}
|
||||
|
||||
func (s *Store) ListAttachments(ctx context.Context, afterObjectKey string, limit int) ([]model.Attachment, string, error) {
|
||||
if limit < 1 || limit > 1000 {
|
||||
return nil, "", fmt.Errorf("attachment list limit must be between 1 and 1000")
|
||||
}
|
||||
query := `
|
||||
SELECT ` + attachmentColumnsWithAlias("a") + `,
|
||||
EXISTS (SELECT 1 FROM message_attachments ma WHERE ma.attachment_id = a.id),
|
||||
objects.object_key
|
||||
FROM (
|
||||
SELECT id AS attachment_id, object_key
|
||||
FROM attachments
|
||||
WHERE object_key <> ''
|
||||
UNION
|
||||
SELECT attachment_id, object_key
|
||||
FROM attachment_variants
|
||||
) objects
|
||||
JOIN attachments a ON a.id = objects.attachment_id
|
||||
WHERE objects.object_key > $1
|
||||
ORDER BY objects.object_key
|
||||
LIMIT $2`
|
||||
rows, err := s.pool.Query(ctx, query, afterObjectKey, limit+1)
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("list attachments: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
attachments, err := pgx.CollectRows(rows, pgx.RowToFunc[model.Attachment](func(row pgx.CollectableRow) (model.Attachment, error) {
|
||||
var attachment model.Attachment
|
||||
var objectKey string
|
||||
err := scanAttachmentWithReferenceAndObjectKey(row, &attachment, &objectKey)
|
||||
attachment.ObjectKey = objectKey
|
||||
return publicAttachment(attachment), err
|
||||
}))
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("scan attachments: %w", err)
|
||||
}
|
||||
var next string
|
||||
if len(attachments) > limit {
|
||||
attachments = attachments[:limit]
|
||||
next = attachments[len(attachments)-1].ObjectKey
|
||||
}
|
||||
return attachments, next, nil
|
||||
}
|
||||
|
||||
func scanAttachmentWithReferenceAndObjectKey(
|
||||
row rowScanner,
|
||||
attachment *model.Attachment,
|
||||
objectKey *string,
|
||||
) error {
|
||||
var stagingKey *string
|
||||
err := row.Scan(
|
||||
&attachment.ID, &attachment.ChatID, &attachment.OwnerID, &attachment.Filename,
|
||||
&attachment.ContentType, &attachment.SizeBytes, &attachment.SHA256, &attachment.ObjectKey,
|
||||
&attachment.Status, &attachment.CreatedAt, &attachment.UpdatedAt, &attachment.ReadyAt,
|
||||
&attachment.PipelineVersion, &attachment.ErrorCode, &stagingKey,
|
||||
&attachment.Referenced, objectKey,
|
||||
)
|
||||
if stagingKey != nil {
|
||||
attachment.StagingKey = *stagingKey
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func scanAttachmentWithReference(row rowScanner, attachment *model.Attachment) error {
|
||||
var stagingKey *string
|
||||
err := row.Scan(
|
||||
&attachment.ID, &attachment.ChatID, &attachment.OwnerID, &attachment.Filename,
|
||||
&attachment.ContentType, &attachment.SizeBytes, &attachment.SHA256, &attachment.ObjectKey,
|
||||
&attachment.Status, &attachment.CreatedAt, &attachment.UpdatedAt, &attachment.ReadyAt,
|
||||
&attachment.PipelineVersion, &attachment.ErrorCode, &stagingKey,
|
||||
&attachment.Referenced,
|
||||
)
|
||||
if stagingKey != nil {
|
||||
attachment.StagingKey = *stagingKey
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) AttachmentReferenced(ctx context.Context, attachmentID string) (bool, error) {
|
||||
const query = `SELECT EXISTS (SELECT 1 FROM message_attachments WHERE attachment_id = $1)`
|
||||
var referenced bool
|
||||
if err := s.pool.QueryRow(ctx, query, attachmentID).Scan(&referenced); err != nil {
|
||||
return false, fmt.Errorf("check attachment references: %w", err)
|
||||
}
|
||||
return referenced, nil
|
||||
}
|
||||
|
||||
func (s *Store) ClaimAttachmentForDeletion(ctx context.Context, candidate model.Attachment, createdBefore time.Time) (bool, error) {
|
||||
tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("begin attachment deletion claim: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(context.WithoutCancel(ctx)) }()
|
||||
|
||||
var status string
|
||||
var createdAt time.Time
|
||||
var readyAt *time.Time
|
||||
err = tx.QueryRow(
|
||||
ctx, `SELECT status, created_at, ready_at FROM attachments WHERE id = $1 FOR UPDATE`, candidate.ID,
|
||||
).Scan(&status, &createdAt, &readyAt)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("lock attachment deletion candidate: %w", err)
|
||||
}
|
||||
if status != candidate.Status {
|
||||
return false, nil
|
||||
}
|
||||
var age time.Time
|
||||
switch status {
|
||||
case model.AttachmentPending:
|
||||
age = createdAt
|
||||
case model.AttachmentReady:
|
||||
if readyAt == nil {
|
||||
return false, nil
|
||||
}
|
||||
age = *readyAt
|
||||
default:
|
||||
return false, nil
|
||||
}
|
||||
if age.After(createdBefore) {
|
||||
return false, nil
|
||||
}
|
||||
var referenced bool
|
||||
if err := tx.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM message_attachments WHERE attachment_id = $1)`, candidate.ID).Scan(&referenced); err != nil {
|
||||
return false, fmt.Errorf("recheck attachment references: %w", err)
|
||||
}
|
||||
if referenced {
|
||||
return false, nil
|
||||
}
|
||||
if _, err := tx.Exec(
|
||||
ctx,
|
||||
`UPDATE attachments SET status = 'deleting', updated_at = clock_timestamp() WHERE id = $1 AND status = $2`,
|
||||
candidate.ID, candidate.Status,
|
||||
); err != nil {
|
||||
return false, fmt.Errorf("mark attachment deleting: %w", err)
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return false, fmt.Errorf("commit attachment deletion claim: %w", err)
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (s *Store) DeleteAttachmentIfDeleting(ctx context.Context, attachmentID string) (bool, error) {
|
||||
const query = `
|
||||
DELETE FROM attachments a
|
||||
WHERE a.id = $1
|
||||
AND a.status = 'deleting'
|
||||
AND NOT EXISTS (SELECT 1 FROM message_attachments ma WHERE ma.attachment_id = a.id)`
|
||||
result, err := s.pool.Exec(ctx, query, attachmentID)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("delete claimed attachment: %w", err)
|
||||
}
|
||||
return result.RowsAffected() == 1, nil
|
||||
}
|
||||
|
||||
func scanAttachment(row rowScanner, attachment *model.Attachment) error {
|
||||
var stagingKey *string
|
||||
err := row.Scan(
|
||||
&attachment.ID, &attachment.ChatID, &attachment.OwnerID, &attachment.Filename,
|
||||
&attachment.ContentType, &attachment.SizeBytes, &attachment.SHA256, &attachment.ObjectKey,
|
||||
&attachment.Status, &attachment.CreatedAt, &attachment.UpdatedAt, &attachment.ReadyAt,
|
||||
&attachment.PipelineVersion, &attachment.ErrorCode, &stagingKey,
|
||||
)
|
||||
if stagingKey != nil {
|
||||
attachment.StagingKey = *stagingKey
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func attachmentColumnsWithAlias(alias string) string {
|
||||
return fmt.Sprintf(
|
||||
"%[1]s.id, %[1]s.chat_id, %[1]s.owner_id, %[1]s.filename, %[1]s.content_type, "+
|
||||
"%[1]s.size_bytes, %[1]s.sha256, %[1]s.object_key, %[1]s.status, "+
|
||||
"%[1]s.created_at, %[1]s.updated_at, %[1]s.ready_at, %[1]s.pipeline_version, "+
|
||||
"%[1]s.error_code, %[1]s.staging_key",
|
||||
alias,
|
||||
)
|
||||
}
|
||||
|
||||
func publicAttachment(attachment model.Attachment) model.Attachment {
|
||||
variants := make([]model.Variant, 0, len(attachment.Variants))
|
||||
for _, variant := range attachment.Variants {
|
||||
if variant.Name != "original" {
|
||||
variants = append(variants, variant)
|
||||
}
|
||||
}
|
||||
attachment.Variants = variants
|
||||
return attachment
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package postgres
|
||||
|
||||
import "gitea.privcloud.tech/dizi/mtusi2026lab5/internal/model"
|
||||
|
||||
var (
|
||||
ErrConflict = model.ErrConflict
|
||||
ErrNotFound = model.ErrNotFound
|
||||
ErrInvalidMembers = model.ErrInvalidMembers
|
||||
ErrInvalidCursor = model.ErrInvalidCursor
|
||||
ErrIdempotencyConflict = model.ErrIdempotencyConflict
|
||||
ErrStaleLease = model.ErrStaleLease
|
||||
ErrStaleAttempt = model.ErrStaleAttempt
|
||||
ErrStalePipeline = model.ErrStalePipeline
|
||||
ErrJobBusy = model.ErrJobBusy
|
||||
ErrJobComplete = model.ErrJobComplete
|
||||
ErrJobNotDue = model.ErrJobNotDue
|
||||
)
|
||||
@@ -0,0 +1,374 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/model"
|
||||
)
|
||||
|
||||
const expiredIdempotencyCleanupBatch = 100
|
||||
|
||||
func (s *Store) CreateMessage(
|
||||
ctx context.Context,
|
||||
chatID string,
|
||||
senderID string,
|
||||
text string,
|
||||
attachmentIDs []string,
|
||||
idempotencyKey string,
|
||||
idempotencyTTL time.Duration,
|
||||
) (model.Message, bool, error) {
|
||||
if attachmentIDs == nil {
|
||||
attachmentIDs = []string{}
|
||||
}
|
||||
var (
|
||||
tx pgx.Tx
|
||||
err error
|
||||
visible bool
|
||||
requestHash [sha256.Size]byte
|
||||
message model.Message
|
||||
replay bool
|
||||
)
|
||||
|
||||
tx, err = s.pool.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return model.Message{}, false, fmt.Errorf("begin create message transaction: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(context.WithoutCancel(ctx)) }()
|
||||
|
||||
visible, err = chatVisibleInTransaction(ctx, tx, chatID, senderID)
|
||||
if err != nil {
|
||||
return model.Message{}, false, err
|
||||
}
|
||||
if !visible {
|
||||
return model.Message{}, false, ErrNotFound
|
||||
}
|
||||
validAttachments, failedAttachment, err := attachmentsBelongToChat(ctx, tx, chatID, attachmentIDs)
|
||||
if err != nil {
|
||||
return model.Message{}, false, err
|
||||
}
|
||||
if !validAttachments {
|
||||
return model.Message{}, false, ErrNotFound
|
||||
}
|
||||
if failedAttachment {
|
||||
return model.Message{}, false, ErrConflict
|
||||
}
|
||||
if err = deleteExpiredIdempotencyRecords(ctx, tx, expiredIdempotencyCleanupBatch); err != nil {
|
||||
return model.Message{}, false, err
|
||||
}
|
||||
|
||||
requestHash, err = messageRequestHash(text, attachmentIDs)
|
||||
if err != nil {
|
||||
return model.Message{}, false, err
|
||||
}
|
||||
message, replay, err = createIdempotentMessage(
|
||||
ctx, tx, chatID, senderID, text, attachmentIDs, idempotencyKey, requestHash[:], idempotencyTTL,
|
||||
)
|
||||
if err != nil {
|
||||
return model.Message{}, false, err
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return model.Message{}, false, fmt.Errorf("commit create message transaction: %w", err)
|
||||
}
|
||||
return message, replay, nil
|
||||
}
|
||||
|
||||
func messageRequestHash(text string, attachmentIDs []string) ([sha256.Size]byte, error) {
|
||||
if attachmentIDs == nil {
|
||||
attachmentIDs = []string{}
|
||||
}
|
||||
payload, err := json.Marshal(struct {
|
||||
Text string `json:"text"`
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
}{text, attachmentIDs})
|
||||
if err != nil {
|
||||
return [sha256.Size]byte{}, fmt.Errorf("marshal message request: %w", err)
|
||||
}
|
||||
return sha256.Sum256(payload), nil
|
||||
}
|
||||
|
||||
func attachmentsBelongToChat(ctx context.Context, tx pgx.Tx, chatID string, attachmentIDs []string) (bool, bool, error) {
|
||||
if len(attachmentIDs) == 0 {
|
||||
return true, false, nil
|
||||
}
|
||||
const query = `
|
||||
SELECT id, status
|
||||
FROM attachments
|
||||
WHERE chat_id = $1 AND id::text = ANY($2)
|
||||
AND status IN ('queued', 'processing', 'ready', 'failed')
|
||||
FOR UPDATE`
|
||||
rows, err := tx.Query(ctx, query, chatID, attachmentIDs)
|
||||
if err != nil {
|
||||
return false, false, fmt.Errorf("validate message attachments: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
var count int
|
||||
var failed bool
|
||||
for rows.Next() {
|
||||
var id, status string
|
||||
if err := rows.Scan(&id, &status); err != nil {
|
||||
return false, false, fmt.Errorf("scan message attachment: %w", err)
|
||||
}
|
||||
count++
|
||||
failed = failed || status == model.AttachmentFailed
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return false, false, fmt.Errorf("validate message attachments: %w", err)
|
||||
}
|
||||
return count == len(attachmentIDs), failed, nil
|
||||
}
|
||||
|
||||
func chatVisibleInTransaction(ctx context.Context, tx pgx.Tx, chatID, userID string) (bool, error) {
|
||||
const query = `
|
||||
SELECT EXISTS (
|
||||
SELECT 1
|
||||
FROM chat_members
|
||||
WHERE chat_id = $1 AND user_id = $2
|
||||
)`
|
||||
|
||||
var visible bool
|
||||
if err := tx.QueryRow(ctx, query, chatID, userID).Scan(&visible); err != nil {
|
||||
return false, fmt.Errorf("check chat visibility: %w", err)
|
||||
}
|
||||
return visible, nil
|
||||
}
|
||||
|
||||
func createIdempotentMessage(
|
||||
ctx context.Context,
|
||||
tx pgx.Tx,
|
||||
chatID string,
|
||||
senderID string,
|
||||
text string,
|
||||
attachmentIDs []string,
|
||||
idempotencyKey string,
|
||||
requestHash []byte,
|
||||
idempotencyTTL time.Duration,
|
||||
) (model.Message, bool, error) {
|
||||
for {
|
||||
var (
|
||||
record idempotencyRecord
|
||||
found bool
|
||||
err error
|
||||
messageID string
|
||||
reserved bool
|
||||
message model.Message
|
||||
)
|
||||
|
||||
record, found, err = lockIdempotencyRecord(ctx, tx, senderID, chatID, idempotencyKey)
|
||||
if err != nil {
|
||||
return model.Message{}, false, err
|
||||
}
|
||||
if found && record.active {
|
||||
if !bytes.Equal(record.requestHash, requestHash) {
|
||||
return model.Message{}, false, ErrIdempotencyConflict
|
||||
}
|
||||
message, err = messageByID(ctx, tx, record.messageID)
|
||||
return message, true, err
|
||||
}
|
||||
if found {
|
||||
if err := deleteIdempotencyRecord(ctx, tx, senderID, chatID, idempotencyKey); err != nil {
|
||||
return model.Message{}, false, err
|
||||
}
|
||||
}
|
||||
|
||||
messageID = uuid.NewString()
|
||||
reserved, err = reserveIdempotencyKey(
|
||||
ctx, tx, senderID, chatID, idempotencyKey, requestHash, messageID, idempotencyTTL,
|
||||
)
|
||||
if err != nil {
|
||||
return model.Message{}, false, err
|
||||
}
|
||||
if !reserved {
|
||||
continue
|
||||
}
|
||||
|
||||
message, err = insertMessage(ctx, tx, messageID, chatID, senderID, text, attachmentIDs)
|
||||
return message, false, err
|
||||
}
|
||||
}
|
||||
|
||||
func deleteExpiredIdempotencyRecords(ctx context.Context, tx pgx.Tx, limit int) error {
|
||||
const query = `
|
||||
WITH expired AS (
|
||||
SELECT ctid
|
||||
FROM message_idempotency
|
||||
WHERE expires_at <= statement_timestamp()
|
||||
ORDER BY expires_at
|
||||
LIMIT $1
|
||||
FOR UPDATE SKIP LOCKED
|
||||
)
|
||||
DELETE FROM message_idempotency records
|
||||
USING expired
|
||||
WHERE records.ctid = expired.ctid`
|
||||
|
||||
if _, err := tx.Exec(ctx, query, limit); err != nil {
|
||||
return fmt.Errorf("delete expired idempotency records: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type idempotencyRecord struct {
|
||||
requestHash []byte
|
||||
messageID string
|
||||
active bool
|
||||
}
|
||||
|
||||
func lockIdempotencyRecord(
|
||||
ctx context.Context,
|
||||
tx pgx.Tx,
|
||||
userID string,
|
||||
chatID string,
|
||||
key string,
|
||||
) (idempotencyRecord, bool, error) {
|
||||
const query = `
|
||||
SELECT request_hash, message_id, expires_at > statement_timestamp()
|
||||
FROM message_idempotency
|
||||
WHERE user_id = $1 AND chat_id = $2 AND key = $3
|
||||
FOR UPDATE`
|
||||
|
||||
var (
|
||||
record idempotencyRecord
|
||||
err error
|
||||
)
|
||||
err = tx.QueryRow(ctx, query, userID, chatID, key).Scan(
|
||||
&record.requestHash,
|
||||
&record.messageID,
|
||||
&record.active,
|
||||
)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return idempotencyRecord{}, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return idempotencyRecord{}, false, fmt.Errorf("lock idempotency key: %w", err)
|
||||
}
|
||||
return record, true, nil
|
||||
}
|
||||
|
||||
func deleteIdempotencyRecord(ctx context.Context, tx pgx.Tx, userID, chatID, key string) error {
|
||||
const query = `
|
||||
DELETE FROM message_idempotency
|
||||
WHERE user_id = $1 AND chat_id = $2 AND key = $3`
|
||||
if _, err := tx.Exec(ctx, query, userID, chatID, key); err != nil {
|
||||
return fmt.Errorf("delete expired idempotency key: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func reserveIdempotencyKey(
|
||||
ctx context.Context,
|
||||
tx pgx.Tx,
|
||||
userID string,
|
||||
chatID string,
|
||||
key string,
|
||||
requestHash []byte,
|
||||
messageID string,
|
||||
ttl time.Duration,
|
||||
) (bool, error) {
|
||||
const query = `
|
||||
INSERT INTO message_idempotency (user_id, chat_id, key, request_hash, message_id, expires_at)
|
||||
VALUES ($1, $2, $3, $4, $5, statement_timestamp() + $6 * INTERVAL '1 second')
|
||||
ON CONFLICT (user_id, chat_id, key) DO NOTHING
|
||||
RETURNING true`
|
||||
|
||||
var (
|
||||
inserted bool
|
||||
err error
|
||||
)
|
||||
err = tx.QueryRow(ctx, query, userID, chatID, key, requestHash, messageID, int64(ttl/time.Second)).Scan(&inserted)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("reserve idempotency key: %w", err)
|
||||
}
|
||||
return inserted, nil
|
||||
}
|
||||
|
||||
func insertMessage(
|
||||
ctx context.Context,
|
||||
tx pgx.Tx,
|
||||
messageID string,
|
||||
chatID string,
|
||||
senderID string,
|
||||
text string,
|
||||
attachmentIDs []string,
|
||||
) (model.Message, error) {
|
||||
const query = `
|
||||
INSERT INTO messages (id, chat_id, sender_id, text)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING id, chat_id, sender_id, text, created_at`
|
||||
|
||||
var (
|
||||
message model.Message
|
||||
err error
|
||||
)
|
||||
err = tx.QueryRow(ctx, query, messageID, chatID, senderID, text).Scan(
|
||||
&message.ID,
|
||||
&message.ChatID,
|
||||
&message.SenderID,
|
||||
&message.Text,
|
||||
&message.CreatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return model.Message{}, fmt.Errorf("insert message: %w", err)
|
||||
}
|
||||
if err := insertMessageAttachments(ctx, tx, messageID, chatID, attachmentIDs); err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
message.AttachmentIDs = make([]string, len(attachmentIDs))
|
||||
copy(message.AttachmentIDs, attachmentIDs)
|
||||
return message, nil
|
||||
}
|
||||
|
||||
func insertMessageAttachments(ctx context.Context, tx pgx.Tx, messageID, chatID string, attachmentIDs []string) error {
|
||||
const query = `
|
||||
INSERT INTO message_attachments (message_id, chat_id, attachment_id, position)
|
||||
VALUES ($1, $2, $3, $4)`
|
||||
for position, attachmentID := range attachmentIDs {
|
||||
if _, err := tx.Exec(ctx, query, messageID, chatID, attachmentID, position); err != nil {
|
||||
return fmt.Errorf("insert message attachment: %w", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func messageByID(ctx context.Context, tx pgx.Tx, messageID string) (model.Message, error) {
|
||||
const query = `
|
||||
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at,
|
||||
ARRAY(
|
||||
SELECT ma.attachment_id::text
|
||||
FROM message_attachments ma
|
||||
WHERE ma.message_id = m.id
|
||||
ORDER BY ma.position
|
||||
)
|
||||
FROM messages m
|
||||
WHERE m.id = $1`
|
||||
|
||||
var (
|
||||
message model.Message
|
||||
err error
|
||||
)
|
||||
err = tx.QueryRow(ctx, query, messageID).Scan(
|
||||
&message.ID,
|
||||
&message.ChatID,
|
||||
&message.SenderID,
|
||||
&message.Text,
|
||||
&message.CreatedAt,
|
||||
&message.AttachmentIDs,
|
||||
)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.Message{}, fmt.Errorf("idempotency result message not found")
|
||||
}
|
||||
if err != nil {
|
||||
return model.Message{}, fmt.Errorf("get idempotency result message: %w", err)
|
||||
}
|
||||
return message, nil
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/model"
|
||||
)
|
||||
|
||||
func (s *Store) ClaimOutboxEvents(
|
||||
ctx context.Context,
|
||||
limit int,
|
||||
leaseDuration time.Duration,
|
||||
) ([]model.OutboxEvent, error) {
|
||||
if limit < 1 || limit > 1000 || leaseDuration <= 0 {
|
||||
return nil, model.ErrInvalidInput
|
||||
}
|
||||
claimToken := uuid.NewString()
|
||||
query := `
|
||||
WITH candidates AS (
|
||||
SELECT id
|
||||
FROM outbox_events
|
||||
WHERE published_at IS NULL
|
||||
AND available_at <= clock_timestamp()
|
||||
AND (claim_until IS NULL OR claim_until <= clock_timestamp())
|
||||
ORDER BY available_at, id
|
||||
LIMIT $1
|
||||
FOR UPDATE SKIP LOCKED
|
||||
)
|
||||
UPDATE outbox_events event
|
||||
SET claim_token = $2,
|
||||
claim_until = clock_timestamp() + $3 * INTERVAL '1 millisecond',
|
||||
publish_tries = event.publish_tries + 1
|
||||
FROM candidates
|
||||
WHERE event.id = candidates.id
|
||||
RETURNING event.id, event.topic, event.partition_key, event.payload, event.job_id,
|
||||
event.attempt, event.available_at, event.publish_tries, event.claim_token,
|
||||
event.claim_until, event.last_error_code, event.created_at`
|
||||
rows, err := s.pool.Query(ctx, query, limit, claimToken, leaseDuration.Milliseconds())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("claim outbox events: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
events, err := pgx.CollectRows(rows, pgx.RowToFunc[model.OutboxEvent](func(row pgx.CollectableRow) (model.OutboxEvent, error) {
|
||||
var event model.OutboxEvent
|
||||
err := row.Scan(
|
||||
&event.ID, &event.Topic, &event.PartitionKey, &event.Payload, &event.JobID,
|
||||
&event.Attempt, &event.AvailableAt, &event.PublishTries, &event.LeaseToken,
|
||||
&event.LeaseUntil, &event.LastErrorCode, &event.CreatedAt,
|
||||
)
|
||||
return event, err
|
||||
}))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("scan claimed outbox events: %w", err)
|
||||
}
|
||||
return events, nil
|
||||
}
|
||||
|
||||
func (s *Store) MarkOutboxPublished(ctx context.Context, eventID, leaseToken string) (bool, error) {
|
||||
const query = `
|
||||
UPDATE outbox_events
|
||||
SET published_at = clock_timestamp(), claim_token = NULL, claim_until = NULL,
|
||||
last_error_code = NULL
|
||||
WHERE id = $1 AND claim_token = $2 AND published_at IS NULL
|
||||
AND claim_until > clock_timestamp()`
|
||||
result, err := s.pool.Exec(ctx, query, eventID, leaseToken)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("mark outbox event published: %w", err)
|
||||
}
|
||||
return result.RowsAffected() == 1, nil
|
||||
}
|
||||
|
||||
func (s *Store) ReleaseOutboxEvent(
|
||||
ctx context.Context,
|
||||
eventID string,
|
||||
leaseToken string,
|
||||
errorCode string,
|
||||
nextAttemptAt time.Time,
|
||||
) (bool, error) {
|
||||
if !validErrorCode(errorCode) || nextAttemptAt.IsZero() {
|
||||
return false, model.ErrInvalidInput
|
||||
}
|
||||
const query = `
|
||||
UPDATE outbox_events
|
||||
SET available_at = $3, claim_token = NULL, claim_until = NULL, last_error_code = $4
|
||||
WHERE id = $1 AND claim_token = $2 AND published_at IS NULL
|
||||
AND claim_until > clock_timestamp()`
|
||||
result, err := s.pool.Exec(ctx, query, eventID, leaseToken, nextAttemptAt.UTC(), errorCode)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("release outbox event: %w", err)
|
||||
}
|
||||
return result.RowsAffected() == 1, nil
|
||||
}
|
||||
|
||||
func (s *Store) RecoverExpiredOutboxEvents(ctx context.Context, now time.Time) (int, error) {
|
||||
if now.IsZero() {
|
||||
now = time.Now().UTC()
|
||||
}
|
||||
const query = `
|
||||
UPDATE outbox_events
|
||||
SET claim_token = NULL, claim_until = NULL
|
||||
WHERE published_at IS NULL AND claim_until <= $1`
|
||||
result, err := s.pool.Exec(ctx, query, now.UTC())
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("recover expired outbox events: %w", err)
|
||||
}
|
||||
return int(result.RowsAffected()), nil
|
||||
}
|
||||
|
||||
func (s *Store) DeletePublishedOutboxEvents(ctx context.Context, publishedBefore time.Time, limit int) (int, error) {
|
||||
if publishedBefore.IsZero() || limit < 1 || limit > 1000 {
|
||||
return 0, model.ErrInvalidInput
|
||||
}
|
||||
const query = `
|
||||
WITH candidates AS (
|
||||
SELECT id
|
||||
FROM outbox_events
|
||||
WHERE published_at < $1
|
||||
ORDER BY published_at, id
|
||||
LIMIT $2
|
||||
FOR UPDATE SKIP LOCKED
|
||||
)
|
||||
DELETE FROM outbox_events event
|
||||
USING candidates
|
||||
WHERE event.id = candidates.id`
|
||||
result, err := s.pool.Exec(ctx, query, publishedBefore.UTC(), limit)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("delete published outbox events: %w", err)
|
||||
}
|
||||
return int(result.RowsAffected()), nil
|
||||
}
|
||||
@@ -0,0 +1,442 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/model"
|
||||
)
|
||||
|
||||
type Store struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func New(pool *pgxpool.Pool) *Store {
|
||||
return &Store{pool: pool}
|
||||
}
|
||||
|
||||
func (s *Store) Ping(ctx context.Context) error {
|
||||
return s.pool.Ping(ctx)
|
||||
}
|
||||
|
||||
func (s *Store) CreateUser(
|
||||
ctx context.Context,
|
||||
username string,
|
||||
displayName string,
|
||||
passwordHash string,
|
||||
) (model.User, error) {
|
||||
const query = `
|
||||
INSERT INTO users (id, username, display_name, password_hash)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING id, username, display_name, created_at`
|
||||
|
||||
var user model.User
|
||||
err := s.pool.QueryRow(ctx, query, uuid.NewString(), username, displayName, passwordHash).Scan(
|
||||
&user.ID,
|
||||
&user.Username,
|
||||
&user.DisplayName,
|
||||
&user.CreatedAt,
|
||||
)
|
||||
if isUniqueViolation(err) {
|
||||
return model.User{}, ErrConflict
|
||||
}
|
||||
if err != nil {
|
||||
return model.User{}, fmt.Errorf("create user: %w", err)
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (s *Store) UserByID(ctx context.Context, id string) (model.User, error) {
|
||||
const query = `
|
||||
SELECT id, username, display_name, created_at
|
||||
FROM users
|
||||
WHERE id = $1`
|
||||
|
||||
var user model.User
|
||||
err := s.pool.QueryRow(ctx, query, id).Scan(
|
||||
&user.ID,
|
||||
&user.Username,
|
||||
&user.DisplayName,
|
||||
&user.CreatedAt,
|
||||
)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.User{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return model.User{}, fmt.Errorf("get user by id: %w", err)
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (s *Store) UserByUsername(ctx context.Context, username string) (model.UserCredentials, error) {
|
||||
const query = `
|
||||
SELECT id, username, display_name, created_at, password_hash
|
||||
FROM users
|
||||
WHERE username = $1`
|
||||
|
||||
var credentials model.UserCredentials
|
||||
err := s.pool.QueryRow(ctx, query, username).Scan(
|
||||
&credentials.ID,
|
||||
&credentials.Username,
|
||||
&credentials.DisplayName,
|
||||
&credentials.CreatedAt,
|
||||
&credentials.PasswordHash,
|
||||
)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.UserCredentials{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return model.UserCredentials{}, fmt.Errorf("get user by username: %w", err)
|
||||
}
|
||||
|
||||
return credentials, nil
|
||||
}
|
||||
|
||||
func (s *Store) CreateChat(
|
||||
ctx context.Context,
|
||||
title string,
|
||||
memberIDs []string,
|
||||
callerID string,
|
||||
) (model.Chat, error) {
|
||||
if !validMembers(memberIDs, callerID) {
|
||||
return model.Chat{}, ErrInvalidMembers
|
||||
}
|
||||
|
||||
tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return model.Chat{}, fmt.Errorf("begin create chat transaction: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(context.WithoutCancel(ctx)) }()
|
||||
|
||||
valid, err := allUsersExist(ctx, tx, memberIDs)
|
||||
if err != nil {
|
||||
return model.Chat{}, err
|
||||
}
|
||||
if !valid {
|
||||
return model.Chat{}, ErrInvalidMembers
|
||||
}
|
||||
|
||||
chat, err := insertChat(ctx, tx, title)
|
||||
if err != nil {
|
||||
return model.Chat{}, err
|
||||
}
|
||||
if err := insertMembers(ctx, tx, chat.ID, memberIDs); err != nil {
|
||||
return model.Chat{}, err
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return model.Chat{}, fmt.Errorf("commit create chat transaction: %w", err)
|
||||
}
|
||||
|
||||
chat.MemberIDs = append([]string(nil), memberIDs...)
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
func validMembers(memberIDs []string, callerID string) bool {
|
||||
callerUUID, err := uuid.Parse(callerID)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
seen := make(map[uuid.UUID]struct{}, len(memberIDs))
|
||||
callerIncluded := false
|
||||
for _, memberID := range memberIDs {
|
||||
memberUUID, err := uuid.Parse(memberID)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if _, exists := seen[memberUUID]; exists {
|
||||
return false
|
||||
}
|
||||
|
||||
seen[memberUUID] = struct{}{}
|
||||
callerIncluded = callerIncluded || memberUUID == callerUUID
|
||||
}
|
||||
|
||||
return callerIncluded
|
||||
}
|
||||
|
||||
func allUsersExist(ctx context.Context, tx pgx.Tx, memberIDs []string) (bool, error) {
|
||||
const query = `
|
||||
SELECT count(*)
|
||||
FROM users
|
||||
WHERE id::text = ANY($1)`
|
||||
|
||||
var count int
|
||||
if err := tx.QueryRow(ctx, query, memberIDs).Scan(&count); err != nil {
|
||||
return false, fmt.Errorf("check chat members: %w", err)
|
||||
}
|
||||
|
||||
return count == len(memberIDs), nil
|
||||
}
|
||||
|
||||
func insertChat(ctx context.Context, tx pgx.Tx, title string) (model.Chat, error) {
|
||||
const query = `
|
||||
INSERT INTO chats (id, title)
|
||||
VALUES ($1, $2)
|
||||
RETURNING id, title, created_at`
|
||||
|
||||
var chat model.Chat
|
||||
if err := tx.QueryRow(ctx, query, uuid.NewString(), title).Scan(&chat.ID, &chat.Title, &chat.CreatedAt); err != nil {
|
||||
return model.Chat{}, fmt.Errorf("insert chat: %w", err)
|
||||
}
|
||||
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
func insertMembers(ctx context.Context, tx pgx.Tx, chatID string, memberIDs []string) error {
|
||||
const query = `
|
||||
INSERT INTO chat_members (chat_id, user_id, position)
|
||||
VALUES ($1, $2, $3)`
|
||||
|
||||
batch := &pgx.Batch{}
|
||||
for position, memberID := range memberIDs {
|
||||
batch.Queue(query, chatID, memberID, position)
|
||||
}
|
||||
|
||||
results := tx.SendBatch(ctx, batch)
|
||||
defer func() { _ = results.Close() }()
|
||||
for range memberIDs {
|
||||
if _, err := results.Exec(); err != nil {
|
||||
return fmt.Errorf("insert chat member: %w", err)
|
||||
}
|
||||
}
|
||||
if err := results.Close(); err != nil {
|
||||
return fmt.Errorf("close chat members batch: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) ChatForUser(ctx context.Context, chatID, userID string) (model.Chat, error) {
|
||||
const query = `
|
||||
SELECT c.id, c.title, c.created_at,
|
||||
array_agg(cm.user_id::text ORDER BY cm.position)
|
||||
FROM chats c
|
||||
JOIN chat_members cm ON cm.chat_id = c.id
|
||||
WHERE c.id = $1
|
||||
AND EXISTS (
|
||||
SELECT 1
|
||||
FROM chat_members visible
|
||||
WHERE visible.chat_id = c.id AND visible.user_id = $2
|
||||
)
|
||||
GROUP BY c.id, c.title, c.created_at`
|
||||
|
||||
var chat model.Chat
|
||||
err := s.pool.QueryRow(ctx, query, chatID, userID).Scan(
|
||||
&chat.ID,
|
||||
&chat.Title,
|
||||
&chat.CreatedAt,
|
||||
&chat.MemberIDs,
|
||||
)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.Chat{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return model.Chat{}, fmt.Errorf("get chat for user: %w", err)
|
||||
}
|
||||
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
func (s *Store) ListChats(
|
||||
ctx context.Context,
|
||||
userID string,
|
||||
after *model.Position,
|
||||
limit int,
|
||||
) ([]model.Chat, bool, error) {
|
||||
if after != nil {
|
||||
valid, err := s.visibleChatPositionExists(ctx, userID, *after)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
if !valid {
|
||||
return nil, false, ErrInvalidCursor
|
||||
}
|
||||
}
|
||||
|
||||
const query = `
|
||||
SELECT c.id, c.title, c.created_at,
|
||||
array_agg(all_members.user_id::text ORDER BY all_members.position)
|
||||
FROM chats c
|
||||
JOIN chat_members visible ON visible.chat_id = c.id AND visible.user_id = $1
|
||||
JOIN chat_members all_members ON all_members.chat_id = c.id
|
||||
WHERE ($2::timestamptz IS NULL OR (c.created_at, c.id) > ($2, $3::uuid))
|
||||
GROUP BY c.id, c.title, c.created_at
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT $4`
|
||||
|
||||
var afterTime any
|
||||
var afterID any
|
||||
if after != nil {
|
||||
afterTime = after.CreatedAt
|
||||
afterID = after.ID
|
||||
}
|
||||
|
||||
rows, err := s.pool.Query(ctx, query, userID, afterTime, afterID, limit+1)
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("list chats: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
chats, err := pgx.CollectRows(rows, pgx.RowToFunc[model.Chat](func(row pgx.CollectableRow) (model.Chat, error) {
|
||||
var chat model.Chat
|
||||
err := row.Scan(&chat.ID, &chat.Title, &chat.CreatedAt, &chat.MemberIDs)
|
||||
return chat, err
|
||||
}))
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("scan chats: %w", err)
|
||||
}
|
||||
|
||||
return page(chats, limit)
|
||||
}
|
||||
|
||||
func (s *Store) visibleChatPositionExists(
|
||||
ctx context.Context,
|
||||
userID string,
|
||||
position model.Position,
|
||||
) (bool, error) {
|
||||
const query = `
|
||||
SELECT EXISTS (
|
||||
SELECT 1
|
||||
FROM chats c
|
||||
JOIN chat_members cm ON cm.chat_id = c.id
|
||||
WHERE cm.user_id = $1 AND c.created_at = $2 AND c.id = $3
|
||||
)`
|
||||
|
||||
var exists bool
|
||||
if err := s.pool.QueryRow(ctx, query, userID, position.CreatedAt, position.ID).Scan(&exists); err != nil {
|
||||
return false, fmt.Errorf("validate chat cursor: %w", err)
|
||||
}
|
||||
|
||||
return exists, nil
|
||||
}
|
||||
|
||||
func (s *Store) ListMessages(
|
||||
ctx context.Context,
|
||||
chatID string,
|
||||
userID string,
|
||||
after *model.Position,
|
||||
limit int,
|
||||
) ([]model.Message, bool, error) {
|
||||
visible, err := s.chatVisible(ctx, chatID, userID)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
if !visible {
|
||||
return nil, false, ErrNotFound
|
||||
}
|
||||
if after != nil {
|
||||
valid, err := s.messagePositionExists(ctx, chatID, *after)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
if !valid {
|
||||
return nil, false, ErrInvalidCursor
|
||||
}
|
||||
}
|
||||
|
||||
const query = `
|
||||
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at,
|
||||
ARRAY(
|
||||
SELECT ma.attachment_id::text
|
||||
FROM message_attachments ma
|
||||
WHERE ma.message_id = m.id
|
||||
ORDER BY ma.position
|
||||
)
|
||||
FROM messages m
|
||||
WHERE m.chat_id = $1
|
||||
AND ($2::timestamptz IS NULL OR (m.created_at, m.id) > ($2, $3::uuid))
|
||||
ORDER BY m.created_at, m.id
|
||||
LIMIT $4`
|
||||
|
||||
var afterTime any
|
||||
var afterID any
|
||||
if after != nil {
|
||||
afterTime = after.CreatedAt
|
||||
afterID = after.ID
|
||||
}
|
||||
|
||||
rows, err := s.pool.Query(ctx, query, chatID, afterTime, afterID, limit+1)
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("list messages: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
messages, err := pgx.CollectRows(rows, pgx.RowToFunc[model.Message](func(row pgx.CollectableRow) (model.Message, error) {
|
||||
var message model.Message
|
||||
err := row.Scan(
|
||||
&message.ID,
|
||||
&message.ChatID,
|
||||
&message.SenderID,
|
||||
&message.Text,
|
||||
&message.CreatedAt,
|
||||
&message.AttachmentIDs,
|
||||
)
|
||||
return message, err
|
||||
}))
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("scan messages: %w", err)
|
||||
}
|
||||
|
||||
return page(messages, limit)
|
||||
}
|
||||
|
||||
func (s *Store) chatVisible(ctx context.Context, chatID, userID string) (bool, error) {
|
||||
const query = `
|
||||
SELECT EXISTS (
|
||||
SELECT 1
|
||||
FROM chat_members
|
||||
WHERE chat_id = $1 AND user_id = $2
|
||||
)`
|
||||
|
||||
var exists bool
|
||||
if err := s.pool.QueryRow(ctx, query, chatID, userID).Scan(&exists); err != nil {
|
||||
return false, fmt.Errorf("check chat visibility: %w", err)
|
||||
}
|
||||
|
||||
return exists, nil
|
||||
}
|
||||
|
||||
func (s *Store) messagePositionExists(
|
||||
ctx context.Context,
|
||||
chatID string,
|
||||
position model.Position,
|
||||
) (bool, error) {
|
||||
const query = `
|
||||
SELECT EXISTS (
|
||||
SELECT 1
|
||||
FROM messages
|
||||
WHERE chat_id = $1 AND created_at = $2 AND id = $3
|
||||
)`
|
||||
|
||||
var exists bool
|
||||
if err := s.pool.QueryRow(ctx, query, chatID, position.CreatedAt, position.ID).Scan(&exists); err != nil {
|
||||
return false, fmt.Errorf("validate message cursor: %w", err)
|
||||
}
|
||||
|
||||
return exists, nil
|
||||
}
|
||||
|
||||
func page[T any](items []T, limit int) ([]T, bool, error) {
|
||||
if limit < 1 {
|
||||
return nil, false, fmt.Errorf("limit must be positive")
|
||||
}
|
||||
if len(items) <= limit {
|
||||
return items, false, nil
|
||||
}
|
||||
|
||||
return items[:limit], true, nil
|
||||
}
|
||||
|
||||
func isUniqueViolation(err error) bool {
|
||||
var postgresError *pgconn.PgError
|
||||
return errors.As(err, &postgresError) && postgresError.Code == "23505"
|
||||
}
|
||||
@@ -0,0 +1,711 @@
|
||||
package postgres_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/database"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/model"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/postgres"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/reconcile"
|
||||
)
|
||||
|
||||
type PostgresSuite struct {
|
||||
suite.Suite
|
||||
pool *pgxpool.Pool
|
||||
store *postgres.Store
|
||||
}
|
||||
|
||||
func TestPostgresSuite(t *testing.T) {
|
||||
suite.Run(t, new(PostgresSuite))
|
||||
}
|
||||
|
||||
func (s *PostgresSuite) SetupSuite() {
|
||||
s.pool = openTestDatabase(s.T())
|
||||
s.store = postgres.New(s.pool)
|
||||
}
|
||||
|
||||
func (s *PostgresSuite) TearDownSuite() {
|
||||
if s.pool != nil {
|
||||
s.pool.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func (s *PostgresSuite) TestConcurrentUsernameCreation() {
|
||||
t := s.T()
|
||||
store := s.store
|
||||
username := "race_" + strings.ReplaceAll(uuid.NewString(), "-", "")[:16]
|
||||
|
||||
const workers = 8
|
||||
results := make(chan error, workers)
|
||||
var group sync.WaitGroup
|
||||
for range workers {
|
||||
group.Add(1)
|
||||
go func() {
|
||||
defer group.Done()
|
||||
_, err := store.CreateUser(context.Background(), username, "Race user", "password-hash")
|
||||
results <- err
|
||||
}()
|
||||
}
|
||||
group.Wait()
|
||||
close(results)
|
||||
|
||||
var created, conflicts int
|
||||
for err := range results {
|
||||
switch {
|
||||
case err == nil:
|
||||
created++
|
||||
case errors.Is(err, postgres.ErrConflict):
|
||||
conflicts++
|
||||
default:
|
||||
t.Fatalf("CreateUser() error = %v", err)
|
||||
}
|
||||
}
|
||||
if created != 1 || conflicts != workers-1 {
|
||||
t.Fatalf("created = %d, conflicts = %d", created, conflicts)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *PostgresSuite) TestCreateChatRollsBackForUnknownMember() {
|
||||
t := s.T()
|
||||
pool := s.pool
|
||||
store := s.store
|
||||
owner, err := store.CreateUser(context.Background(), uniqueUsername(), "Owner", "password-hash")
|
||||
if err != nil {
|
||||
t.Fatalf("CreateUser() error = %v", err)
|
||||
}
|
||||
|
||||
before := chatCount(t, pool)
|
||||
_, err = store.CreateChat(context.Background(), "Invalid chat", []string{owner.ID, uuid.NewString()}, owner.ID)
|
||||
if !errors.Is(err, postgres.ErrInvalidMembers) {
|
||||
t.Fatalf("CreateChat() error = %v, want ErrInvalidMembers", err)
|
||||
}
|
||||
if after := chatCount(t, pool); after != before {
|
||||
t.Fatalf("chat count changed from %d to %d", before, after)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *PostgresSuite) TestMessageIdempotencyReplayAndConflict() {
|
||||
t := s.T()
|
||||
pool := s.pool
|
||||
store := s.store
|
||||
owner, chatID := createOwnerAndChat(t, store)
|
||||
key := uuid.NewString()
|
||||
|
||||
first, replay, err := store.CreateMessage(context.Background(), chatID, owner.ID, "same body", nil, key, 24*time.Hour)
|
||||
if err != nil || replay {
|
||||
t.Fatalf("first CreateMessage() = (%v, %t, %v)", first, replay, err)
|
||||
}
|
||||
second, replay, err := store.CreateMessage(context.Background(), chatID, owner.ID, "same body", []string{}, key, 24*time.Hour)
|
||||
if err != nil || !replay {
|
||||
t.Fatalf("replay CreateMessage() = (%v, %t, %v)", second, replay, err)
|
||||
}
|
||||
s.Equal(first, second)
|
||||
if _, _, err := store.CreateMessage(context.Background(), chatID, owner.ID, "different body", nil, key, 24*time.Hour); !errors.Is(err, postgres.ErrIdempotencyConflict) {
|
||||
t.Fatalf("conflicting CreateMessage() error = %v, want ErrIdempotencyConflict", err)
|
||||
}
|
||||
if count := messageCount(t, pool, chatID); count != 1 {
|
||||
t.Fatalf("message count = %d, want 1", count)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *PostgresSuite) TestAttachmentAccessAndMessageLinking() {
|
||||
owner, chatID := createOwnerAndChat(s.T(), s.store)
|
||||
outsider, err := s.store.CreateUser(context.Background(), uniqueUsername(), "Outsider", "password-hash")
|
||||
s.Require().NoError(err)
|
||||
attachment := model.Attachment{
|
||||
ID: uuid.NewString(), ChatID: chatID, OwnerID: owner.ID, Filename: "photo.png",
|
||||
ContentType: "image/png", SizeBytes: 128, SHA256: strings.Repeat("a", 64),
|
||||
ObjectKey: "attachments/" + uuid.NewString() + "/original",
|
||||
}
|
||||
pending, err := s.store.CreatePendingAttachment(context.Background(), attachment)
|
||||
s.Require().NoError(err)
|
||||
created, err := s.store.MarkAttachmentReady(context.Background(), pending.ID, pending.ObjectKey)
|
||||
s.Require().NoError(err)
|
||||
s.Equal("ready", created.Status)
|
||||
s.Empty(created.Variants)
|
||||
s.Nil(created.ErrorCode)
|
||||
|
||||
visible, err := s.store.AttachmentForUser(context.Background(), created.ID, owner.ID)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(created, visible)
|
||||
_, err = s.store.AttachmentForUser(context.Background(), created.ID, outsider.ID)
|
||||
s.ErrorIs(err, postgres.ErrNotFound)
|
||||
|
||||
message, replay, err := s.store.CreateMessage(
|
||||
context.Background(), chatID, owner.ID, "", []string{created.ID}, uuid.NewString(), 24*time.Hour,
|
||||
)
|
||||
s.Require().NoError(err)
|
||||
s.False(replay)
|
||||
s.Equal([]string{created.ID}, message.AttachmentIDs)
|
||||
|
||||
messages, _, err := s.store.ListMessages(context.Background(), chatID, owner.ID, nil, 10)
|
||||
s.Require().NoError(err)
|
||||
s.Len(messages, 1)
|
||||
s.Equal([]string{created.ID}, messages[0].AttachmentIDs)
|
||||
referenced, err := s.store.AttachmentReferenced(context.Background(), created.ID)
|
||||
s.Require().NoError(err)
|
||||
s.True(referenced)
|
||||
deleted, err := s.store.ClaimAttachmentForDeletion(context.Background(), created, time.Now().Add(time.Hour))
|
||||
s.Require().NoError(err)
|
||||
s.False(deleted)
|
||||
}
|
||||
|
||||
func (s *PostgresSuite) TestAttachmentJobLifecycleAndOutboxFencing() {
|
||||
owner, chatID := createOwnerAndChat(s.T(), s.store)
|
||||
attachment, job := createQueuedAttachment(s.T(), s.store, owner.ID, chatID)
|
||||
s.Equal(model.AttachmentQueued, attachment.Status)
|
||||
|
||||
events, err := s.store.ClaimOutboxEvents(context.Background(), 10, time.Minute)
|
||||
s.Require().NoError(err)
|
||||
s.Require().NotEmpty(events)
|
||||
var event model.OutboxEvent
|
||||
for _, candidate := range events {
|
||||
if candidate.JobID == job.ID {
|
||||
event = candidate
|
||||
break
|
||||
}
|
||||
}
|
||||
s.Require().NotEmpty(event.ID)
|
||||
var message model.AttachmentJobMessage
|
||||
s.Require().NoError(json.Unmarshal(event.Payload, &message))
|
||||
s.Equal(job.ID, message.JobID)
|
||||
s.Equal(attachment.ID, message.AttachmentID)
|
||||
s.Equal(1, message.Attempt)
|
||||
published, err := s.store.MarkOutboxPublished(context.Background(), event.ID, event.LeaseToken)
|
||||
s.Require().NoError(err)
|
||||
s.True(published)
|
||||
|
||||
_, replay, err := s.store.CreateMessage(
|
||||
context.Background(), chatID, owner.ID, "queued attachment",
|
||||
[]string{attachment.ID}, uuid.NewString(), 24*time.Hour,
|
||||
)
|
||||
s.Require().NoError(err)
|
||||
s.False(replay)
|
||||
|
||||
_, err = s.store.ClaimAttachmentJob(
|
||||
context.Background(), job.ID, uuid.NewString(), job.PipelineVersion, job.Attempt, "worker-invalid", time.Minute,
|
||||
)
|
||||
s.ErrorIs(err, model.ErrInvalidInput)
|
||||
|
||||
lease, err := s.store.ClaimAttachmentJob(
|
||||
context.Background(), job.ID, attachment.ID, job.PipelineVersion, job.Attempt, "worker-1", time.Minute,
|
||||
)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(model.AttachmentProcessing, lease.Attachment.Status)
|
||||
s.NotEmpty(lease.Attachment.StagingKey)
|
||||
|
||||
variants := completedVariants(attachment.ID, 1)
|
||||
result, err := s.store.CompleteAttachmentJob(context.Background(), lease, variants)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(model.JobMutationApplied, result)
|
||||
result, err = s.store.CompleteAttachmentJob(context.Background(), lease, variants)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(model.JobMutationAlreadyComplete, result)
|
||||
|
||||
metadata, variant, err := s.store.AttachmentVariantForUser(
|
||||
context.Background(), attachment.ID, owner.ID, "thumbnail",
|
||||
)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(model.AttachmentReady, metadata.Status)
|
||||
s.Len(metadata.Variants, 3)
|
||||
s.Equal(variants[1].ObjectKey, variant.ObjectKey)
|
||||
listedKeys := make(map[string]struct{})
|
||||
var after string
|
||||
for {
|
||||
listed, next, err := s.store.ListAttachments(context.Background(), after, 1000)
|
||||
s.Require().NoError(err)
|
||||
for _, candidate := range listed {
|
||||
if candidate.ID == attachment.ID {
|
||||
listedKeys[candidate.ObjectKey] = struct{}{}
|
||||
}
|
||||
}
|
||||
if next == "" {
|
||||
break
|
||||
}
|
||||
after = next
|
||||
}
|
||||
for _, candidate := range variants {
|
||||
s.Contains(listedKeys, candidate.ObjectKey)
|
||||
}
|
||||
|
||||
v2 := model.AttachmentJob{ID: uuid.NewString(), PipelineVersion: 2}
|
||||
queuedV2, err := s.store.QueueAttachmentPipelineVersion(
|
||||
context.Background(), attachment.ID, v2, "", "",
|
||||
)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(model.AttachmentQueued, queuedV2.Status)
|
||||
s.Equal(2, queuedV2.PipelineVersion)
|
||||
result, err = s.store.CompleteAttachmentJob(context.Background(), lease, variants)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(model.JobMutationStale, result)
|
||||
}
|
||||
|
||||
func (s *PostgresSuite) TestPublishedOutboxRetentionIsBatched() {
|
||||
owner, chatID := createOwnerAndChat(s.T(), s.store)
|
||||
_, firstJob := createQueuedAttachment(s.T(), s.store, owner.ID, chatID)
|
||||
_, secondJob := createQueuedAttachment(s.T(), s.store, owner.ID, chatID)
|
||||
events, err := s.store.ClaimOutboxEvents(context.Background(), 1000, time.Minute)
|
||||
s.Require().NoError(err)
|
||||
|
||||
eventIDs := make([]string, 0, 2)
|
||||
for _, event := range events {
|
||||
if event.JobID != firstJob.ID && event.JobID != secondJob.ID {
|
||||
continue
|
||||
}
|
||||
published, err := s.store.MarkOutboxPublished(context.Background(), event.ID, event.LeaseToken)
|
||||
s.Require().NoError(err)
|
||||
s.True(published)
|
||||
eventIDs = append(eventIDs, event.ID)
|
||||
}
|
||||
s.Require().Len(eventIDs, 2)
|
||||
_, err = s.pool.Exec(
|
||||
context.Background(),
|
||||
`UPDATE outbox_events SET published_at = clock_timestamp() - INTERVAL '2 days' WHERE id IN ($1, $2)`,
|
||||
eventIDs[0], eventIDs[1],
|
||||
)
|
||||
s.Require().NoError(err)
|
||||
|
||||
deleted, err := s.store.DeletePublishedOutboxEvents(context.Background(), time.Now().Add(-24*time.Hour), 1)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(1, deleted)
|
||||
deleted, err = s.store.DeletePublishedOutboxEvents(context.Background(), time.Now().Add(-24*time.Hour), 1)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(1, deleted)
|
||||
|
||||
var remaining int
|
||||
err = s.pool.QueryRow(
|
||||
context.Background(), `SELECT count(*) FROM outbox_events WHERE id IN ($1, $2)`, eventIDs[0], eventIDs[1],
|
||||
).Scan(&remaining)
|
||||
s.Require().NoError(err)
|
||||
s.Zero(remaining)
|
||||
}
|
||||
|
||||
func (s *PostgresSuite) TestFailedAttachmentReplayIsAudited() {
|
||||
owner, chatID := createOwnerAndChat(s.T(), s.store)
|
||||
attachment, job := createQueuedAttachment(s.T(), s.store, owner.ID, chatID)
|
||||
lease, err := s.store.ClaimAttachmentJob(
|
||||
context.Background(), job.ID, attachment.ID, job.PipelineVersion, job.Attempt, "worker-1", time.Minute,
|
||||
)
|
||||
s.Require().NoError(err)
|
||||
result, err := s.store.FailAttachmentJob(context.Background(), lease, "invalid_image")
|
||||
s.Require().NoError(err)
|
||||
s.Equal(model.JobMutationApplied, result)
|
||||
|
||||
_, _, err = s.store.CreateMessage(
|
||||
context.Background(), chatID, owner.ID, "failed attachment",
|
||||
[]string{attachment.ID}, uuid.NewString(), 24*time.Hour,
|
||||
)
|
||||
s.ErrorIs(err, postgres.ErrConflict)
|
||||
metadata, err := s.store.AttachmentForUser(context.Background(), attachment.ID, owner.ID)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(model.AttachmentFailed, metadata.Status)
|
||||
s.Require().NotNil(metadata.ErrorCode)
|
||||
s.Equal("invalid_image", *metadata.ErrorCode)
|
||||
|
||||
replayed, err := s.store.ReplayFailedAttachment(
|
||||
context.Background(), attachment.ID, "operator@example", "input repaired",
|
||||
)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(2, replayed.Attempt)
|
||||
s.Equal(model.AttachmentJobQueued, replayed.Status)
|
||||
|
||||
var auditCount int
|
||||
err = s.pool.QueryRow(
|
||||
context.Background(), `SELECT count(*) FROM attachment_replay_audit WHERE job_id = $1`, job.ID,
|
||||
).Scan(&auditCount)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(1, auditCount)
|
||||
}
|
||||
|
||||
func (s *PostgresSuite) TestExpiredLeaseRecoveryFencesOldWorker() {
|
||||
owner, chatID := createOwnerAndChat(s.T(), s.store)
|
||||
attachment, job := createQueuedAttachment(s.T(), s.store, owner.ID, chatID)
|
||||
lease, err := s.store.ClaimAttachmentJob(
|
||||
context.Background(), job.ID, attachment.ID, job.PipelineVersion, job.Attempt, "worker-1", time.Minute,
|
||||
)
|
||||
s.Require().NoError(err)
|
||||
_, err = s.pool.Exec(
|
||||
context.Background(),
|
||||
`UPDATE attachment_jobs SET lease_until = clock_timestamp() - INTERVAL '1 second' WHERE id = $1`,
|
||||
job.ID,
|
||||
)
|
||||
s.Require().NoError(err)
|
||||
|
||||
recovered, err := s.store.RecoverExpiredAttachmentJobs(context.Background(), 10, 5, time.Now())
|
||||
s.Require().NoError(err)
|
||||
s.Equal(1, recovered.Requeued)
|
||||
s.Zero(recovered.Failed)
|
||||
current, err := s.store.AttachmentJob(context.Background(), job.ID)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(2, current.Attempt)
|
||||
s.Equal(model.AttachmentJobQueued, current.Status)
|
||||
|
||||
result, err := s.store.CompleteAttachmentJob(context.Background(), lease, completedVariants(attachment.ID, 1))
|
||||
s.Require().NoError(err)
|
||||
s.Equal(model.JobMutationStale, result)
|
||||
}
|
||||
|
||||
func (s *PostgresSuite) TestCompleteAttachmentJobRejectsIncompleteOrMismatchedVariants() {
|
||||
owner, chatID := createOwnerAndChat(s.T(), s.store)
|
||||
attachment, job := createQueuedAttachment(s.T(), s.store, owner.ID, chatID)
|
||||
lease, err := s.store.ClaimAttachmentJob(
|
||||
context.Background(), job.ID, attachment.ID, job.PipelineVersion, job.Attempt, "worker-1", time.Minute,
|
||||
)
|
||||
s.Require().NoError(err)
|
||||
|
||||
complete := completedVariants(attachment.ID, job.PipelineVersion)
|
||||
_, err = s.store.CompleteAttachmentJob(context.Background(), lease, complete[:3])
|
||||
s.ErrorIs(err, model.ErrInvalidInput)
|
||||
|
||||
duplicate := append([]model.Variant(nil), complete...)
|
||||
duplicate[3].Name = duplicate[2].Name
|
||||
_, err = s.store.CompleteAttachmentJob(context.Background(), lease, duplicate)
|
||||
s.ErrorIs(err, model.ErrInvalidInput)
|
||||
|
||||
mismatched := append([]model.Variant(nil), complete...)
|
||||
mismatched[3].PipelineVersion++
|
||||
_, err = s.store.CompleteAttachmentJob(context.Background(), lease, mismatched)
|
||||
s.ErrorIs(err, model.ErrInvalidInput)
|
||||
}
|
||||
|
||||
func (s *PostgresSuite) TestAttachmentDeletionClaimChecksLifecycleUnderLock() {
|
||||
owner, chatID := createOwnerAndChat(s.T(), s.store)
|
||||
pending, err := s.store.CreatePendingAttachment(context.Background(), model.Attachment{
|
||||
ID: uuid.NewString(), ChatID: chatID, OwnerID: owner.ID, Filename: "pending.png",
|
||||
ContentType: "image/png", SizeBytes: 128, SHA256: strings.Repeat("c", 64),
|
||||
ObjectKey: "attachments/" + uuid.NewString() + "/original",
|
||||
})
|
||||
s.Require().NoError(err)
|
||||
|
||||
claimed, err := s.store.ClaimAttachmentForDeletion(context.Background(), pending, time.Now().Add(time.Hour))
|
||||
s.Require().NoError(err)
|
||||
s.True(claimed)
|
||||
deleted, err := s.store.DeleteAttachmentIfDeleting(context.Background(), pending.ID)
|
||||
s.Require().NoError(err)
|
||||
s.True(deleted)
|
||||
|
||||
pending, err = s.store.CreatePendingAttachment(context.Background(), model.Attachment{
|
||||
ID: uuid.NewString(), ChatID: chatID, OwnerID: owner.ID, Filename: "completed.png",
|
||||
ContentType: "image/png", SizeBytes: 128, SHA256: strings.Repeat("d", 64),
|
||||
ObjectKey: "attachments/" + uuid.NewString() + "/original",
|
||||
})
|
||||
s.Require().NoError(err)
|
||||
ready, err := s.store.MarkAttachmentReady(context.Background(), pending.ID, pending.ObjectKey)
|
||||
s.Require().NoError(err)
|
||||
|
||||
claimed, err = s.store.ClaimAttachmentForDeletion(context.Background(), pending, time.Now().Add(time.Hour))
|
||||
s.Require().NoError(err)
|
||||
s.False(claimed)
|
||||
visible, err := s.store.AttachmentForUser(context.Background(), ready.ID, owner.ID)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(model.AttachmentReady, visible.Status)
|
||||
}
|
||||
|
||||
func (s *PostgresSuite) TestReconciliationDryRunPreservesDeletingAttachment() {
|
||||
owner, chatID := createOwnerAndChat(s.T(), s.store)
|
||||
pending, err := s.store.CreatePendingAttachment(context.Background(), model.Attachment{
|
||||
ID: uuid.NewString(), ChatID: chatID, OwnerID: owner.ID, Filename: "deleting.png",
|
||||
ContentType: "image/png", SizeBytes: 128, SHA256: strings.Repeat("e", 64),
|
||||
ObjectKey: "attachments/" + uuid.NewString() + "/original",
|
||||
})
|
||||
s.Require().NoError(err)
|
||||
claimed, err := s.store.ClaimAttachmentForDeletion(context.Background(), pending, time.Now().Add(time.Hour))
|
||||
s.Require().NoError(err)
|
||||
s.True(claimed)
|
||||
|
||||
reconciler, err := reconcile.New(s.store, emptyObjectStore{}, reconcile.Config{
|
||||
Prefix: "attachments/", PageSize: 1000, GraceTime: time.Minute,
|
||||
UnreferencedRetention: time.Hour,
|
||||
})
|
||||
s.Require().NoError(err)
|
||||
report, err := reconciler.Run(context.Background())
|
||||
s.Require().NoError(err)
|
||||
s.Zero(report.DeletedUnreferencedRows)
|
||||
|
||||
var status string
|
||||
err = s.pool.QueryRow(context.Background(), "SELECT status FROM attachments WHERE id = $1", pending.ID).Scan(&status)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(model.AttachmentDeleting, status)
|
||||
}
|
||||
|
||||
type emptyObjectStore struct{}
|
||||
|
||||
func (emptyObjectStore) List(context.Context, string, string, int) ([]model.StoredObject, string, error) {
|
||||
return nil, "", nil
|
||||
}
|
||||
|
||||
func (emptyObjectStore) Delete(context.Context, string) error {
|
||||
return errors.New("unexpected object deletion")
|
||||
}
|
||||
|
||||
func (s *PostgresSuite) TestMessageRejectsAttachmentFromAnotherChat() {
|
||||
owner, firstChatID := createOwnerAndChat(s.T(), s.store)
|
||||
secondChat, err := s.store.CreateChat(context.Background(), "Second", []string{owner.ID}, owner.ID)
|
||||
s.Require().NoError(err)
|
||||
pending, err := s.store.CreatePendingAttachment(context.Background(), model.Attachment{
|
||||
ID: uuid.NewString(), ChatID: firstChatID, OwnerID: owner.ID, Filename: "photo.png",
|
||||
ContentType: "image/png", SizeBytes: 128, SHA256: strings.Repeat("b", 64),
|
||||
ObjectKey: "attachments/" + uuid.NewString() + "/original",
|
||||
})
|
||||
s.Require().NoError(err)
|
||||
attachment, err := s.store.MarkAttachmentReady(context.Background(), pending.ID, pending.ObjectKey)
|
||||
s.Require().NoError(err)
|
||||
_, _, err = s.store.CreateMessage(
|
||||
context.Background(), secondChat.ID, owner.ID, "wrong chat", []string{attachment.ID}, uuid.NewString(), 24*time.Hour,
|
||||
)
|
||||
s.ErrorIs(err, postgres.ErrNotFound)
|
||||
}
|
||||
|
||||
func (s *PostgresSuite) TestConcurrentMessageIdempotency() {
|
||||
t := s.T()
|
||||
pool := s.pool
|
||||
stores := []*postgres.Store{postgres.New(pool), postgres.New(pool)}
|
||||
owner, chatID := createOwnerAndChat(t, stores[0])
|
||||
key := uuid.NewString()
|
||||
|
||||
const workers = 8
|
||||
type result struct {
|
||||
message model.Message
|
||||
replay bool
|
||||
err error
|
||||
}
|
||||
results := make(chan result, workers)
|
||||
var group sync.WaitGroup
|
||||
for worker := range workers {
|
||||
group.Add(1)
|
||||
go func() {
|
||||
defer group.Done()
|
||||
message, replay, err := stores[worker%len(stores)].CreateMessage(
|
||||
context.Background(), chatID, owner.ID, "concurrent body", nil, key, 24*time.Hour,
|
||||
)
|
||||
results <- result{message: message, replay: replay, err: err}
|
||||
}()
|
||||
}
|
||||
group.Wait()
|
||||
close(results)
|
||||
|
||||
var messageID string
|
||||
var created int
|
||||
for result := range results {
|
||||
if result.err != nil {
|
||||
t.Fatalf("CreateMessage() error = %v", result.err)
|
||||
}
|
||||
if messageID == "" {
|
||||
messageID = result.message.ID
|
||||
}
|
||||
if result.message.ID != messageID {
|
||||
t.Fatalf("message ID = %s, want %s", result.message.ID, messageID)
|
||||
}
|
||||
if !result.replay {
|
||||
created++
|
||||
}
|
||||
}
|
||||
if created != 1 {
|
||||
t.Fatalf("new message results = %d, want 1", created)
|
||||
}
|
||||
if count := messageCount(t, pool, chatID); count != 1 {
|
||||
t.Fatalf("message count = %d, want 1", count)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *PostgresSuite) TestMessageIdempotencyScopeAndExpiry() {
|
||||
t := s.T()
|
||||
pool := s.pool
|
||||
store := s.store
|
||||
owner, chatID := createOwnerAndChat(t, store)
|
||||
second, err := store.CreateUser(context.Background(), uniqueUsername(), "Second", "password-hash")
|
||||
if err != nil {
|
||||
t.Fatalf("CreateUser() error = %v", err)
|
||||
}
|
||||
chat, err := store.CreateChat(context.Background(), "Shared", []string{owner.ID, second.ID}, owner.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("CreateChat() error = %v", err)
|
||||
}
|
||||
key := uuid.NewString()
|
||||
|
||||
if _, _, err := store.CreateMessage(context.Background(), chat.ID, owner.ID, "owner", nil, key, 24*time.Hour); err != nil {
|
||||
t.Fatalf("owner CreateMessage() error = %v", err)
|
||||
}
|
||||
if _, _, err := store.CreateMessage(context.Background(), chat.ID, second.ID, "second", nil, key, 24*time.Hour); err != nil {
|
||||
t.Fatalf("second user CreateMessage() error = %v", err)
|
||||
}
|
||||
if _, _, err := store.CreateMessage(context.Background(), chatID, owner.ID, "other chat", nil, key, 24*time.Hour); err != nil {
|
||||
t.Fatalf("other chat CreateMessage() error = %v", err)
|
||||
}
|
||||
if _, err := pool.Exec(context.Background(), `
|
||||
UPDATE message_idempotency
|
||||
SET created_at = clock_timestamp() - INTERVAL '2 days',
|
||||
expires_at = clock_timestamp() - INTERVAL '1 day'
|
||||
WHERE user_id = $1 AND chat_id = $2 AND key = $3`, owner.ID, chat.ID, key); err != nil {
|
||||
t.Fatalf("expire idempotency key: %v", err)
|
||||
}
|
||||
message, replay, err := store.CreateMessage(context.Background(), chat.ID, owner.ID, "after expiry", nil, key, 24*time.Hour)
|
||||
if err != nil || replay || message.Text != "after expiry" {
|
||||
t.Fatalf("expired CreateMessage() = (%v, %t, %v)", message, replay, err)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *PostgresSuite) TestExpiredIdempotencyRecordsAreCleanedOnNewMessages() {
|
||||
t := s.T()
|
||||
owner, chatID := createOwnerAndChat(t, s.store)
|
||||
expiredKey := uuid.NewString()
|
||||
if _, _, err := s.store.CreateMessage(context.Background(), chatID, owner.ID, "expired", nil, expiredKey, 24*time.Hour); err != nil {
|
||||
t.Fatalf("create expired message: %v", err)
|
||||
}
|
||||
if _, err := s.pool.Exec(context.Background(), `
|
||||
UPDATE message_idempotency
|
||||
SET created_at = clock_timestamp() - INTERVAL '2 days',
|
||||
expires_at = clock_timestamp() - INTERVAL '1 day'
|
||||
WHERE user_id = $1 AND chat_id = $2 AND key = $3`, owner.ID, chatID, expiredKey); err != nil {
|
||||
t.Fatalf("expire idempotency key: %v", err)
|
||||
}
|
||||
if _, _, err := s.store.CreateMessage(
|
||||
context.Background(), chatID, owner.ID, "new message", nil, uuid.NewString(), 24*time.Hour,
|
||||
); err != nil {
|
||||
t.Fatalf("create new message: %v", err)
|
||||
}
|
||||
|
||||
var remaining int
|
||||
if err := s.pool.QueryRow(context.Background(), `
|
||||
SELECT count(*)
|
||||
FROM message_idempotency
|
||||
WHERE user_id = $1 AND chat_id = $2 AND key = $3`, owner.ID, chatID, expiredKey).Scan(&remaining); err != nil {
|
||||
t.Fatalf("count expired idempotency records: %v", err)
|
||||
}
|
||||
if remaining != 0 {
|
||||
t.Fatalf("expired idempotency records = %d, want 0", remaining)
|
||||
}
|
||||
}
|
||||
|
||||
func createOwnerAndChat(t *testing.T, store *postgres.Store) (model.User, string) {
|
||||
t.Helper()
|
||||
owner, err := store.CreateUser(context.Background(), uniqueUsername(), "Owner", "password-hash")
|
||||
if err != nil {
|
||||
t.Fatalf("CreateUser() error = %v", err)
|
||||
}
|
||||
chat, err := store.CreateChat(context.Background(), "Chat", []string{owner.ID}, owner.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("CreateChat() error = %v", err)
|
||||
}
|
||||
return owner, chat.ID
|
||||
}
|
||||
|
||||
func createQueuedAttachment(
|
||||
t *testing.T,
|
||||
store *postgres.Store,
|
||||
ownerID string,
|
||||
chatID string,
|
||||
) (model.Attachment, model.AttachmentJob) {
|
||||
t.Helper()
|
||||
attachmentID := uuid.NewString()
|
||||
stagingKey := "staging/" + attachmentID + "/original"
|
||||
pending, err := store.CreatePendingAttachment(context.Background(), model.Attachment{
|
||||
ID: attachmentID, ChatID: chatID, OwnerID: ownerID, Filename: "photo.png",
|
||||
ContentType: "image/png", SizeBytes: 128, SHA256: strings.Repeat("a", 64),
|
||||
ObjectKey: stagingKey,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("CreatePendingAttachment() error = %v", err)
|
||||
}
|
||||
job := model.AttachmentJob{
|
||||
ID: uuid.NewString(), AttachmentID: attachmentID, PipelineVersion: 1, Attempt: 1,
|
||||
}
|
||||
queued, err := store.QueueAttachmentWithJobAndOutbox(
|
||||
context.Background(), pending.ID, stagingKey, job, "", "",
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("QueueAttachmentWithJobAndOutbox() error = %v", err)
|
||||
}
|
||||
return queued, job
|
||||
}
|
||||
|
||||
func completedVariants(attachmentID string, pipelineVersion int) []model.Variant {
|
||||
types := []struct {
|
||||
name string
|
||||
contentType string
|
||||
extension string
|
||||
}{
|
||||
{name: "original", contentType: "image/png", extension: "png"},
|
||||
{name: "thumbnail", contentType: "image/jpeg", extension: "jpg"},
|
||||
{name: "crop", contentType: "image/jpeg", extension: "jpg"},
|
||||
{name: "optimized", contentType: "image/webp", extension: "webp"},
|
||||
}
|
||||
variants := make([]model.Variant, 0, len(types))
|
||||
for index, variant := range types {
|
||||
variants = append(variants, model.Variant{
|
||||
Name: variant.name, ContentType: variant.contentType, SizeBytes: int64(128 - index*16),
|
||||
SHA256: strings.Repeat(string(rune('a'+index)), 64), Width: 320 - index*32, Height: 200 - index*20,
|
||||
ObjectKey: fmt.Sprintf("attachments/%s/v%d/%s.%s", attachmentID, pipelineVersion, variant.name, variant.extension),
|
||||
PipelineVersion: pipelineVersion,
|
||||
})
|
||||
}
|
||||
return variants
|
||||
}
|
||||
|
||||
func messageCount(t *testing.T, pool *pgxpool.Pool, chatID string) int {
|
||||
t.Helper()
|
||||
var count int
|
||||
if err := pool.QueryRow(context.Background(), "SELECT count(*) FROM messages WHERE chat_id = $1", chatID).Scan(&count); err != nil {
|
||||
t.Fatalf("count messages: %v", err)
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
func openTestDatabase(t *testing.T) *pgxpool.Pool {
|
||||
t.Helper()
|
||||
url := testSecret(t, "TEST_DATABASE_URL", "TEST_DATABASE_URL_FILE")
|
||||
pool, err := database.Open(context.Background(), database.Config{
|
||||
URL: url, MinConnections: 0, MaxConnections: 10,
|
||||
MaxConnectionAge: time.Minute, MaxConnectionIdle: time.Minute,
|
||||
HealthCheckPeriod: time.Minute, ConnectTimeout: 5 * time.Second,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("database.Open() error = %v", err)
|
||||
}
|
||||
if err := database.Migrate(context.Background(), pool, 30*time.Second); err != nil {
|
||||
pool.Close()
|
||||
t.Fatalf("database.Migrate() error = %v", err)
|
||||
}
|
||||
return pool
|
||||
}
|
||||
|
||||
func testSecret(t *testing.T, valueName, fileName string) string {
|
||||
t.Helper()
|
||||
if value := strings.TrimSpace(os.Getenv(valueName)); value != "" {
|
||||
return value
|
||||
}
|
||||
path := strings.TrimSpace(os.Getenv(fileName))
|
||||
if path == "" {
|
||||
t.Skipf("set %s or %s to run integration tests", valueName, fileName)
|
||||
}
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatalf("read %s: %v", fileName, err)
|
||||
}
|
||||
return strings.TrimSpace(string(data))
|
||||
}
|
||||
|
||||
func uniqueUsername() string {
|
||||
return "u_" + strings.ReplaceAll(uuid.NewString(), "-", "")[:20]
|
||||
}
|
||||
|
||||
func chatCount(t *testing.T, pool *pgxpool.Pool) int {
|
||||
t.Helper()
|
||||
var count int
|
||||
if err := pool.QueryRow(context.Background(), "SELECT count(*) FROM chats").Scan(&count); err != nil {
|
||||
t.Fatalf("count chats: %v", err)
|
||||
}
|
||||
return count
|
||||
}
|
||||
Reference in New Issue
Block a user