package invitation import ( "context" "encoding/json" "errors" "fmt" "time" "github.com/google/uuid" "lincodex/backend/internal/domain" "lincodex/backend/internal/port/outbound" ) // ErrAnswerBlocked reports a candidate answer that the state of the invitation // or its deadline does not allow: a terminal state, another reason or comment // on a declined invitation, a state without an open answer, or a command at // the deadline or later. The API answers 409 state_conflict. var ErrAnswerBlocked = errors.New("candidate invitation answer is not allowed") const ( declineOperation = "candidate_invitation.decline" declineLocation = "invitation.Service.DeclineMine" ) // DeclineCommand binds the session candidate and the path to one structured // decline over the invitation version the client read. type DeclineCommand struct { ActorID uuid.UUID InvitationID uuid.UUID IdempotencyKey string ExpectedVersion int64 Choice domain.InvitationDeclineChoice } type declineRequest struct { fingerprint [outbound.IdempotencyDigestSize]byte scope [outbound.IdempotencyDigestSize]byte record outbound.IdempotencyRecord now time.Time } // declineOutcome is what a committed decline transaction decided: the // invitation, or a refusal that the contract stores under the key and that // the caller returns after the commit. type declineOutcome struct { view domain.CandidateInvitationView refusal error } // declineFingerprint is the canonical request of a decline. An absent comment // and null are the same request. type declineFingerprint struct { InvitationID uuid.UUID `json:"invitation_id"` ExpectedVersion int64 `json:"expected_version"` Reason domain.InvitationDeclineReason `json:"reason"` Comment *string `json:"comment"` } // DeclineMine declines an invitation of the session candidate with a // structured reason. In one transaction it checks the candidate, the key, // the invitation, the repeat of the same decline, a terminal state or a // passed deadline, the version, and the state, then moves the invitation to // declined, stores the decline, and appends the audit event. A due expiry is // applied first. The decline is the candidate's answer for the responsiveness // metrics; it creates no consent and no contact grant, and the organization // sees only the state and the time of the answer. // // Locks: the idempotency record of the candidate's own key, then the // organization lock, then the invitation row. The organization lock is what // orders a decline against a send of the same pair, so a send never misses a // decline that committed before it counted the pause. func (service *Service) DeclineMine(ctx context.Context, command DeclineCommand) (domain.CandidateInvitationView, error) { request, err := service.prepareDecline(command) if err != nil { return domain.CandidateInvitationView{}, err } var outcome declineOutcome err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { var err error outcome, err = service.declineInTransaction(ctx, unit, command, request) return err }) if err != nil { return domain.CandidateInvitationView{}, fmt.Errorf("%s - run transaction: %w", declineLocation, err) } if outcome.refusal != nil { return domain.CandidateInvitationView{}, fmt.Errorf("%s - %w", declineLocation, outcome.refusal) } return outcome.view, nil } // prepareDecline validates the request before any storage is read, in the // order of the contract: the request is validated before the account. func (service *Service) prepareDecline(command DeclineCommand) (declineRequest, error) { const location = "invitation.Service.prepareDecline" switch { case command.ActorID == uuid.Nil: return declineRequest{}, fmt.Errorf("%s - actor ID must be set: %w", location, ErrForbidden) case command.IdempotencyKey == "" || len(command.IdempotencyKey) > maxIdempotencyKeySize: return declineRequest{}, fmt.Errorf("%s - idempotency key must have 1 to 255 bytes: %w", location, ErrInvalidIdempotencyKey) case command.ExpectedVersion < 1: return declineRequest{}, fmt.Errorf("%s - %w", location, &domain.InvitationFieldError{Pointer: "/expected_version", Reason: "must be positive"}) } if err := command.Choice.Validate(); err != nil { return declineRequest{}, fmt.Errorf("%s - validate choice: %w", location, err) } now, err := service.now(location) if err != nil { return declineRequest{}, err } // The fingerprint covers the path and the body, so one key used for // another invitation, version, reason, or comment is a reused key. canonical, err := json.Marshal(declineFingerprint{ InvitationID: command.InvitationID, ExpectedVersion: command.ExpectedVersion, Reason: command.Choice.Reason, Comment: command.Choice.Comment, }) if err != nil { return declineRequest{}, fmt.Errorf("%s - encode canonical request: %w", location, err) } fingerprint := service.keyring.Fingerprint(canonical) scope := service.keyring.IdempotencyScope(declineOperation, command.IdempotencyKey, command.ActorID.String()) return declineRequest{ fingerprint: fingerprint, scope: scope, now: now, record: outbound.IdempotencyRecord{Scope: scope, Fingerprint: fingerprint, CreatedAt: now, ExpiresAt: now.Add(outbound.IdempotencyRetention)}, }, nil } // declineInTransaction follows the order of checks of the contract after the // HTTP boundary: the account (403), the key (422 or a replay), the invitation // (404, stored), the repeat of the same decline (200), a terminal state or a // passed deadline (409 whatever the version, stored), the version (412, not // stored), and any other state without an open answer (409, stored). func (service *Service) declineInTransaction( ctx context.Context, unit outbound.UnitOfWork, command DeclineCommand, request declineRequest, ) (declineOutcome, error) { if err := authorizeCandidate(ctx, unit, command.ActorID); err != nil { return declineOutcome{}, err } stored, created, err := unit.IdempotencyRecords().Reserve(ctx, request.record) if err != nil { return declineOutcome{}, fmt.Errorf("%s - reserve idempotency record: %w", declineLocation, err) } if !created { return service.replayDecline(ctx, unit, request, command, stored) } // A decline changes the pause of the organization and the candidate, so it // takes the organization lock before the invitation row, as every command // that may change a pair does. The organization of an invitation never // changes, so the unlocked read names the lock to take. unlocked, err := readCandidateEntry(ctx, unit, command.ActorID, command.InvitationID, false) if errors.Is(err, outbound.ErrInvitationNotFound) { return refuseDecline(ctx, unit, command, request, outbound.InvitationDeclineNotFound) } if err != nil { return declineOutcome{}, err } if err := lockOrganizationFirst(ctx, unit, unlocked.Invitation.OrganizationID(), declineLocation); err != nil { return declineOutcome{}, err } entry, err := readCandidateEntry(ctx, unit, command.ActorID, command.InvitationID, true) if errors.Is(err, outbound.ErrInvitationNotFound) { return refuseDecline(ctx, unit, command, request, outbound.InvitationDeclineNotFound) } if err != nil { return declineOutcome{}, err } return service.declineFound(ctx, unit, command, request, entry) } // declineFound applies the checks that follow a found invitation: the repeat // of the same decline, a terminal state or a passed deadline, the version, // and the state, and then stores the decline. A delivered invitation whose // deadline has passed is expired first, so the late decline answers with the // expired state. func (service *Service) declineFound( ctx context.Context, unit outbound.UnitOfWork, command DeclineCommand, request declineRequest, entry outbound.CandidateInvitationEntry, ) (declineOutcome, error) { now, err := service.now(declineLocation) if err != nil { return declineOutcome{}, err } entry, err = settleCandidateEntry(ctx, unit, entry, now) if err != nil { return declineOutcome{}, fmt.Errorf("%s - expire due invitation: %w", declineLocation, err) } current := entry.Invitation at := notBefore(now, current.UpdatedAt()) if current.State() == domain.InvitationDeclined { previous, err := unit.Invitations().GetDecline(ctx, current.OrganizationID(), current.ID()) if err != nil { return declineOutcome{}, fmt.Errorf("%s - read decline: %w", declineLocation, err) } if previous.Choice.Equal(command.Choice) { // The same decline answers with the invitation as it is, whatever // the key or the version, and records nothing again. return service.completeDecline(ctx, unit, request, entry) } return refuseDecline(ctx, unit, command, request, outbound.InvitationDeclineStateConflict) } if current.IsTerminal() || current.ResponseDeadlinePassed(at) { return refuseDecline(ctx, unit, command, request, outbound.InvitationDeclineStateConflict) } if command.ExpectedVersion != current.Version() { return declineOutcome{}, fmt.Errorf("%s - compare expected version: %w", declineLocation, domain.ErrInvitationVersionConflict) } declined, decline, err := current.Decline(command.Choice, at) if errors.Is(err, domain.ErrInvitationNotAnswerable) { return refuseDecline(ctx, unit, command, request, outbound.InvitationDeclineStateConflict) } if err != nil { return declineOutcome{}, fmt.Errorf("%s - decline invitation: %w", declineLocation, err) } event, err := declined.AnswerEvent(command.ActorID) if err != nil { return declineOutcome{}, fmt.Errorf("%s - build audit event: %w", declineLocation, err) } if err := unit.Invitations().Decline(ctx, current.Version(), declined, decline, event); err != nil { if errors.Is(err, outbound.ErrInvitationVersionConflict) { return declineOutcome{}, fmt.Errorf("%s - store decline: %w", declineLocation, domain.ErrInvitationVersionConflict) } return declineOutcome{}, fmt.Errorf("%s - store decline: %w", declineLocation, err) } entry.Invitation = declined return service.completeDecline(ctx, unit, request, entry) } // completeDecline stores the successful outcome under the key and builds the // response with the stored decline. func (service *Service) completeDecline( ctx context.Context, unit outbound.UnitOfWork, request declineRequest, entry outbound.CandidateInvitationEntry, ) (declineOutcome, error) { view, err := service.candidateView(ctx, unit, entry, request.now) if err != nil { return declineOutcome{}, err } result := outbound.InvitationDeclineResult{InvitationID: entry.Invitation.ID(), Outcome: outbound.InvitationDeclineDeclined} if err := finishDecline(ctx, unit, request, result); err != nil { return declineOutcome{}, err } return declineOutcome{view: view}, nil } // refuseDecline stores a refusal that the contract keeps under the key and // lets the transaction commit, since nothing else was written. func refuseDecline( ctx context.Context, unit outbound.UnitOfWork, command DeclineCommand, request declineRequest, outcome outbound.InvitationDeclineOutcome, ) (declineOutcome, error) { result := outbound.InvitationDeclineResult{InvitationID: command.InvitationID, Outcome: outcome} if err := finishDecline(ctx, unit, request, result); err != nil { return declineOutcome{}, err } return declineOutcome{refusal: declineRefusal(outcome)}, nil } func finishDecline(ctx context.Context, unit outbound.UnitOfWork, request declineRequest, result outbound.InvitationDeclineResult) error { if err := unit.InvitationDeclineResults().SaveDeclineResult(ctx, request.scope, result); err != nil { return fmt.Errorf("%s - store outcome: %w", declineLocation, err) } if _, err := unit.IdempotencyRecords().PurgeExpired(ctx, request.now, purgeExpiredBatch); err != nil { return fmt.Errorf("%s - purge expired idempotency records: %w", declineLocation, err) } return nil } func declineRefusal(outcome outbound.InvitationDeclineOutcome) error { if outcome == outbound.InvitationDeclineNotFound { return outbound.ErrInvitationNotFound } return ErrAnswerBlocked } // replayDecline returns the stored outcome of the same request, or refuses a // key used with another request. A stored success is rebuilt from the // declined invitation and its decline: both are final, so the replay shows // the same answer without a second copy of the comment. func (service *Service) replayDecline( ctx context.Context, unit outbound.UnitOfWork, request declineRequest, command DeclineCommand, stored outbound.IdempotencyRecord, ) (declineOutcome, error) { if stored.Fingerprint != request.fingerprint { return declineOutcome{}, fmt.Errorf("%s - compare request fingerprint: %w", declineLocation, ErrIdempotencyKeyReused) } original, err := unit.InvitationDeclineResults().GetDeclineResult(ctx, request.scope) if err != nil { return declineOutcome{}, fmt.Errorf("%s - read original outcome: %w", declineLocation, err) } if original.InvitationID != command.InvitationID { return declineOutcome{}, fmt.Errorf("%s - validate original outcome: %w", declineLocation, domain.ErrInvalidInvitation) } if original.Outcome != outbound.InvitationDeclineDeclined { return declineOutcome{refusal: declineRefusal(original.Outcome)}, nil } entry, err := readCandidateEntry(ctx, unit, command.ActorID, command.InvitationID, false) if err != nil { return declineOutcome{}, err } if entry.Invitation.State() != domain.InvitationDeclined { return declineOutcome{}, fmt.Errorf("%s - validate original response: %w", declineLocation, domain.ErrInvalidInvitation) } view, err := service.candidateView(ctx, unit, entry, request.now) if err != nil { return declineOutcome{}, err } return declineOutcome{view: view}, nil }