Files
lincodex/backend/internal/usecase/invitation/draft.go
T

468 lines
19 KiB
Go

package invitation
import (
"context"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/candidateview"
)
const (
createLocation = "invitation.Service.Create"
updateLocation = "invitation.Service.Update"
getLocation = "invitation.Service.Get"
listLocation = "invitation.Service.List"
)
// CreateCommand binds the authenticated actor and the path organization to
// one validated create request. The candidate is named only by the handle.
type CreateCommand struct {
ActorID uuid.UUID
OrganizationID uuid.UUID
IdempotencyKey string
CanonicalBody []byte
CandidateHandle string
Need *domain.InvitationNeedRef
ResponsePeriodDays *int32
Terms domain.InvitationTerms
}
type createRequest struct {
fingerprint [outbound.IdempotencyDigestSize]byte
scope [outbound.IdempotencyDigestSize]byte
record outbound.IdempotencyRecord
now time.Time
}
// Create stores a new draft addressed to one candidate of the organization's
// visible cards, or replays the original response of the same request within
// the idempotency window. Nothing is stored when any rule fails.
func (service *Service) Create(ctx context.Context, command CreateCommand) (domain.OrganizationInvitationView, error) {
request, err := service.prepareCreate(command)
if err != nil {
return domain.OrganizationInvitationView{}, err
}
var result domain.OrganizationInvitationView
// The visible cohort can change while it is locked. The whole command is
// then repeated, a bounded number of times, and the writes of a failed
// attempt roll back with it.
for range maxCreateAttempts {
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 !errors.Is(err, candidateview.ErrConcurrentVisibilityChange) {
break
}
}
if err != nil {
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - run transaction: %w", createLocation, err)
}
return result, nil
}
func (service *Service) prepareCreate(command CreateCommand) (createRequest, error) {
const location = "invitation.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, ErrInvalidRequest)
}
now, err := service.now(location)
if err != nil {
return createRequest{}, err
}
expiresAt := now.Add(outbound.IdempotencyRetention)
principal := command.ActorID.String() + ":" + command.OrganizationID.String()
fingerprint := service.keyring.Fingerprint(command.CanonicalBody)
scope := service.keyring.IdempotencyScope(createOperation, command.IdempotencyKey, principal)
return createRequest{
fingerprint: fingerprint, scope: scope, now: now,
record: outbound.IdempotencyRecord{Scope: scope, Fingerprint: fingerprint, CreatedAt: now, ExpiresAt: expiresAt},
}, nil
}
func (service *Service) createInTransaction(
ctx context.Context,
unit outbound.UnitOfWork,
command CreateCommand,
request createRequest,
) (domain.OrganizationInvitationView, error) {
if err := lockOrganizationFirst(ctx, unit, command.OrganizationID, createLocation); err != nil {
return domain.OrganizationInvitationView{}, err
}
if err := authorizeOwner(ctx, unit, command.ActorID, command.OrganizationID, createLocation); err != nil {
return domain.OrganizationInvitationView{}, err
}
stored, created, err := unit.IdempotencyRecords().Reserve(ctx, request.record)
if err != nil {
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - reserve idempotency record: %w", createLocation, err)
}
if !created {
return replayCreation(ctx, unit, request, command.OrganizationID, stored)
}
invitation, err := service.buildDraft(ctx, unit, command, request.now)
if err != nil {
return domain.OrganizationInvitationView{}, err
}
event, err := invitation.DraftEvent(command.ActorID, nil)
if err != nil {
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - build audit event: %w", createLocation, err)
}
if err := unit.Invitations().Create(ctx, invitation, event); err != nil {
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - store draft: %w", createLocation, err)
}
view, err := service.view(ctx, unit, invitation)
if err != nil {
return domain.OrganizationInvitationView{}, err
}
if err := unit.InvitationCreationResults().SaveCreationResult(ctx, request.scope, view); err != nil {
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - store original response: %w", createLocation, err)
}
if _, err := unit.IdempotencyRecords().PurgeExpired(ctx, request.now, purgeExpiredBatch); err != nil {
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - purge expired idempotency records: %w", createLocation, err)
}
return view, nil
}
// buildDraft applies the domain rules in the order of the contract: the
// candidate handle, the need link, then the terms. The handle is resolved
// through the same visibility barrier as a card read, so a draft cannot be
// addressed to a candidate that the organization may not see.
func (service *Service) buildDraft(
ctx context.Context,
unit outbound.UnitOfWork,
command CreateCommand,
now time.Time,
) (domain.Invitation, error) {
policy, policyVersionID, err := effectiveInvitationPolicy(ctx, unit, now, createLocation)
if err != nil {
return domain.Invitation{}, err
}
var requested *domain.CalendarDays
if command.ResponsePeriodDays != nil {
period := domain.CalendarDays(*command.ResponsePeriodDays)
requested = &period
}
period, err := policy.ResolveResponsePeriod(requested)
if err != nil {
return domain.Invitation{}, fmt.Errorf("%s - resolve response period: %w", createLocation, err)
}
candidateID, err := service.candidates(ctx, unit, command.ActorID, command.OrganizationID, command.CandidateHandle)
if err != nil {
if errors.Is(err, candidateview.ErrCandidateCardNotFound) || errors.Is(err, candidateview.ErrInvalidCandidateHandle) {
return domain.Invitation{}, fmt.Errorf("%s - resolve candidate handle: %w", createLocation,
&domain.InvitationFieldError{Pointer: "/candidate_handle", Reason: "must be a handle of a candidate this organization can see"})
}
return domain.Invitation{}, fmt.Errorf("%s - resolve candidate handle: %w", createLocation, err)
}
if err := checkNeedLink(ctx, unit, command.OrganizationID, command.Need); err != nil {
return domain.Invitation{}, fmt.Errorf("%s - %w", createLocation, err)
}
draftID, err := uuid.NewV7()
if err != nil {
return domain.Invitation{}, fmt.Errorf("%s - generate invitation ID: %w", createLocation, err)
}
invitation, err := domain.NewInvitationDraft(domain.NewInvitationDraftInput{
ID: draftID, OrganizationID: command.OrganizationID, CandidateID: candidateID, ActorID: command.ActorID,
PolicyVersionID: policyVersionID, At: now,
Content: domain.InvitationDraftContent{Need: command.Need, ResponsePeriod: period, Terms: command.Terms},
})
if err != nil {
return domain.Invitation{}, fmt.Errorf("%s - build draft: %w", createLocation, err)
}
return invitation, nil
}
// checkNeedLink requires that a linked need belongs to the organization and
// has had the stated requirements version. Both cases give one pointer, so the
// answer does not tell whether the need exists in another organization.
func checkNeedLink(ctx context.Context, unit outbound.UnitOfWork, organizationID uuid.UUID, need *domain.InvitationNeedRef) error {
if need == nil {
return nil
}
exists, err := unit.Invitations().NeedVersionExists(ctx, organizationID, need.NeedID, need.RequirementsVersion)
if err != nil {
return fmt.Errorf("check need link: %w", err)
}
if !exists {
return &domain.InvitationFieldError{Pointer: "/need", Reason: "must be a need of this organization with a requirements version it has had"}
}
return nil
}
func replayCreation(
ctx context.Context,
unit outbound.UnitOfWork,
request createRequest,
organizationID uuid.UUID,
stored outbound.IdempotencyRecord,
) (domain.OrganizationInvitationView, error) {
if stored.Fingerprint != request.fingerprint {
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - compare request fingerprint: %w", createLocation, ErrIdempotencyKeyReused)
}
original, err := unit.InvitationCreationResults().GetCreationResult(ctx, request.scope)
if err != nil {
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - read original response: %w", createLocation, err)
}
if original.OrganizationID != organizationID {
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - validate original response: %w", createLocation, domain.ErrInvalidInvitation)
}
return original, nil
}
// Field distinguishes a property that the request left out from one it set,
// and from one it set to null.
type Field[T any] struct {
Set bool
Null bool
Value T
}
// UpdateCommand binds one versioned replacement to a trusted actor and path.
// A field that is not set stays unchanged; terms are replaced as a whole.
type UpdateCommand struct {
ActorID uuid.UUID
OrganizationID uuid.UUID
InvitationID uuid.UUID
ExpectedVersion int64
Need Field[domain.InvitationNeedRef]
ResponsePeriodDays *int32
Terms *domain.InvitationTerms
}
// Update replaces the fields the request sets, in the order of the contract:
// a request that changes nothing returns the current invitation, then the
// version is compared, then the state, then the domain rules. Only a draft
// changes. A change appends the next invitation version, and a change of the
// terms appends the next immutable terms version.
func (service *Service) Update(ctx context.Context, command UpdateCommand) (domain.OrganizationInvitationView, error) {
if command.ActorID == uuid.Nil || command.OrganizationID == uuid.Nil {
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - actor and organization IDs must be set: %w", updateLocation, ErrForbidden)
}
if command.ExpectedVersion < 1 {
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - %w", updateLocation,
&domain.InvitationFieldError{Pointer: "/expected_version", Reason: "must be positive"})
}
now, err := service.now(updateLocation)
if err != nil {
return domain.OrganizationInvitationView{}, err
}
var result domain.OrganizationInvitationView
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.OrganizationInvitationView{}, fmt.Errorf("%s - run transaction: %w", updateLocation, err)
}
return result, nil
}
func (service *Service) updateInTransaction(
ctx context.Context,
unit outbound.UnitOfWork,
command UpdateCommand,
now time.Time,
) (domain.OrganizationInvitationView, error) {
// Every invitation command takes the organization lock before the
// membership share lock and the invitation row lock, in the order of the
// create, the card read, and the search, so a later command that also
// charges the organization (sending, the salary limit) cannot deadlock
// against an update.
if err := lockOrganizationFirst(ctx, unit, command.OrganizationID, updateLocation); err != nil {
return domain.OrganizationInvitationView{}, err
}
if err := authorizeOwner(ctx, unit, command.ActorID, command.OrganizationID, updateLocation); err != nil {
return domain.OrganizationInvitationView{}, err
}
// The nil identifier cannot name an invitation. It answers like any
// unknown identifier, after the authorization above.
if command.InvitationID == uuid.Nil {
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - nil invitation: %w", updateLocation, outbound.ErrInvitationNotFound)
}
current, err := unit.Invitations().GetForUpdate(ctx, command.OrganizationID, command.InvitationID)
if err != nil {
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - lock invitation: %w", updateLocation, err)
}
before := current.DraftContent()
merged := mergeDraft(before, command)
changed := before.ChangedFields(merged)
if len(changed) == 0 {
return service.view(ctx, unit, current)
}
if command.ExpectedVersion != current.Version() {
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - compare expected version: %w", updateLocation, domain.ErrInvitationVersionConflict)
}
if current.State() != domain.InvitationDraft {
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - require a draft: %w", updateLocation, domain.ErrInvitationNotDraft)
}
policyVersionID, err := service.checkRevision(ctx, unit, current, merged, changed, now)
if err != nil {
return domain.OrganizationInvitationView{}, err
}
// A clock that stepped back must not make the revision older than the
// draft it revises.
at := now
if at.Before(current.UpdatedAt()) {
at = current.UpdatedAt()
}
next, appliedFields, err := current.ReviseDraft(merged, policyVersionID, at)
if err != nil {
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - revise draft: %w", updateLocation, err)
}
event, err := next.DraftEvent(command.ActorID, appliedFields)
if err != nil {
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - build audit event: %w", updateLocation, err)
}
termsChanged := next.TermsVersion() != current.TermsVersion()
if err := unit.Invitations().SaveDraft(ctx, current.Version(), next, termsChanged, event); err != nil {
if errors.Is(err, outbound.ErrInvitationVersionConflict) {
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - save draft: %w", updateLocation, domain.ErrInvitationVersionConflict)
}
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - save draft: %w", updateLocation, err)
}
return service.view(ctx, unit, next)
}
// mergeDraft applies the fields the command sets over the current content.
func mergeDraft(current domain.InvitationDraftContent, command UpdateCommand) domain.InvitationDraftContent {
merged := current
if command.Need.Set {
merged.Need = nil
if !command.Need.Null {
need := command.Need.Value
merged.Need = &need
}
}
if command.ResponsePeriodDays != nil {
merged.ResponsePeriod = domain.CalendarDays(*command.ResponsePeriodDays)
}
if command.Terms != nil {
merged.Terms = *command.Terms
}
return merged
}
// checkRevision runs the rules that need storage or the policy and returns the
// policy version that governs the stored response period. The period is
// checked against the policy in force only when the request changes it.
func (service *Service) checkRevision(
ctx context.Context,
unit outbound.UnitOfWork,
current domain.Invitation,
merged domain.InvitationDraftContent,
changed []domain.InvitationChangedField,
now time.Time,
) (domain.PolicyVersionID, error) {
policyVersionID := current.PolicyVersionID()
for _, field := range changed {
switch field {
case domain.InvitationChangedResponsePeriod:
policy, versionID, err := effectiveInvitationPolicy(ctx, unit, now, updateLocation)
if err != nil {
return domain.PolicyVersionID{}, err
}
if _, err := policy.ResolveResponsePeriod(&merged.ResponsePeriod); err != nil {
return domain.PolicyVersionID{}, fmt.Errorf("%s - resolve response period: %w", updateLocation, err)
}
policyVersionID = versionID
case domain.InvitationChangedNeed:
if err := checkNeedLink(ctx, unit, current.OrganizationID(), merged.Need); err != nil {
return domain.PolicyVersionID{}, fmt.Errorf("%s - %w", updateLocation, err)
}
case domain.InvitationChangedTerms:
// The terms need no storage: the domain validates them when the
// draft is revised, after the need link, as on creation.
}
}
return policyVersionID, nil
}
// Get reads the current invitation for an active owner.
func (service *Service) Get(ctx context.Context, actorID, organizationID, invitationID uuid.UUID) (domain.OrganizationInvitationView, error) {
if actorID == uuid.Nil || organizationID == uuid.Nil {
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - actor and organization IDs must be set: %w", getLocation, ErrForbidden)
}
var result domain.OrganizationInvitationView
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := authorizeOwner(ctx, unit, actorID, organizationID, getLocation); err != nil {
return err
}
if invitationID == uuid.Nil {
return fmt.Errorf("%s - nil invitation: %w", getLocation, outbound.ErrInvitationNotFound)
}
current, err := unit.Invitations().Get(ctx, organizationID, invitationID)
if err != nil {
return fmt.Errorf("%s - read invitation: %w", getLocation, err)
}
result, err = service.view(ctx, unit, current)
return err
})
if err != nil {
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - run transaction: %w", getLocation, err)
}
return result, nil
}
// ListCommand selects an owner-scoped page of invitations.
type ListCommand struct {
ActorID uuid.UUID
OrganizationID uuid.UUID
After *outbound.InvitationListPosition
Limit int32
}
// Page is one page of invitations, newest first.
type Page struct {
Items []domain.OrganizationInvitationView
HasMore bool
}
// List reads one page of the organization's invitations of every state after
// checking the current account and owner membership in the same transaction.
func (service *Service) List(ctx context.Context, command ListCommand) (Page, error) {
if command.ActorID == uuid.Nil || command.OrganizationID == uuid.Nil {
return Page{}, fmt.Errorf("%s - actor and organization IDs must be set: %w", listLocation, ErrForbidden)
}
if command.Limit < 1 || command.Limit > outbound.MaxInvitationPageSize {
return Page{}, fmt.Errorf("%s - page limit must be 1 to %d: %w", listLocation, outbound.MaxInvitationPageSize, ErrInvalidRequest)
}
var result Page
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := authorizeOwner(ctx, unit, command.ActorID, command.OrganizationID, listLocation); err != nil {
return err
}
page, err := unit.Invitations().List(ctx, outbound.InvitationListQuery{
OrganizationID: command.OrganizationID, After: command.After, Limit: command.Limit,
})
if err != nil {
return fmt.Errorf("%s - list invitations: %w", listLocation, err)
}
result = Page{Items: make([]domain.OrganizationInvitationView, 0, len(page.Items)), HasMore: page.HasMore}
for _, invitation := range page.Items {
item, err := service.view(ctx, unit, invitation)
if err != nil {
return err
}
result.Items = append(result.Items, item)
}
return nil
})
if err != nil {
return Page{}, fmt.Errorf("%s - run transaction: %w", listLocation, err)
}
return result, nil
}