607 lines
26 KiB
Go
607 lines
26 KiB
Go
//go:build integration
|
|
|
|
package integration_test
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"log/slog"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"slices"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgconn"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
|
|
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
|
|
"lincodex/backend/internal/adapter/secondary/prometheus"
|
|
"lincodex/backend/internal/domain"
|
|
"lincodex/backend/internal/port/outbound"
|
|
"lincodex/backend/internal/usecase/notification"
|
|
"lincodex/backend/internal/usecase/notification/mailtemplate"
|
|
"lincodex/backend/internal/worker/eventconsumer"
|
|
)
|
|
|
|
const (
|
|
deliveryTestTimeout = 5 * time.Minute
|
|
// The private markers are searched for in logs and events; they must
|
|
// appear only in the mail request and delivery rows.
|
|
deliveryRecipientAddress = "Delivery.Recipient@Example.com"
|
|
deliverySubject = "PRIVATE-SUBJECT about an invitation"
|
|
deliveryBody = "PRIVATE-BODY: a company invited you to an interview."
|
|
deliveryLinkPath = "/candidate/invitations"
|
|
deliveryProvider = "resend"
|
|
deliveryAccount = "integration"
|
|
deliveryOtherAccount = "integration-eu"
|
|
deliveryMessageID = "4ef9a417-02e9-4d39-ad75-9611e0fcc33c"
|
|
// deliveryLaterVersion is a template version that exists only in this test:
|
|
// it is later than the committed notification.v2.
|
|
deliveryLaterVersion = "notification.v3"
|
|
// renamedDeliveryConsumer replays requests as a renamed consumer would:
|
|
// the dedup markers of the real name do not apply to it.
|
|
renamedDeliveryConsumer = "notification_delivery_replay"
|
|
// deliveryRetryAfter has sub-millisecond parts, so a lossy round trip
|
|
// would show.
|
|
deliveryRetryAfter = 2*time.Second + 1500*time.Microsecond + 7*time.Nanosecond
|
|
)
|
|
|
|
var (
|
|
deliveryTables = []pgx.Identifier{{"delivery_attempts"}, {"deliveries"}, {"mail_requests"}}
|
|
deliveryPrivacyMarkers = []string{deliveryRecipientAddress, strings.ToLower(deliveryRecipientAddress), "PRIVATE-SUBJECT", "PRIVATE-BODY"}
|
|
)
|
|
|
|
// deliveryHarness wires the request usecase, the delivery handler, and the
|
|
// stores against one database.
|
|
type deliveryHarness struct {
|
|
env *testEnvironment
|
|
pool *pgxpool.Pool
|
|
transactor *postgresadapter.Transactor
|
|
consumers *postgresadapter.EventConsumerStore
|
|
identity *postgresadapter.IdentityStore
|
|
requester *notification.MailRequester
|
|
handler *notification.DeliveryHandler
|
|
account domain.MailProviderAccount
|
|
logs *syncBuffer
|
|
// now is truncated to microseconds, the precision PostgreSQL stores.
|
|
now time.Time
|
|
}
|
|
|
|
// syncBuffer collects the logs of a consumer goroutine and the test.
|
|
type syncBuffer struct {
|
|
mu sync.Mutex
|
|
buffer bytes.Buffer
|
|
}
|
|
|
|
func (buffer *syncBuffer) Write(data []byte) (int, error) {
|
|
buffer.mu.Lock()
|
|
defer buffer.mu.Unlock()
|
|
return buffer.buffer.Write(data)
|
|
}
|
|
|
|
func (buffer *syncBuffer) String() string {
|
|
buffer.mu.Lock()
|
|
defer buffer.mu.Unlock()
|
|
return buffer.buffer.String()
|
|
}
|
|
|
|
// laterVersionRenderer stands for a later template version: it renders other
|
|
// copy under deliveryLaterVersion without touching the committed templates.
|
|
type laterVersionRenderer struct{}
|
|
|
|
func (laterVersionRenderer) RenderNotification(mailtemplate.NotificationData) (domain.MailContent, error) {
|
|
return domain.NewMailContent(domain.MailKindNotification, deliveryLaterVersion,
|
|
"Новая версия письма", "Текст новой версии шаблона.\n", "<p>Текст новой версии шаблона.</p>\n")
|
|
}
|
|
|
|
func TestMailDelivery(t *testing.T) {
|
|
env := bootstrap(t, postgresService, kafkaService)
|
|
ctx, cancel := context.WithTimeout(t.Context(), deliveryTestTimeout)
|
|
defer cancel()
|
|
pool := env.newPool(ctx, t)
|
|
templates, err := mailtemplate.NewRenderer(env.Config.AppPublicURL)
|
|
if err != nil {
|
|
t.Fatalf("NewRenderer() error = %v", err)
|
|
}
|
|
account, err := domain.NewMailProviderAccount(deliveryProvider, deliveryAccount)
|
|
if err != nil {
|
|
t.Fatalf("NewMailProviderAccount() error = %v", err)
|
|
}
|
|
renderer := notification.NewTemplateRenderer(templates)
|
|
harness := &deliveryHarness{
|
|
env: env,
|
|
pool: pool,
|
|
transactor: postgresadapter.NewTransactor(pool),
|
|
consumers: postgresadapter.NewEventConsumerStore(pool, consumerHandlerTime),
|
|
identity: postgresadapter.NewIdentityStore(pool),
|
|
account: account,
|
|
logs: &syncBuffer{},
|
|
now: time.Now().UTC().Truncate(time.Microsecond),
|
|
}
|
|
harness.requester = notification.NewMailRequester(renderer, harness.clock)
|
|
harness.handler = harness.newHandler(renderer)
|
|
// Subtests share tables and run sequentially; each starts from empty
|
|
// tables.
|
|
reset := func(t *testing.T) {
|
|
t.Helper()
|
|
tables := append([]pgx.Identifier{
|
|
outboxEventsTable,
|
|
{"consumer_processed_events"},
|
|
{"consumer_dead_letters"},
|
|
}, deliveryTables...)
|
|
truncateTables(ctx, t, pool, slices.Concat(tables, usersDependentTables)...)
|
|
}
|
|
|
|
t.Run("one event processed twice through the consumer creates one delivery", func(t *testing.T) {
|
|
reset(t)
|
|
recipient := harness.createRecipient(ctx, t, true)
|
|
deliveryID := harness.requestNotification(ctx, t, recipient)
|
|
event := harness.outboxEvent(ctx, t, deliveryID)
|
|
topic := env.createKafkaTopic(ctx, t, 1)
|
|
|
|
// The relay publishes the event, then publishes it again as after a
|
|
// crash between the broker acknowledgement and the published_at
|
|
// commit; both records carry the same event_id.
|
|
relay := (&relayHarness{env: env, pool: pool, store: postgresadapter.NewOutboxRelayStore(pool, relayStoreTimeouts)}).
|
|
newRelay((&relayHarness{env: env}).newPublisher(t, topic))
|
|
for publication := range 2 {
|
|
if result, err := relay.PublishPending(ctx); err != nil || result.Published != 1 {
|
|
t.Fatalf("publication %d: PublishPending() = %+v, %v; want one event", publication+1, result, err)
|
|
}
|
|
if _, err := pool.Exec(ctx, "UPDATE outbox_events SET published_at = NULL"); err != nil {
|
|
t.Fatalf("mark the event unpublished again: %v", err)
|
|
}
|
|
}
|
|
|
|
metrics := prometheus.New()
|
|
group := newConsumerGroup()
|
|
source, _ := (&consumerHarness{env: env}).newSource(t, topic, group)
|
|
consumerLogger := slog.New(slog.NewJSONHandler(harness.logs, nil))
|
|
consumer, err := eventconsumer.New(harness.handler, source, harness.consumers, metrics, consumerLogger, consumerTestSettings(consumerGrace))
|
|
if err != nil {
|
|
t.Fatalf("eventconsumer.New() error = %v", err)
|
|
}
|
|
runConsumer(ctx, t, consumer)
|
|
env.waitForCommittedOffsets(ctx, t, group, topic, map[int32]int64{0: 2})
|
|
|
|
assertRowCount(ctx, t, pool, pgx.Identifier{"deliveries"}, 1)
|
|
assertRowCount(ctx, t, pool, pgx.Identifier{"mail_requests"}, 0)
|
|
assertDeliveryRecords(t, metrics, "applied", 1)
|
|
assertDeliveryRecords(t, metrics, "duplicate", 1)
|
|
delivery := harness.getDelivery(ctx, t, pool, deliveryID)
|
|
content := delivery.Content()
|
|
switch {
|
|
case delivery.SourceEventID() != event.EventID:
|
|
t.Fatal("the delivery does not name the event it came from")
|
|
case delivery.RecipientUserID() != recipient.ID || delivery.Recipient().Address() != deliveryRecipientAddress:
|
|
t.Fatal("the delivery is not addressed to the recipient account")
|
|
case delivery.Kind() != domain.MailKindNotification || content.TemplateVersion() != "notification.v2":
|
|
t.Fatalf("delivery kind %s, version %s", delivery.Kind(), content.TemplateVersion())
|
|
case delivery.ProviderAccount() != harness.account:
|
|
t.Fatal("the delivery is not pinned to the configured provider account")
|
|
case delivery.IdempotencyKey() != "delivery/"+deliveryID.String():
|
|
t.Fatalf("idempotency key %q", delivery.IdempotencyKey())
|
|
case delivery.Status() != domain.DeliveryStatusPending || delivery.AttemptCount() != 0 || delivery.Version() != 1:
|
|
t.Fatalf("new delivery is %s with %d attempts at version %d", delivery.Status(), delivery.AttemptCount(), delivery.Version())
|
|
case !strings.Contains(content.Text(), "PRIVATE-BODY") || !strings.Contains(content.Text(), env.Config.AppPublicURL+deliveryLinkPath):
|
|
t.Fatal("the stored body is not the rendering of the request")
|
|
}
|
|
harness.assertLogsHoldNoPersonalData(t)
|
|
})
|
|
|
|
t.Run("a stored delivery keeps its body after the template changes", func(t *testing.T) {
|
|
reset(t)
|
|
recipient := harness.createRecipient(ctx, t, true)
|
|
first := harness.requestNotification(ctx, t, recipient)
|
|
firstEvent := harness.outboxEvent(ctx, t, first)
|
|
harness.apply(ctx, t, notification.DeliveryConsumerName, harness.handler, firstEvent)
|
|
original := harness.getDelivery(ctx, t, pool, first)
|
|
|
|
// The template moves on to a later version. A new request gets the new
|
|
// version; a replay of the first request under another consumer name
|
|
// finds the request consumed and stores nothing.
|
|
laterHandler := harness.newHandler(laterVersionRenderer{})
|
|
second := harness.requestNotification(ctx, t, recipient)
|
|
harness.apply(ctx, t, notification.DeliveryConsumerName, laterHandler, harness.outboxEvent(ctx, t, second))
|
|
harness.apply(ctx, t, renamedDeliveryConsumer, laterHandler, firstEvent)
|
|
|
|
assertRowCount(ctx, t, pool, pgx.Identifier{"deliveries"}, 2)
|
|
if got := harness.getDelivery(ctx, t, pool, second).Content(); got.TemplateVersion() != deliveryLaterVersion {
|
|
t.Fatalf("the new request rendered %s, want %s", got.TemplateVersion(), deliveryLaterVersion)
|
|
}
|
|
// Read through a fresh pool and store, as another instance would.
|
|
kept := harness.getDelivery(ctx, t, newPoolFor(ctx, t, env.Config.DatabaseURL), first).Content()
|
|
want := original.Content()
|
|
if kept.TemplateVersion() != "notification.v2" || kept.Subject() != want.Subject() ||
|
|
kept.Text() != want.Text() || kept.HTML() != want.HTML() || kept.Hash() != want.Hash() {
|
|
t.Fatal("the stored delivery changed after the template version changed")
|
|
}
|
|
|
|
// The database refuses a direct change of the stored body.
|
|
_, err := pool.Exec(ctx, "UPDATE deliveries SET text_body = 'rewritten' WHERE id = $1", first)
|
|
assertSQLRefusal(t, err, "deliveries_content_immutable")
|
|
harness.assertLogsHoldNoPersonalData(t)
|
|
})
|
|
|
|
t.Run("attempts and the provider message ID survive a restart", func(t *testing.T) {
|
|
reset(t)
|
|
recipient := harness.createRecipient(ctx, t, true)
|
|
deliveryID := harness.requestNotification(ctx, t, recipient)
|
|
harness.apply(ctx, t, notification.DeliveryConsumerName, harness.handler, harness.outboxEvent(ctx, t, deliveryID))
|
|
|
|
// The first instance records two attempts through its own pool.
|
|
firstPool := newPoolFor(ctx, t, env.Config.DatabaseURL)
|
|
firstStore := postgresadapter.NewDeliveryStore(firstPool).Deliveries()
|
|
created, err := firstStore.Get(ctx, deliveryID)
|
|
if err != nil {
|
|
t.Fatalf("Get() error = %v", err)
|
|
}
|
|
uncertainAt := harness.now.Add(time.Minute)
|
|
uncertain, firstAttempt, err := created.RecordAttempt(domain.DeliveryAttemptInput{
|
|
At: uncertainAt,
|
|
Outcome: domain.DeliveryOutcomeUnknown,
|
|
ProviderCode: "concurrent_idempotent_requests",
|
|
RetryAfter: deliveryRetryAfter,
|
|
NextAttemptAt: uncertainAt.Add(time.Minute),
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("RecordAttempt(unknown) error = %v", err)
|
|
}
|
|
if err := firstStore.RecordAttempt(ctx, uncertain, firstAttempt); err != nil {
|
|
t.Fatalf("store the unknown attempt: %v", err)
|
|
}
|
|
// A second writer of the same attempt loses on the version.
|
|
if err := firstStore.RecordAttempt(ctx, uncertain, firstAttempt); !errors.Is(err, outbound.ErrDeliveryVersionConflict) {
|
|
t.Fatalf("store the same attempt again: error = %v, want ErrDeliveryVersionConflict", err)
|
|
}
|
|
acceptedAt := uncertainAt.Add(2 * time.Minute)
|
|
accepted, secondAttempt, err := uncertain.RecordAttempt(domain.DeliveryAttemptInput{
|
|
At: acceptedAt,
|
|
Outcome: domain.DeliveryOutcomeAccepted,
|
|
ProviderMessageID: deliveryMessageID,
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("RecordAttempt(accepted) error = %v", err)
|
|
}
|
|
if err := firstStore.RecordAttempt(ctx, accepted, secondAttempt); err != nil {
|
|
t.Fatalf("store the accepted attempt: %v", err)
|
|
}
|
|
firstPool.Close()
|
|
|
|
// A new instance reads the state back.
|
|
secondStore := postgresadapter.NewDeliveryStore(newPoolFor(ctx, t, env.Config.DatabaseURL)).Deliveries()
|
|
restored, err := secondStore.Get(ctx, deliveryID)
|
|
if err != nil {
|
|
t.Fatalf("Get() after restart error = %v", err)
|
|
}
|
|
switch {
|
|
case restored.Status() != domain.DeliveryStatusAccepted || restored.ProviderMessageID() != deliveryMessageID:
|
|
t.Fatalf("restored delivery is %s with message ID %q", restored.Status(), restored.ProviderMessageID())
|
|
case restored.AttemptCount() != 2 || restored.Version() != 3 || !restored.LastAttemptAt().Equal(acceptedAt):
|
|
t.Fatalf("restored delivery has %d attempts, version %d, last at %s", restored.AttemptCount(), restored.Version(), restored.LastAttemptAt())
|
|
case !restored.NextAttemptAt().IsZero() || restored.IdempotencyKey() != created.IdempotencyKey():
|
|
t.Fatal("the restored delivery has a next attempt or another key")
|
|
}
|
|
attempts, err := secondStore.ListAttempts(ctx, deliveryID)
|
|
if err != nil {
|
|
t.Fatalf("ListAttempts() error = %v", err)
|
|
}
|
|
// sameAttempt compares RetryAfter exactly, nanoseconds included.
|
|
if len(attempts) != 2 || !sameAttempt(attempts[0], firstAttempt) || !sameAttempt(attempts[1], secondAttempt) {
|
|
t.Fatalf("restored attempts = %+v, want %+v and %+v", attempts, firstAttempt, secondAttempt)
|
|
}
|
|
if _, _, err := restored.RecordAttempt(domain.DeliveryAttemptInput{At: acceptedAt.Add(time.Minute), Outcome: domain.DeliveryOutcomeUnknown}); !errors.Is(err, domain.ErrDeliveryTransition) {
|
|
t.Fatalf("an attempt after acceptance: error = %v, want ErrDeliveryTransition", err)
|
|
}
|
|
_, err = pool.Exec(ctx, "UPDATE delivery_attempts SET outcome = 'unknown' WHERE delivery_id = $1", deliveryID)
|
|
assertSQLRefusal(t, err, "delivery_attempts_immutable")
|
|
harness.assertLogsHoldNoPersonalData(t)
|
|
})
|
|
|
|
t.Run("a delivery is rebound and parked for the quota only within its rules", func(t *testing.T) {
|
|
reset(t)
|
|
recipient := harness.createRecipient(ctx, t, true)
|
|
deliveryID := harness.requestNotification(ctx, t, recipient)
|
|
harness.apply(ctx, t, notification.DeliveryConsumerName, harness.handler, harness.outboxEvent(ctx, t, deliveryID))
|
|
store := postgresadapter.NewDeliveryStore(pool).Deliveries()
|
|
created := harness.getDelivery(ctx, t, pool, deliveryID)
|
|
|
|
otherAccount, err := domain.NewMailProviderAccount(deliveryProvider, deliveryOtherAccount)
|
|
if err != nil {
|
|
t.Fatalf("NewMailProviderAccount() error = %v", err)
|
|
}
|
|
rebound, err := created.Rebind(harness.now.Add(time.Minute), otherAccount)
|
|
if err != nil {
|
|
t.Fatalf("Rebind() error = %v", err)
|
|
}
|
|
if err := store.Rebind(ctx, rebound); err != nil {
|
|
t.Fatalf("store Rebind() error = %v", err)
|
|
}
|
|
// A local quota defers the delivery before any attempt; the reset is
|
|
// unknown.
|
|
waiting, err := rebound.WaitForQuota(harness.now.Add(2*time.Minute), time.Time{})
|
|
if err != nil {
|
|
t.Fatalf("WaitForQuota() error = %v", err)
|
|
}
|
|
if err := store.WaitForQuota(ctx, waiting); err != nil {
|
|
t.Fatalf("store WaitForQuota() error = %v", err)
|
|
}
|
|
if err := store.WaitForQuota(ctx, waiting); !errors.Is(err, outbound.ErrDeliveryVersionConflict) {
|
|
t.Fatalf("store WaitForQuota() over a stale version error = %v, want ErrDeliveryVersionConflict", err)
|
|
}
|
|
stored := harness.getDelivery(ctx, t, pool, deliveryID)
|
|
if stored.Status() != domain.DeliveryStatusWaitingQuota || !stored.NextAttemptAt().IsZero() ||
|
|
stored.ProviderAccount() != otherAccount || stored.AttemptCount() != 0 || stored.Version() != 3 {
|
|
t.Fatalf("stored delivery is %s due %s on %s/%s with %d attempts at version %d", stored.Status(), stored.NextAttemptAt(),
|
|
stored.ProviderAccount().Provider(), stored.ProviderAccount().Account(), stored.AttemptCount(), stored.Version())
|
|
}
|
|
assertRowCount(ctx, t, pool, pgx.Identifier{"delivery_attempts"}, 0)
|
|
|
|
// After the first attempt the account is fixed, in the domain and in
|
|
// the database.
|
|
attemptAt := harness.now.Add(3 * time.Minute)
|
|
attempted, attempt, err := stored.RecordAttempt(domain.DeliveryAttemptInput{
|
|
At: attemptAt, Outcome: domain.DeliveryOutcomeRejected, Rejection: domain.DeliveryRejectionTemporary, NextAttemptAt: attemptAt.Add(time.Minute),
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("RecordAttempt() error = %v", err)
|
|
}
|
|
if err := store.RecordAttempt(ctx, attempted, attempt); err != nil {
|
|
t.Fatalf("store RecordAttempt() error = %v", err)
|
|
}
|
|
if _, err := attempted.Rebind(attemptAt.Add(time.Minute), harness.account); !errors.Is(err, domain.ErrDeliveryTransition) {
|
|
t.Fatalf("Rebind() after an attempt error = %v, want ErrDeliveryTransition", err)
|
|
}
|
|
_, err = pool.Exec(ctx, "UPDATE deliveries SET provider_account = $2 WHERE id = $1", deliveryID, deliveryAccount)
|
|
assertSQLRefusal(t, err, "deliveries_provider_pinned")
|
|
harness.assertLogsHoldNoPersonalData(t)
|
|
})
|
|
|
|
t.Run("a notification to an unverified address is skipped", func(t *testing.T) {
|
|
reset(t)
|
|
recipient := harness.createRecipient(ctx, t, false)
|
|
deliveryID := harness.requestNotification(ctx, t, recipient)
|
|
harness.apply(ctx, t, notification.DeliveryConsumerName, harness.handler, harness.outboxEvent(ctx, t, deliveryID))
|
|
assertRowCount(ctx, t, pool, pgx.Identifier{"deliveries"}, 0)
|
|
assertRowCount(ctx, t, pool, pgx.Identifier{"mail_requests"}, 0)
|
|
if !strings.Contains(harness.logs.String(), deliveryID.String()) {
|
|
t.Fatal("the skip is not logged with the delivery ID")
|
|
}
|
|
harness.assertLogsHoldNoPersonalData(t)
|
|
})
|
|
|
|
t.Run("a request for an account that no longer exists is skipped", func(t *testing.T) {
|
|
reset(t)
|
|
recipient := harness.createRecipient(ctx, t, true)
|
|
deliveryID := harness.requestNotification(ctx, t, recipient)
|
|
event := harness.outboxEvent(ctx, t, deliveryID)
|
|
if _, err := pool.Exec(ctx, "DELETE FROM users WHERE id = $1", recipient.ID); err != nil {
|
|
t.Fatalf("delete the recipient: %v", err)
|
|
}
|
|
// The request text goes with the account; the outbox keeps only IDs.
|
|
assertRowCount(ctx, t, pool, pgx.Identifier{"mail_requests"}, 0)
|
|
harness.apply(ctx, t, notification.DeliveryConsumerName, harness.handler, event)
|
|
assertRowCount(ctx, t, pool, pgx.Identifier{"deliveries"}, 0)
|
|
if !strings.Contains(harness.logs.String(), deliveryID.String()) {
|
|
t.Fatal("the skip is not logged with the delivery ID")
|
|
}
|
|
harness.assertLogsHoldNoPersonalData(t)
|
|
})
|
|
|
|
t.Run("the unverified account cleanup removes requests and deliveries and skips a locked one", func(t *testing.T) {
|
|
reset(t)
|
|
recipient := harness.createRecipient(ctx, t, false)
|
|
// A pending request and a delivery created directly, as the identity
|
|
// flows will create token mail.
|
|
harness.requestNotification(ctx, t, recipient)
|
|
deliveryID := harness.createDeliveryDirectly(ctx, t, recipient)
|
|
cutoff := harness.now.Add(time.Hour)
|
|
users := harness.identity.Users()
|
|
|
|
// A worker holds the delivery row; the cleanup skips the account
|
|
// instead of waiting.
|
|
held, err := pool.Begin(ctx)
|
|
if err != nil {
|
|
t.Fatalf("begin the holding transaction: %v", err)
|
|
}
|
|
if _, err := held.Exec(ctx, "SELECT 1 FROM deliveries WHERE id = $1 FOR UPDATE", deliveryID); err != nil {
|
|
t.Fatalf("lock the delivery: %v", err)
|
|
}
|
|
deleted, err := users.DeleteUnverifiedRegisteredBefore(ctx, cutoff, 10)
|
|
if rollbackErr := held.Rollback(ctx); rollbackErr != nil {
|
|
t.Fatalf("release the delivery lock: %v", rollbackErr)
|
|
}
|
|
if err != nil || deleted != 0 {
|
|
t.Fatalf("DeleteUnverifiedRegisteredBefore() with a locked delivery = %d, %v, want 0", deleted, err)
|
|
}
|
|
|
|
deleted, err = users.DeleteUnverifiedRegisteredBefore(ctx, cutoff, 10)
|
|
if err != nil || deleted != 1 {
|
|
t.Fatalf("DeleteUnverifiedRegisteredBefore() = %d, %v, want 1", deleted, err)
|
|
}
|
|
assertRowCount(ctx, t, pool, pgx.Identifier{"deliveries"}, 0)
|
|
assertRowCount(ctx, t, pool, pgx.Identifier{"mail_requests"}, 0)
|
|
harness.assertLogsHoldNoPersonalData(t)
|
|
})
|
|
}
|
|
|
|
func (harness *deliveryHarness) clock() time.Time { return harness.now }
|
|
|
|
func (harness *deliveryHarness) newHandler(renderer notification.NotificationRenderer) *notification.DeliveryHandler {
|
|
logger := slog.New(slog.NewJSONHandler(harness.logs, nil))
|
|
return notification.NewDeliveryHandler(renderer, harness.account, harness.clock, logger)
|
|
}
|
|
|
|
// createRecipient creates an account with deliveryRecipientAddress,
|
|
// confirmed when verified is true.
|
|
func (harness *deliveryHarness) createRecipient(ctx context.Context, t *testing.T, verified bool) domain.User {
|
|
t.Helper()
|
|
hash, err := domain.NewPasswordHash(identityTestPasswordHash)
|
|
if err != nil {
|
|
t.Fatalf("NewPasswordHash() error = %v", err)
|
|
}
|
|
user, err := domain.NewUser(domain.Registration{
|
|
Email: mustEmail(t, deliveryRecipientAddress),
|
|
PasswordHash: hash,
|
|
Scenario: domain.ScenarioCandidate,
|
|
RegisteredAt: harness.now,
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("NewUser() error = %v", err)
|
|
}
|
|
users := harness.identity.Users()
|
|
if err := users.Create(ctx, user); err != nil {
|
|
t.Fatalf("create the recipient account: %v", err)
|
|
}
|
|
if !verified {
|
|
return user
|
|
}
|
|
confirmed, err := users.MarkEmailVerified(ctx, user.ID, user.RegistrationVersion, harness.now)
|
|
if err != nil {
|
|
t.Fatalf("confirm the recipient address: %v", err)
|
|
}
|
|
return confirmed
|
|
}
|
|
|
|
// requestNotification records a request in a business transaction, as a
|
|
// product usecase would, and returns the delivery ID.
|
|
func (harness *deliveryHarness) requestNotification(ctx context.Context, t *testing.T, recipient domain.User) uuid.UUID {
|
|
t.Helper()
|
|
var deliveryID uuid.UUID
|
|
err := harness.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
|
var err error
|
|
deliveryID, err = harness.requester.RequestNotification(ctx, unit, notification.NotificationRequest{
|
|
RecipientUserID: recipient.ID,
|
|
Notification: mailtemplate.NotificationData{Subject: deliverySubject, Body: deliveryBody, LinkPath: deliveryLinkPath},
|
|
})
|
|
return err
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("RequestNotification() error = %v", err)
|
|
}
|
|
return deliveryID
|
|
}
|
|
|
|
// createDeliveryDirectly stores a delivery without a request, as a
|
|
// transaction that issues a token will.
|
|
func (harness *deliveryHarness) createDeliveryDirectly(ctx context.Context, t *testing.T, recipient domain.User) uuid.UUID {
|
|
t.Helper()
|
|
content, err := domain.NewMailContent(domain.MailKindVerification, "verification.v1", "Подтвердите почту", "PRIVATE-BODY link\n", "")
|
|
if err != nil {
|
|
t.Fatalf("NewMailContent() error = %v", err)
|
|
}
|
|
delivery, err := domain.NewDelivery(domain.NewDeliveryInput{
|
|
ID: uuid.Must(uuid.NewV7()),
|
|
RecipientUserID: recipient.ID,
|
|
Recipient: recipient.Email,
|
|
Content: content,
|
|
ProviderAccount: harness.account,
|
|
CreatedAt: harness.now,
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("NewDelivery() error = %v", err)
|
|
}
|
|
if created, err := postgresadapter.NewDeliveryStore(harness.pool).Deliveries().Create(ctx, delivery); err != nil || !created {
|
|
t.Fatalf("Create() = %t, %v; want the delivery stored", created, err)
|
|
}
|
|
return delivery.ID()
|
|
}
|
|
|
|
// outboxEvent reads the request event from the outbox as the consumer
|
|
// receives it, and checks that it carries no personal data.
|
|
func (harness *deliveryHarness) outboxEvent(ctx context.Context, t *testing.T, deliveryID uuid.UUID) outbound.ConsumedEvent {
|
|
t.Helper()
|
|
for _, stored := range readOutboxEvents(ctx, t, harness.pool) {
|
|
if stored.aggregateID != deliveryID {
|
|
continue
|
|
}
|
|
for _, marker := range append([]string{"@"}, deliveryPrivacyMarkers...) {
|
|
if strings.Contains(string(stored.payload), marker) {
|
|
t.Fatalf("the outbox event carries personal data: %s", stored.payload)
|
|
}
|
|
}
|
|
return outbound.ConsumedEvent{
|
|
EventID: stored.eventID,
|
|
EventType: stored.eventType,
|
|
SchemaVersion: stored.schemaVersion,
|
|
AggregateType: stored.aggregateType,
|
|
AggregateID: stored.aggregateID,
|
|
AggregateVersion: stored.aggregateVersion,
|
|
OccurredAt: harness.now,
|
|
Payload: stored.payload,
|
|
}
|
|
}
|
|
t.Fatalf("no outbox event for delivery %s", deliveryID)
|
|
return outbound.ConsumedEvent{}
|
|
}
|
|
|
|
// apply runs handler in a consumer transaction with its dedup marker, as the
|
|
// consumer runtime does, and expects the event to be applied.
|
|
func (harness *deliveryHarness) apply(
|
|
ctx context.Context,
|
|
t *testing.T,
|
|
consumer string,
|
|
handler *notification.DeliveryHandler,
|
|
event outbound.ConsumedEvent,
|
|
) {
|
|
t.Helper()
|
|
applied, err := harness.consumers.ApplyOnce(ctx, consumer, event.EventID, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
|
return handler.Handle(ctx, unit, event)
|
|
})
|
|
if err != nil || !applied {
|
|
t.Fatalf("ApplyOnce(%s) = %t, %v; want the event applied", consumer, applied, err)
|
|
}
|
|
}
|
|
|
|
func (harness *deliveryHarness) getDelivery(ctx context.Context, t *testing.T, pool *pgxpool.Pool, id uuid.UUID) domain.Delivery {
|
|
t.Helper()
|
|
delivery, err := postgresadapter.NewDeliveryStore(pool).Deliveries().Get(ctx, id)
|
|
if err != nil {
|
|
t.Fatalf("Get(%s) error = %v", id, err)
|
|
}
|
|
return delivery
|
|
}
|
|
|
|
func (harness *deliveryHarness) assertLogsHoldNoPersonalData(t *testing.T) {
|
|
t.Helper()
|
|
logs := harness.logs.String()
|
|
for _, marker := range deliveryPrivacyMarkers {
|
|
if strings.Contains(logs, marker) {
|
|
t.Fatalf("personal data %q reached the logs:\n%s", marker, logs)
|
|
}
|
|
}
|
|
}
|
|
|
|
// assertDeliveryRecords checks a record counter of the delivery consumer.
|
|
func assertDeliveryRecords(t *testing.T, metrics *prometheus.Metrics, outcome string, want int) {
|
|
t.Helper()
|
|
response := httptest.NewRecorder()
|
|
metrics.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/metrics", nil))
|
|
series := fmt.Sprintf(`lincodex_event_consumer_records_total{consumer=%q,outcome=%q} %d`, notification.DeliveryConsumerName, outcome, want)
|
|
if !strings.Contains(response.Body.String(), series+"\n") {
|
|
t.Fatalf("metrics output lacks %s", series)
|
|
}
|
|
}
|
|
|
|
func assertSQLRefusal(t *testing.T, err error, constraint string) {
|
|
t.Helper()
|
|
var pgError *pgconn.PgError
|
|
if !errors.As(err, &pgError) || pgError.Code != "23000" || pgError.ConstraintName != constraint {
|
|
t.Fatalf("statement error = %v, want SQLSTATE 23000 on %s", err, constraint)
|
|
}
|
|
}
|
|
|
|
func sameAttempt(got, want domain.DeliveryAttempt) bool {
|
|
return got.DeliveryID == want.DeliveryID && got.Number == want.Number && got.At.Equal(want.At) &&
|
|
got.Outcome == want.Outcome && got.Rejection == want.Rejection && got.ProviderCode == want.ProviderCode &&
|
|
got.ProviderMessageID == want.ProviderMessageID && got.RetryAfter == want.RetryAfter &&
|
|
got.StatusAfter == want.StatusAfter && got.NextAttemptAt.Equal(want.NextAttemptAt)
|
|
}
|