package postgres import ( "context" "errors" "fmt" "strings" "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, "deliveries_email_token_id_fkey"}: outbound.ErrEmailTokenNotFound, {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 markRowFault(markTransactionConflict(&databaseError{code: pgError.Code, constraint: pgError.ConstraintName})) } // markRowFault makes an error that the row itself causes (SQLSTATE class 22, // data exception, or 23, integrity constraint violation) also match // outbound.ErrRowFault. Anything else stays transient to the caller. func markRowFault(err error) error { var stateError sqlStateError if !errors.As(err, &stateError) { return err } if code := stateError.SQLState(); strings.HasPrefix(code, "22") || strings.HasPrefix(code, "23") { return fmt.Errorf("postgres.markRowFault - SQLSTATE %s: %w: %w", code, outbound.ErrRowFault, err) } return err } // 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()), EmailTokenID: pgOptionalUUID(delivery.EmailTokenID()), 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(sqlc.Delivery{ ID: row.ID, SourceEventID: row.SourceEventID, RecipientUserID: row.RecipientUserID, RecipientEmail: row.RecipientEmail, Kind: row.Kind, TemplateVersion: row.TemplateVersion, Subject: row.Subject, TextBody: row.TextBody, HtmlBody: row.HtmlBody, ContentSha256: row.ContentSha256, Provider: row.Provider, ProviderAccount: row.ProviderAccount, IdempotencyKey: row.IdempotencyKey, Status: row.Status, AttemptCount: row.AttemptCount, NextAttemptAt: row.NextAttemptAt, LastAttemptAt: row.LastAttemptAt, ProviderMessageID: row.ProviderMessageID, Version: row.Version, CreatedAt: row.CreatedAt, UpdatedAt: row.UpdatedAt, EmailTokenID: row.EmailTokenID, CancelReason: row.CancelReason, ClaimOwner: row.ClaimOwner, ClaimedUntil: row.ClaimedUntil, FirstSendStartedAt: row.FirstSendStartedAt, FailureCount: row.FailureCount, BodyRedactedAt: row.BodyRedactedAt, }) } func (repository deliveryRepository) GetRetrySnapshot(ctx context.Context, id uuid.UUID) (outbound.DeliveryRetrySnapshot, error) { const location = "deliveryRepository.GetRetrySnapshot" row, err := repository.queries.GetDeliveryRetrySnapshot(ctx, pgUUID(id)) if errors.Is(err, pgx.ErrNoRows) { return outbound.DeliveryRetrySnapshot{}, fmt.Errorf("%s - select delivery: %w", location, outbound.ErrDeliveryNotFound) } if err != nil { return outbound.DeliveryRetrySnapshot{}, fmt.Errorf("%s - select delivery: %w", location, mapDeliveryError(err)) } if _, err := domain.NewMailProviderAccount(row.Provider, row.ProviderAccount); err != nil { return outbound.DeliveryRetrySnapshot{}, fmt.Errorf("%s - decode provider account: %w", location, err) } status, err := domain.ParseDeliveryStatus(row.Status) if err != nil { return outbound.DeliveryRetrySnapshot{}, fmt.Errorf("%s - decode status: %w", location, err) } return outbound.DeliveryRetrySnapshot{ ID: uuid.UUID(row.ID.Bytes), Provider: row.Provider, ProviderAccount: row.ProviderAccount, Status: status, AttemptCount: row.AttemptCount, NextAttemptAt: zeroableTime(row.NextAttemptAt), FirstSendStartedAt: zeroableTime(row.FirstSendStartedAt), ManualRetryStartedAt: zeroableTime(row.ManualRetryStartedAt), }, nil } func (repository deliveryRepository) AuthorizeUnknownRetry( ctx context.Context, id uuid.UUID, account domain.MailProviderAccount, actor domain.MailRetryActor, acknowledgeDuplicateRisk bool, at time.Time, minimumAge time.Duration, ) error { const location = "deliveryRepository.AuthorizeUnknownRetry" if id == uuid.Nil || account.IsZero() || actor == "" || !acknowledgeDuplicateRisk || at.IsZero() || minimumAge < 0 { return fmt.Errorf("%s - invalid authorization request: %w", location, outbound.ErrDeliveryRetryNotAllowed) } updated, err := repository.queries.AuthorizeUnknownDeliveryRetry(ctx, sqlc.AuthorizeUnknownDeliveryRetryParams{ Actor: string(actor), DuplicateRiskAcknowledged: acknowledgeDuplicateRisk, DeliveryID: pgUUID(id), Provider: account.Provider(), ProviderAccount: account.Account(), MinimumAgeSeconds: minimumAge.Seconds(), Now: pgTime(at), }) if err != nil { return fmt.Errorf("%s - authorize retry: %w", location, mapDeliveryError(err)) } if updated == 0 { return fmt.Errorf("%s - current delivery state is not eligible: %w", location, outbound.ErrDeliveryRetryNotAllowed) } return nil } 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 { return repository.recordAttempt(ctx, "deliveryRepository.RecordAttempt", uuid.Nil, next, attempt) } func (repository deliveryRepository) RecordClaimedAttempt(ctx context.Context, owner uuid.UUID, next domain.Delivery, attempt domain.DeliveryAttempt) error { if owner == uuid.Nil { return fmt.Errorf("deliveryRepository.RecordClaimedAttempt - lease owner must be set: %w", domain.ErrInvalidDelivery) } return repository.recordAttempt(ctx, "deliveryRepository.RecordClaimedAttempt", owner, next, attempt) } // recordAttempt stores an attempt over the version before it; a non-nil owner // also has to hold the lease. func (repository deliveryRepository) recordAttempt(ctx context.Context, location string, owner uuid.UUID, next domain.Delivery, attempt domain.DeliveryAttempt) error { 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, LeaseOwner: pgOptionalUUID(owner), }) 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, true) } 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) } // The sending worker rebinds a delivery it holds and then sends it, so // its lease stays. return repository.updateState(ctx, "deliveryRepository.Rebind", next, false) } func (repository deliveryRepository) Cancel(ctx context.Context, next domain.Delivery) error { if next.Status() != domain.DeliveryStatusCancelled { return fmt.Errorf("deliveryRepository.Cancel - state was not built by domain.Delivery.Cancel: %w", domain.ErrInvalidDelivery) } return repository.updateState(ctx, "deliveryRepository.Cancel", next, true) } func (repository deliveryRepository) StopUnknownRetry(ctx context.Context, owner uuid.UUID, next domain.Delivery) error { const location = "deliveryRepository.StopUnknownRetry" if next.IsZero() || next.Status() != domain.DeliveryStatusUnknown || !next.NextAttemptAt().IsZero() || owner == uuid.Nil || next.Version() <= 1 { return fmt.Errorf("%s - state was not built by domain.Delivery.StopAutomaticRetry: %w", location, domain.ErrInvalidDelivery) } updated, err := repository.queries.StopUnknownDeliveryRetry(ctx, sqlc.StopUnknownDeliveryRetryParams{ Now: pgTime(next.UpdatedAt()), ID: pgUUID(next.ID()), LeaseOwner: pgUUID(owner), }) if err != nil { return fmt.Errorf("%s - stop retry: %w", location, mapDeliveryError(err)) } if updated == 0 { return fmt.Errorf("%s - expected version %d: %w", location, next.Version()-1, outbound.ErrDeliveryVersionConflict) } return nil } func (repository deliveryRepository) ScheduleUnknownRetry(ctx context.Context, owner uuid.UUID, next domain.Delivery) error { const location = "deliveryRepository.ScheduleUnknownRetry" if owner == uuid.Nil || next.IsZero() || next.Status() != domain.DeliveryStatusUnknown || next.NextAttemptAt().IsZero() || next.Version() <= 1 { return fmt.Errorf("%s - state was not built by domain.Delivery.ScheduleUnknownRetry: %w", location, domain.ErrInvalidDelivery) } return repository.updateState(ctx, location, next, true) } // updateState stores a state change without an attempt over the version // before it. releaseClaim ends the sending worker's lease with the change. func (repository deliveryRepository) updateState(ctx context.Context, location string, next domain.Delivery, releaseClaim bool) 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()), CancelReason: pgOptionalText(string(next.CancelReason())), Provider: next.ProviderAccount().Provider(), ProviderAccount: next.ProviderAccount().Account(), ReleaseClaim: releaseClaim, 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 (repository deliveryRepository) ClaimDue(ctx context.Context, claim outbound.DeliveryClaim) (outbound.ClaimedDelivery, error) { const location = "deliveryRepository.ClaimDue" if claim.Owner == uuid.Nil || claim.Account.IsZero() || len(claim.Kinds) == 0 || claim.Now.IsZero() || claim.Lease <= 0 { return outbound.ClaimedDelivery{}, fmt.Errorf("%s - owner, account, kinds, time, and lease must be set: %w", location, domain.ErrInvalidDelivery) } kinds := make([]string, 0, len(claim.Kinds)) for _, kind := range claim.Kinds { if _, err := domain.ParseMailKind(string(kind)); err != nil { return outbound.ClaimedDelivery{}, fmt.Errorf("%s - kind: %w", location, err) } kinds = append(kinds, string(kind)) } row, err := repository.queries.ClaimDueDelivery(ctx, sqlc.ClaimDueDeliveryParams{ LeaseOwner: pgUUID(claim.Owner), LeaseSeconds: claim.Lease.Seconds(), Kinds: kinds, Now: pgTime(claim.Now), Provider: claim.Account.Provider(), ProviderAccount: claim.Account.Account(), RebindProvider: claim.RebindProvider, }) if errors.Is(err, pgx.ErrNoRows) { return outbound.ClaimedDelivery{}, outbound.ErrNoDeliveryDue } if err != nil { return outbound.ClaimedDelivery{}, fmt.Errorf("%s - claim due delivery: %w", location, mapDeliveryError(err)) } delivery, err := deliveryFromRow(sqlc.Delivery{ ID: row.ID, SourceEventID: row.SourceEventID, RecipientUserID: row.RecipientUserID, RecipientEmail: row.RecipientEmail, Kind: row.Kind, TemplateVersion: row.TemplateVersion, Subject: row.Subject, TextBody: row.TextBody, HtmlBody: row.HtmlBody, ContentSha256: row.ContentSha256, Provider: row.Provider, ProviderAccount: row.ProviderAccount, IdempotencyKey: row.IdempotencyKey, Status: row.Status, AttemptCount: row.AttemptCount, NextAttemptAt: row.NextAttemptAt, LastAttemptAt: row.LastAttemptAt, ProviderMessageID: row.ProviderMessageID, EmailTokenID: row.EmailTokenID, CancelReason: row.CancelReason, BodyRedactedAt: row.BodyRedactedAt, Version: row.Version, CreatedAt: row.CreatedAt, UpdatedAt: row.UpdatedAt, }) if err != nil { unreadable := &outbound.UnreadableDeliveryError{DeliveryID: uuid.UUID(row.ID.Bytes), FailureCount: row.FailureCount, Err: err} // Only a content hash mismatch is permanent: the row was changed // outside the application. It is cancelled here, in the caller's // transaction, so it does not stay at the head of the queue. Any // other cause may be transient, so the row is left alone and the // caller records a failure of the row. if errors.Is(err, domain.ErrMailContentIntegrity) { if _, cancelErr := repository.queries.CancelUnreadableDelivery(ctx, sqlc.CancelUnreadableDeliveryParams{ Now: pgTime(claim.Now), ID: row.ID, }); cancelErr != nil { return outbound.ClaimedDelivery{}, fmt.Errorf("%s - cancel unreadable delivery: %w", location, mapDeliveryError(cancelErr)) } unreadable.Cancelled = true } return outbound.ClaimedDelivery{}, fmt.Errorf("%s - decode claimed delivery: %w", location, unreadable) } claimed := outbound.ClaimedDelivery{ Delivery: delivery, PreviousClaimedUntil: zeroableTime(row.PreviousClaimedUntil), ManualRetryPending: row.ManualRetryPending.Bool, ManualRetryCycleStarted: row.ManualRetryCycleStarted, SendStartUnsettled: row.SendStartUnsettled, HasUncertainAttempt: row.HasUncertainAttempt, FailureCount: row.FailureCount, } if row.SinceFirstSendSeconds >= 0 { claimed.FirstSendStarted = true claimed.SinceFirstSend = time.Duration(row.SinceFirstSendSeconds * float64(time.Second)) } return claimed, nil } func (repository deliveryRepository) LockClaimed(ctx context.Context, id, owner uuid.UUID) (bool, error) { _, err := repository.queries.LockClaimedDelivery(ctx, sqlc.LockClaimedDeliveryParams{ID: pgUUID(id), LeaseOwner: pgUUID(owner)}) if errors.Is(err, pgx.ErrNoRows) { return false, nil } if err != nil { return false, fmt.Errorf("deliveryRepository.LockClaimed - lock delivery: %w", mapDeliveryError(err)) } return true, nil } func (repository deliveryRepository) MarkSendStarted(ctx context.Context, id, owner uuid.UUID, requireDedupWindow bool, safeWindow time.Duration) (bool, error) { started, err := repository.queries.MarkDeliverySendStarted(ctx, sqlc.MarkDeliverySendStartedParams{ ID: pgUUID(id), LeaseOwner: pgUUID(owner), RequireDedupWindow: requireDedupWindow, RetryWindowSeconds: safeWindow.Seconds(), }) if err != nil { return false, fmt.Errorf("deliveryRepository.MarkSendStarted - mark send started: %w", mapDeliveryError(err)) } return started == 1, nil } func (repository deliveryRepository) RecordFailure(ctx context.Context, id, owner uuid.UUID, at, nextAttemptAt time.Time, maxFailures int32, countFailure bool) (bool, error) { status, err := repository.queries.RecordDeliveryFailure(ctx, sqlc.RecordDeliveryFailureParams{ CountFailure: countFailure, LeaseOwner: pgUUID(owner), MaxFailures: maxFailures, NextAttemptAt: pgTime(nextAttemptAt), Now: pgTime(at), ID: pgUUID(id), }) if errors.Is(err, pgx.ErrNoRows) { return false, nil } if err != nil { return false, fmt.Errorf("deliveryRepository.RecordFailure - record failure: %w", mapDeliveryError(err)) } return status == string(domain.DeliveryStatusCancelled), nil } func (repository deliveryRepository) ReleaseClaim(ctx context.Context, id, owner uuid.UUID) (bool, error) { released, err := repository.queries.ReleaseDeliveryClaim(ctx, sqlc.ReleaseDeliveryClaimParams{ ID: pgUUID(id), LeaseOwner: pgUUID(owner), }) if err != nil { return false, fmt.Errorf("deliveryRepository.ReleaseClaim - release lease: %w", mapDeliveryError(err)) } return released == 1, nil } func (repository deliveryRepository) ServiceMailState(ctx context.Context, id uuid.UUID) (domain.ServiceMailState, error) { const location = "deliveryRepository.ServiceMailState" row, err := repository.queries.GetServiceMailState(ctx, pgUUID(id)) if errors.Is(err, pgx.ErrNoRows) { return domain.ServiceMailState{}, fmt.Errorf("%s - select state: %w", location, outbound.ErrDeliveryNotFound) } if err != nil { return domain.ServiceMailState{}, fmt.Errorf("%s - select state: %w", location, mapDeliveryError(err)) } return domain.ServiceMailState{ TokenFound: row.TokenFound, TokenPurpose: domain.EmailTokenPurpose(row.TokenPurpose.String), TokenUserID: optionalUUID(row.TokenUserID), TokenRegistrationVersion: row.TokenRegistrationVersion.Int64, TokenConsumedAt: zeroableTime(row.TokenConsumedAt), TokenInvalidatedAt: zeroableTime(row.TokenInvalidatedAt), TokenExpiresAt: zeroableTime(row.TokenExpiresAt), AccountRegistrationVersion: row.AccountRegistrationVersion, AccountEmailVerified: row.AccountEmailVerified, AccountEmailKey: row.AccountEmailKey, }, 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) } var content domain.MailContent if row.BodyRedactedAt.Valid { content, err = domain.RestoreRedactedMailContent(kind, row.TemplateVersion, row.Subject, row.ContentSha256) } else { 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, EmailTokenID: optionalUUID(row.EmailTokenID), CancelReason: domain.DeliveryCancelReason(row.CancelReason.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 }