feat(invitations): send invitations into the candidate inbox atomically

This commit is contained in:
shira committed 2026-10-09 16:50:36 +03:00
1 parent fc35e27af5
commit 1a067221f7
46 files changed
+3276 -113

No files matched your search

@@ -0,0 +1,85 @@
package invitation
import (
"context"
"errors"
"fmt"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
const listMineLocation = "invitation.Service.ListMine"
// CandidateListCommand selects one page of the inbox of the session candidate.
// The candidate comes only from the session.
type CandidateListCommand struct {
ActorID uuid.UUID
After *outbound.CandidateInvitationPosition
Limit int32
}
// CandidatePage is one page of the candidate's inbox, newest first by
// delivery time.
type CandidatePage struct {
Items []domain.CandidateInvitationSummary
HasMore bool
}
// ListMine reads one page of the invitations delivered to the session
// candidate, in any later state. Listing has no side effect: it records no
// view. Drafts and invitations of other candidates are never listed.
func (service *Service) ListMine(ctx context.Context, command CandidateListCommand) (CandidatePage, error) {
if command.ActorID == uuid.Nil {
return CandidatePage{}, fmt.Errorf("%s - actor ID must be set: %w", listMineLocation, ErrForbidden)
}
if command.Limit < 1 || command.Limit > outbound.MaxInvitationPageSize {
return CandidatePage{}, fmt.Errorf("%s - page limit must be 1 to %d: %w", listMineLocation, outbound.MaxInvitationPageSize, ErrInvalidRequest)
}
var result CandidatePage
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := authorizeCandidate(ctx, unit, command.ActorID); err != nil {
return err
}
page, err := unit.Invitations().ListForCandidate(ctx, outbound.CandidateInvitationListQuery{
CandidateID: command.ActorID, After: command.After, Limit: command.Limit,
})
if err != nil {
return fmt.Errorf("%s - list invitations: %w", listMineLocation, err)
}
result = CandidatePage{Items: make([]domain.CandidateInvitationSummary, 0, len(page.Items)), HasMore: page.HasMore}
for _, entry := range page.Items {
summary, err := entry.Invitation.CandidateSummary(domain.InvitationOrganizationRef{
ID: entry.Invitation.OrganizationID(), Name: entry.OrganizationName,
})
if err != nil {
return fmt.Errorf("%s - build inbox entry: %w", listMineLocation, err)
}
result.Items = append(result.Items, summary)
}
return nil
})
if err != nil {
return CandidatePage{}, fmt.Errorf("%s - run transaction: %w", listMineLocation, err)
}
return result, nil
}
// authorizeCandidate requires an existing candidate account with a confirmed
// email. An employer account, which has no inbox of invitations, is refused.
func authorizeCandidate(ctx context.Context, unit outbound.UnitOfWork, actorID uuid.UUID) error {
const location = "invitation.authorizeCandidate"
user, err := unit.Users().GetByID(ctx, actorID)
if errors.Is(err, outbound.ErrUserNotFound) {
return fmt.Errorf("%s - require existing candidate account: %w", location, ErrForbidden)
}
if err != nil {
return fmt.Errorf("%s - read account: %w", location, err)
}
if user.Scenario != domain.ScenarioCandidate || !user.EmailVerified() {
return fmt.Errorf("%s - require verified candidate account: %w", location, ErrForbidden)
}
return nil
}
+346
View File
@@ -0,0 +1,346 @@
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
}
@@ -0,0 +1,180 @@
package invitation
import (
"errors"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// draftFor creates a draft for a new visible candidate and returns it with
// the candidate's handle and identifier.
func (test *harness) draftFor(t *testing.T, period *int32) (domain.OrganizationInvitationView, string, uuid.UUID) {
t.Helper()
handle, candidateID := test.showCandidate(t)
command := test.createCommand(handle, "create-"+handle)
command.ResponsePeriodDays = period
view, err := test.service.Create(t.Context(), command)
if err != nil {
t.Fatalf("Create() error = %v", err)
}
return view, handle, candidateID
}
func (test *harness) sendCommand(invitationID uuid.UUID, version int64, key string) SendCommand {
return SendCommand{
ActorID: test.actorID, OrganizationID: test.organizationID, InvitationID: invitationID,
IdempotencyKey: key, ExpectedVersion: version,
}
}
func TestSendDeliversTheDraftWithTheDeadlineChargeAndNotificationAtOnce(t *testing.T) {
test := newHarness(t)
threeDays := int32(3)
draft, _, _ := test.draftFor(t, &threeDays)
sentAt := time.Date(2026, time.October, 9, 11, 0, 0, 0, time.UTC)
test.setTime(sentAt)
view, err := test.service.Send(t.Context(), test.sendCommand(draft.ID, draft.Version, "send-1"))
if err != nil {
t.Fatalf("Send() error = %v", err)
}
if view.State != domain.InvitationDelivered || view.Version != draft.Version+1 || view.TermsVersion != draft.TermsVersion ||
view.DeliveredAt == nil || !view.DeliveredAt.Equal(sentAt) ||
view.ResponseDeadlineAt == nil || !view.ResponseDeadlineAt.Equal(sentAt.Add(3*24*time.Hour)) {
t.Fatalf("sent view = %+v, want delivered now with a deadline three days later", view.InvitationSnapshot)
}
state := test.transactor.snapshot()
last := state.events[len(state.events)-1]
if last.Kind != domain.InvitationEventDelivered || last.Version != view.Version || last.ActorID != test.actorID || len(last.ChangedFields) != 0 {
t.Fatalf("audit event = %+v, want one delivery event of the sent version", last)
}
if len(state.charged) != 1 || state.charged[0] != draft.ID || len(state.notified) != 1 || state.notified[0] != draft.ID {
t.Fatalf("charged %v and notified %v, want the invitation once each", state.charged, state.notified)
}
}
func TestSendRepeatsReturnTheSameInvitationWithoutASecondChargeOrEvent(t *testing.T) {
test := newHarness(t)
draft, _, _ := test.draftFor(t, nil)
first, err := test.service.Send(t.Context(), test.sendCommand(draft.ID, draft.Version, "send-repeat"))
if err != nil {
t.Fatalf("Send() error = %v", err)
}
events := len(test.transactor.snapshot().events)
test.setTime(time.Date(2026, time.October, 10, 10, 0, 0, 0, time.UTC))
replay, err := test.service.Send(t.Context(), test.sendCommand(draft.ID, draft.Version, "send-repeat"))
if err != nil || replay.Version != first.Version || !replay.ResponseDeadlineAt.Equal(*first.ResponseDeadlineAt) {
t.Fatalf("replay = %+v, %v; want the original response", replay.InvitationSnapshot, err)
}
// A new key and the older draft version still answer with the current
// invitation instead of a version conflict.
again, err := test.service.Send(t.Context(), test.sendCommand(draft.ID, draft.Version, "send-repeat-new-key"))
if err != nil || again.State != domain.InvitationDelivered || !again.DeliveredAt.Equal(*first.DeliveredAt) {
t.Fatalf("repeat with a new key = %+v, %v; want the delivered invitation", again.InvitationSnapshot, err)
}
state := test.transactor.snapshot()
if len(state.charged) != 1 || len(state.notified) != 1 || len(state.events) != events {
t.Fatalf("repeats charged %d, notified %d, events %d -> %d; want nothing new", len(state.charged), len(state.notified), events, len(state.events))
}
other, _, _ := test.draftFor(t, nil)
if _, err := test.service.Send(t.Context(), test.sendCommand(other.ID, other.Version, "send-repeat")); !errors.Is(err, ErrIdempotencyKeyReused) {
t.Fatalf("Send(same key, other invitation) error = %v, want ErrIdempotencyKeyReused", err)
}
}
func TestSendRefusesAStaleVersionWithoutStoringTheOutcome(t *testing.T) {
test := newHarness(t)
draft, _, _ := test.draftFor(t, nil)
if _, err := test.service.Send(t.Context(), test.sendCommand(draft.ID, draft.Version+1, "send-stale")); !errors.Is(err, domain.ErrInvitationVersionConflict) {
t.Fatalf("Send(stale) error = %v, want ErrInvitationVersionConflict", err)
}
state := test.transactor.snapshot()
if len(state.sendResults) != 0 || len(state.charged) != 0 || state.invitations[draft.ID].State() != domain.InvitationDraft {
t.Fatalf("a stale send stored %d outcomes and %d charges", len(state.sendResults), len(state.charged))
}
// Nothing was kept under the key, so the corrected request with the
// same key sends the draft.
if view, err := test.service.Send(t.Context(), test.sendCommand(draft.ID, draft.Version, "send-stale")); err != nil || view.State != domain.InvitationDelivered {
t.Fatalf("Send(after stale) = %v, %v; want delivered", view.State, err)
}
}
func TestSendRefusesACandidateWhoIsNoLongerVisibleAndStoresTheRefusal(t *testing.T) {
test := newHarness(t)
draft, handle, candidateID := test.draftFor(t, nil)
delete(test.visible, handle)
if _, err := test.service.Send(t.Context(), test.sendCommand(draft.ID, draft.Version, "send-hidden")); !errors.Is(err, ErrSendBlocked) {
t.Fatalf("Send(hidden candidate) error = %v, want ErrSendBlocked", err)
}
state := test.transactor.snapshot()
if state.invitations[draft.ID].State() != domain.InvitationDraft || len(state.charged) != 0 || len(state.notified) != 0 {
t.Fatal("a refused send changed the draft, charged the quota, or notified")
}
// The refusal is stored under the key and replayed.
test.visible[handle] = candidateID
if _, err := test.service.Send(t.Context(), test.sendCommand(draft.ID, draft.Version, "send-hidden")); !errors.Is(err, ErrSendBlocked) {
t.Fatalf("Send(replay) error = %v, want the stored ErrSendBlocked", err)
}
}
func TestSendAnswersAnUnknownInvitationAsNotFoundAndStoresIt(t *testing.T) {
test := newHarness(t)
command := test.sendCommand(uuid.New(), 1, "send-unknown")
for range 2 {
if _, err := test.service.Send(t.Context(), command); !errors.Is(err, outbound.ErrInvitationNotFound) {
t.Fatalf("Send(unknown) error = %v, want ErrInvitationNotFound", err)
}
}
if state := test.transactor.snapshot(); len(state.sendResults) != 1 {
t.Fatalf("stored %d outcomes, want the one refusal", len(state.sendResults))
}
}
func TestSendRefusesAnExhaustedQuotaAndKeepsTheDraft(t *testing.T) {
test := newHarness(t)
test.quotaLeft = 0
draft, _, _ := test.draftFor(t, nil)
_, err := test.service.Send(t.Context(), test.sendCommand(draft.ID, draft.Version, "send-quota"))
limited, ok := errors.AsType[*QuotaExceededError](err)
if !ok || !errors.Is(err, ErrInvitationQuotaExceeded) || limited.RetryAt.IsZero() {
t.Fatalf("Send(no quota) error = %v, want QuotaExceededError with a retry time", err)
}
state := test.transactor.snapshot()
if state.invitations[draft.ID].State() != domain.InvitationDraft || len(state.sendResults) != 0 || len(state.notified) != 0 {
t.Fatal("a refused quota changed the draft or stored the outcome")
}
// Room in the quota lets the same key send the draft.
test.quotaLeft = 1
if view, err := test.service.Send(t.Context(), test.sendCommand(draft.ID, draft.Version, "send-quota")); err != nil || view.State != domain.InvitationDelivered {
t.Fatalf("Send(after quota) = %v, %v; want delivered", view.State, err)
}
}
func TestListMineShowsOnlyTheDeliveredInvitationsOfTheCandidate(t *testing.T) {
test := newHarness(t)
sent, _, candidateID := test.draftFor(t, nil)
if _, err := test.service.Send(t.Context(), test.sendCommand(sent.ID, sent.Version, "send-list")); err != nil {
t.Fatalf("Send() error = %v", err)
}
verified := time.Date(2026, time.October, 9, 9, 0, 0, 0, time.UTC)
test.transactor.state.users[candidateID] = domain.User{ID: candidateID, Scenario: domain.ScenarioCandidate, EmailVerifiedAt: &verified}
test.draftFor(t, nil)
page, err := test.service.ListMine(t.Context(), CandidateListCommand{ActorID: candidateID, Limit: 10})
if err != nil {
t.Fatalf("ListMine() error = %v", err)
}
if len(page.Items) != 1 || page.Items[0].ID != sent.ID || page.Items[0].State != domain.InvitationDelivered ||
page.Items[0].Organization.ID != test.organizationID || page.Items[0].RoleTitle == "" {
t.Fatalf("inbox = %+v, want the one delivered invitation", page.Items)
}
if _, err := test.service.ListMine(t.Context(), CandidateListCommand{ActorID: test.actorID, Limit: 10}); !errors.Is(err, ErrForbidden) {
t.Fatalf("ListMine(employer) error = %v, want ErrForbidden", err)
}
}
+30 -7
View File
@@ -1,7 +1,9 @@
// Package invitation applies the owner-only rules of invitation drafts: the
// terms and their immutable versions, the link to a candidate card of the
// organization, and the idempotent creation. Sending, the candidate's side, and
// the contact grant belong to later operations that build on the same records.
// 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. It also
// lists that inbox for the candidate. The candidate's answers and the contact
// grant belong to later operations that build on the same records.
package invitation
import (
@@ -60,6 +62,21 @@ type Keyring interface {
// 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)
// 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
@@ -69,21 +86,27 @@ type Dependencies struct {
// a handle in an invitation is the handle of the card.
PseudonymKey domain.CandidateViewPseudonymKey
Candidates CandidateResolver
Quota InvitationQuota
Notifier DeliveryNotifier
Clock func() time.Time
}
// Service applies organization-scoped invitation draft commands and reads.
// Service applies organization-scoped invitation commands and reads, and the
// candidate's read of the own inbox.
type Service struct {
transactor outbound.Transactor
keyring Keyring
pseudonymKey domain.CandidateViewPseudonymKey
candidates CandidateResolver
quota InvitationQuota
notifier DeliveryNotifier
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.Clock == nil {
if deps.Transactor == nil || deps.Keyring == nil || deps.Candidates == nil || deps.Quota == nil ||
deps.Notifier == 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 {
@@ -91,7 +114,7 @@ func NewService(deps Dependencies) (*Service, error) {
}
return &Service{
transactor: deps.Transactor, keyring: deps.Keyring, pseudonymKey: deps.PseudonymKey,
candidates: deps.Candidates, clock: deps.Clock,
candidates: deps.Candidates, quota: deps.Quota, notifier: deps.Notifier, clock: deps.Clock,
}, nil
}
@@ -41,7 +41,12 @@ type testState struct {
events []domain.InvitationEvent
idempotency map[[outbound.IdempotencyDigestSize]byte]outbound.IdempotencyRecord
results map[[outbound.IdempotencyDigestSize]byte]domain.OrganizationInvitationView
sendResults map[[outbound.IdempotencyDigestSize]byte]outbound.InvitationSendResult
needVersions map[[3]string]bool
// charged lists the invitations charged against the organization quota,
// and notified the delivered invitations that were notified.
charged []uuid.UUID
notified []uuid.UUID
}
func newTestState() testState {
@@ -50,6 +55,7 @@ func newTestState() testState {
invitations: map[uuid.UUID]domain.Invitation{}, terms: map[termsKey]domain.InvitationTerms{},
idempotency: map[[outbound.IdempotencyDigestSize]byte]outbound.IdempotencyRecord{},
results: map[[outbound.IdempotencyDigestSize]byte]domain.OrganizationInvitationView{},
sendResults: map[[outbound.IdempotencyDigestSize]byte]outbound.InvitationSendResult{},
needVersions: map[[3]string]bool{},
}
}
@@ -75,9 +81,14 @@ func (state testState) clone() testState {
for scope, result := range state.results {
cloned.results[scope] = result
}
for scope, result := range state.sendResults {
cloned.sendResults[scope] = result
}
for key, found := range state.needVersions {
cloned.needVersions[key] = found
}
cloned.charged = slices.Clone(state.charged)
cloned.notified = slices.Clone(state.notified)
return cloned
}
@@ -129,6 +140,9 @@ func (unit *testUnit) Invitations() outbound.InvitationRepository {
func (unit *testUnit) InvitationCreationResults() outbound.InvitationCreationResultRepository {
return testInvitations{state: unit.state, failResultSave: unit.failResultSave}
}
func (unit *testUnit) InvitationSendResults() outbound.InvitationSendResultRepository {
return testInvitations{state: unit.state}
}
type testUsers struct {
outbound.UserRepository
@@ -158,6 +172,14 @@ func (repository testOrganizations) LockActiveMembership(_ context.Context, orga
return membership, nil
}
func (repository testOrganizations) GetForMember(_ context.Context, organizationID, userID uuid.UUID) (domain.Organization, domain.Membership, error) {
membership, ok := repository.state.memberships[[2]uuid.UUID{organizationID, userID}]
if !ok || !membership.GrantsAccess() {
return domain.Organization{}, domain.Membership{}, outbound.ErrOrganizationNotFound
}
return domain.Organization{}, membership, nil
}
type testQuotas struct {
outbound.CompanyQuotaRepository
}
@@ -194,6 +216,7 @@ func (repository testIdempotency) PurgeExpired(_ context.Context, at time.Time,
if !record.ExpiresAt.After(at) {
delete(repository.state.idempotency, scope)
delete(repository.state.results, scope)
delete(repository.state.sendResults, scope)
deleted++
}
}
@@ -255,6 +278,52 @@ func (repository testInvitations) SaveDraft(_ context.Context, expectedVersion i
return nil
}
func (repository testInvitations) Deliver(_ context.Context, expectedVersion int64, next domain.Invitation, event domain.InvitationEvent) error {
current, ok := repository.state.invitations[next.ID()]
if !ok || current.Version() != expectedVersion || current.State() != domain.InvitationDraft {
return outbound.ErrInvitationVersionConflict
}
repository.state.invitations[next.ID()] = next
repository.state.events = append(repository.state.events, event)
return nil
}
func (repository testInvitations) ListForCandidate(_ context.Context, query outbound.CandidateInvitationListQuery) (outbound.CandidateInvitationPage, error) {
var items []outbound.CandidateInvitationEntry
for _, invitation := range repository.state.invitations {
if invitation.CandidateID() == query.CandidateID && invitation.IsDelivered() {
items = append(items, outbound.CandidateInvitationEntry{Invitation: invitation, OrganizationName: "Test organization"})
}
}
page := outbound.CandidateInvitationPage{HasMore: len(items) > int(query.Limit)}
if page.HasMore {
items = items[:query.Limit]
}
page.Items = items
return page, nil
}
func (repository testInvitations) GetForCandidate(_ context.Context, candidateID, invitationID uuid.UUID) (domain.Invitation, error) {
invitation, ok := repository.state.invitations[invitationID]
if !ok || invitation.CandidateID() != candidateID || !invitation.IsDelivered() {
return domain.Invitation{}, outbound.ErrInvitationNotFound
}
return invitation, nil
}
func (repository testInvitations) SaveSendResult(_ context.Context, scope [outbound.IdempotencyDigestSize]byte, result outbound.InvitationSendResult) error {
repository.state.sendResults[scope] = result
return nil
}
func (repository testInvitations) GetSendResult(_ context.Context, scope [outbound.IdempotencyDigestSize]byte) (outbound.InvitationSendResult, error) {
result, ok := repository.state.sendResults[scope]
if !ok {
return outbound.InvitationSendResult{}, outbound.ErrInvitationSendResultNotFound
}
return result, nil
}
func (repository testInvitations) NeedVersionExists(_ context.Context, organizationID, needID uuid.UUID, version int64) (bool, error) {
return repository.state.needVersions[[3]string{organizationID.String(), needID.String(), fmt.Sprint(version)}], nil
}
@@ -276,8 +345,11 @@ func (repository testInvitations) GetCreationResult(_ context.Context, scope [ou
}
type harness struct {
service *Service
transactor *testTransactor
service *Service
transactor *testTransactor
// quotaLeft is the number of new invitations the organization quota
// still allows.
quotaLeft int
key domain.CandidateViewPseudonymKey
actorID uuid.UUID
organizationID uuid.UUID
@@ -305,7 +377,7 @@ func newHarness(t *testing.T) *harness {
}
test := &harness{
transactor: &testTransactor{state: state, policy: testPolicyVersion(t, now)},
key: key, actorID: actorID, organizationID: organizationID, visible: map[string]uuid.UUID{},
key: key, actorID: actorID, organizationID: organizationID, visible: map[string]uuid.UUID{}, quotaLeft: 10,
setTime: func(value time.Time) { current = value },
}
test.service, err = NewService(Dependencies{
@@ -317,6 +389,18 @@ func newHarness(t *testing.T) *harness {
}
return candidateID, nil
},
Quota: func(_ context.Context, unit outbound.UnitOfWork, _ domain.Organization, invitationID uuid.UUID) (outbound.CompanyQuotaDecision, error) {
state := unit.(*testUnit).state
if slices.Contains(state.charged, invitationID) {
return outbound.CompanyQuotaDecision{Allowed: true, Reused: true}, nil
}
if len(state.charged) >= test.quotaLeft {
return outbound.CompanyQuotaDecision{RetryAt: current.Add(time.Hour)}, nil
}
state.charged = append(state.charged, invitationID)
return outbound.CompanyQuotaDecision{Allowed: true}, nil
},
Notifier: testNotifier{},
})
if err != nil {
t.Fatalf("NewService() error = %v", err)
@@ -337,6 +421,14 @@ func (test *harness) showCandidate(t *testing.T) (string, uuid.UUID) {
return handle, candidateID
}
type testNotifier struct{}
func (testNotifier) InvitationDelivered(_ context.Context, unit outbound.UnitOfWork, invitation domain.Invitation) error {
state := unit.(*testUnit).state
state.notified = append(state.notified, invitation.ID())
return nil
}
func testPolicyVersion(t *testing.T, at time.Time) domain.PolicyVersion {
t.Helper()
draft, err := domain.NewPolicyVersionDraft(domain.NewPolicyVersionDraftInput{
@@ -543,6 +635,10 @@ func TestOnlyTheActiveOwnerOfAnEmployerAccountMayWorkWithInvitations(t *testing.
if _, err := test.service.Get(t.Context(), tt.actor, test.organizationID, uuid.New()); !errors.Is(err, tt.want) {
t.Errorf("Get() error = %v, want %v", err, tt.want)
}
send := SendCommand{ActorID: tt.actor, OrganizationID: test.organizationID, InvitationID: uuid.New(), IdempotencyKey: "send-" + tt.name, ExpectedVersion: 1}
if _, err := test.service.Send(t.Context(), send); !errors.Is(err, tt.want) {
t.Errorf("Send() error = %v, want %v", err, tt.want)
}
})
}
if state := test.transactor.snapshot(); len(state.invitations) != 0 {