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

240 lines
11 KiB
Go

// Package invitation applies the owner-only rules of invitation drafts and of
// their sending: the terms and their immutable versions, the link to a
// candidate card of the organization, the idempotent creation, and the
// idempotent send that delivers a draft to the candidate's inbox. On the
// candidate's side it lists that inbox, reads one invitation, records the
// view, records a structured decline, and accepts the current terms with the
// consent C4 and its contact grant in one transaction. The cancellation and
// the revocation of a grant belong to later operations.
package invitation
import (
"context"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/consent"
)
var (
// ErrForbidden reports an account that may not work with the invitations
// of the organization: not an employer, or not its owner in the MVP.
ErrForbidden = errors.New("organization invitation operation forbidden")
// ErrEmailNotVerified reports an employer without a confirmed email.
ErrEmailNotVerified = errors.New("organization invitation requires a confirmed email")
// ErrIdempotencyKeyReused reports a key that was used with another request.
ErrIdempotencyKeyReused = errors.New("idempotency key reused with a different request")
// ErrInvalidIdempotencyKey reports a key outside 1 to 255 bytes.
ErrInvalidIdempotencyKey = errors.New("invalid idempotency key")
// ErrInvalidRequest reports a command that is incomplete before storage is
// read, such as a missing identifier or canonical body.
ErrInvalidRequest = errors.New("invalid organization invitation request")
// ErrPolicyUnavailable reports an effective product policy that cannot
// answer the invitation rules. It is a configuration error.
ErrPolicyUnavailable = errors.New("invitation policy is unavailable")
)
const (
createOperation = "organization_invitation.create"
maxIdempotencyKeySize = 255
maxCanonicalBodySize = 1 << 20
purgeExpiredBatch = 100
// maxCreateAttempts bounds the repeats of a create after the visible
// cohort changed while it was locked.
maxCreateAttempts = 3
)
// Keyring computes scoped idempotency digests. identity.Keyring implements
// this interface, so invitation 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
}
// CandidateResolver turns a card handle of the organization into the candidate
// it stands for, inside the caller's transaction. It applies the same
// visibility barrier as the card read: the effective publication, the hiding
// of the organization, and the cohort rules. It answers
// candidateview.ErrCandidateCardNotFound for every handle the organization may
// not use. The identifier it returns never leaves the server.
type CandidateResolver func(ctx context.Context, unit outbound.UnitOfWork, actorID, organizationID uuid.UUID, handle string) (uuid.UUID, error)
// InvitationQuota reserves one invitation of the organization quota inside
// the caller's transaction. Bootstrap adapts the shared company-quota usecase,
// so the verification tiers and their limits stay in one place. Repeating an
// invitation that is already charged is allowed without a second charge.
type InvitationQuota func(ctx context.Context, unit outbound.UnitOfWork, organization domain.Organization, invitationID uuid.UUID) (outbound.CompanyQuotaDecision, error)
// ContactConsents is the consent ledger of the acceptance. It reads the
// published C4 text, checks the version that the candidate saw, and records
// the C4 grant inside the caller's transaction. consent.Service implements it.
type ContactConsents interface {
CheckTextVersion(ctx context.Context, repositories outbound.ConsentRepositories, purpose domain.ConsentPurpose, version domain.ConsentTextVersion) (domain.ConsentText, error)
GrantContact(ctx context.Context, repositories outbound.ConsentRepositories, input consent.ContactGrantInput) (consent.GrantResult, error)
}
// DeliveryNotifier records, inside the caller's transaction, the outbox
// events that tell the candidate about a delivered invitation: the in-platform
// notification and the email. Neither blocks the delivery: the invitation is
// in the candidate's inbox when the transaction commits, and an email that
// fails or is retried later never changes it.
type DeliveryNotifier interface {
InvitationDelivered(ctx context.Context, unit outbound.UnitOfWork, invitation domain.Invitation) error
}
// Dependencies configure one stateless invitation service.
type Dependencies struct {
Transactor outbound.Transactor
Keyring Keyring
// PseudonymKey derives the organization-scoped alias that responses show
// instead of the candidate. It is the key of the cards and the search, so
// a handle in an invitation is the handle of the card.
PseudonymKey domain.CandidateViewPseudonymKey
Candidates CandidateResolver
Quota InvitationQuota
Notifier DeliveryNotifier
// Consents records the consent C4 of an acceptance in its transaction.
Consents ContactConsents
Clock func() time.Time
}
// Service applies organization-scoped invitation commands and reads, and the
// candidate's reads, view, decline, and acceptance of the own invitations.
type Service struct {
transactor outbound.Transactor
keyring Keyring
pseudonymKey domain.CandidateViewPseudonymKey
candidates CandidateResolver
quota InvitationQuota
notifier DeliveryNotifier
consents ContactConsents
clock func() time.Time
}
// NewService fails at startup when a required dependency is missing.
func NewService(deps Dependencies) (*Service, error) {
if deps.Transactor == nil || deps.Keyring == nil || deps.Candidates == nil || deps.Quota == nil ||
deps.Notifier == nil || deps.Consents == nil || deps.Clock == nil {
return nil, errors.New("invitation.NewService - every dependency must be set")
}
if _, err := deps.PseudonymKey.ForOrganization(uuid.New(), uuid.New()); err != nil {
return nil, errors.New("invitation.NewService - the pseudonym key must be usable")
}
return &Service{
transactor: deps.Transactor, keyring: deps.Keyring, pseudonymKey: deps.PseudonymKey,
candidates: deps.Candidates, quota: deps.Quota, notifier: deps.Notifier, consents: deps.Consents,
clock: deps.Clock,
}, nil
}
// now returns the application time at the precision the database stores.
func (service *Service) now(location string) (time.Time, error) {
now := service.clock().UTC().Truncate(time.Microsecond)
if now.IsZero() || now.Year() < 1 || now.Year() > 9999 {
return time.Time{}, fmt.Errorf("%s - application time must be representable: %w", location, ErrInvalidRequest)
}
return now, nil
}
// view is the invitation as its organization reads it. The contact access is
// derived in the caller's transaction from the grant of the invitation, with
// the checks of the contact read, so the view shows what a read would decide
// at that time. The salary indicator is not derived from the candidate's
// minimum yet, so it stays not_available, the least revealing value.
func (service *Service) view(
ctx context.Context,
unit outbound.UnitOfWork,
invitation domain.Invitation,
) (domain.OrganizationInvitationView, error) {
const location = "invitation.Service.view"
handle, err := service.pseudonymKey.ForOrganization(invitation.OrganizationID(), invitation.CandidateID())
if err != nil {
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - derive candidate alias: %w", location, err)
}
access, err := contactAccessOf(ctx, unit, invitation)
if err != nil {
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - derive contact access: %w", location, err)
}
return domain.OrganizationInvitationView{
InvitationSnapshot: invitation.Snapshot(),
CandidateHandle: handle,
SalaryFit: domain.InvitationSalaryNotAvailable,
ContactAccess: access,
}, nil
}
// lockOrganizationFirst takes the exclusive organization lock of the company
// quota port, ahead of the share lock of the membership check and of the
// cohort locks, so two commands of one organization queue instead of
// deadlocking on a lock upgrade. An organization that does not exist answers
// like a missing membership.
func lockOrganizationFirst(ctx context.Context, unit outbound.UnitOfWork, organizationID uuid.UUID, location string) error {
if err := unit.CompanyQuotas().LockOrganization(ctx, organizationID); err != nil {
if errors.Is(err, outbound.ErrCompanyQuotaSnapshotChanged) {
return fmt.Errorf("%s - lock organization: %w", location, outbound.ErrOrganizationNotFound)
}
return fmt.Errorf("%s - lock organization: %w", location, err)
}
return nil
}
// authorizeOwner repeats, inside the transaction, the checks of the HTTP
// boundary: an existing employer with a confirmed email whose membership in
// the organization is active and owner. The MVP milestone grants a membership
// by itself no right over invitations.
func authorizeOwner(
ctx context.Context,
unit outbound.UnitOfWork,
actorID, organizationID uuid.UUID,
location string,
) error {
if actorID == uuid.Nil || organizationID == uuid.Nil {
return fmt.Errorf("%s - actor and organization IDs must be set: %w", location, ErrForbidden)
}
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
}
// effectiveInvitationPolicy reads the invitation section of the product
// policy in force at the time, with the version that governed the decision.
func effectiveInvitationPolicy(
ctx context.Context,
unit outbound.UnitOfWork,
at time.Time,
location string,
) (domain.InvitationPolicy, domain.PolicyVersionID, error) {
version, err := unit.Policies().GetEffective(ctx, domain.ProductPolicyKey, at)
if err != nil {
return domain.InvitationPolicy{}, domain.PolicyVersionID{}, fmt.Errorf("%s - read effective product policy: %w: %w", location, ErrPolicyUnavailable, err)
}
return version.Policy().Invitations, version.ID(), nil
}