//go:build integration package integration_test import ( "context" "errors" "fmt" "log/slog" "strings" "testing" "github.com/jackc/pgx/v5" "github.com/twmb/franz-go/pkg/kgo" postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" "lincodex/backend/internal/adapter/secondary/prometheus" "lincodex/backend/internal/domain" "lincodex/backend/internal/port/inbound" "lincodex/backend/internal/usecase/notification" "lincodex/backend/internal/worker/eventconsumer" ) // noticeConsumers names the Kafka groups of the two notification consumers // of one deployment. A restarted process keeps its groups; a group that lost // its offsets is a new name. type noticeConsumers struct { inboxGroup string deliveryGroup string } func newNoticeConsumers() noticeConsumers { return noticeConsumers{inboxGroup: newConsumerGroup(), deliveryGroup: newConsumerGroup()} } // TestInvitationNoticesSurviveRelayAndConsumerRestarts follows the real send // of two invitations through the outbox, the relay, Kafka, and the two // notification consumers that bootstrap registers. The relay dies after the // broker acknowledged the events and before the mark committed; the backend // is then restarted, so the same event IDs are published and consumed again; // finally a consumer group that lost its offsets replays the whole topic. // Each recipient keeps exactly one internal notification and one mail // delivery, and the mail worker sends one message to each. func TestInvitationNoticesSurviveRelayAndConsumerRestarts(t *testing.T) { env := bootstrap(t, postgresService, kafkaService) ctx, cancel := context.WithTimeout(t.Context(), productNoticeTimeout) defer cancel() fixture := newProductNoticeFixture(ctx, t, env) recipients := []domain.User{ fixture.candidate(t, "restart-first@example.test"), fixture.candidate(t, "restart-second@example.test"), } for _, recipient := range recipients { fixture.invite(t, recipient.ID) } // Each send appends invitation.delivered for the inbox and // notification.mail_requested for the mail, each its own aggregate. events := readOutboxEvents(ctx, t, fixture.pool) if len(events) != 2*len(recipients) { t.Fatalf("outbox holds %d events after %d sends, want %d", len(events), len(recipients), 2*len(recipients)) } published := int64(len(events)) // One partition keeps the committed offset equal to the number of // records a consumer has finished. topic := env.createKafkaTopic(ctx, t, 1) relays := &relayHarness{ env: env, pool: fixture.pool, transactor: fixture.transactor, store: postgresadapter.NewOutboxRelayStore(fixture.pool, relayStoreTimeouts), } store := postgresadapter.NewEventConsumerStore(fixture.pool, consumerHandlerTime) // The relay produces every event and is killed before its mark commits. passCtx, killPass := context.WithCancel(ctx) defer killPass() dying := relays.newRelay(crashAfterPublish{EventPublisher: relays.newPublisher(t, topic), crash: killPass}) if result, err := dying.PublishPending(passCtx); !errors.Is(err, context.Canceled) || result.Published != 0 || result.Claimed != len(events) { t.Fatalf("PublishPending() of the dying relay = %+v, %v; want every event claimed, none marked, and context.Canceled", result, err) } assertUnpublished(ctx, t, fixture.pool, len(events)) // The consumers of the first process apply the records. deployment := newNoticeConsumers() firstRun := prometheus.New() fixture.runNoticeConsumers(ctx, t, env, store, topic, deployment, firstRun, published) assertNoticeRecords(t, firstRun, notification.InboxConsumerName, len(recipients), 0) assertNoticeRecords(t, firstRun, notification.DeliveryConsumerName, len(recipients), 0) fixture.assertOneNoticePerRecipient(t, recipients) // After the restart the relay finds the events unmarked and publishes them // again under the same event IDs, and the restarted consumers resume // from their committed offsets. restarted := relays.newRelay(relays.newPublisher(t, topic)) if got := relays.publishUntilDrained(ctx, t, restarted); got != len(events) { t.Fatalf("restarted relay published %d events, want the %d unmarked ones", got, len(events)) } assertUnpublished(ctx, t, fixture.pool, 0) republished := env.consumeKafkaRecords(ctx, t, topic, int(2*published)) assertSameEventIDs(t, republished, events) secondRun := prometheus.New() fixture.runNoticeConsumers(ctx, t, env, store, topic, deployment, secondRun, 2*published) assertNoticeRecords(t, secondRun, notification.InboxConsumerName, 0, len(recipients)) assertNoticeRecords(t, secondRun, notification.DeliveryConsumerName, 0, len(recipients)) fixture.assertOneNoticePerRecipient(t, recipients) // Groups that lost their offsets replay the whole topic: every record is // a duplicate. replay := prometheus.New() fixture.runNoticeConsumers(ctx, t, env, store, topic, newNoticeConsumers(), replay, 2*published) assertNoticeRecords(t, replay, notification.InboxConsumerName, 0, 2*len(recipients)) assertNoticeRecords(t, replay, notification.DeliveryConsumerName, 0, 2*len(recipients)) fixture.assertOneNoticePerRecipient(t, recipients) assertRowCount(ctx, t, fixture.pool, pgx.Identifier{"consumer_dead_letters"}, 0) // The mail worker sends one message to each recipient and then idles. sender := fixture.sender(t, 100, 3000, 0, 0) for range recipients { if result := fixture.harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassAccepted { t.Fatalf("notification pass = %+v, want accepted", result) } } if result := fixture.harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassIdle { t.Fatalf("pass after every notice was sent = %+v, want idle", result) } for _, recipient := range recipients { if sent := fixture.requestsFor(recipient.Email.Address()); len(sent) != 1 { t.Fatalf("provider requests to one recipient = %d, want exactly one", len(sent)) } } } // runNoticeConsumers runs the inbox and delivery consumers, as bootstrap // builds them, in the groups of deployment until both committed offset, and // then stops them as a process shutdown does. func (fixture *productNoticeFixture) runNoticeConsumers( ctx context.Context, t *testing.T, env *testEnvironment, store *postgresadapter.EventConsumerStore, topic string, deployment noticeConsumers, metrics *prometheus.Metrics, offset int64, ) { t.Helper() logger := slog.New(slog.DiscardHandler) handlers := map[string]inbound.EventHandler{ deployment.inboxGroup: notification.NewInboxHandler(logger, false), deployment.deliveryGroup: notification.NewDeliveryHandler( notification.NewTemplateRenderer(fixture.renderer), fixture.account, fixture.clock.Now, logger), } sources := &consumerHarness{env: env} stops := make([]func(), 0, len(handlers)) for group, handler := range handlers { source, closeSource := sources.newSource(t, topic, group) consumer, err := eventconsumer.New(handler, source, store, metrics, logger, consumerTestSettings(consumerGrace)) if err != nil { t.Fatalf("eventconsumer.New(%s) error = %v", handler.ConsumerName(), err) } stopRun := runConsumer(ctx, t, consumer) stops = append(stops, func() { stopRun() closeSource() }) } for group := range handlers { env.waitForCommittedOffsets(ctx, t, group, topic, map[int32]int64{0: offset}) } for _, stop := range stops { stop() } } // assertOneNoticePerRecipient counts the internal notifications and the mail // deliveries of each recipient. func (fixture *productNoticeFixture) assertOneNoticePerRecipient(t *testing.T, recipients []domain.User) { t.Helper() for _, recipient := range recipients { var inbox, deliveries int if err := fixture.pool.QueryRow(fixture.ctx, ` SELECT (SELECT count(*) FROM notification_inbox_events WHERE recipient_user_id = $1), (SELECT count(*) FROM deliveries WHERE recipient_user_id = $1 AND kind = 'notification')`, recipient.ID).Scan(&inbox, &deliveries); err != nil { t.Fatalf("count the notices of a recipient: %v", err) } if inbox != 1 || deliveries != 1 { t.Fatalf("a recipient has %d inbox rows and %d notification deliveries, want one of each", inbox, deliveries) } } } // assertNoticeRecords checks how many records a consumer applied and how many // it recognized as duplicates. func assertNoticeRecords(t *testing.T, metrics *prometheus.Metrics, consumer string, applied, duplicate int) { t.Helper() scraped := scrapeMetrics(metrics) for outcome, want := range map[string]int{eventconsumer.OutcomeApplied: applied, eventconsumer.OutcomeDuplicate: duplicate} { series := fmt.Sprintf(`lincodex_event_consumer_records_total{consumer=%q,outcome=%q} %d`, consumer, outcome, want) if !strings.Contains(scraped, series+"\n") { t.Fatalf("metrics lack %s", series) } } } // assertSameEventIDs checks that the topic holds every outbox event exactly // twice under its original event ID and nothing else. func assertSameEventIDs(t *testing.T, records []*kgo.Record, events []storedEvent) { t.Helper() counts := make(map[string]int, len(events)) for _, record := range records { counts[headerValue(record, "event_id")]++ } for _, event := range events { if counts[event.eventID.String()] != 2 { t.Fatalf("event %s is on the topic %d times, want twice", event.eventID, counts[event.eventID.String()]) } } if len(counts) != len(events) { t.Fatalf("the topic holds %d event IDs, want the %d of the outbox", len(counts), len(events)) } }