//go:build integration package integration_test import ( "context" "encoding/json" "errors" "fmt" "strings" "sync" "testing" "time" "github.com/google/uuid" "github.com/jackc/pgx/v5" postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" "lincodex/backend/internal/domain" "lincodex/backend/internal/port/outbound" ) func TestOrganizationNeedsStorage(t *testing.T) { env := bootstrap(t, postgresService) ctx, cancel := context.WithTimeout(t.Context(), organizationTestTimeout) defer cancel() pool := env.newPool(ctx, t) now := time.Now().UTC().Truncate(time.Microsecond) fixture := organizationFixture{ ctx: ctx, pool: pool, identity: identityFixture{ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: now}, transactor: postgresadapter.NewTransactor(pool), now: now, } reset := func(t *testing.T) { t.Helper() truncateTables(ctx, t, pool, usersDependentTables...) } t.Run("creates current and immutable historical snapshots within organization scope", func(t *testing.T) { reset(t) owner := fixture.employer(t, "owner@example.com") organization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Поиск"), now) otherOrganization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Другая компания"), now.Add(time.Minute)) created := newIntegrationNeed(t, organization.ID(), "Разработчик", now.Add(2*time.Minute)) fixture.createNeed(t, created) initial, err := fixture.getNeed(organization.ID(), created.ID()) if err != nil || initial.Version() != 1 || initial.RequirementsVersion() != 1 || initial.Readiness().Status != domain.NeedReadinessIncomplete { t.Fatalf("Get(initial need) = version %d requirements %d error %v, want incomplete version 1", initial.Version(), initial.RequirementsVersion(), err) } proposal := initial.Snapshot() proposal.Title = "Backend developer" proposal.UpdatedAt = now.Add(3 * time.Minute) titleOnly, changed, err := initial.Revise(1, proposal) if err != nil || !changed { t.Fatalf("Revise(title) = changed %v error %v, want a saved change", changed, err) } fixture.saveNeed(t, organization.ID(), created.ID(), 1, titleOnly) proposal = titleOnly.Snapshot() proposal.Requirements.Specialization = domain.NeedValue[domain.SpecializationCode]{ Status: domain.NeedValueConfirmed, Value: needIntegrationPointer(domain.SpecializationBackend), Source: &domain.NeedValueSource{Origin: domain.NeedValueManual}, } proposal.UpdatedAt = now.Add(4 * time.Minute) confirmed, changed, err := titleOnly.Revise(2, proposal) if err != nil || !changed || confirmed.RequirementsVersion() != 3 { t.Fatalf("Revise(confirmed specialization) = requirements %d changed %v error %v, want requirements version 3", confirmed.RequirementsVersion(), changed, err) } fixture.saveNeed(t, organization.ID(), created.ID(), 2, confirmed) current, err := fixture.getNeed(organization.ID(), created.ID()) if err != nil || current.Version() != 3 || current.RequirementsVersion() != 3 || current.Snapshot().Title != "Backend developer" { t.Fatalf("Get(current need) = version %d requirements %d title %q error %v", current.Version(), current.RequirementsVersion(), current.Snapshot().Title, err) } first, err := fixture.getNeedVersion(organization.ID(), created.ID(), 1) if err != nil || first.Snapshot().Title != "Разработчик" || first.RequirementsVersion() != 1 { t.Fatalf("GetVersion(1) = title %q requirements %d error %v", first.Snapshot().Title, first.RequirementsVersion(), err) } second, err := fixture.getNeedVersion(organization.ID(), created.ID(), 2) if err != nil || second.Snapshot().Title != "Backend developer" || second.RequirementsVersion() != 1 { t.Fatalf("GetVersion(2) = title %q requirements %d error %v", second.Snapshot().Title, second.RequirementsVersion(), err) } if _, err := fixture.getNeed(otherOrganization.ID(), created.ID()); !errors.Is(err, outbound.ErrNeedNotFound) { t.Fatalf("Get from another organization error = %v, want ErrNeedNotFound", err) } if _, err := fixture.getNeedVersion(otherOrganization.ID(), created.ID(), 1); !errors.Is(err, outbound.ErrNeedNotFound) { t.Fatalf("GetVersion from another organization error = %v, want ErrNeedNotFound", err) } if _, err := fixture.getNeedVersion(organization.ID(), created.ID(), 4); !errors.Is(err, outbound.ErrNeedNotFound) { t.Fatalf("GetVersion(missing version) error = %v, want ErrNeedNotFound", err) } if err := fixture.createNeedError(created); !errors.Is(err, outbound.ErrNeedAlreadyExists) { t.Fatalf("Create(duplicate ID) error = %v, want ErrNeedAlreadyExists", err) } }) t.Run("rejects nil scope and noninitial creation snapshots", func(t *testing.T) { reset(t) owner := fixture.employer(t, "owner@example.com") organization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Первая версия"), now) created := newIntegrationNeed(t, organization.ID(), "Черновик", now.Add(time.Minute)) for _, scope := range []struct { name string organizationID uuid.UUID needID uuid.UUID }{ {name: "organization", organizationID: uuid.Nil, needID: created.ID()}, {name: "need", organizationID: organization.ID(), needID: uuid.Nil}, } { err := fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { _, err := integrationNeedRepositoryForTest(unit).Get(ctx, scope.organizationID, scope.needID) return err }) if !errors.Is(err, domain.ErrInvalidNeed) { t.Errorf("Get with nil %s ID error = %v, want ErrInvalidNeed", scope.name, err) } } if err := fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { return integrationNeedRepositoryForTest(unit).Create(ctx, domain.Need{}) }); !errors.Is(err, domain.ErrInvalidNeed) { t.Fatalf("Create(zero need) error = %v, want ErrInvalidNeed", err) } laterSnapshot := created.Snapshot() laterSnapshot.Version = 2 later, err := domain.RestoreNeed(laterSnapshot) if err != nil { t.Fatalf("RestoreNeed(version 2) error = %v", err) } err = fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { return integrationNeedRepositoryForTest(unit).Create(ctx, later) }) if !errors.Is(err, domain.ErrInvalidNeed) { t.Fatalf("Create(version 2) error = %v, want ErrInvalidNeed", err) } assertRowCount(ctx, t, pool, pgx.Identifier{"organization_needs"}, 0) assertRowCount(ctx, t, pool, pgx.Identifier{"organization_need_versions"}, 0) }) t.Run("competing compare-and-swap updates have one winner", func(t *testing.T) { reset(t) owner := fixture.employer(t, "owner@example.com") organization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Конкурент"), now) created := newIntegrationNeed(t, organization.ID(), "Исходное название", now.Add(time.Minute)) fixture.createNeed(t, created) concurrent := postgresadapter.NewTransactor(env.newPoolWithMaxConns(ctx, t, 3)) ready := make(chan error, 2) start := make(chan struct{}) errs := make([]error, 2) var group sync.WaitGroup for index := range 2 { group.Go(func() { errs[index] = concurrent.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { repository := integrationNeedRepositoryForTest(unit) current, err := repository.Get(ctx, organization.ID(), created.ID()) if err != nil { ready <- err return err } proposal := current.Snapshot() proposal.Title = fmt.Sprintf("Вариант %d", index+1) proposal.UpdatedAt = now.Add(time.Duration(index+2) * time.Minute) next, changed, err := current.Revise(1, proposal) if err != nil { ready <- err return fmt.Errorf("prepare concurrent need: %w", err) } if !changed { err := domain.ErrInvalidNeed ready <- err return fmt.Errorf("prepare concurrent need: %w", err) } ready <- nil <-start return repository.Save(ctx, organization.ID(), created.ID(), 1, next) }) }) } setupErrors := []error{<-ready, <-ready} close(start) group.Wait() for _, err := range setupErrors { if err != nil { t.Fatalf("prepare concurrent need: %v", err) } } successes := 0 conflicts := 0 for index, err := range errs { switch { case err == nil: successes++ case errors.Is(err, outbound.ErrNeedVersionConflict): conflicts++ default: t.Fatalf("concurrent update %d error = %v, want success or ErrNeedVersionConflict", index, err) } } if successes != 1 || conflicts != 1 { t.Fatalf("concurrent updates had %d successes and %d conflicts, want one each", successes, conflicts) } current, err := fixture.getNeed(organization.ID(), created.ID()) if err != nil || current.Version() != 2 { t.Fatalf("Get after concurrent updates = version %d, error %v, want version 2", current.Version(), err) } }) t.Run("create and save participate in caller rollback", func(t *testing.T) { reset(t) owner := fixture.employer(t, "owner@example.com") organization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Откат"), now) created := newIntegrationNeed(t, organization.ID(), "Новый профиль", now.Add(time.Minute)) rollback := errors.New("roll back need write") err := fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { if err := integrationNeedRepositoryForTest(unit).Create(ctx, created); err != nil { return err } return rollback }) if !errors.Is(err, rollback) { t.Fatalf("create transaction error = %v, want rollback sentinel", err) } if _, err := fixture.getNeed(organization.ID(), created.ID()); !errors.Is(err, outbound.ErrNeedNotFound) { t.Fatalf("Get rolled-back need error = %v, want ErrNeedNotFound", err) } assertRowCount(ctx, t, pool, pgx.Identifier{"organization_needs"}, 0) assertRowCount(ctx, t, pool, pgx.Identifier{"organization_need_versions"}, 0) fixture.createNeed(t, created) current, err := fixture.getNeed(organization.ID(), created.ID()) if err != nil { t.Fatalf("Get need before save rollback: %v", err) } proposal := current.Snapshot() proposal.Title = "Не сохранять" proposal.UpdatedAt = now.Add(2 * time.Minute) next, changed, err := current.Revise(1, proposal) if err != nil || !changed { t.Fatalf("Revise before rollback = changed %t, error %v", changed, err) } err = fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { if err := integrationNeedRepositoryForTest(unit).Save(ctx, organization.ID(), created.ID(), 1, next); err != nil { return err } return rollback }) if !errors.Is(err, rollback) { t.Fatalf("save transaction error = %v, want rollback sentinel", err) } current, err = fixture.getNeed(organization.ID(), created.ID()) if err != nil || current.Version() != 1 || current.Snapshot().Title != "Новый профиль" { t.Fatalf("Get after rolled-back save = version %d title %q error %v", current.Version(), current.Snapshot().Title, err) } assertRowCount(ctx, t, pool, pgx.Identifier{"organization_need_versions"}, 1) }) t.Run("database bounds snapshots and rejects update or deletion", func(t *testing.T) { reset(t) owner := fixture.employer(t, "owner@example.com") organization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Версии"), now) created := newIntegrationNeed(t, organization.ID(), "Неизменяемая версия", now.Add(time.Minute)) fixture.createNeed(t, created) _, err := pool.Exec(ctx, `UPDATE organization_need_versions SET snapshot = snapshot WHERE organization_id = $1 AND need_id = $2 AND version = 1`, organization.ID(), created.ID()) assertSQLError(t, "update immutable need snapshot", err, "23000", "organization_need_versions_immutable") _, err = pool.Exec(ctx, `DELETE FROM organization_need_versions WHERE organization_id = $1 AND need_id = $2 AND version = 1`, organization.ID(), created.ID()) assertSQLError(t, "delete immutable need snapshot", err, "23000", "organization_need_versions_immutable") assertRowCount(ctx, t, pool, pgx.Identifier{"organization_need_versions"}, 1) padded := created.Snapshot() encoded, err := json.Marshal(padded) if err != nil { t.Fatalf("marshal snapshot for storage-bound check: %v", err) } var body map[string]any if err := json.Unmarshal(encoded, &body); err != nil { t.Fatalf("decode snapshot for storage-bound check: %v", err) } insertRejectedSnapshot := func(id uuid.UUID, snapshot []byte, name string) { t.Helper() tx, err := pool.Begin(ctx) if err != nil { t.Fatalf("begin %s transaction: %v", name, err) } defer func() { _ = tx.Rollback(context.WithoutCancel(ctx)) }() if _, err := tx.Exec(ctx, `INSERT INTO organization_needs (id, organization_id, current_version, requirements_version, created_at, updated_at) VALUES ($1, $2, 1, 1, $3, $3)`, id, organization.ID(), now); err != nil { t.Fatalf("insert parent for %s: %v", name, err) } _, err = tx.Exec(ctx, `INSERT INTO organization_need_versions (organization_id, need_id, version, snapshot) VALUES ($1, $2, 1, $3::jsonb)`, organization.ID(), id, snapshot) assertSQLError(t, name, err, organizationCheckViolation, "organization_need_versions_snapshot_shape") } invalidTypeID := uuid.New() body["id"] = invalidTypeID.String() body["requirements_version"] = "1" invalidRequirementsVersion, err := json.Marshal(body) if err != nil { t.Fatalf("encode snapshot with invalid requirements version type: %v", err) } insertRejectedSnapshot(invalidTypeID, invalidRequirementsVersion, "insert string requirements version") largeID := uuid.New() body["id"] = largeID.String() body["requirements_version"] = 1 body["padding"] = strings.Repeat("x", domain.MaxNeedSnapshotBytes+1) oversized, err := json.Marshal(body) if err != nil { t.Fatalf("encode oversized storage snapshot: %v", err) } insertRejectedSnapshot(largeID, oversized, "insert oversized snapshot") }) } func (fixture organizationFixture) createNeed(t *testing.T, need domain.Need) { t.Helper() if err := fixture.createNeedError(need); err != nil { t.Fatalf("Create(need) error = %v", err) } } func (fixture organizationFixture) createNeedError(need domain.Need) error { return fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { return integrationNeedRepositoryForTest(unit).Create(ctx, need) }) } func (fixture organizationFixture) getNeed(organizationID, needID uuid.UUID) (domain.Need, error) { var need domain.Need err := fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { var err error need, err = integrationNeedRepositoryForTest(unit).Get(ctx, organizationID, needID) return err }) return need, err } func (fixture organizationFixture) getNeedVersion(organizationID, needID uuid.UUID, version int64) (domain.Need, error) { var need domain.Need err := fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { var err error need, err = integrationNeedRepositoryForTest(unit).GetVersion(ctx, organizationID, needID, version) return err }) return need, err } func (fixture organizationFixture) saveNeed(t *testing.T, organizationID, needID uuid.UUID, expectedVersion int64, next domain.Need) { t.Helper() if err := fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { return integrationNeedRepositoryForTest(unit).Save(ctx, organizationID, needID, expectedVersion, next) }); err != nil { t.Fatalf("Save(need) error = %v", err) } } func integrationNeedRepositoryForTest(unit outbound.UnitOfWork) outbound.NeedRepository { repositories, ok := unit.(outbound.NeedRepositories) if !ok { panic("unit of work does not expose need repositories") } return repositories.Needs() } func newIntegrationNeed(t *testing.T, organizationID uuid.UUID, title string, at time.Time) domain.Need { t.Helper() need, err := domain.NewNeed(domain.NeedSnapshot{ ID: uuid.New(), OrganizationID: organizationID, Title: title, Version: 1, RequirementsVersion: 1, Requirements: domain.EmptyNeedRequirements(), CreatedAt: at, UpdatedAt: at, }) if err != nil { t.Fatalf("NewNeed() error = %v", err) } return need } func needIntegrationPointer[T any](value T) *T { return &value }