588 lines
26 KiB
Go
588 lines
26 KiB
Go
//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"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
|
|
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.MaxNeedSnapshotStorageBytes+1)
|
|
oversized, err := json.Marshal(body)
|
|
if err != nil {
|
|
t.Fatalf("encode oversized storage snapshot: %v", err)
|
|
}
|
|
insertRejectedSnapshot(largeID, oversized, "insert oversized snapshot")
|
|
})
|
|
|
|
t.Run("maximum bounded need shape stays within JSONB representation headroom", func(t *testing.T) {
|
|
reset(t)
|
|
owner := fixture.employer(t, "owner@example.com")
|
|
organization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Большой профиль"), now)
|
|
maximum := maximumBoundedIntegrationNeed(t, organization.ID(), now.Add(time.Minute))
|
|
compact, err := json.Marshal(maximum.Snapshot())
|
|
if err != nil {
|
|
t.Fatalf("marshal maximum bounded need: %v", err)
|
|
}
|
|
if len(compact) > domain.MaxNeedSnapshotBytes {
|
|
t.Fatalf("maximum bounded need compact JSON = %d bytes, exceeds %d", len(compact), domain.MaxNeedSnapshotBytes)
|
|
}
|
|
if len(compact) < 64*1024 {
|
|
t.Fatalf("maximum bounded need compact JSON = %d bytes, want a substantial combined source and requirement payload", len(compact))
|
|
}
|
|
fixture.createNeed(t, maximum)
|
|
var storedBytes int
|
|
if err := pool.QueryRow(ctx, `
|
|
SELECT octet_length(snapshot::text)
|
|
FROM organization_need_versions
|
|
WHERE organization_id = $1 AND need_id = $2 AND version = 1
|
|
`, organization.ID(), maximum.ID()).Scan(&storedBytes); err != nil {
|
|
t.Fatalf("measure maximum need JSONB text size: %v", err)
|
|
}
|
|
if storedBytes < len(compact) || storedBytes-len(compact) > domain.MaxNeedJSONBTextHeadroom || storedBytes > domain.MaxNeedSnapshotStorageBytes {
|
|
t.Fatalf("maximum need storage = %d bytes, compact=%d headroom=%d; want storage within the explicit JSONB margin",
|
|
storedBytes, len(compact), domain.MaxNeedJSONBTextHeadroom)
|
|
}
|
|
if _, err := fixture.getNeed(organization.ID(), maximum.ID()); err != nil {
|
|
t.Fatalf("restore maximum bounded need: %v", err)
|
|
}
|
|
})
|
|
}
|
|
|
|
// needCreationResultMigrationVersion is the migration that creates
|
|
// organization_need_creation_results.
|
|
const needCreationResultMigrationVersion = 26
|
|
|
|
func TestNeedCreationResultMigrationRollbackPreflight(t *testing.T) {
|
|
env := bootstrap(t, postgresService)
|
|
ctx, cancel := context.WithTimeout(t.Context(), organizationTestTimeout)
|
|
defer cancel()
|
|
databaseURL := env.createIsolatedDatabase(ctx, t)
|
|
migrator := newMigrator(t, databaseURL)
|
|
if _, err := migrator.Up(ctx); err != nil {
|
|
t.Fatalf("apply migrations to rollback test database: %v", err)
|
|
}
|
|
// The preflight belongs to the migration that created the replay table, so
|
|
// the migrations added after it are rolled back first. The database holds
|
|
// no data yet, which keeps their own guarded rollbacks out of this test.
|
|
rollBackAboveMigration(ctx, t, migrator, needCreationResultMigrationVersion)
|
|
pool := newPoolFor(ctx, t, databaseURL)
|
|
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,
|
|
}
|
|
scope := []byte(strings.Repeat("s", outbound.IdempotencyDigestSize))
|
|
fingerprint := []byte(strings.Repeat("f", outbound.IdempotencyDigestSize))
|
|
if _, err := pool.Exec(ctx, `
|
|
INSERT INTO idempotency_records (scope_hash, fingerprint, created_at, expires_at)
|
|
VALUES ($1, $2, $3, $4)
|
|
`, scope, fingerprint, now, now.Add(outbound.IdempotencyRetention)); err != nil {
|
|
t.Fatalf("insert live idempotency row: %v", err)
|
|
}
|
|
if _, err := pool.Exec(ctx, `
|
|
INSERT INTO organization_need_creation_results (scope_hash, snapshot)
|
|
VALUES ($1, '{"need":{},"readiness":{},"recommendations":{}}'::jsonb)
|
|
`, scope); err != nil {
|
|
t.Fatalf("insert live creation result: %v", err)
|
|
}
|
|
if _, err := migrator.DownOne(ctx); err == nil {
|
|
t.Fatal("DownOne() succeeded while a need creation replay remained live")
|
|
}
|
|
assertNeedResultMigrationPresent(ctx, t, pool, 1)
|
|
|
|
if _, err := pool.Exec(ctx, "UPDATE idempotency_records SET created_at = $1, expires_at = $2 WHERE scope_hash = $3",
|
|
now.Add(-outbound.IdempotencyRetention-time.Second), now.Add(-time.Second), scope); err != nil {
|
|
t.Fatalf("expire idempotency replay before checking historical bounds: %v", err)
|
|
}
|
|
owner := fixture.employer(t, "need-migration-owner@example.test")
|
|
organization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Миграция needs"), now)
|
|
need := newIntegrationNeed(t, organization.ID(), "Bounded rollback fixture", now.Add(time.Minute))
|
|
encoded, err := json.Marshal(need.Snapshot())
|
|
if err != nil {
|
|
t.Fatalf("marshal rollback snapshot: %v", err)
|
|
}
|
|
var body map[string]any
|
|
if err := json.Unmarshal(encoded, &body); err != nil {
|
|
t.Fatalf("decode rollback snapshot: %v", err)
|
|
}
|
|
body["rollback_bound_fixture"] = strings.Repeat("p", 265000)
|
|
encoded, err = json.Marshal(body)
|
|
if err != nil {
|
|
t.Fatalf("encode rollback-bound snapshot: %v", err)
|
|
}
|
|
var storageSize int
|
|
if err := pool.QueryRow(ctx, "SELECT octet_length($1::jsonb::text)", encoded).Scan(&storageSize); err != nil {
|
|
t.Fatalf("measure rollback-bound snapshot: %v", err)
|
|
}
|
|
if storageSize <= domain.MaxNeedSnapshotBytes || storageSize > domain.MaxNeedSnapshotStorageBytes {
|
|
t.Fatalf("rollback fixture JSONB size = %d, want (%d, %d]", storageSize, domain.MaxNeedSnapshotBytes, domain.MaxNeedSnapshotStorageBytes)
|
|
}
|
|
tx, err := pool.Begin(ctx)
|
|
if err != nil {
|
|
t.Fatalf("begin oversized-history fixture transaction: %v", 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)
|
|
`, need.ID(), organization.ID(), now.Add(time.Minute)); err != nil {
|
|
t.Fatalf("insert oversized-history need parent: %v", err)
|
|
}
|
|
if _, err := tx.Exec(ctx, `
|
|
INSERT INTO organization_need_versions (organization_id, need_id, version, snapshot)
|
|
VALUES ($1, $2, 1, $3::jsonb)
|
|
`, organization.ID(), need.ID(), encoded); err != nil {
|
|
t.Fatalf("insert snapshot within current storage bound: %v", err)
|
|
}
|
|
if err := tx.Commit(ctx); err != nil {
|
|
t.Fatalf("commit oversized-history fixture: %v", err)
|
|
}
|
|
if _, err := migrator.DownOne(ctx); err == nil {
|
|
t.Fatal("DownOne() succeeded while retained need history exceeded the prior bound")
|
|
}
|
|
assertNeedResultMigrationPresent(ctx, t, pool, 1)
|
|
}
|
|
|
|
func assertNeedResultMigrationPresent(ctx context.Context, t *testing.T, pool *pgxpool.Pool, resultRows int64) {
|
|
t.Helper()
|
|
var tableExists bool
|
|
var rows int64
|
|
if err := pool.QueryRow(ctx, `
|
|
SELECT to_regclass('organization_need_creation_results') IS NOT NULL,
|
|
(SELECT count(*) FROM organization_need_creation_results)
|
|
`).Scan(&tableExists, &rows); err != nil {
|
|
t.Fatalf("inspect migration preflight after rollback attempt: %v", err)
|
|
}
|
|
if !tableExists || rows != resultRows {
|
|
t.Fatalf("migration rollback changed state: result table exists=%t rows=%d, want true/%d", tableExists, rows, resultRows)
|
|
}
|
|
}
|
|
|
|
func maximumBoundedIntegrationNeed(t *testing.T, organizationID uuid.UUID, at time.Time) domain.Need {
|
|
t.Helper()
|
|
quote := strings.Repeat("q", 300)
|
|
extractedVersion := int64(1)
|
|
extractor := "need-rules.2026-10.1"
|
|
source := domain.NeedValueSource{
|
|
Origin: domain.NeedValueExtractedFromText, Quote: "e,
|
|
ExtractedInVersion: &extractedVersion, ExtractionVersion: &extractor,
|
|
}
|
|
makeSkills := func(prefix string) []domain.NeedSkill {
|
|
skills := make([]domain.NeedSkill, 0, 30)
|
|
for index := range 30 {
|
|
name := fmt.Sprintf("%s-%02d-%s", prefix, index, strings.Repeat("s", 80))
|
|
skills = append(skills, domain.NeedSkill{Name: name, Status: domain.NeedItemExtracted, Source: source})
|
|
}
|
|
return skills
|
|
}
|
|
tasks := make([]domain.NeedTask, 0, 20)
|
|
for index := range 20 {
|
|
prefix := fmt.Sprintf("task-%02d-", index)
|
|
tasks = append(tasks, domain.NeedTask{
|
|
Text: prefix + strings.Repeat("t", 290-len(prefix)), Status: domain.NeedItemExtracted, Source: source,
|
|
})
|
|
}
|
|
rejected := make([]domain.NeedRejectedSuggestion, 0, domain.MaxNeedRejectedSuggestions)
|
|
for index := range domain.MaxNeedRejectedSuggestions {
|
|
rejected = append(rejected, domain.NeedRejectedSuggestion{
|
|
Field: domain.NeedRejectedSkills, Value: fmt.Sprintf("rejected-%02d-%s", index, strings.Repeat("r", 280)),
|
|
})
|
|
}
|
|
manual := &domain.NeedValueSource{Origin: domain.NeedValueManual}
|
|
formats := []domain.NeedWorkFormat{domain.NeedWorkFormatRemote, domain.NeedWorkFormatOffice, domain.NeedWorkFormatHybrid}
|
|
grade := domain.GradeSenior
|
|
specialization := domain.SpecializationBackend
|
|
domainName := strings.Repeat("d", 100)
|
|
location := strings.Repeat("l", 100)
|
|
formatValue := formats
|
|
salary := domain.NeedSalaryRange{SalaryFrom: 100000, SalaryTo: 120000, Currency: "RUB", Period: "month", TaxBasis: "gross"}
|
|
requirements := domain.NeedRequirements{
|
|
Specialization: domain.NeedValue[domain.SpecializationCode]{Status: domain.NeedValueConfirmed, Value: &specialization, Source: manual},
|
|
Grade: domain.NeedValue[domain.GradeCode]{Status: domain.NeedValueConfirmed, Value: &grade, Source: manual},
|
|
RequiredSkills: makeSkills("required"), DesiredSkills: makeSkills("desired"), Tasks: tasks,
|
|
Domain: domain.NeedValue[string]{Status: domain.NeedValueConfirmed, Value: &domainName, Source: manual},
|
|
WorkFormats: domain.NeedValue[[]domain.NeedWorkFormat]{Status: domain.NeedValueConfirmed, Value: &formatValue, Source: manual},
|
|
Location: domain.NeedValue[string]{Status: domain.NeedValueConfirmed, Value: &location, Source: manual},
|
|
Salary: domain.NeedValue[domain.NeedSalaryRange]{Status: domain.NeedValueConfirmed, Value: &salary, Source: manual},
|
|
}
|
|
need, err := domain.NewNeed(domain.NeedSnapshot{
|
|
ID: uuid.New(), OrganizationID: organizationID, Title: strings.Repeat("n", 200), SourceText: needIntegrationPointer(strings.Repeat("s", 10000)),
|
|
Version: 1, RequirementsVersion: 1, Requirements: requirements, RejectedSuggestions: rejected,
|
|
CreatedAt: at, UpdatedAt: at,
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("NewNeed(maximum bounded shape) error = %v", err)
|
|
}
|
|
return need
|
|
}
|
|
|
|
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 }
|