Files

402 lines
16 KiB
Go

package need
import (
"context"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
const (
createOperation = "organization_need.create"
createLocation = "need.Service.Create"
maxIdempotencyKeySize = 255
maxCanonicalBodySize = 1 << 20
purgeExpiredBatch = 100
)
// Keyring computes scoped idempotency digests. identity.Keyring implements
// this interface so need commands use the existing server secret and store.
type Keyring interface {
IdempotencyScope(operation, key, principal string) [outbound.IdempotencyDigestSize]byte
Fingerprint(canonicalBody []byte) [outbound.IdempotencyDigestSize]byte
}
// Dependencies configure one stateless need service.
type Dependencies struct {
Transactor outbound.Transactor
Keyring Keyring
Clock func() time.Time
// Semantic schedules the vectors of a new requirements snapshot; nil
// schedules nothing.
Semantic SemanticTrigger
}
// SemanticTrigger schedules the vectors of a need's requirements snapshot.
type SemanticTrigger interface {
NeedRequirementsChanged(ctx context.Context, unit outbound.UnitOfWork, organizationID, needID uuid.UUID, requirementsVersion int64, at time.Time) error
}
// Service applies organization-scoped need commands and reads.
type Service struct {
transactor outbound.Transactor
keyring Keyring
clock func() time.Time
semantic SemanticTrigger
}
// NewService fails at startup when a required dependency is missing.
func NewService(deps Dependencies) (*Service, error) {
if deps.Transactor == nil || deps.Keyring == nil || deps.Clock == nil {
return nil, errors.New("need.NewService - every dependency must be set")
}
return &Service{transactor: deps.Transactor, keyring: deps.Keyring, clock: deps.Clock, semantic: deps.Semantic}, nil
}
// CreateCommand binds the authenticated actor and path organization to one
// validated create request.
type CreateCommand struct {
ActorID uuid.UUID
OrganizationID uuid.UUID
IdempotencyKey string
CanonicalBody []byte
Input CreateInput
}
// Create returns the original immutable response snapshot, including on an
// identical retry after the live need has changed.
func (service *Service) Create(ctx context.Context, command CreateCommand) (domain.NeedResponseSnapshot, error) {
request, err := service.prepareCreate(command)
if err != nil {
return domain.NeedResponseSnapshot{}, err
}
var result domain.NeedResponseSnapshot
err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
var err error
result, err = service.createInTransaction(ctx, unit, command, request)
return err
})
if err != nil {
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - run transaction: %w", createLocation, err)
}
return result, nil
}
func (service *Service) createInTransaction(
ctx context.Context,
unit outbound.UnitOfWork,
command CreateCommand,
request createRequest,
) (domain.NeedResponseSnapshot, error) {
if err := authorizeNeedOwner(ctx, unit, command.ActorID, command.OrganizationID, createLocation); err != nil {
return domain.NeedResponseSnapshot{}, err
}
stored, created, err := unit.IdempotencyRecords().Reserve(ctx, request.record)
if err != nil {
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - reserve idempotency record: %w", createLocation, err)
}
if !created {
return replayNeedCreation(ctx, unit.NeedCreationResults(), request, command.OrganizationID, stored)
}
needID, err := uuid.NewV7()
if err != nil {
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - generate need ID: %w", createLocation, err)
}
createdNeed, err := createNeed(command.Input, command.OrganizationID, needID, request.now)
if err != nil {
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - validate need: %w", createLocation, err)
}
snapshot := createdNeed.ResponseSnapshot()
if err := validateCreationResultSize(snapshot); err != nil {
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - validate immutable creation response: %w", createLocation, err)
}
if err := unit.Needs().Create(ctx, createdNeed); err != nil {
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - store need: %w", createLocation, err)
}
if err := service.scheduleSemantic(ctx, unit, command.OrganizationID, needID, createdNeed.RequirementsVersion(), request.now); err != nil {
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - %w", createLocation, err)
}
if err := unit.NeedCreationResults().SaveCreationResult(ctx, request.scope, snapshot); err != nil {
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - store immutable creation response: %w", createLocation, err)
}
if _, err := unit.IdempotencyRecords().PurgeExpired(ctx, request.now, purgeExpiredBatch); err != nil {
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - purge expired idempotency records: %w", createLocation, err)
}
return snapshot, nil
}
func replayNeedCreation(
ctx context.Context,
results outbound.NeedCreationResultRepository,
request createRequest,
organizationID uuid.UUID,
stored outbound.IdempotencyRecord,
) (domain.NeedResponseSnapshot, error) {
if stored.Fingerprint != request.fingerprint {
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - compare request fingerprint: %w", createLocation, ErrIdempotencyKeyReused)
}
snapshot, err := results.GetCreationResult(ctx, request.scope)
if err != nil {
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - read immutable creation response: %w", createLocation, err)
}
result, err := domain.RestoreNeedResponseSnapshot(snapshot)
if err != nil || result.Need.OrganizationID != organizationID {
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - validate immutable creation response: %w", createLocation, domain.ErrInvalidNeed)
}
return result, nil
}
func validateCreationResultSize(snapshot domain.NeedResponseSnapshot) error {
encoded, err := json.Marshal(snapshot)
if err != nil {
return fmt.Errorf("%s - encode immutable creation response: %w", createLocation, err)
}
if len(encoded) > domain.MaxNeedCreationResultBytes {
return invalidRequest("", "combined need response exceeds its storage bound")
}
return nil
}
type createRequest struct {
fingerprint [outbound.IdempotencyDigestSize]byte
scope [outbound.IdempotencyDigestSize]byte
record outbound.IdempotencyRecord
now time.Time
}
func (service *Service) prepareCreate(command CreateCommand) (createRequest, error) {
const location = "need.Service.prepareCreate"
switch {
case command.ActorID == uuid.Nil || command.OrganizationID == uuid.Nil:
return createRequest{}, fmt.Errorf("%s - actor and organization IDs must be set: %w", location, ErrForbidden)
case command.IdempotencyKey == "" || len(command.IdempotencyKey) > maxIdempotencyKeySize:
return createRequest{}, fmt.Errorf("%s - idempotency key must have 1 to 255 bytes: %w", location, ErrInvalidIdempotencyKey)
case len(command.CanonicalBody) == 0 || len(command.CanonicalBody) > maxCanonicalBodySize:
return createRequest{}, fmt.Errorf("%s - canonical request body is outside its bound: %w", location, ErrInvalidCreateRequest)
}
fingerprint := service.keyring.Fingerprint(command.CanonicalBody)
principal := command.ActorID.String() + ":" + command.OrganizationID.String()
scope := service.keyring.IdempotencyScope(createOperation, command.IdempotencyKey, principal)
now := service.clock().UTC().Truncate(time.Microsecond)
if !validNeedApplicationTime(now) {
return createRequest{}, invalidRequest("", "application time must be representable by the need contract")
}
expiresAt := now.Add(outbound.IdempotencyRetention)
if !validNeedApplicationTime(expiresAt) {
return createRequest{}, invalidRequest("", "idempotency expiry exceeds the need contract date range")
}
record := outbound.IdempotencyRecord{
Scope: scope, Fingerprint: fingerprint, CreatedAt: now, ExpiresAt: expiresAt,
}
return createRequest{fingerprint: fingerprint, scope: scope, record: record, now: now}, nil
}
// ListCommand selects an owner-scoped page of needs.
type ListCommand struct {
ActorID uuid.UUID
OrganizationID uuid.UUID
After *outbound.NeedListPosition
Limit int32
}
// List reads one page after checking the current account and owner membership
// in the same transaction.
func (service *Service) List(ctx context.Context, command ListCommand) (outbound.NeedPage, error) {
const location = "need.Service.List"
if command.ActorID == uuid.Nil || command.OrganizationID == uuid.Nil {
return outbound.NeedPage{}, fmt.Errorf("%s - actor and organization IDs must be set: %w", location, ErrForbidden)
}
if command.Limit < 1 || command.Limit > outbound.MaxNeedPageSize {
return outbound.NeedPage{}, fmt.Errorf("%s - page limit must be 1 to %d: %w", location, outbound.MaxNeedPageSize, domain.ErrInvalidNeed)
}
var result outbound.NeedPage
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := authorizeNeedOwner(ctx, unit, command.ActorID, command.OrganizationID, location); err != nil {
return err
}
page, err := unit.NeedLists().List(ctx, outbound.NeedListQuery{
OrganizationID: command.OrganizationID, After: command.After, Limit: command.Limit,
})
if err != nil {
return fmt.Errorf("%s - list organization needs: %w", location, err)
}
result = page
return nil
})
if err != nil {
return outbound.NeedPage{}, fmt.Errorf("%s - run transaction: %w", location, err)
}
return result, nil
}
// Get reads the current need version for an active owner.
func (service *Service) Get(ctx context.Context, actorID, organizationID, needID uuid.UUID) (domain.Need, error) {
const location = "need.Service.Get"
if actorID == uuid.Nil || organizationID == uuid.Nil || needID == uuid.Nil {
return domain.Need{}, fmt.Errorf("%s - actor, organization, and need IDs must be set: %w", location, ErrForbidden)
}
var result domain.Need
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := authorizeNeedOwner(ctx, unit, actorID, organizationID, location); err != nil {
return err
}
need, err := unit.Needs().Get(ctx, organizationID, needID)
if err != nil {
return fmt.Errorf("%s - read organization need: %w", location, err)
}
result = need
return nil
})
if err != nil {
return domain.Need{}, fmt.Errorf("%s - run transaction: %w", location, err)
}
return result, nil
}
// Update replaces the fields explicitly supplied by an active owner and
// commits one immutable version when the merged request changes content.
func (service *Service) Update(ctx context.Context, command UpdateCommand) (domain.Need, error) {
const location = "need.Service.Update"
if command.ActorID == uuid.Nil || command.OrganizationID == uuid.Nil || command.NeedID == uuid.Nil {
return domain.Need{}, fmt.Errorf("%s - actor, organization, and need IDs must be set: %w", location, ErrForbidden)
}
if command.Input.ExpectedVersion < 1 {
return domain.Need{}, invalidRequest("/expected_version", "must be positive")
}
now := service.clock().UTC().Truncate(time.Microsecond)
if !validNeedApplicationTime(now) {
return domain.Need{}, invalidRequest("", "application time must be representable by the need contract")
}
var result domain.Need
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
var err error
result, err = service.updateInTransaction(ctx, unit, command, now)
return err
})
if err != nil {
return domain.Need{}, fmt.Errorf("%s - run transaction: %w", location, err)
}
return result, nil
}
func validNeedApplicationTime(value time.Time) bool {
return !value.IsZero() && value.Year() >= 1 && value.Year() <= 9999
}
func (service *Service) updateInTransaction(
ctx context.Context,
unit outbound.UnitOfWork,
command UpdateCommand,
now time.Time,
) (domain.Need, error) {
const location = "need.Service.Update"
if err := authorizeNeedOwner(ctx, unit, command.ActorID, command.OrganizationID, location); err != nil {
return domain.Need{}, err
}
store := unit.Needs()
current, err := store.Get(ctx, command.OrganizationID, command.NeedID)
if err != nil {
return domain.Need{}, fmt.Errorf("%s - read organization need: %w", location, err)
}
updated, changed, err := reviseNeed(current, command.Input, now)
if err != nil {
return domain.Need{}, fmt.Errorf("%s - merge need update: %w", location, err)
}
if !changed {
return updated, nil
}
if err := store.Save(ctx, command.OrganizationID, command.NeedID, current.Version(), updated); err != nil {
if !errors.Is(err, outbound.ErrNeedVersionConflict) {
return domain.Need{}, fmt.Errorf("%s - append need version: %w", location, err)
}
return service.recoverConcurrentUpdate(ctx, store, command, now)
}
if updated.RequirementsVersion() != current.RequirementsVersion() {
if err := service.scheduleSemantic(ctx, unit, command.OrganizationID, command.NeedID, updated.RequirementsVersion(), now); err != nil {
return domain.Need{}, fmt.Errorf("%s - %w", location, err)
}
}
return updated, nil
}
// scheduleSemantic schedules the vectors of a new requirements snapshot in
// the transaction that created it.
func (service *Service) scheduleSemantic(
ctx context.Context, unit outbound.UnitOfWork, organizationID, needID uuid.UUID, requirementsVersion int64, at time.Time,
) error {
if service.semantic == nil {
return nil
}
if err := service.semantic.NeedRequirementsChanged(ctx, unit, organizationID, needID, requirementsVersion, at); err != nil {
return fmt.Errorf("schedule need vectors: %w", err)
}
return nil
}
func (service *Service) recoverConcurrentUpdate(
ctx context.Context,
store outbound.NeedRepository,
command UpdateCommand,
now time.Time,
) (domain.Need, error) {
const location = "need.Service.Update"
latest, err := store.Get(ctx, command.OrganizationID, command.NeedID)
if err != nil {
return domain.Need{}, fmt.Errorf("%s - read winning need version: %w", location, err)
}
latest, changed, err := reviseNeed(latest, command.Input, now)
if err != nil {
return domain.Need{}, fmt.Errorf("%s - compare concurrent need update: %w", location, err)
}
if changed {
return domain.Need{}, fmt.Errorf("%s - append need version: %w", location, outbound.ErrNeedVersionConflict)
}
return latest, nil
}
// UpdateCommand binds one versioned replacement to a trusted actor and path.
type UpdateCommand struct {
ActorID uuid.UUID
OrganizationID uuid.UUID
NeedID uuid.UUID
Input UpdateInput
}
func authorizeNeedOwner(
ctx context.Context,
unit outbound.UnitOfWork,
actorID, organizationID uuid.UUID,
location string,
) error {
user, err := unit.Users().GetByID(ctx, actorID)
if err != nil {
if errors.Is(err, outbound.ErrUserNotFound) {
return fmt.Errorf("%s - require existing employer account: %w", location, ErrForbidden)
}
return fmt.Errorf("%s - read account: %w", location, err)
}
if user.Scenario != domain.ScenarioEmployer {
return fmt.Errorf("%s - require employer account: %w", location, ErrForbidden)
}
if !user.EmailVerified() {
return fmt.Errorf("%s - require verified email: %w", location, ErrEmailNotVerified)
}
membership, err := unit.Organizations().LockActiveMembership(ctx, organizationID, actorID)
if err != nil {
if errors.Is(err, outbound.ErrOrganizationNotFound) {
return fmt.Errorf("%s - require active membership: %w", location, outbound.ErrOrganizationNotFound)
}
return fmt.Errorf("%s - lock active membership: %w", location, err)
}
if membership.Role() != domain.OrganizationRoleOwner {
return fmt.Errorf("%s - require active owner: %w", location, outbound.ErrOrganizationManagerRequired)
}
return nil
}