478 lines
17 KiB
Go
478 lines
17 KiB
Go
package need
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha256"
|
|
"errors"
|
|
"fmt"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"lincodex/backend/internal/domain"
|
|
"lincodex/backend/internal/port/outbound"
|
|
)
|
|
|
|
type serviceTestKeyring struct{}
|
|
|
|
func (serviceTestKeyring) IdempotencyScope(operation, key, principal string) [outbound.IdempotencyDigestSize]byte {
|
|
return sha256.Sum256([]byte(operation + "\x00" + key + "\x00" + principal))
|
|
}
|
|
|
|
func (serviceTestKeyring) Fingerprint(body []byte) [outbound.IdempotencyDigestSize]byte {
|
|
return sha256.Sum256(body)
|
|
}
|
|
|
|
type serviceTestState struct {
|
|
users map[uuid.UUID]domain.User
|
|
memberships map[serviceTestMembershipKey]domain.Membership
|
|
needs map[serviceTestNeedKey]domain.Need
|
|
versions map[serviceTestVersionKey]domain.Need
|
|
idempotency map[[outbound.IdempotencyDigestSize]byte]outbound.IdempotencyRecord
|
|
results map[[outbound.IdempotencyDigestSize]byte]domain.NeedResponseSnapshot
|
|
createCount int
|
|
updateCount int
|
|
}
|
|
|
|
type serviceTestMembershipKey struct {
|
|
organizationID uuid.UUID
|
|
userID uuid.UUID
|
|
}
|
|
|
|
type serviceTestNeedKey struct {
|
|
organizationID uuid.UUID
|
|
needID uuid.UUID
|
|
}
|
|
|
|
type serviceTestVersionKey struct {
|
|
serviceTestNeedKey
|
|
|
|
version int64
|
|
}
|
|
|
|
func newServiceTestState() serviceTestState {
|
|
return serviceTestState{
|
|
users: map[uuid.UUID]domain.User{}, memberships: map[serviceTestMembershipKey]domain.Membership{},
|
|
needs: map[serviceTestNeedKey]domain.Need{}, versions: map[serviceTestVersionKey]domain.Need{},
|
|
idempotency: map[[outbound.IdempotencyDigestSize]byte]outbound.IdempotencyRecord{},
|
|
results: map[[outbound.IdempotencyDigestSize]byte]domain.NeedResponseSnapshot{},
|
|
}
|
|
}
|
|
|
|
func (state serviceTestState) clone() serviceTestState {
|
|
cloned := newServiceTestState()
|
|
for id, user := range state.users {
|
|
cloned.users[id] = user
|
|
}
|
|
for key, membership := range state.memberships {
|
|
cloned.memberships[key] = membership
|
|
}
|
|
for key, need := range state.needs {
|
|
copyNeed, err := domain.RestoreNeed(need.Snapshot())
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
cloned.needs[key] = copyNeed
|
|
}
|
|
for key, need := range state.versions {
|
|
copyNeed, err := domain.RestoreNeed(need.Snapshot())
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
cloned.versions[key] = copyNeed
|
|
}
|
|
for scope, record := range state.idempotency {
|
|
cloned.idempotency[scope] = record
|
|
}
|
|
for scope, result := range state.results {
|
|
copyResult, err := domain.RestoreNeedResponseSnapshot(result)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
cloned.results[scope] = copyResult
|
|
}
|
|
cloned.createCount = state.createCount
|
|
cloned.updateCount = state.updateCount
|
|
return cloned
|
|
}
|
|
|
|
type serviceTestTransactor struct {
|
|
mu sync.Mutex
|
|
|
|
state serviceTestState
|
|
failResultSave bool
|
|
}
|
|
|
|
func newServiceTestTransactor(state serviceTestState) *serviceTestTransactor {
|
|
return &serviceTestTransactor{state: state}
|
|
}
|
|
|
|
func (transactor *serviceTestTransactor) WithinTransaction(ctx context.Context, work func(context.Context, outbound.UnitOfWork) error) error {
|
|
transactor.mu.Lock()
|
|
defer transactor.mu.Unlock()
|
|
working := transactor.state.clone()
|
|
unit := &serviceTestUnit{state: &working, failResultSave: transactor.failResultSave}
|
|
if err := work(ctx, unit); err != nil {
|
|
return err
|
|
}
|
|
transactor.state = working
|
|
return nil
|
|
}
|
|
|
|
func (transactor *serviceTestTransactor) snapshot() serviceTestState {
|
|
transactor.mu.Lock()
|
|
defer transactor.mu.Unlock()
|
|
return transactor.state.clone()
|
|
}
|
|
|
|
type serviceTestUnit struct {
|
|
outbound.UnitOfWork
|
|
|
|
state *serviceTestState
|
|
failResultSave bool
|
|
}
|
|
|
|
func (unit *serviceTestUnit) Users() outbound.UserRepository {
|
|
return serviceTestUsers{state: unit.state}
|
|
}
|
|
|
|
func (unit *serviceTestUnit) Organizations() outbound.OrganizationRepository {
|
|
return serviceTestOrganizations{state: unit.state}
|
|
}
|
|
|
|
func (unit *serviceTestUnit) IdempotencyRecords() outbound.IdempotencyRepository {
|
|
return serviceTestIdempotency{state: unit.state}
|
|
}
|
|
|
|
func (unit *serviceTestUnit) Needs() outbound.NeedRepository {
|
|
return serviceTestNeeds{state: unit.state, failResultSave: unit.failResultSave}
|
|
}
|
|
|
|
func (unit *serviceTestUnit) NeedLists() outbound.NeedListRepository {
|
|
return serviceTestNeeds{state: unit.state, failResultSave: unit.failResultSave}
|
|
}
|
|
|
|
func (unit *serviceTestUnit) NeedCreationResults() outbound.NeedCreationResultRepository {
|
|
return serviceTestNeeds{state: unit.state, failResultSave: unit.failResultSave}
|
|
}
|
|
|
|
type serviceTestUsers struct {
|
|
outbound.UserRepository
|
|
|
|
state *serviceTestState
|
|
}
|
|
|
|
func (repository serviceTestUsers) GetByID(_ context.Context, id uuid.UUID) (domain.User, error) {
|
|
user, ok := repository.state.users[id]
|
|
if !ok {
|
|
return domain.User{}, outbound.ErrUserNotFound
|
|
}
|
|
return user, nil
|
|
}
|
|
|
|
type serviceTestOrganizations struct {
|
|
outbound.OrganizationRepository
|
|
|
|
state *serviceTestState
|
|
}
|
|
|
|
func (repository serviceTestOrganizations) LockActiveMembership(_ context.Context, organizationID, userID uuid.UUID) (domain.Membership, error) {
|
|
membership, ok := repository.state.memberships[serviceTestMembershipKey{organizationID: organizationID, userID: userID}]
|
|
if !ok || !membership.GrantsAccess() {
|
|
return domain.Membership{}, outbound.ErrOrganizationNotFound
|
|
}
|
|
return membership, nil
|
|
}
|
|
|
|
type serviceTestIdempotency struct {
|
|
outbound.IdempotencyRepository
|
|
|
|
state *serviceTestState
|
|
}
|
|
|
|
func (repository serviceTestIdempotency) Reserve(_ context.Context, record outbound.IdempotencyRecord) (outbound.IdempotencyRecord, bool, error) {
|
|
if existing, ok := repository.state.idempotency[record.Scope]; ok && existing.ExpiresAt.After(record.CreatedAt) {
|
|
return existing, false, nil
|
|
}
|
|
repository.state.idempotency[record.Scope] = record
|
|
return record, true, nil
|
|
}
|
|
|
|
func (repository serviceTestIdempotency) Find(_ context.Context, scope [outbound.IdempotencyDigestSize]byte, at time.Time) (outbound.IdempotencyRecord, error) {
|
|
record, ok := repository.state.idempotency[scope]
|
|
if !ok || !record.ExpiresAt.After(at) {
|
|
return outbound.IdempotencyRecord{}, outbound.ErrIdempotencyRecordNotFound
|
|
}
|
|
return record, nil
|
|
}
|
|
|
|
func (repository serviceTestIdempotency) PurgeExpired(_ context.Context, at time.Time, limit int32) (int64, error) {
|
|
var deleted int64
|
|
for scope, record := range repository.state.idempotency {
|
|
if deleted >= int64(limit) {
|
|
break
|
|
}
|
|
if !record.ExpiresAt.After(at) {
|
|
delete(repository.state.idempotency, scope)
|
|
delete(repository.state.results, scope)
|
|
deleted++
|
|
}
|
|
}
|
|
return deleted, nil
|
|
}
|
|
|
|
type serviceTestNeeds struct {
|
|
outbound.NeedRepository
|
|
|
|
state *serviceTestState
|
|
failResultSave bool
|
|
}
|
|
|
|
func (repository serviceTestNeeds) Create(_ context.Context, need domain.Need) error {
|
|
key := serviceTestNeedKey{organizationID: need.OrganizationID(), needID: need.ID()}
|
|
if _, exists := repository.state.needs[key]; exists {
|
|
return outbound.ErrNeedAlreadyExists
|
|
}
|
|
repository.state.needs[key] = need
|
|
repository.state.versions[serviceTestVersionKey{serviceTestNeedKey: key, version: need.Version()}] = need
|
|
repository.state.createCount++
|
|
return nil
|
|
}
|
|
|
|
func (repository serviceTestNeeds) Get(_ context.Context, organizationID, needID uuid.UUID) (domain.Need, error) {
|
|
need, ok := repository.state.needs[serviceTestNeedKey{organizationID: organizationID, needID: needID}]
|
|
if !ok {
|
|
return domain.Need{}, outbound.ErrNeedNotFound
|
|
}
|
|
return need, nil
|
|
}
|
|
|
|
func (repository serviceTestNeeds) GetVersion(_ context.Context, organizationID, needID uuid.UUID, version int64) (domain.Need, error) {
|
|
need, ok := repository.state.versions[serviceTestVersionKey{serviceTestNeedKey: serviceTestNeedKey{organizationID: organizationID, needID: needID}, version: version}]
|
|
if !ok {
|
|
return domain.Need{}, outbound.ErrNeedNotFound
|
|
}
|
|
return need, nil
|
|
}
|
|
|
|
func (repository serviceTestNeeds) Save(_ context.Context, organizationID, needID uuid.UUID, expectedVersion int64, next domain.Need) error {
|
|
key := serviceTestNeedKey{organizationID: organizationID, needID: needID}
|
|
current, ok := repository.state.needs[key]
|
|
if !ok {
|
|
return outbound.ErrNeedNotFound
|
|
}
|
|
if !current.IsNextVersionOf(next, expectedVersion) {
|
|
return outbound.ErrNeedVersionConflict
|
|
}
|
|
repository.state.needs[key] = next
|
|
repository.state.versions[serviceTestVersionKey{serviceTestNeedKey: key, version: next.Version()}] = next
|
|
repository.state.updateCount++
|
|
return nil
|
|
}
|
|
|
|
func (repository serviceTestNeeds) List(_ context.Context, query outbound.NeedListQuery) (outbound.NeedPage, error) {
|
|
items := make([]domain.Need, 0)
|
|
for key, need := range repository.state.needs {
|
|
if key.organizationID != query.OrganizationID {
|
|
continue
|
|
}
|
|
position := outbound.NeedCreationPosition(need)
|
|
if query.After != nil && needPositionIsNotBefore(position, *query.After) {
|
|
continue
|
|
}
|
|
items = append(items, need)
|
|
}
|
|
for left := 0; left < len(items); left++ {
|
|
for right := left + 1; right < len(items); right++ {
|
|
leftPosition, rightPosition := outbound.NeedCreationPosition(items[left]), outbound.NeedCreationPosition(items[right])
|
|
if rightPosition.CreatedAt.After(leftPosition.CreatedAt) || rightPosition.CreatedAt.Equal(leftPosition.CreatedAt) && rightPosition.NeedID.String() > leftPosition.NeedID.String() {
|
|
items[left], items[right] = items[right], items[left]
|
|
}
|
|
}
|
|
}
|
|
page := outbound.NeedPage{Items: make([]domain.Need, 0, min(int(query.Limit), len(items)))}
|
|
if len(items) > int(query.Limit) {
|
|
page.HasMore = true
|
|
items = items[:query.Limit]
|
|
}
|
|
page.Items = append(page.Items, items...)
|
|
return page, nil
|
|
}
|
|
|
|
func needPositionIsNotBefore(position, after outbound.NeedListPosition) bool {
|
|
if position.CreatedAt.After(after.CreatedAt) {
|
|
return true
|
|
}
|
|
if position.CreatedAt.Before(after.CreatedAt) {
|
|
return false
|
|
}
|
|
return position.NeedID.String() >= after.NeedID.String()
|
|
}
|
|
|
|
func (repository serviceTestNeeds) SaveCreationResult(_ context.Context, scope [outbound.IdempotencyDigestSize]byte, snapshot domain.NeedResponseSnapshot) error {
|
|
if repository.failResultSave {
|
|
return errors.New("simulated response snapshot failure")
|
|
}
|
|
if _, ok := repository.state.idempotency[scope]; !ok {
|
|
return outbound.ErrIdempotencyRecordNotFound
|
|
}
|
|
repository.state.results[scope] = snapshot
|
|
return nil
|
|
}
|
|
|
|
func (repository serviceTestNeeds) GetCreationResult(_ context.Context, scope [outbound.IdempotencyDigestSize]byte) (domain.NeedResponseSnapshot, error) {
|
|
snapshot, ok := repository.state.results[scope]
|
|
if !ok {
|
|
return domain.NeedResponseSnapshot{}, outbound.ErrNeedCreationResultNotFound
|
|
}
|
|
return snapshot, nil
|
|
}
|
|
|
|
func newNeedServiceHarness(t *testing.T) (*Service, *serviceTestTransactor, uuid.UUID, uuid.UUID, func(time.Time)) {
|
|
t.Helper()
|
|
now := time.Date(2026, time.October, 7, 10, 0, 0, 0, time.UTC)
|
|
current := now
|
|
userID, organizationID := uuid.Must(uuid.NewV7()), uuid.Must(uuid.NewV7())
|
|
verifiedAt := now.Add(-time.Hour)
|
|
state := newServiceTestState()
|
|
state.users[userID] = domain.User{ID: userID, Scenario: domain.ScenarioEmployer, EmailVerifiedAt: &verifiedAt}
|
|
membership, err := domain.NewOwnerMembership(organizationID, userID, now)
|
|
if err != nil {
|
|
t.Fatalf("NewOwnerMembership() error = %v", err)
|
|
}
|
|
state.memberships[serviceTestMembershipKey{organizationID: organizationID, userID: userID}] = membership
|
|
transactor := newServiceTestTransactor(state)
|
|
service, err := NewService(Dependencies{Transactor: transactor, Keyring: serviceTestKeyring{}, Clock: func() time.Time { return current }})
|
|
if err != nil {
|
|
t.Fatalf("NewService() error = %v", err)
|
|
}
|
|
setTime := func(value time.Time) { current = value }
|
|
return service, transactor, userID, organizationID, setTime
|
|
}
|
|
|
|
func testNeedCreateCommand(actorID, organizationID uuid.UUID, key, title string) CreateCommand {
|
|
return CreateCommand{
|
|
ActorID: actorID, OrganizationID: organizationID, IdempotencyKey: key,
|
|
CanonicalBody: []byte(fmt.Sprintf(`{"title":%q}`, title)),
|
|
Input: CreateInput{Title: title},
|
|
}
|
|
}
|
|
|
|
func TestCreateReplaysOriginalNeedAfterUpdate(t *testing.T) {
|
|
service, transactor, actorID, organizationID, _ := newNeedServiceHarness(t)
|
|
command := testNeedCreateCommand(actorID, organizationID, "request-1", "Initial need")
|
|
created, err := service.Create(t.Context(), command)
|
|
if err != nil {
|
|
t.Fatalf("Create() error = %v", err)
|
|
}
|
|
updated, err := service.Update(t.Context(), UpdateCommand{
|
|
ActorID: actorID, OrganizationID: organizationID, NeedID: created.Need.ID,
|
|
Input: UpdateInput{ExpectedVersion: 1, Title: Field[string]{Set: true, Value: "Updated need"}},
|
|
})
|
|
if err != nil || updated.Version() != 2 {
|
|
t.Fatalf("Update() version = %d, error = %v", updated.Version(), err)
|
|
}
|
|
replayed, err := service.Create(t.Context(), command)
|
|
if err != nil || replayed.Need.ID != created.Need.ID || replayed.Need.Version != 1 || replayed.Need.Title != "Initial need" {
|
|
t.Fatalf("Create(retry) = id %s version %d title %q error %v, want the original response", replayed.Need.ID, replayed.Need.Version, replayed.Need.Title, err)
|
|
}
|
|
current, err := service.Get(t.Context(), actorID, organizationID, created.Need.ID)
|
|
if err != nil || current.Version() != 2 || current.Snapshot().Title != "Updated need" {
|
|
t.Fatalf("Get after replay = version %d title %q error %v", current.Version(), current.Snapshot().Title, err)
|
|
}
|
|
state := transactor.snapshot()
|
|
if state.createCount != 1 || state.updateCount != 1 {
|
|
t.Fatalf("stored creates = %d updates = %d, want 1 create and 1 update", state.createCount, state.updateCount)
|
|
}
|
|
command.CanonicalBody = []byte(`{"title":"Different body"}`)
|
|
command.Input.Title = "Different body"
|
|
if _, err := service.Create(t.Context(), command); !errors.Is(err, ErrIdempotencyKeyReused) {
|
|
t.Fatalf("Create(same key, changed body) error = %v, want ErrIdempotencyKeyReused", err)
|
|
}
|
|
}
|
|
|
|
func TestCreateReusesExpiredIdempotencyScopeAtExactDeadline(t *testing.T) {
|
|
service, transactor, actorID, organizationID, setTime := newNeedServiceHarness(t)
|
|
firstCommand := testNeedCreateCommand(actorID, organizationID, "request-2", "Before expiry")
|
|
first, err := service.Create(t.Context(), firstCommand)
|
|
if err != nil {
|
|
t.Fatalf("Create(first) error = %v", err)
|
|
}
|
|
setTime(first.Need.CreatedAt.Add(outbound.IdempotencyRetention))
|
|
secondCommand := testNeedCreateCommand(actorID, organizationID, "request-2", "After expiry")
|
|
second, err := service.Create(t.Context(), secondCommand)
|
|
if err != nil || second.Need.ID == first.Need.ID || second.Need.Title != "After expiry" {
|
|
t.Fatalf("Create(expired key) = id %s title %q error %v", second.Need.ID, second.Need.Title, err)
|
|
}
|
|
state := transactor.snapshot()
|
|
if state.createCount != 2 || len(state.results) != 1 {
|
|
t.Fatalf("stored creates = %d results = %d, want two creates and one replaced snapshot", state.createCount, len(state.results))
|
|
}
|
|
replayed, err := service.Create(t.Context(), secondCommand)
|
|
if err != nil || replayed.Need.ID != second.Need.ID || replayed.Need.Title != "After expiry" {
|
|
t.Fatalf("Create(replay after reuse) = id %s title %q error %v", replayed.Need.ID, replayed.Need.Title, err)
|
|
}
|
|
}
|
|
|
|
func TestCreateRejectsIdempotencyExpiryOutsideNeedDateRange(t *testing.T) {
|
|
service, transactor, actorID, organizationID, setTime := newNeedServiceHarness(t)
|
|
setTime(time.Date(9999, time.December, 31, 23, 59, 59, 0, time.UTC))
|
|
if _, err := service.Create(t.Context(), testNeedCreateCommand(actorID, organizationID, "request-edge", "Edge need")); !errors.Is(err, ErrInvalidRequest) {
|
|
t.Fatalf("Create() at the final contract date error = %v, want ErrInvalidRequest for 24-hour expiry", err)
|
|
}
|
|
state := transactor.snapshot()
|
|
if state.createCount != 0 || len(state.idempotency) != 0 || len(state.results) != 0 {
|
|
t.Fatalf("out-of-range expiry wrote state: creates=%d keys=%d results=%d", state.createCount, len(state.idempotency), len(state.results))
|
|
}
|
|
}
|
|
|
|
func TestCreateRollbackLeavesNoNeedOrReplayResult(t *testing.T) {
|
|
service, transactor, actorID, organizationID, _ := newNeedServiceHarness(t)
|
|
transactor.failResultSave = true
|
|
command := testNeedCreateCommand(actorID, organizationID, "request-3", "Rollback need")
|
|
if _, err := service.Create(t.Context(), command); err == nil {
|
|
t.Fatal("Create() succeeded despite result snapshot failure")
|
|
}
|
|
state := transactor.snapshot()
|
|
if state.createCount != 0 || len(state.needs) != 0 || len(state.idempotency) != 0 || len(state.results) != 0 {
|
|
t.Fatalf("failed create left state: creates %d needs %d keys %d results %d", state.createCount, len(state.needs), len(state.idempotency), len(state.results))
|
|
}
|
|
}
|
|
|
|
func TestConcurrentCreateWithSameKeyCreatesOneNeed(t *testing.T) {
|
|
service, transactor, actorID, organizationID, _ := newNeedServiceHarness(t)
|
|
command := testNeedCreateCommand(actorID, organizationID, "request-4", "One need")
|
|
var group sync.WaitGroup
|
|
errorsFound := make(chan error, 2)
|
|
ids := make(chan uuid.UUID, 2)
|
|
for range 2 {
|
|
group.Go(func() {
|
|
result, err := service.Create(t.Context(), command)
|
|
if err != nil {
|
|
errorsFound <- err
|
|
return
|
|
}
|
|
ids <- result.Need.ID
|
|
})
|
|
}
|
|
group.Wait()
|
|
close(errorsFound)
|
|
for err := range errorsFound {
|
|
t.Fatalf("concurrent Create() error = %v", err)
|
|
}
|
|
close(ids)
|
|
var first uuid.UUID
|
|
for id := range ids {
|
|
if first != uuid.Nil && first != id {
|
|
t.Fatalf("concurrent calls returned different need IDs: %s and %s", first, id)
|
|
}
|
|
first = id
|
|
}
|
|
state := transactor.snapshot()
|
|
if first == uuid.Nil || state.createCount != 1 || len(state.needs) != 1 {
|
|
t.Fatalf("concurrent calls left ID %s, creates %d, needs %d", first, state.createCount, len(state.needs))
|
|
}
|
|
}
|