//go:build integration package integration_test import ( "context" "errors" "fmt" "testing" "time" "github.com/google/uuid" "github.com/jackc/pgx/v5/pgxpool" postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" "lincodex/backend/internal/domain" "lincodex/backend/internal/port/outbound" ) // holdingConcurrentConns sizes the pool of the concurrency subtests, so that // every goroutine of one subtest holds a connection at the same time. const holdingConcurrentConns = 8 // TestHoldings covers the E0 quota pools that the organizations of one holding // share, the isolation of accounts, and the creation of holdings. func TestHoldings(t *testing.T) { env := bootstrap(t, postgresService) ctx, cancel := context.WithTimeout(t.Context(), companyQuotaTestTimeout) defer cancel() databaseURL := env.createIsolatedDatabase(ctx, t) fixture := newCompanyQuotaFixture(ctx, t, databaseURL) t.Run("organizations of one account share the E0 pools and keep the E1 pools apart", func(t *testing.T) { owner := fixture.organizations.employer(t, uniqueHoldingEmail("shared-owner")) first := fixture.organizationOf(t, owner, "shared-first", domain.OrganizationVerificationE0) second := fixture.organizationOf(t, owner, "shared-second", domain.OrganizationVerificationE0) verified := fixture.organizationOf(t, owner, "shared-verified", domain.OrganizationVerificationE1) fixture.assertSameHolding(t, owner.ID, first.ID(), second.ID(), verified.ID()) // The verified organization draws on its own pool, and its usage does // not count toward the E0 pool that follows. for range 3 { fixture.reserveInvitationAllowed(t, verified, fixture.newInvitationID(t, verified)) fixture.reserveCardViewAllowed(t, verified, fixture.newCandidateID(t)) } for range 6 { fixture.reserveInvitationAllowed(t, first, fixture.newInvitationID(t, first)) } for range 4 { fixture.reserveInvitationAllowed(t, second, fixture.newInvitationID(t, second)) } fixture.assertInvitationDenied(t, first, fixture.clock.Now().Add(7*24*time.Hour)) fixture.assertInvitationDenied(t, second, fixture.clock.Now().Add(7*24*time.Hour)) fixture.assertQuotaRowCounts(t, first.ID(), 6, 0) fixture.assertQuotaRowCounts(t, second.ID(), 4, 0) fixture.assertQuotaRowCounts(t, verified.ID(), 3, 3) for range 30 { fixture.reserveCardViewAllowed(t, first, fixture.newCandidateID(t)) } for range 20 { fixture.reserveCardViewAllowed(t, second, fixture.newCandidateID(t)) } fixture.assertCardViewDenied(t, first, fixture.clock.Now().Add(24*time.Hour)) fixture.assertCardViewDenied(t, second, fixture.clock.Now().Add(24*time.Hour)) fixture.assertQuotaRowCounts(t, first.ID(), 6, 30) fixture.assertQuotaRowCounts(t, second.ID(), 4, 20) // The verified organization keeps its own pool: it still has room. fixture.reserveInvitationAllowed(t, verified, fixture.newInvitationID(t, verified)) fixture.reserveCardViewAllowed(t, verified, fixture.newCandidateID(t)) }) t.Run("a second account forms its own holding and pool", func(t *testing.T) { owner := fixture.organizations.employer(t, uniqueHoldingEmail("other-owner")) other := fixture.organizationOf(t, owner, "other-first", domain.OrganizationVerificationE0) for range 10 { fixture.reserveInvitationAllowed(t, other, fixture.newInvitationID(t, other)) } fixture.assertInvitationDenied(t, other, fixture.clock.Now().Add(7*24*time.Hour)) neighbour := fixture.organizations.employer(t, uniqueHoldingEmail("neighbour-owner")) separate := fixture.organizationOf(t, neighbour, "neighbour-first", domain.OrganizationVerificationE0) if fixture.holdingOf(t, separate.ID()) == fixture.holdingOf(t, other.ID()) { t.Fatal("organizations of two accounts share one holding") } fixture.reserveInvitationAllowed(t, separate, fixture.newInvitationID(t, separate)) fixture.reserveCardViewAllowed(t, separate, fixture.newCandidateID(t)) }) t.Run("usage leaves the E0 pool with its organization", func(t *testing.T) { owner := fixture.organizations.employer(t, uniqueHoldingEmail("leave-owner")) raised := fixture.organizationOf(t, owner, "leave-raised", domain.OrganizationVerificationE0) sibling := fixture.organizationOf(t, owner, "leave-sibling", domain.OrganizationVerificationE0) for range 6 { fixture.reserveInvitationAllowed(t, raised, fixture.newInvitationID(t, raised)) } if _, err := fixture.pool.Exec(fixture.ctx, ` UPDATE organizations SET verification_level = 'e1', verification_basis = 'corporate_domain', verification_changed_at = $2 WHERE id = $1`, raised.ID(), fixture.clock.Now().Add(-30*time.Second)); err != nil { t.Fatalf("raise organization to E1: %v", err) } raisedNow, _, err := fixture.organizations.read(owner.ID, raised.ID()) if err != nil { t.Fatalf("read raised organization: %v", err) } // The six invitations stay stored, but they no longer count toward the // E0 pool, which the sibling can use in full. for range 10 { fixture.reserveInvitationAllowed(t, sibling, fixture.newInvitationID(t, sibling)) } fixture.assertInvitationDenied(t, sibling, fixture.clock.Now().Add(7*24*time.Hour)) fixture.assertQuotaRowCounts(t, raised.ID(), 6, 0) fixture.reserveInvitationAllowed(t, raisedNow, fixture.newInvitationID(t, raisedNow)) }) t.Run("concurrent reservations of one E0 pool never exceed its limits", func(t *testing.T) { owner := fixture.organizations.employer(t, uniqueHoldingEmail("race-owner")) first := fixture.organizationOf(t, owner, "race-first", domain.OrganizationVerificationE0) second := fixture.organizationOf(t, owner, "race-second", domain.OrganizationVerificationE0) concurrent := newConcurrentTransactor(ctx, t, databaseURL) for range 5 { fixture.reserveInvitationAllowed(t, first, fixture.newInvitationID(t, first)) } for range 4 { fixture.reserveInvitationAllowed(t, second, fixture.newInvitationID(t, second)) } // Nine of the ten invitations are used. Four reservations race for the // last place, two from each organization. racers := []domain.Organization{first, second, first, second} invitationIDs := make([]uuid.UUID, len(racers)) for index, organization := range racers { invitationIDs[index] = fixture.newInvitationID(t, organization) } decisions := make([]outbound.CompanyQuotaDecision, len(racers)) runConcurrently(t, len(racers), func(index int) error { decision, err := fixture.reserveInvitationLocked(concurrent, racers[index], invitationIDs[index]) decisions[index] = decision return err }) fixture.assertOneAllowed(t, decisions, fixture.clock.Now().Add(7*24*time.Hour)) fixture.assertInvitationRowsOf(t, 10, first.ID(), second.ID()) viewCandidates := make([]uuid.UUID, 0, 49) for range 49 { viewCandidates = append(viewCandidates, fixture.newCandidateID(t)) } for index, candidateID := range viewCandidates { organization := first if index%2 == 1 { organization = second } fixture.reserveCardViewAllowed(t, organization, candidateID) } viewRacers := make([]uuid.UUID, len(racers)) for index := range racers { viewRacers[index] = fixture.newCandidateID(t) } viewDecisions := make([]outbound.CompanyQuotaDecision, len(racers)) runConcurrently(t, len(racers), func(index int) error { decision, err := fixture.reserveCardViewLocked(concurrent, racers[index], viewRacers[index]) viewDecisions[index] = decision return err }) fixture.assertOneAllowed(t, viewDecisions, fixture.clock.Now().Add(24*time.Hour)) fixture.assertCardViewRowsOf(t, 50, first.ID(), second.ID()) }) t.Run("concurrent creations by one account end in one holding", func(t *testing.T) { owner := fixture.organizations.employer(t, uniqueHoldingEmail("create-owner")) concurrent := newConcurrentTransactor(ctx, t, databaseURL) const creations = holdingConcurrentConns at := fixture.clock.Now().Add(-time.Minute) organizationIDs := make([]uuid.UUID, creations) runConcurrently(t, creations, func(index int) error { profile, err := domain.NewOrganizationProfile(domain.OrganizationProfileInput{Name: fmt.Sprintf("Concurrent company %d", index)}) if err != nil { return fmt.Errorf("profile: %w", err) } company, err := domain.NewOrganization(profile, at) if err != nil { return fmt.Errorf("organization: %w", err) } membership, err := domain.NewOwnerMembership(company.ID(), owner.ID, at) if err != nil { return fmt.Errorf("owner membership: %w", err) } organizationIDs[index] = company.ID() return concurrent.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { return unit.Organizations().CreateWithOwner(ctx, company, membership) }) }) fixture.assertSameHolding(t, owner.ID, organizationIDs...) if got := fixture.holdingCount(t, owner.ID); got != 1 { t.Fatalf("holdings of the founder = %d, want 1", got) } }) t.Run("an unknown founder stores no holding", func(t *testing.T) { before := fixture.totalHoldings(t) unknown := uuid.New() profile := mustOrganizationProfile(t, domain.OrganizationProfileInput{Name: "Orphan company"}) company, err := domain.NewOrganization(profile, fixture.clock.Now().Add(-time.Minute)) if err != nil { t.Fatalf("NewOrganization() error = %v", err) } membership, err := domain.NewOwnerMembership(company.ID(), unknown, company.CreatedAt()) if err != nil { t.Fatalf("NewOwnerMembership() error = %v", err) } err = fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { return unit.Organizations().CreateWithOwner(ctx, company, membership) }) if !errors.Is(err, outbound.ErrUserNotFound) { t.Fatalf("CreateWithOwner(unknown founder) error = %v, want ErrUserNotFound", err) } if after := fixture.totalHoldings(t); after != before { t.Fatalf("holdings = %d after the refused creation, want %d", after, before) } }) } // uniqueHoldingEmail returns a fresh address so that every subtest creates its // own account and therefore its own holding. func uniqueHoldingEmail(prefix string) string { return fmt.Sprintf("holding-%s-%s@example.test", prefix, uuid.NewString()) } // newConcurrentTransactor opens a pool of the isolated database that lets every // goroutine of a subtest run its transaction at the same time. func newConcurrentTransactor(ctx context.Context, t *testing.T, databaseURL string) *postgresadapter.Transactor { t.Helper() poolConfig, err := pgxpool.ParseConfig(databaseURL) if err != nil { t.Fatalf("parse isolated database URL: %v", err) } poolConfig.MaxConns = holdingConcurrentConns pool, err := pgxpool.NewWithConfig(ctx, poolConfig) if err != nil { t.Fatalf("create concurrent PostgreSQL pool: %v", err) } t.Cleanup(pool.Close) return postgresadapter.NewTransactor(pool) } // runConcurrently calls work for every index at once, after all goroutines // have started, and fails the test on the first error. work must not call // testing methods that stop the test goroutine. func runConcurrently(t *testing.T, count int, work func(index int) error) { t.Helper() errs := make([]error, count) start := make(chan struct{}) done := make(chan struct{}, count) for index := range count { go func() { defer func() { done <- struct{}{} }() <-start errs[index] = work(index) }() } close(start) for range count { <-done } for index, err := range errs { if err != nil { t.Fatalf("concurrent call %d error = %v", index, err) } } } // reserveInvitationLocked reserves one invitation the way the production // callers do: the organization lock first, then the reservation, in one // transaction. func (fixture companyQuotaFixture) reserveInvitationLocked( transactor *postgresadapter.Transactor, organization domain.Organization, invitationID uuid.UUID, ) (outbound.CompanyQuotaDecision, error) { var decision outbound.CompanyQuotaDecision err := transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { if err := unit.CompanyQuotas().LockOrganization(ctx, organization.ID()); err != nil { return err } var err error decision, err = fixture.service.ReserveInvitation(ctx, unit, organization, invitationID) return err }) return decision, err } // reserveCardViewLocked is reserveInvitationLocked for a distinct card view. func (fixture companyQuotaFixture) reserveCardViewLocked( transactor *postgresadapter.Transactor, organization domain.Organization, candidateID uuid.UUID, ) (outbound.CompanyQuotaDecision, error) { var decision outbound.CompanyQuotaDecision err := transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { if err := unit.CompanyQuotas().LockOrganization(ctx, organization.ID()); err != nil { return err } var err error decision, err = fixture.service.ReserveCardView(ctx, unit, organization, candidateID) return err }) return decision, err } // assertSameHolding checks that every organization is in the holding of the // owner and that the owner has exactly one holding. func (fixture companyQuotaFixture) assertSameHolding(t *testing.T, founderID uuid.UUID, organizationIDs ...uuid.UUID) { t.Helper() if got := fixture.holdingCount(t, founderID); got != 1 { t.Fatalf("holdings of the founder = %d, want 1", got) } want := fixture.holdingOf(t, organizationIDs[0]) for _, organizationID := range organizationIDs { if got := fixture.holdingOf(t, organizationID); got != want { t.Fatalf("organization %s is in holding %s, want %s", organizationID, got, want) } } } func (fixture companyQuotaFixture) holdingOf(t *testing.T, organizationID uuid.UUID) uuid.UUID { t.Helper() var holdingID uuid.UUID if err := fixture.pool.QueryRow(fixture.ctx, `SELECT holding_id FROM organizations WHERE id = $1`, organizationID).Scan(&holdingID); err != nil { t.Fatalf("read holding of organization: %v", err) } return holdingID } func (fixture companyQuotaFixture) holdingCount(t *testing.T, founderID uuid.UUID) int64 { t.Helper() var count int64 if err := fixture.pool.QueryRow(fixture.ctx, `SELECT count(*) FROM holdings WHERE founder_account_id = $1`, founderID).Scan(&count); err != nil { t.Fatalf("count holdings of founder: %v", err) } return count } func (fixture companyQuotaFixture) totalHoldings(t *testing.T) int64 { t.Helper() var count int64 if err := fixture.pool.QueryRow(fixture.ctx, `SELECT count(*) FROM holdings`).Scan(&count); err != nil { t.Fatalf("count holdings: %v", err) } return count } // assertInvitationDenied checks that the organization cannot reserve a new // invitation and that the denial retries at retryAt. func (fixture companyQuotaFixture) assertInvitationDenied(t *testing.T, organization domain.Organization, retryAt time.Time) { t.Helper() decision, err := fixture.reserveInvitation(organization, fixture.newInvitationID(t, organization)) if err != nil || decision.Allowed || !decision.RetryAt.Equal(retryAt) { t.Fatalf("ReserveInvitation() = %+v, %v; want a denial that retries at %s", decision, err, retryAt) } } // assertCardViewDenied is assertInvitationDenied for a distinct card view. func (fixture companyQuotaFixture) assertCardViewDenied(t *testing.T, organization domain.Organization, retryAt time.Time) { t.Helper() decision, err := fixture.reserveCardView(organization, fixture.newCandidateID(t)) if err != nil || decision.Allowed || !decision.RetryAt.Equal(retryAt) { t.Fatalf("ReserveCardView() = %+v, %v; want a denial that retries at %s", decision, err, retryAt) } } // assertOneAllowed checks that exactly one of the decisions was allowed and // that the others were denied with the given retry time. func (fixture companyQuotaFixture) assertOneAllowed(t *testing.T, decisions []outbound.CompanyQuotaDecision, retryAt time.Time) { t.Helper() allowed := 0 for _, decision := range decisions { switch { case decision.Allowed && decision.RetryAt.IsZero() && !decision.Reused: allowed++ case !decision.Allowed && decision.RetryAt.Equal(retryAt): default: t.Fatalf("unexpected concurrent decision %+v, want retry at %s", decision, retryAt) } } if allowed != 1 { t.Fatalf("allowed concurrent reservations = %d, want exactly 1 of %d", allowed, len(decisions)) } } // assertInvitationRowsOf checks the invitation usage stored for the given // organizations together, which is the count of the shared pool. func (fixture companyQuotaFixture) assertInvitationRowsOf(t *testing.T, want int64, organizationIDs ...uuid.UUID) { t.Helper() var got int64 if err := fixture.pool.QueryRow(fixture.ctx, ` SELECT count(*) FROM company_invitation_quota_usage WHERE organization_id = ANY($1)`, organizationIDs).Scan(&got); err != nil { t.Fatalf("count invitation usage rows: %v", err) } if got != want { t.Fatalf("invitation usage rows of the pool = %d, want %d", got, want) } } // assertCardViewRowsOf is assertInvitationRowsOf for distinct card views. func (fixture companyQuotaFixture) assertCardViewRowsOf(t *testing.T, want int64, organizationIDs ...uuid.UUID) { t.Helper() var got int64 if err := fixture.pool.QueryRow(fixture.ctx, ` SELECT count(*) FROM company_card_view_quota_usage WHERE organization_id = ANY($1)`, organizationIDs).Scan(&got); err != nil { t.Fatalf("count card-view usage rows: %v", err) } if got != want { t.Fatalf("card-view usage rows of the pool = %d, want %d", got, want) } }