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

347 lines
14 KiB
Go

package invitation
import (
"context"
"errors"
"fmt"
"strconv"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/candidateview"
)
var (
// ErrSendBlocked reports a send that the state of the invitation or the
// current visibility of its candidate does not allow. The API answers 409
// state_conflict without telling which rule applied.
ErrSendBlocked = errors.New("organization invitation cannot be sent")
// ErrInvitationQuotaExceeded reports that the rolling invitation quota of
// the organization is spent. QuotaExceededError carries the retry time.
ErrInvitationQuotaExceeded = errors.New("organization invitation quota is exhausted")
)
// QuotaExceededError carries only the time when the organization quota frees
// room again; it holds no candidate or invitation value.
type QuotaExceededError struct{ RetryAt time.Time }
func (err *QuotaExceededError) Error() string { return ErrInvitationQuotaExceeded.Error() }
func (err *QuotaExceededError) Unwrap() error { return ErrInvitationQuotaExceeded }
const (
sendOperation = "organization_invitation.send"
sendLocation = "invitation.Service.Send"
// maxSendAttempts bounds the repeats of a send after the visible cohort
// changed while it was locked, as for a create.
maxSendAttempts = 3
)
// SendCommand binds the authenticated actor and the path to one send of the
// current terms version of a draft.
type SendCommand struct {
ActorID uuid.UUID
OrganizationID uuid.UUID
InvitationID uuid.UUID
IdempotencyKey string
ExpectedVersion int64
}
type sendRequest struct {
fingerprint [outbound.IdempotencyDigestSize]byte
scope [outbound.IdempotencyDigestSize]byte
record outbound.IdempotencyRecord
now time.Time
}
// sendOutcome is what a committed send transaction decided: the invitation,
// or a refusal that the contract stores under the key and that the caller
// returns after the commit.
type sendOutcome struct {
view domain.OrganizationInvitationView
refusal error
}
// Send delivers the current terms version of a draft to the candidate's
// inbox. In one transaction it checks the owner, the key, the invitation, its
// version and state, and the current visibility of the candidate, spends one
// invitation of the organization quota, records the delivery with its
// deadline and the audit event, and writes the outbox events of the
// notification. The internal sending step is never visible: a success means
// the invitation is already delivered. A send of an invitation that was
// already delivered answers with its current state and charges nothing.
func (service *Service) Send(ctx context.Context, command SendCommand) (domain.OrganizationInvitationView, error) {
request, err := service.prepareSend(command)
if err != nil {
return domain.OrganizationInvitationView{}, err
}
var outcome sendOutcome
for range maxSendAttempts {
err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
var err error
outcome, err = service.sendInTransaction(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", sendLocation, err)
}
if outcome.refusal != nil {
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - %w", sendLocation, outcome.refusal)
}
return outcome.view, nil
}
func (service *Service) prepareSend(command SendCommand) (sendRequest, error) {
const location = "invitation.Service.prepareSend"
switch {
case command.ActorID == uuid.Nil || command.OrganizationID == uuid.Nil:
return sendRequest{}, fmt.Errorf("%s - actor and organization IDs must be set: %w", location, ErrForbidden)
case command.IdempotencyKey == "" || len(command.IdempotencyKey) > maxIdempotencyKeySize:
return sendRequest{}, fmt.Errorf("%s - idempotency key must have 1 to 255 bytes: %w", location, ErrInvalidIdempotencyKey)
case command.ExpectedVersion < 1:
return sendRequest{}, fmt.Errorf("%s - %w", location, &domain.InvitationFieldError{Pointer: "/expected_version", Reason: "must be positive"})
}
now, err := service.now(location)
if err != nil {
return sendRequest{}, err
}
// The fingerprint covers the path and the body, so one key used for
// another invitation or another version is a reused key.
canonical := []byte(`{"invitation_id":"` + command.InvitationID.String() + `","expected_version":` +
strconv.FormatInt(command.ExpectedVersion, 10) + `}`)
principal := command.ActorID.String() + ":" + command.OrganizationID.String()
fingerprint := service.keyring.Fingerprint(canonical)
scope := service.keyring.IdempotencyScope(sendOperation, command.IdempotencyKey, principal)
return sendRequest{
fingerprint: fingerprint, scope: scope, now: now,
record: outbound.IdempotencyRecord{Scope: scope, Fingerprint: fingerprint, CreatedAt: now, ExpiresAt: now.Add(outbound.IdempotencyRetention)},
}, nil
}
// sendInTransaction follows the order of checks of the contract after the
// HTTP boundary: the owner, the key, the invitation (404, stored), the repeat
// of a completed send (200), the version (412, not stored), the state and the
// visibility of the candidate (409, stored), and the quota (429, not stored).
// The locks follow the order of every invitation command: the organization,
// the membership, the invitation row, and then the cohort of the cards.
func (service *Service) sendInTransaction(
ctx context.Context,
unit outbound.UnitOfWork,
command SendCommand,
request sendRequest,
) (sendOutcome, error) {
if err := lockOrganizationFirst(ctx, unit, command.OrganizationID, sendLocation); err != nil {
return sendOutcome{}, err
}
if err := authorizeOwner(ctx, unit, command.ActorID, command.OrganizationID, sendLocation); err != nil {
return sendOutcome{}, err
}
stored, created, err := unit.IdempotencyRecords().Reserve(ctx, request.record)
if err != nil {
return sendOutcome{}, fmt.Errorf("%s - reserve idempotency record: %w", sendLocation, err)
}
if !created {
return replaySend(ctx, unit, request, command, stored)
}
if command.InvitationID == uuid.Nil {
return service.refuseSend(ctx, unit, command, request, outbound.InvitationSendNotFound)
}
current, err := unit.Invitations().GetForUpdate(ctx, command.OrganizationID, command.InvitationID)
if errors.Is(err, outbound.ErrInvitationNotFound) {
return service.refuseSend(ctx, unit, command, request, outbound.InvitationSendNotFound)
}
if err != nil {
return sendOutcome{}, fmt.Errorf("%s - lock invitation: %w", sendLocation, err)
}
if current.IsDelivered() {
// A completed send answers with the current invitation, whatever the
// key or the version, and charges nothing again.
return service.completeSend(ctx, unit, request, current)
}
if command.ExpectedVersion != current.Version() {
return sendOutcome{}, fmt.Errorf("%s - compare expected version: %w", sendLocation, domain.ErrInvitationVersionConflict)
}
if current.State() != domain.InvitationDraft {
return service.refuseSend(ctx, unit, command, request, outbound.InvitationSendStateConflict)
}
visible, err := service.candidateStillVisible(ctx, unit, command, current)
if err != nil {
return sendOutcome{}, err
}
if !visible {
return service.refuseSend(ctx, unit, command, request, outbound.InvitationSendStateConflict)
}
if err := service.chargeQuota(ctx, unit, command, current); err != nil {
return sendOutcome{}, err
}
delivered, err := service.deliver(ctx, unit, command, current, request.now)
if err != nil {
return sendOutcome{}, err
}
return service.completeSend(ctx, unit, request, delivered)
}
// candidateStillVisible runs the visibility barrier of the card read again:
// a draft keeps its candidate after a revoked publication C2, a hiding of the
// organization, or a cohort that fell below its minimum, and none of them may
// be bypassed by sending an older draft. The answer does not say which rule
// applied.
func (service *Service) candidateStillVisible(
ctx context.Context,
unit outbound.UnitOfWork,
command SendCommand,
current domain.Invitation,
) (bool, error) {
handle, err := service.pseudonymKey.ForOrganization(current.OrganizationID(), current.CandidateID())
if err != nil {
return false, fmt.Errorf("%s - derive candidate alias: %w", sendLocation, err)
}
candidateID, err := service.candidates(ctx, unit, command.ActorID, command.OrganizationID, handle)
switch {
case errors.Is(err, candidateview.ErrCandidateCardNotFound), errors.Is(err, candidateview.ErrInvalidCandidateHandle):
return false, nil
case err != nil:
return false, fmt.Errorf("%s - check candidate visibility: %w", sendLocation, err)
}
return candidateID == current.CandidateID(), nil
}
// chargeQuota spends one invitation of the organization quota. The charge is
// keyed by the invitation, so it is written once; a denial writes nothing and
// the whole send rolls back.
func (service *Service) chargeQuota(ctx context.Context, unit outbound.UnitOfWork, command SendCommand, current domain.Invitation) error {
organization, _, err := unit.Organizations().GetForMember(ctx, command.OrganizationID, command.ActorID)
if err != nil {
return fmt.Errorf("%s - read organization: %w", sendLocation, err)
}
decision, err := service.quota(ctx, unit, organization, current.ID())
if err != nil {
return fmt.Errorf("%s - reserve invitation quota: %w", sendLocation, err)
}
if !decision.Allowed {
return &QuotaExceededError{RetryAt: decision.RetryAt.UTC()}
}
return nil
}
// deliver stores the delivered version with its deadline and audit event and
// writes the notification events in the same transaction.
func (service *Service) deliver(
ctx context.Context,
unit outbound.UnitOfWork,
command SendCommand,
current domain.Invitation,
now time.Time,
) (domain.Invitation, error) {
// A clock that stepped back must not deliver before the last change.
at := now
if at.Before(current.UpdatedAt()) {
at = current.UpdatedAt()
}
delivered, err := current.Deliver(at)
if err != nil {
return domain.Invitation{}, fmt.Errorf("%s - deliver draft: %w", sendLocation, err)
}
event, err := delivered.DeliveryEvent(command.ActorID)
if err != nil {
return domain.Invitation{}, fmt.Errorf("%s - build audit event: %w", sendLocation, err)
}
if err := unit.Invitations().Deliver(ctx, current.Version(), delivered, event); err != nil {
if errors.Is(err, outbound.ErrInvitationVersionConflict) {
return domain.Invitation{}, fmt.Errorf("%s - store delivery: %w", sendLocation, domain.ErrInvitationVersionConflict)
}
return domain.Invitation{}, fmt.Errorf("%s - store delivery: %w", sendLocation, err)
}
if err := service.notifier.InvitationDelivered(ctx, unit, delivered); err != nil {
return domain.Invitation{}, fmt.Errorf("%s - record notification: %w", sendLocation, err)
}
return delivered, nil
}
// completeSend stores the successful response under the key.
func (service *Service) completeSend(
ctx context.Context,
unit outbound.UnitOfWork,
request sendRequest,
invitation domain.Invitation,
) (sendOutcome, error) {
view, err := service.view(invitation)
if err != nil {
return sendOutcome{}, err
}
result := outbound.InvitationSendResult{
OrganizationID: invitation.OrganizationID(), InvitationID: invitation.ID(), Outcome: outbound.InvitationSendSent, View: &view,
}
if err := finishSend(ctx, unit, request, result); err != nil {
return sendOutcome{}, err
}
return sendOutcome{view: view}, nil
}
// refuseSend stores a refusal that the contract keeps under the key and lets
// the transaction commit, since nothing else was written.
func (service *Service) refuseSend(
ctx context.Context,
unit outbound.UnitOfWork,
command SendCommand,
request sendRequest,
outcome outbound.InvitationSendOutcome,
) (sendOutcome, error) {
result := outbound.InvitationSendResult{OrganizationID: command.OrganizationID, InvitationID: command.InvitationID, Outcome: outcome}
if err := finishSend(ctx, unit, request, result); err != nil {
return sendOutcome{}, err
}
return sendOutcome{refusal: sendRefusal(outcome)}, nil
}
func finishSend(ctx context.Context, unit outbound.UnitOfWork, request sendRequest, result outbound.InvitationSendResult) error {
if err := unit.InvitationSendResults().SaveSendResult(ctx, request.scope, result); err != nil {
return fmt.Errorf("%s - store outcome: %w", sendLocation, err)
}
if _, err := unit.IdempotencyRecords().PurgeExpired(ctx, request.now, purgeExpiredBatch); err != nil {
return fmt.Errorf("%s - purge expired idempotency records: %w", sendLocation, err)
}
return nil
}
func sendRefusal(outcome outbound.InvitationSendOutcome) error {
if outcome == outbound.InvitationSendNotFound {
return outbound.ErrInvitationNotFound
}
return ErrSendBlocked
}
// replaySend returns the stored outcome of the same request, or refuses a key
// used with another request.
func replaySend(
ctx context.Context,
unit outbound.UnitOfWork,
request sendRequest,
command SendCommand,
stored outbound.IdempotencyRecord,
) (sendOutcome, error) {
if stored.Fingerprint != request.fingerprint {
return sendOutcome{}, fmt.Errorf("%s - compare request fingerprint: %w", sendLocation, ErrIdempotencyKeyReused)
}
original, err := unit.InvitationSendResults().GetSendResult(ctx, request.scope)
if err != nil {
return sendOutcome{}, fmt.Errorf("%s - read original outcome: %w", sendLocation, err)
}
if original.OrganizationID != command.OrganizationID {
return sendOutcome{}, fmt.Errorf("%s - validate original outcome: %w", sendLocation, domain.ErrInvalidInvitation)
}
if original.Outcome != outbound.InvitationSendSent {
return sendOutcome{refusal: sendRefusal(original.Outcome)}, nil
}
if original.View == nil || original.InvitationID != command.InvitationID {
return sendOutcome{}, fmt.Errorf("%s - validate original response: %w", sendLocation, domain.ErrInvalidInvitation)
}
return sendOutcome{view: *original.View}, nil
}