package postgres import ( "context" "errors" "fmt" "time" "github.com/google/uuid" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" "lincodex/backend/internal/adapter/secondary/postgres/sqlc" "lincodex/backend/internal/domain" "lincodex/backend/internal/port/outbound" ) // deliveryConstraintErrors maps the delivery constraints and triggers whose // violation is a caller-visible outcome to port sentinels, by SQLSTATE and // constraint name, never by text. var deliveryConstraintErrors = map[constraintViolation]error{ {foreignKeyViolationCode, "deliveries_recipient_user_id_fkey"}: outbound.ErrUserNotFound, {foreignKeyViolationCode, "delivery_attempts_delivery_id_fkey"}: outbound.ErrDeliveryNotFound, {integrityConstraintViolationCode, "deliveries_content_immutable"}: outbound.ErrDeliveryContentImmutable, {integrityConstraintViolationCode, "delivery_attempts_immutable"}: outbound.ErrDeliveryContentImmutable, {integrityConstraintViolationCode, "deliveries_provider_pinned"}: outbound.ErrDeliveryProviderPinned, {foreignKeyViolationCode, "mail_requests_recipient_user_id_fkey"}: outbound.ErrUserNotFound, // A backstop: the version check already stops a second writer of the // same attempt number. {uniqueViolationCode, "delivery_attempts_pkey"}: outbound.ErrDeliveryVersionConflict, } // mapDeliveryError turns a known delivery or mail request constraint // violation into its sentinel and replaces any other PostgreSQL error with // its SQLSTATE and constraint name, because the message and detail can quote // the recipient address, request text, or a body that holds a token. Deadlocks and serialization failures // also match ErrTransactionConflict. func mapDeliveryError(err error) error { var pgError *pgconn.PgError if !errors.As(err, &pgError) { return sanitizeConnectError(err) } if sentinel, ok := deliveryConstraintErrors[constraintViolation{code: pgError.Code, constraint: pgError.ConstraintName}]; ok { return fmt.Errorf("postgres.mapDeliveryError - violate constraint %s: %w", pgError.ConstraintName, sentinel) } return markTransactionConflict(&databaseError{code: pgError.Code, constraint: pgError.ConstraintName}) } // DeliveryStore provides the delivery repository outside a transaction. Every // call runs as its own statement on a pool connection; RecordAttempt is one // statement, so it stays atomic. Called with a context that belongs to a // Transactor callback, it fails with outbound.ErrNestedTransaction; use // UnitOfWork.Deliveries there. type DeliveryStore struct { queries *sqlc.Queries } func NewDeliveryStore(pool *pgxpool.Pool) *DeliveryStore { return &DeliveryStore{queries: sqlc.New(standaloneDB{pool: pool})} } func (store *DeliveryStore) Deliveries() outbound.DeliveryRepository { return deliveryRepository{queries: store.queries} } func (unit *UnitOfWork) Deliveries() outbound.DeliveryRepository { return deliveryRepository{queries: unit.queries} } // MailRequests is available only inside a transaction: a request is written // with the outbox event that announces it and consumed under a row lock. func (unit *UnitOfWork) MailRequests() outbound.MailRequestRepository { return mailRequestRepository{queries: unit.queries} } type deliveryRepository struct { queries *sqlc.Queries } var _ outbound.DeliveryRepository = deliveryRepository{} func (repository deliveryRepository) Create(ctx context.Context, delivery domain.Delivery) (bool, error) { if delivery.IsZero() || delivery.Content().IsZero() { return false, fmt.Errorf("deliveryRepository.Create - delivery was not built by domain.NewDelivery: %w", domain.ErrInvalidDelivery) } content := delivery.Content() hash := content.Hash() inserted, err := repository.queries.InsertDelivery(ctx, sqlc.InsertDeliveryParams{ ID: pgUUID(delivery.ID()), SourceEventID: pgOptionalUUID(delivery.SourceEventID()), RecipientUserID: pgUUID(delivery.RecipientUserID()), RecipientEmail: delivery.Recipient().Address(), Kind: string(content.Kind()), TemplateVersion: content.TemplateVersion(), Subject: content.Subject(), TextBody: content.Text(), HtmlBody: content.HTML(), ContentSha256: hash[:], Provider: delivery.ProviderAccount().Provider(), ProviderAccount: delivery.ProviderAccount().Account(), IdempotencyKey: delivery.IdempotencyKey(), Status: string(delivery.Status()), AttemptCount: delivery.AttemptCount(), NextAttemptAt: pgZeroableTime(delivery.NextAttemptAt()), LastAttemptAt: pgZeroableTime(delivery.LastAttemptAt()), ProviderMessageID: pgOptionalText(delivery.ProviderMessageID()), Version: delivery.Version(), CreatedAt: pgTime(delivery.CreatedAt()), UpdatedAt: pgTime(delivery.UpdatedAt()), }) if err != nil { return false, fmt.Errorf("deliveryRepository.Create - insert delivery: %w", mapDeliveryError(err)) } return inserted == 1, nil } func (repository deliveryRepository) Get(ctx context.Context, id uuid.UUID) (domain.Delivery, error) { row, err := repository.queries.GetDeliveryByID(ctx, pgUUID(id)) if errors.Is(err, pgx.ErrNoRows) { return domain.Delivery{}, fmt.Errorf("deliveryRepository.Get - select delivery: %w", outbound.ErrDeliveryNotFound) } if err != nil { return domain.Delivery{}, fmt.Errorf("deliveryRepository.Get - select delivery: %w", mapDeliveryError(err)) } return deliveryFromRow(row) } func (repository deliveryRepository) ListAttempts(ctx context.Context, id uuid.UUID) ([]domain.DeliveryAttempt, error) { rows, err := repository.queries.ListDeliveryAttempts(ctx, pgUUID(id)) if err != nil { return nil, fmt.Errorf("deliveryRepository.ListAttempts - select attempts: %w", mapDeliveryError(err)) } attempts := make([]domain.DeliveryAttempt, 0, len(rows)) for _, row := range rows { attempt, err := domain.RestoreDeliveryAttempt(domain.DeliveryAttempt{ DeliveryID: uuid.UUID(row.DeliveryID.Bytes), Number: row.AttemptNumber, At: row.AttemptedAt.Time, Outcome: domain.DeliveryAttemptOutcome(row.Outcome), Rejection: domain.DeliveryRejection(row.Rejection.String), ProviderCode: row.ProviderCode.String, ProviderMessageID: row.ProviderMessageID.String, RetryAfter: time.Duration(row.RetryAfterNs), StatusAfter: domain.DeliveryStatus(row.StatusAfter), NextAttemptAt: zeroableTime(row.NextAttemptAt), }) if err != nil { return nil, fmt.Errorf("deliveryRepository.ListAttempts - decode attempt %d: %w", row.AttemptNumber, err) } attempts = append(attempts, attempt) } return attempts, nil } func (repository deliveryRepository) LatestForRecipient(ctx context.Context, recipientUserID uuid.UUID, kind domain.MailKind) (outbound.DeliveryStatusSnapshot, error) { const location = "deliveryRepository.LatestForRecipient" row, err := repository.queries.GetLatestDeliveryStatus(ctx, sqlc.GetLatestDeliveryStatusParams{ RecipientUserID: pgUUID(recipientUserID), Kind: string(kind), }) if errors.Is(err, pgx.ErrNoRows) { return outbound.DeliveryStatusSnapshot{}, fmt.Errorf("%s - select delivery status: %w", location, outbound.ErrDeliveryNotFound) } if err != nil { return outbound.DeliveryStatusSnapshot{}, fmt.Errorf("%s - select delivery status: %w", location, mapDeliveryError(err)) } storedKind, err := domain.ParseMailKind(row.Kind) if err != nil { return outbound.DeliveryStatusSnapshot{}, fmt.Errorf("%s - decode kind: %w", location, err) } status, err := domain.ParseDeliveryStatus(row.Status) if err != nil { return outbound.DeliveryStatusSnapshot{}, fmt.Errorf("%s - decode status: %w", location, err) } return outbound.DeliveryStatusSnapshot{ DeliveryID: uuid.UUID(row.ID.Bytes), Kind: storedKind, Status: status, NextAttemptAt: zeroableTime(row.NextAttemptAt), CreatedAt: row.CreatedAt.Time, UpdatedAt: row.UpdatedAt.Time, }, nil } func (repository deliveryRepository) RecordAttempt(ctx context.Context, next domain.Delivery, attempt domain.DeliveryAttempt) error { const location = "deliveryRepository.RecordAttempt" if next.IsZero() || attempt.DeliveryID != next.ID() || attempt.Number != next.AttemptCount() || next.Version() <= 1 { return fmt.Errorf("%s - state and attempt were not built by domain.Delivery.RecordAttempt: %w", location, domain.ErrInvalidDelivery) } recorded, err := repository.queries.RecordDeliveryAttempt(ctx, sqlc.RecordDeliveryAttemptParams{ AttemptNumber: attempt.Number, AttemptedAt: pgTime(attempt.At), Outcome: string(attempt.Outcome), Rejection: pgOptionalText(string(attempt.Rejection)), ProviderCode: pgOptionalText(attempt.ProviderCode), ProviderMessageID: pgOptionalText(attempt.ProviderMessageID), RetryAfterNs: int64(attempt.RetryAfter), Status: string(next.Status()), NextAttemptAt: pgZeroableTime(next.NextAttemptAt()), UpdatedAt: pgTime(next.UpdatedAt()), DeliveryID: pgUUID(next.ID()), ExpectedVersion: next.Version() - 1, }) if err != nil { return fmt.Errorf("%s - update delivery and insert attempt: %w", location, mapDeliveryError(err)) } if recorded == 0 { return fmt.Errorf("%s - expected version %d: %w", location, next.Version()-1, outbound.ErrDeliveryVersionConflict) } return nil } func (repository deliveryRepository) WaitForQuota(ctx context.Context, next domain.Delivery) error { if next.Status() != domain.DeliveryStatusWaitingQuota { return fmt.Errorf("deliveryRepository.WaitForQuota - state was not built by domain.Delivery.WaitForQuota: %w", domain.ErrInvalidDelivery) } return repository.updateState(ctx, "deliveryRepository.WaitForQuota", next) } func (repository deliveryRepository) Rebind(ctx context.Context, next domain.Delivery) error { if next.AttemptCount() != 0 { return fmt.Errorf("deliveryRepository.Rebind - state was not built by domain.Delivery.Rebind: %w", domain.ErrInvalidDelivery) } return repository.updateState(ctx, "deliveryRepository.Rebind", next) } // updateState stores a state change without an attempt over the version // before it. func (repository deliveryRepository) updateState(ctx context.Context, location string, next domain.Delivery) error { if next.IsZero() || next.Version() <= 1 { return fmt.Errorf("%s - state was not built by a domain.Delivery transition: %w", location, domain.ErrInvalidDelivery) } updated, err := repository.queries.UpdateDeliveryState(ctx, sqlc.UpdateDeliveryStateParams{ Status: string(next.Status()), NextAttemptAt: pgZeroableTime(next.NextAttemptAt()), Provider: next.ProviderAccount().Provider(), ProviderAccount: next.ProviderAccount().Account(), UpdatedAt: pgTime(next.UpdatedAt()), ID: pgUUID(next.ID()), ExpectedVersion: next.Version() - 1, }) if err != nil { return fmt.Errorf("%s - update delivery: %w", location, mapDeliveryError(err)) } if updated == 0 { return fmt.Errorf("%s - expected version %d: %w", location, next.Version()-1, outbound.ErrDeliveryVersionConflict) } return nil } func deliveryFromRow(row sqlc.Delivery) (domain.Delivery, error) { kind, err := domain.ParseMailKind(row.Kind) if err != nil { return domain.Delivery{}, fmt.Errorf("postgres.deliveryFromRow - decode kind: %w", err) } content, err := domain.RestoreMailContent(kind, row.TemplateVersion, row.Subject, row.TextBody, row.HtmlBody, row.ContentSha256) if err != nil { return domain.Delivery{}, fmt.Errorf("postgres.deliveryFromRow - decode content: %w", err) } providerAccount, err := domain.NewMailProviderAccount(row.Provider, row.ProviderAccount) if err != nil { return domain.Delivery{}, fmt.Errorf("postgres.deliveryFromRow - decode provider account: %w", err) } delivery, err := domain.RestoreDelivery(domain.DeliverySnapshot{ ID: uuid.UUID(row.ID.Bytes), SourceEventID: optionalUUID(row.SourceEventID), RecipientUserID: uuid.UUID(row.RecipientUserID.Bytes), RecipientAddress: row.RecipientEmail, Content: content, ProviderAccount: providerAccount, IdempotencyKey: row.IdempotencyKey, Status: domain.DeliveryStatus(row.Status), AttemptCount: row.AttemptCount, NextAttemptAt: zeroableTime(row.NextAttemptAt), LastAttemptAt: zeroableTime(row.LastAttemptAt), ProviderMessageID: row.ProviderMessageID.String, Version: row.Version, CreatedAt: row.CreatedAt.Time, UpdatedAt: row.UpdatedAt.Time, }) if err != nil { return domain.Delivery{}, fmt.Errorf("postgres.deliveryFromRow - decode delivery: %w", err) } return delivery, nil } // pgZeroableTime stores the zero time, which the domain uses for "not set", // as NULL. func pgZeroableTime(value time.Time) pgtype.Timestamptz { if value.IsZero() { return pgtype.Timestamptz{} } return pgTime(value) } func zeroableTime(value pgtype.Timestamptz) time.Time { if !value.Valid { return time.Time{} } return value.Time } func pgOptionalText(value string) pgtype.Text { return pgtype.Text{String: value, Valid: value != ""} } func pgOptionalUUID(id uuid.UUID) pgtype.UUID { return pgtype.UUID{Bytes: id, Valid: id != uuid.Nil} } func optionalUUID(value pgtype.UUID) uuid.UUID { if !value.Valid { return uuid.Nil } return uuid.UUID(value.Bytes) } type mailRequestRepository struct { queries *sqlc.Queries } var _ outbound.MailRequestRepository = mailRequestRepository{} func (repository mailRequestRepository) Create(ctx context.Context, request domain.MailRequest) error { if _, err := domain.NewMailRequest(request); err != nil { return fmt.Errorf("mailRequestRepository.Create - validate request: %w", err) } err := repository.queries.InsertMailRequest(ctx, sqlc.InsertMailRequestParams{ ID: pgUUID(request.ID), RecipientUserID: pgUUID(request.RecipientUserID), Kind: string(request.Kind), Subject: request.Notification.Subject, Body: request.Notification.Body, LinkPath: request.Notification.LinkPath, CreatedAt: pgTime(request.CreatedAt), }) if err != nil { return fmt.Errorf("mailRequestRepository.Create - insert mail request: %w", mapDeliveryError(err)) } return nil } func (repository mailRequestRepository) Lock(ctx context.Context, id uuid.UUID) (domain.MailRequest, error) { row, err := repository.queries.LockMailRequest(ctx, pgUUID(id)) if errors.Is(err, pgx.ErrNoRows) { return domain.MailRequest{}, fmt.Errorf("mailRequestRepository.Lock - select mail request: %w", outbound.ErrMailRequestNotFound) } if err != nil { return domain.MailRequest{}, fmt.Errorf("mailRequestRepository.Lock - select mail request: %w", mapDeliveryError(err)) } kind, err := domain.ParseMailKind(row.Kind) if err != nil { return domain.MailRequest{}, fmt.Errorf("mailRequestRepository.Lock - decode kind: %w", err) } request, err := domain.NewMailRequest(domain.MailRequest{ ID: uuid.UUID(row.ID.Bytes), RecipientUserID: uuid.UUID(row.RecipientUserID.Bytes), Kind: kind, Notification: domain.NotificationText{Subject: row.Subject, Body: row.Body, LinkPath: row.LinkPath}, CreatedAt: row.CreatedAt.Time, }) if err != nil { return domain.MailRequest{}, fmt.Errorf("mailRequestRepository.Lock - decode mail request: %w", err) } return request, nil } func (repository mailRequestRepository) Delete(ctx context.Context, id uuid.UUID) error { if _, err := repository.queries.DeleteMailRequest(ctx, pgUUID(id)); err != nil { return fmt.Errorf("mailRequestRepository.Delete - delete mail request: %w", mapDeliveryError(err)) } return nil }