Files
lincodex/backend/integration_test/product_notification_test.go
T

626 lines
29 KiB
Go

//go:build integration
package integration_test
import (
"context"
"errors"
"fmt"
"log/slog"
"strings"
"sync"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgtype"
"github.com/jackc/pgx/v5/pgxpool"
"lincodex/backend/internal/adapter/secondary/mail/resend"
"lincodex/backend/internal/adapter/secondary/mail/resend/resendfixture"
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/inbound"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/candidateview"
"lincodex/backend/internal/usecase/companyquota"
"lincodex/backend/internal/usecase/consent"
identityusecase "lincodex/backend/internal/usecase/identity"
invitationusecase "lincodex/backend/internal/usecase/invitation"
"lincodex/backend/internal/usecase/notification"
"lincodex/backend/internal/usecase/notification/mailtemplate"
"lincodex/backend/internal/usecase/policy"
)
const (
productNoticeTimeout = 5 * time.Minute
// productNoticeOrganization names the sending organization. The notice
// must never carry it, so the tests look for it in the mail and the logs.
productNoticeOrganization = "Notice company"
// productNoticeBody is the start of the neutral body of an invitation
// notice; the full text stays in the mail templates.
productNoticeBody = "Работодатель отправил вам приглашение"
// productNoticeConcurrentWorkers drain one queue at once, each with its
// own sender, as separate processes do.
productNoticeConcurrentWorkers = 4
productNoticeQueued = 6
// productNoticeBacklog is the number of due rows that the other lane holds
// while the product claim is explained.
productNoticeBacklog = 5000
)
// productNoticeFixture drives the invitation send with the real notifier, the
// consumer that stores its notice, and the notification sender, against one
// isolated database and the local Resend fixture.
type productNoticeFixture struct {
ctx context.Context
pool *pgxpool.Pool
transactor *postgresadapter.Transactor
identity identityFixture
organizations organizationFixture
clock *testClock
key domain.CandidateViewPseudonymKey
handles map[string]uuid.UUID
organization domain.Organization
owner domain.User
service *invitationusecase.Service
renderer *mailtemplate.Renderer
account domain.MailProviderAccount
mail *resendfixture.Server
transport outbound.MailSender
logs *syncBuffer
// harness reads the deliveries and runs the service sender, which the
// notice tests share.
harness *senderHarness
publicURL string
}
func newProductNoticeFixture(ctx context.Context, t *testing.T, env *testEnvironment) *productNoticeFixture {
t.Helper()
databaseURL := env.createIsolatedDatabase(ctx, t)
applyMigrations(ctx, t, databaseURL)
pool := newPoolFor(ctx, t, databaseURL)
if _, err := policy.NewPublisher(postgresadapter.NewPolicyStore(pool).Policies(), time.Now).EnsureDemoProductPolicy(ctx); err != nil {
t.Fatalf("EnsureDemoProductPolicy() error = %v", err)
}
clock := &testClock{now: time.Now().UTC().Truncate(time.Microsecond).Add(time.Second)}
transactor := postgresadapter.NewTransactor(pool)
identities := identityFixture{ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: clock.Now()}
organizations := organizationFixture{ctx: ctx, pool: pool, identity: identities, transactor: transactor, now: clock.Now()}
owner := organizations.employer(t, "notice-owner@example.test")
confirmEmail(ctx, t, pool, owner, clock.Now().Add(-time.Minute))
organization := organizations.create(t, owner, organizations.completeProfile(t, productNoticeOrganization), clock.Now())
keyring, err := identityusecase.NewKeyring([]byte(env.Config.IdentityKeySecret))
if err != nil {
t.Fatalf("NewKeyring() error = %v", err)
}
key, err := keyring.CandidateViewPseudonymKey()
if err != nil {
t.Fatalf("CandidateViewPseudonymKey() error = %v", err)
}
renderer, err := mailtemplate.NewRenderer(env.Config.AppPublicURL)
if err != nil {
t.Fatalf("NewRenderer() error = %v", err)
}
account, err := domain.NewMailProviderAccount("resend", mailSenderAccount)
if err != nil {
t.Fatalf("NewMailProviderAccount() error = %v", err)
}
mail := resendfixture.New()
t.Cleanup(mail.Close)
mail.SetClock(clock.Now)
transport, err := resend.NewLoopbackSender(resendfixture.APIKey, mailSenderFrom, 10*time.Second, mail.URL(), clock.Now)
if err != nil {
t.Fatalf("NewLoopbackSender() error = %v", err)
}
notifier, err := notification.NewInvitationNotifier(notification.NewMailRequester(notification.NewTemplateRenderer(renderer), clock.Now))
if err != nil {
t.Fatalf("NewInvitationNotifier() error = %v", err)
}
logs := &syncBuffer{}
fixture := &productNoticeFixture{
ctx: ctx, pool: pool, transactor: transactor, identity: identities, organizations: organizations, clock: clock,
key: key, handles: map[string]uuid.UUID{}, organization: organization, owner: owner, renderer: renderer,
account: account, mail: mail, transport: transport, logs: logs, publicURL: env.Config.AppPublicURL,
}
quota := companyquota.NewService(clock.Now)
fixture.service, err = invitationusecase.NewService(invitationusecase.Dependencies{
Transactor: transactor, Keyring: keyring, PseudonymKey: key,
Candidates: func(_ context.Context, _ outbound.UnitOfWork, _, organizationID uuid.UUID, handle string) (uuid.UUID, error) {
candidateID, ok := fixture.handles[handle]
if !ok || organizationID != organization.ID() {
return uuid.Nil, candidateview.ErrCandidateCardNotFound
}
return candidateID, nil
},
Quota: func(ctx context.Context, unit outbound.UnitOfWork, organization domain.Organization, invitationID uuid.UUID) (outbound.CompanyQuotaDecision, error) {
return quota.ReserveInvitation(ctx, unit, organization, invitationID)
},
Notifier: notifier, Consents: consent.NewService(transactor, clock.Now), Clock: clock.Now,
})
if err != nil {
t.Fatalf("invitation.NewService() error = %v", err)
}
// The organization is E1, so one owner may send more than the E0 quota
// allows; the rights under test do not depend on the quota.
if _, err := pool.Exec(ctx, `
UPDATE organizations
SET verification_level = 'e1', verification_basis = 'corporate_domain', verification_changed_at = $2
WHERE id = $1`, organization.ID(), clock.Now()); err != nil {
t.Fatalf("raise the organization to E1: %v", err)
}
fixture.harness = &senderHarness{
pool: pool,
transactor: transactor,
identity: postgresadapter.NewIdentityStore(pool),
deliveries: postgresadapter.NewDeliveryStore(pool).Deliveries(),
mailer: notification.NewServiceMailer(notification.NewTemplateRenderer(renderer), account, clock.Now),
fixture: mail,
transport: transport,
account: account,
clock: clock,
logs: logs,
publicURL: env.Config.AppPublicURL,
}
return fixture
}
// candidate makes a verified candidate with a current publication (C2) and
// the card handle of the organization, so that the send accepts it.
func (fixture *productNoticeFixture) candidate(t *testing.T, email string) domain.User {
t.Helper()
user := fixture.identity.createUser(t, email, domain.ScenarioCandidate, fixture.clock.Now().Add(-time.Hour))
confirmEmail(fixture.ctx, t, fixture.pool, user, fixture.clock.Now().Add(-time.Minute))
handle, err := fixture.key.ForOrganization(fixture.organization.ID(), user.ID)
if err != nil {
t.Fatalf("ForOrganization() error = %v", err)
}
fixture.handles[handle] = user.ID
fixture.publish(t, user.ID)
return user
}
// publish stores a C2 grant and a published card that names it, the state an
// invitation is sent under.
func (fixture *productNoticeFixture) publish(t *testing.T, userID uuid.UUID) {
t.Helper()
ledger := postgresadapter.NewConsentStore(fixture.pool)
text, err := ledger.ConsentTexts().Get(fixture.ctx, domain.ConsentPurposePublication, privacyC2Version)
if err != nil {
t.Fatalf("ConsentTexts().Get(c2) error = %v", err)
}
grant, err := domain.NewConsentGrant(domain.ConsentGrantInput{
SubjectID: userID, Purpose: domain.ConsentPurposePublication, TextVersion: text.Version(), TextHash: text.Hash(),
Source: domain.ConsentSourceConsentSettings, GrantedAt: fixture.clock.Now().Add(-time.Hour),
})
if err != nil {
t.Fatalf("NewConsentGrant() error = %v", err)
}
record, created, err := ledger.ConsentLedger().Grant(fixture.ctx, grant)
if err != nil || !created {
t.Fatalf("Grant(c2) = %t, %v; want a new record", created, err)
}
request, err := domain.NewPublicationRequest(domain.PublicationPublished, []domain.CardField{domain.CardFieldStack, domain.CardFieldCategories})
if err != nil {
t.Fatalf("NewPublicationRequest() error = %v", err)
}
empty, err := domain.NewPublication(userID)
if err != nil {
t.Fatalf("NewPublication() error = %v", err)
}
change, err := empty.Apply(request, 0, record.ID(), fixture.clock.Now())
if err != nil || !change.Changed {
t.Fatalf("Apply(publish) = %+v, %v; want a change", change, err)
}
if _, err := sqlc.New(fixture.pool).InsertCandidatePublication(fixture.ctx, sqlc.InsertCandidatePublicationParams{
UserID: uuidParam(userID), State: string(change.Publication.StoredState()), Fields: change.Publication.StoredFields(),
ConsentRecordID: uuidParam(record.ID()), PublishedAt: timeParam(change.Publication.PublishedAt()),
ClosedAt: pgtype.Timestamptz{}, At: timeParam(fixture.clock.Now()),
}); err != nil {
t.Fatalf("InsertCandidatePublication() error = %v", err)
}
}
func (fixture *productNoticeFixture) handleOf(t *testing.T, candidateID uuid.UUID) string {
t.Helper()
handle, err := fixture.key.ForOrganization(fixture.organization.ID(), candidateID)
if err != nil {
t.Fatalf("ForOrganization() error = %v", err)
}
return handle
}
// invite drafts an invitation for the candidate and sends it. The send records
// the notice request in the same transaction, as it does in production.
func (fixture *productNoticeFixture) invite(t *testing.T, candidateID uuid.UUID) domain.OrganizationInvitationView {
t.Helper()
key := "create-" + uuid.NewString()
draft, err := fixture.service.Create(fixture.ctx, invitationusecase.CreateCommand{
ActorID: fixture.owner.ID, OrganizationID: fixture.organization.ID(), IdempotencyKey: key,
CanonicalBody: []byte(fmt.Sprintf(`{"key":%q}`, key)), CandidateHandle: fixture.handleOf(t, candidateID),
Terms: invitationStorageTerms(),
})
if err != nil {
t.Fatalf("Create() error = %v", err)
}
sent, err := fixture.service.Send(fixture.ctx, invitationusecase.SendCommand{
ActorID: fixture.owner.ID, OrganizationID: fixture.organization.ID(), InvitationID: draft.ID,
IdempotencyKey: "send-" + uuid.NewString(), ExpectedVersion: draft.Version,
})
if err != nil {
t.Fatalf("Send() error = %v", err)
}
return sent
}
// deliverNotice runs the delivery consumer on the notice request that the send
// recorded, as the event consumer does, and returns the delivery ID.
func (fixture *productNoticeFixture) deliverNotice(t *testing.T, candidateID uuid.UUID) uuid.UUID {
t.Helper()
var event outbound.ConsumedEvent
var payload string
if err := fixture.pool.QueryRow(fixture.ctx, `
SELECT event_id, event_type, schema_version, aggregate_type, aggregate_id, aggregate_version, payload::text, occurred_at
FROM outbox_events
WHERE event_type = 'notification.mail_requested'
AND aggregate_id IN (SELECT id FROM mail_requests WHERE recipient_user_id = $1)`, candidateID).
Scan(&event.EventID, &event.EventType, &event.SchemaVersion, &event.AggregateType, &event.AggregateID,
&event.AggregateVersion, &payload, &event.OccurredAt); err != nil {
t.Fatalf("read the notice request: %v", err)
}
event.Payload = []byte(payload)
event.OccurredAt = event.OccurredAt.UTC().Truncate(time.Microsecond)
handler := notification.NewDeliveryHandler(notification.NewTemplateRenderer(fixture.renderer), fixture.account, fixture.clock.Now, slog.New(slog.DiscardHandler))
if err := fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
return handler.Handle(ctx, unit, event)
}); err != nil {
t.Fatalf("DeliveryHandler.Handle() error = %v", err)
}
var deliveryID uuid.UUID
if err := fixture.pool.QueryRow(fixture.ctx,
`SELECT id FROM deliveries WHERE recipient_user_id = $1 AND kind = 'notification'`, candidateID).Scan(&deliveryID); err != nil {
t.Fatalf("read the notice delivery: %v", err)
}
return deliveryID
}
// sender builds the notification lane with the reserve of its quota gate. The
// lane shares the transport, account, and timing of the service lane.
func (fixture *productNoticeFixture) sender(t *testing.T, daily, monthly, reserveDaily, reserveMonthly int64) *notification.DeliverySender {
t.Helper()
limits, err := domain.NewMailQuotaLimits(daily, monthly)
if err != nil {
t.Fatalf("NewMailQuotaLimits() error = %v", err)
}
logger := slog.New(slog.NewJSONHandler(fixture.logs, nil))
gate, err := notification.NewQuotaGate(fixture.account, limits, resend.IdempotencyWindow, fixture.clock.Now, logger).WithReserve(reserveDaily, reserveMonthly)
if err != nil {
t.Fatalf("WithReserve() error = %v", err)
}
sender, err := notification.NewNotificationSender(fixture.transactor, fixture.transport, gate, notification.DeliverySenderSettings{
Account: fixture.account,
Lease: mailSenderLease,
StoreTimeout: 30 * time.Second,
SettleBudget: mailSenderSettleBudget,
ShutdownSettleBudget: time.Second,
MaxFailures: 3,
Retry: notification.RetryPolicy{Initial: time.Minute, Max: 30 * time.Minute},
}, fixture.clock.Now, logger, []notification.SubjectRights{notification.NewInvitationNoticeRights()})
if err != nil {
t.Fatalf("NewNotificationSender() error = %v", err)
}
return sender
}
// deliveryRow reads the stored status, cancel reason, and bodies of a delivery,
// without decoding it, so a test sees what is in the table.
func (fixture *productNoticeFixture) deliveryRow(t *testing.T, id uuid.UUID) (status, reason, text, html string, redacted bool) {
t.Helper()
var cancelReason *string
var redactedAt *time.Time
if err := fixture.pool.QueryRow(fixture.ctx, `
SELECT status, cancel_reason, text_body, html_body, body_redacted_at FROM deliveries WHERE id = $1`, id).
Scan(&status, &cancelReason, &text, &html, &redactedAt); err != nil {
t.Fatalf("read delivery %s: %v", id, err)
}
if cancelReason != nil {
reason = *cancelReason
}
return status, reason, text, html, redactedAt != nil
}
// requestsFor returns the provider requests addressed to the address.
func (fixture *productNoticeFixture) requestsFor(address string) []resendfixture.Request {
var matching []resendfixture.Request
for _, request := range fixture.mail.Requests() {
for _, to := range request.To {
if to == address {
matching = append(matching, request)
break
}
}
}
return matching
}
func TestProductNoticeIsSentOnceByItsOwnWorker(t *testing.T) {
env := bootstrap(t, postgresService)
ctx, cancel := context.WithTimeout(t.Context(), productNoticeTimeout)
defer cancel()
fixture := newProductNoticeFixture(ctx, t, env)
candidate := fixture.candidate(t, "notice-sent@example.test")
fixture.invite(t, candidate.ID)
deliveryID := fixture.deliverNotice(t, candidate.ID)
calls := len(fixture.mail.Requests())
serviceSender := fixture.harness.newSender(t, fixture.transactor, 100, 3000)
if result := fixture.harness.pass(ctx, t, serviceSender); result.Outcome != inbound.MailPassIdle || len(fixture.mail.Requests()) != calls {
t.Fatalf("service pass = %+v with %d provider calls; want idle and none: the service worker takes only service mail", result, len(fixture.mail.Requests())-calls)
}
if got := fixture.harness.delivery(ctx, t, deliveryID); got.Kind() != domain.MailKindNotification || got.Status() != domain.DeliveryStatusPending || got.Subject().Kind() != domain.MailSubjectInvitation {
t.Fatalf("stored notice = %s %s with subject %v; want a pending notification that names its invitation", got.Kind(), got.Status(), got.Subject())
}
productSender := fixture.sender(t, 100, 3000, 0, 0)
if result := fixture.harness.pass(ctx, t, productSender); result.Outcome != inbound.MailPassAccepted {
t.Fatalf("product pass = %+v, want accepted", result)
}
sent := fixture.requestsFor(candidate.Email.Address())
if len(sent) != 1 {
t.Fatalf("provider requests to the candidate = %d, want exactly one", len(sent))
}
if !strings.Contains(sent[0].Text, productNoticeBody) || strings.Contains(sent[0].Text, productNoticeOrganization) ||
strings.Contains(sent[0].Text, candidate.ID.String()) || !strings.Contains(sent[0].Text, "/candidate/invitations") {
t.Fatalf("notice body = %q; want the neutral text with the inbox link and no organization or identifier", sent[0].Text)
}
if got := fixture.harness.delivery(ctx, t, deliveryID); got.Status() != domain.DeliveryStatusAccepted || got.AttemptCount() != 1 {
t.Fatalf("delivery is %s after %d attempts, want accepted after one", got.Status(), got.AttemptCount())
}
if result := fixture.harness.pass(ctx, t, productSender); result.Outcome != inbound.MailPassIdle || len(fixture.mail.Requests()) != calls+1 {
t.Fatalf("pass after the send = %+v; want idle with no second request", result)
}
fixture.harness.assertLogsHoldNoSecrets(t, candidate.Email.Address(), candidate.ID.String(), fixture.handleOf(t, candidate.ID))
}
func TestProductNoticeRightsAreCheckedBeforeEverySend(t *testing.T) {
env := bootstrap(t, postgresService)
ctx, cancel := context.WithTimeout(t.Context(), productNoticeTimeout)
defer cancel()
fixture := newProductNoticeFixture(ctx, t, env)
productSender := fixture.sender(t, 100, 3000, 0, 0)
t.Run("a candidate who hides the organization after the send gets no mail and the body is cleared", func(t *testing.T) {
candidate := fixture.candidate(t, "notice-hidden@example.test")
fixture.invite(t, candidate.ID)
deliveryID := fixture.deliverNotice(t, candidate.ID)
fixture.hide(t, candidate.ID)
calls := len(fixture.mail.Requests())
if result := fixture.harness.pass(ctx, t, productSender); result.Outcome != inbound.MailPassCancelled || result.CancelReason != domain.DeliveryCancelRightsRevoked {
t.Fatalf("pass = %+v, want cancelled as rights_revoked", result)
}
if len(fixture.mail.Requests()) != calls {
t.Fatal("the transport was called for a notice whose organization is hidden")
}
status, reason, text, html, redacted := fixture.deliveryRow(t, deliveryID)
if status != "cancelled" || reason != "rights_revoked" || text != "" || html != "" || !redacted {
t.Fatalf("stored notice is %s (%s) with bodies %q/%q redacted %v; want cancelled as rights_revoked with no body", status, reason, text, html, redacted)
}
if result := fixture.harness.pass(ctx, t, productSender); result.Outcome != inbound.MailPassIdle {
t.Fatalf("pass after the cancellation = %+v, want idle", result)
}
fixture.harness.assertLogsHoldNoSecrets(t, candidate.Email.Address(), candidate.ID.String(), fixture.handleOf(t, candidate.ID))
})
t.Run("an address that is no longer verified gets no mail and is cancelled as recipient_ineligible", func(t *testing.T) {
candidate := fixture.candidate(t, "notice-unverified@example.test")
fixture.invite(t, candidate.ID)
deliveryID := fixture.deliverNotice(t, candidate.ID)
if _, err := fixture.pool.Exec(ctx, `UPDATE users SET email_verified_at = NULL, version = version + 1 WHERE id = $1`, candidate.ID); err != nil {
t.Fatalf("unverify the address: %v", err)
}
calls := len(fixture.mail.Requests())
if result := fixture.harness.pass(ctx, t, productSender); result.Outcome != inbound.MailPassCancelled || result.CancelReason != domain.DeliveryCancelRecipientIneligible {
t.Fatalf("pass = %+v, want cancelled as recipient_ineligible", result)
}
if len(fixture.mail.Requests()) != calls {
t.Fatal("the transport was called for an unverified address")
}
if status, reason, _, _, _ := fixture.deliveryRow(t, deliveryID); status != "cancelled" || reason != "recipient_ineligible" {
t.Fatalf("stored notice is %s (%s), want cancelled as recipient_ineligible", status, reason)
}
})
t.Run("a notice that names no subject has no right to check and is cancelled as source_closed", func(t *testing.T) {
candidate := fixture.candidate(t, "notice-no-subject@example.test")
content, err := domain.NewMailContent(domain.MailKindNotification, "notification.v1", "Синтетическое уведомление", "PRIVATE-BODY notification\n", "")
if err != nil {
t.Fatalf("NewMailContent() error = %v", err)
}
delivery, err := domain.NewDelivery(domain.NewDeliveryInput{
ID: uuid.Must(uuid.NewV7()), RecipientUserID: candidate.ID, Recipient: candidate.Email,
Content: content, ProviderAccount: fixture.account, CreatedAt: fixture.clock.Now(),
})
if err != nil {
t.Fatalf("NewDelivery() error = %v", err)
}
if created, err := fixture.harness.deliveries.Create(ctx, delivery); err != nil || !created {
t.Fatalf("Create() = %t, %v; want the notice stored", created, err)
}
if result := fixture.harness.pass(ctx, t, productSender); result.Outcome != inbound.MailPassCancelled || result.CancelReason != domain.DeliveryCancelSourceClosed {
t.Fatalf("pass = %+v, want cancelled as source_closed", result)
}
if status, _, text, _, _ := fixture.deliveryRow(t, delivery.ID()); status != "cancelled" || text != "" {
t.Fatalf("stored notice is %s with text %q, want cancelled with no body", status, text)
}
})
// The clock moves past the response deadline, so this subtest comes last.
t.Run("an invitation that passed its response deadline gets no mail and is cancelled as rights_revoked", func(t *testing.T) {
candidate := fixture.candidate(t, "notice-expired@example.test")
fixture.invite(t, candidate.ID)
deliveryID := fixture.deliverNotice(t, candidate.ID)
fixture.clock.Advance(400 * 24 * time.Hour)
calls := len(fixture.mail.Requests())
if result := fixture.harness.pass(ctx, t, productSender); result.Outcome != inbound.MailPassCancelled || result.CancelReason != domain.DeliveryCancelRightsRevoked {
t.Fatalf("pass = %+v, want cancelled as rights_revoked", result)
}
if len(fixture.mail.Requests()) != calls {
t.Fatal("the transport was called for an expired invitation")
}
if status, reason, _, _, _ := fixture.deliveryRow(t, deliveryID); status != "cancelled" || reason != "rights_revoked" {
t.Fatalf("stored notice is %s (%s), want cancelled as rights_revoked", status, reason)
}
})
}
// hide records that the candidate hid the organization, as the privacy
// settings do.
func (fixture *productNoticeFixture) hide(t *testing.T, candidateID uuid.UUID) {
t.Helper()
if _, err := fixture.pool.Exec(fixture.ctx, `
INSERT INTO candidate_hidden_organizations (user_id, organization_id, hidden_at) VALUES ($1, $2, $3)`,
candidateID, fixture.organization.ID(), fixture.clock.Now()); err != nil {
t.Fatalf("hide the organization: %v", err)
}
}
func TestProductNoticeReserveLeavesServiceQuotaToServiceMail(t *testing.T) {
env := bootstrap(t, postgresService)
ctx, cancel := context.WithTimeout(t.Context(), productNoticeTimeout)
defer cancel()
fixture := newProductNoticeFixture(ctx, t, env)
// The day holds ten recipients. The notification lane keeps eight for other
// mail, so it admits two notices, and the service lane still has the full
// day.
productSender := fixture.sender(t, 10, 3000, 8, 0)
var waiting uuid.UUID
for index := range 3 {
candidate := fixture.candidate(t, fmt.Sprintf("notice-reserve-%d@example.test", index))
fixture.invite(t, candidate.ID)
id := fixture.deliverNotice(t, candidate.ID)
if index == 2 {
waiting = id
}
}
for range 2 {
if result := fixture.harness.pass(ctx, t, productSender); result.Outcome != inbound.MailPassAccepted {
t.Fatalf("notice pass = %+v, want accepted within the lane's share", result)
}
}
if result := fixture.harness.pass(ctx, t, productSender); result.Outcome != inbound.MailPassWaitingQuota {
t.Fatalf("third notice pass = %+v, want waiting_quota at the reserve", result)
}
midnight := domain.MailQuotaWindowsAt(fixture.clock.Now()).ResetAt(domain.MailQuotaPeriodDay)
if got := fixture.harness.delivery(ctx, t, waiting); got.Status() != domain.DeliveryStatusWaitingQuota || !got.NextAttemptAt().Equal(midnight) {
t.Fatalf("waiting notice is %s due %s, want waiting_quota until %s", got.Status(), got.NextAttemptAt(), midnight)
}
if result := fixture.harness.pass(ctx, t, productSender); result.Outcome != inbound.MailPassIdle {
t.Fatalf("notice pass while the reserve holds = %+v, want idle without a spin", result)
}
service := fixture.harness.createUser(ctx, t, false)
_, _, serviceID := fixture.harness.enqueueVerification(ctx, t, service, mailSenderTokenLifetime)
serviceSender := fixture.harness.newSender(t, fixture.transactor, 10, 3000)
if result := fixture.harness.pass(ctx, t, serviceSender); result.Outcome != inbound.MailPassAccepted {
t.Fatalf("service pass = %+v, want the verification mail accepted under the reserve", result)
}
if got := fixture.harness.delivery(ctx, t, serviceID); got.Status() != domain.DeliveryStatusAccepted {
t.Fatalf("service mail is %s, want accepted", got.Status())
}
fixture.harness.assertQuotaUsage(ctx, t, 3)
if got := len(fixture.mail.Requests()); got != 3 {
t.Fatalf("provider calls = %d, want two notices and the service mail", got)
}
}
func TestProductNoticeQueueIsDrainedOnceByConcurrentWorkers(t *testing.T) {
env := bootstrap(t, postgresService)
ctx, cancel := context.WithTimeout(t.Context(), productNoticeTimeout)
defer cancel()
fixture := newProductNoticeFixture(ctx, t, env)
ids := make([]uuid.UUID, 0, productNoticeQueued)
for index := range productNoticeQueued {
candidate := fixture.candidate(t, fmt.Sprintf("notice-queue-%d@example.test", index))
fixture.invite(t, candidate.ID)
ids = append(ids, fixture.deliverNotice(t, candidate.ID))
}
var group sync.WaitGroup
errs := make([]error, productNoticeConcurrentWorkers)
for worker := range productNoticeConcurrentWorkers {
sender := fixture.sender(t, 1000, 3000, 0, 0)
group.Go(func() {
for {
result, err := sender.ProcessNext(ctx, ctx)
if err != nil {
errs[worker] = err
return
}
if result.Outcome == inbound.MailPassIdle {
return
}
}
})
}
group.Wait()
if err := errors.Join(errs...); err != nil {
t.Fatalf("a worker failed: %v", err)
}
if got := len(fixture.mail.Requests()); got != productNoticeQueued {
t.Fatalf("provider calls = %d, want one per notice (%d)", got, productNoticeQueued)
}
for _, id := range ids {
if got := fixture.harness.delivery(ctx, t, id); got.Status() != domain.DeliveryStatusAccepted || got.AttemptCount() != 1 {
t.Fatalf("notice %s is %s after %d attempts, want accepted after one", id, got.Status(), got.AttemptCount())
}
}
}
func TestProductNoticeClaimReadsItsOwnDueIndex(t *testing.T) {
env := bootstrap(t, postgresService)
ctx, cancel := context.WithTimeout(t.Context(), productNoticeTimeout)
defer cancel()
fixture := newProductNoticeFixture(ctx, t, env)
// Service mail backlog: the product claim must not scan it.
if _, err := fixture.pool.Exec(ctx, `INSERT INTO deliveries (
id, recipient_user_id, recipient_email, kind, template_version, subject, text_body, html_body, content_sha256,
provider, provider_account, idempotency_key, status, attempt_count, next_attempt_at, version, created_at, updated_at
)
SELECT gen_random_uuid(), $1, 'backlog@example.com', 'verification', 'verification.v1', 's', 't', '', decode(repeat('00', 32), 'hex'),
'resend', $2, 'delivery/service-backlog-' || n, 'pending', 0, $3::timestamptz - interval '1 day', 1, $3, $3
FROM generate_series(1, $4::int) AS n`, fixture.identity.createUser(t, "backlog-owner@example.test", domain.ScenarioCandidate, fixture.clock.Now()).ID,
fixture.account.Account(), fixture.clock.Now(), productNoticeBacklog); err != nil {
t.Fatalf("insert the service backlog: %v", err)
}
if _, err := fixture.pool.Exec(ctx, "ANALYZE deliveries"); err != nil {
t.Fatalf("ANALYZE deliveries: %v", err)
}
rows, err := fixture.pool.Query(ctx, `EXPLAIN (COSTS OFF) SELECT due.id FROM deliveries AS due
WHERE due.kind = 'notification'
AND due.status IN ('pending', 'waiting_quota', 'unknown') AND due.next_attempt_at IS NOT NULL
AND due.next_attempt_at <= $1::timestamptz AND due.provider = 'resend' AND due.provider_account = $2
AND (due.claim_owner IS NULL OR due.claimed_until <= clock_timestamp())
ORDER BY due.next_attempt_at, due.id LIMIT 1 FOR UPDATE SKIP LOCKED`,
fixture.clock.Now(), fixture.account.Account())
if err != nil {
t.Fatalf("explain the product claim: %v", err)
}
defer rows.Close()
var plan strings.Builder
for rows.Next() {
var line string
if err := rows.Scan(&line); err != nil {
t.Fatalf("scan the plan: %v", err)
}
plan.WriteString(line + "\n")
}
if !strings.Contains(plan.String(), "deliveries_product_due_idx") || strings.Contains(plan.String(), "Seq Scan") {
t.Fatalf("the product claim does not use deliveries_product_due_idx over the service backlog:\n%s", plan.String())
}
}