feat(invitations): check contact grants on every read, cap pending invitations, and expire them at the deadline

This commit is contained in:
shira committed 2026-10-09 19:06:50 +03:00
1 parent 676b3c6e24
commit 12a7213d4a
67 files changed
+4255 -149

No files matched your search

+12 -2
View File
@@ -171,7 +171,9 @@ func (service *Service) acceptInTransaction(
}
// acceptFound applies the checks that follow a found invitation and, when they
// pass, stores the acceptance with its consent and grant.
// pass, stores the acceptance with its consent and grant. The deadline is judged
// at the time the row is held, and a due expiry is applied first, so an
// acceptance at the deadline or later is refused with the expired state.
func (service *Service) acceptFound(
ctx context.Context,
unit outbound.UnitOfWork,
@@ -179,8 +181,16 @@ func (service *Service) acceptFound(
request acceptRequest,
entry outbound.CandidateInvitationEntry,
) (acceptOutcome, error) {
now, err := service.now(acceptLocation)
if err != nil {
return acceptOutcome{}, err
}
entry, err = settleCandidateEntry(ctx, unit, entry, now)
if err != nil {
return acceptOutcome{}, fmt.Errorf("%s - expire due invitation: %w", acceptLocation, err)
}
current := entry.Invitation
at := notBefore(request.now, current.UpdatedAt())
at := notBefore(now, current.UpdatedAt())
switch {
case current.State() == domain.InvitationAccepted:
return service.repeatAccept(ctx, unit, command, request, entry)
@@ -372,8 +372,11 @@ func TestAcceptMineAtTheDeadlineStoresTheConflictAndGrantsNothing(t *testing.T)
if result := state.acceptResults[testKeyring{}.IdempotencyScope(acceptOperation, "late", candidateID.String())]; result.Outcome != outbound.InvitationAcceptStateConflict {
t.Fatalf("stored outcome = %+v, want state_conflict under the key", result)
}
if len(state.grants) != 0 || len(state.consentRecords) != 0 || state.invitations[sent.ID].State() != domain.InvitationDelivered {
t.Fatalf("a late acceptance changed the invitation: grants %d, consents %d", len(state.grants), len(state.consentRecords))
// The late command applies the due expiry first, so the invitation is
// expired, and it grants and records nothing.
if len(state.grants) != 0 || len(state.consentRecords) != 0 || state.invitations[sent.ID].State() != domain.InvitationExpired {
t.Fatalf("a late acceptance left %v with grants %d, consents %d; want expired with none",
state.invitations[sent.ID].State(), len(state.grants), len(state.consentRecords))
}
}
@@ -134,13 +134,13 @@ func TestGetMineHasNoSideEffectAndViewMineKeepsTheDeadline(t *testing.T) {
}
}
func TestViewMineAtTheDeadlineChangesNothing(t *testing.T) {
func TestViewMineAtTheDeadlineExpiresTheInvitationAndRecordsNoView(t *testing.T) {
test := newHarness(t)
sent, candidateID := test.deliveredTo(t)
test.setTime(*sent.ResponseDeadlineAt)
view, err := test.service.ViewMine(t.Context(), candidateID, sent.ID)
if err != nil || view.State != domain.InvitationDelivered || view.Version != sent.Version || view.ViewedAt != nil {
t.Fatalf("late view = %+v, %v; want the delivered invitation unchanged", view, err)
if err != nil || view.State != domain.InvitationExpired || view.Version != sent.Version+1 || view.ViewedAt != nil {
t.Fatalf("late view = %+v, %v; want the invitation expired by the due expiry and no view", view, err)
}
}
@@ -211,8 +211,8 @@ func TestDeclineMineFollowsTheOrderOfChecks(t *testing.T) {
t.Fatalf("late decline error = %v, want ErrAnswerBlocked", err)
}
}
if state := test.transactor.snapshot(); len(state.declineResults) != 1 || state.invitations[sent.ID].State() != domain.InvitationDelivered {
t.Fatal("a late decline was not stored once or changed the invitation")
if state := test.transactor.snapshot(); len(state.declineResults) != 1 || state.invitations[sent.ID].State() != domain.InvitationExpired || len(state.declines) != 0 {
t.Fatal("a late decline was not stored once, or it recorded a decline or left the expired state unchanged")
}
// An unknown identifier is not found and stored as well.
@@ -0,0 +1,48 @@
package invitation
import (
"context"
"errors"
"fmt"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
const contactAccessLocation = "invitation.contactAccessOf"
// contactAccessOf derives the contact access that the organization sees
// through one invitation. An invitation without a grant is not_granted. A
// revoked grant, and a grant that the contact read refuses now, are closed.
// Only an active grant that the read allows is available, and it lists the
// kinds of the grant.
//
// The derivation uses the checks and the locks of the contact read, through
// readableContactGrant, so the view never claims access that a read would
// refuse. It runs in the caller's transaction, and the locks it takes last
// until that transaction ends. Every state is checked, not only the accepted
// one, because a withdrawn invitation keeps its grant.
func contactAccessOf(ctx context.Context, unit outbound.UnitOfWork, invitation domain.Invitation) (domain.InvitationContactAccessView, error) {
organizationID := invitation.OrganizationID()
grant, err := unit.ContactGrants().GetByInvitation(ctx, organizationID, invitation.ID())
if errors.Is(err, outbound.ErrContactGrantNotFound) {
return domain.NewInvitationContactAccessView(domain.InvitationContactAccessNone, nil), nil
}
if err != nil {
return domain.InvitationContactAccessView{}, fmt.Errorf("%s - read contact grant: %w", contactAccessLocation, err)
}
// A revoked grant never becomes readable again, so the unlocked read is final.
if grant.Status() == domain.ContactGrantRevoked {
return domain.NewInvitationContactAccessView(domain.InvitationContactAccessClosed, nil), nil
}
stored, readable, err := readableContactGrant(ctx, unit, grant, organizationID)
switch {
case errors.Is(err, outbound.ErrContactGrantNotFound):
return domain.NewInvitationContactAccessView(domain.InvitationContactAccessClosed, nil), nil
case err != nil:
return domain.InvitationContactAccessView{}, fmt.Errorf("%s - check contact read: %w", contactAccessLocation, err)
case !readable:
return domain.NewInvitationContactAccessView(domain.InvitationContactAccessClosed, nil), nil
}
return domain.NewInvitationContactAccessView(domain.InvitationContactAccessAvailable, stored.Fields().Fields()), nil
}
@@ -0,0 +1,199 @@
package invitation
import (
"errors"
"slices"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// organizationAccess reads the invitation as its organization and returns the
// contact access of the response.
func organizationAccess(t *testing.T, test *harness, invitationID uuid.UUID) domain.InvitationContactAccessView {
t.Helper()
view, err := test.service.Get(t.Context(), test.actorID, test.organizationID, invitationID)
if err != nil {
t.Fatalf("Get() error = %v", err)
}
return view.ContactAccess
}
func requireContactAccess(t *testing.T, got domain.InvitationContactAccessView, status domain.InvitationContactAccess, fields ...domain.ContactField) {
t.Helper()
if got.Status != status || !slices.Equal(got.Fields, fields) {
t.Fatalf("contact access = %+v, want status %q with fields %v", got, status, fields)
}
}
func TestOrganizationAccessIsNotGrantedBeforeAnAcceptance(t *testing.T) {
test := newHarness(t)
sent, _ := test.deliveredTo(t)
requireContactAccess(t, organizationAccess(t, test, sent.ID), domain.InvitationContactAccessNone)
page, err := test.service.List(t.Context(), ListCommand{ActorID: test.actorID, OrganizationID: test.organizationID, Limit: 10})
if err != nil || len(page.Items) != 1 {
t.Fatalf("List() = %d items, %v; want the delivered invitation", len(page.Items), err)
}
requireContactAccess(t, page.Items[0].ContactAccess, domain.InvitationContactAccessNone)
}
func TestOrganizationAccessIsAvailableWithTheGrantedKindsAfterAnAcceptance(t *testing.T) {
test := newHarness(t)
sent, _ := acceptedForContacts(t, test)
requireContactAccess(t, organizationAccess(t, test, sent.ID), domain.InvitationContactAccessAvailable, domain.ContactFieldEmail)
page, err := test.service.List(t.Context(), ListCommand{ActorID: test.actorID, OrganizationID: test.organizationID, Limit: 10})
if err != nil || len(page.Items) != 1 {
t.Fatalf("List() = %d items, %v; want the accepted invitation", len(page.Items), err)
}
requireContactAccess(t, page.Items[0].ContactAccess, domain.InvitationContactAccessAvailable, domain.ContactFieldEmail)
}
// TestOrganizationAccessAgreesWithTheContactRead checks each state of a grant
// against the read: the view claims available exactly when the read answers.
func TestOrganizationAccessAgreesWithTheContactRead(t *testing.T) {
tests := []struct {
name string
change func(t *testing.T, test *harness, candidateID uuid.UUID, sent domain.OrganizationInvitationView)
want domain.InvitationContactAccess
}{
{
name: "no change",
change: func(*testing.T, *harness, uuid.UUID, domain.OrganizationInvitationView) {},
want: domain.InvitationContactAccessAvailable,
},
{
name: "the C4 revocation stamps the grant and its record",
change: func(t *testing.T, test *harness, _ uuid.UUID, sent domain.OrganizationInvitationView) {
t.Helper()
stored := test.transactor.snapshot().grants[sent.ID].Stored()
revokedAt := sent.DeliveredAt.Add(2 * time.Hour)
stored.RevokedAt, stored.RevocationReason = &revokedAt, string(domain.ContactRevocationConsentRevoked)
revoked, err := domain.RestoreContactGrant(stored)
if err != nil {
t.Fatalf("RestoreContactGrant() error = %v", err)
}
test.setState(func(state *testState) {
state.grants[sent.ID] = revoked
delete(state.consentRecords, sent.ID)
})
},
want: domain.InvitationContactAccessClosed,
},
{
name: "the C4 record is no longer current while the grant is active",
change: func(_ *testing.T, test *harness, _ uuid.UUID, sent domain.OrganizationInvitationView) {
test.setState(func(state *testState) { delete(state.consentRecords, sent.ID) })
},
want: domain.InvitationContactAccessClosed,
},
{
name: "the organization is hidden",
change: func(_ *testing.T, test *harness, candidateID uuid.UUID, _ domain.OrganizationInvitationView) {
test.setState(func(state *testState) { state.hidden[[2]uuid.UUID{candidateID, test.organizationID}] = true })
},
want: domain.InvitationContactAccessClosed,
},
{
name: "the publication is closed",
change: func(_ *testing.T, test *harness, candidateID uuid.UUID, _ domain.OrganizationInvitationView) {
test.setState(func(state *testState) { delete(state.publications, candidateID) })
},
want: domain.InvitationContactAccessClosed,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
test := newHarness(t)
sent, candidateID := acceptedForContacts(t, test)
tc.change(t, test, candidateID, sent)
access := organizationAccess(t, test, sent.ID)
if access.Status != tc.want {
t.Fatalf("contact access = %+v, want %q", access, tc.want)
}
if access.Status == domain.InvitationContactAccessClosed && len(access.Fields) != 0 {
t.Fatalf("closed access lists fields %v", access.Fields)
}
_, readErr := test.service.ReadContacts(t.Context(), test.actorID, test.organizationID, sent.ID)
readable := readErr == nil
if readErr != nil && !errors.Is(readErr, outbound.ErrContactGrantNotFound) {
t.Fatalf("ReadContacts() error = %v, want nil or not found", readErr)
}
if readable != (access.Status == domain.InvitationContactAccessAvailable) {
t.Fatalf("read succeeds = %t while the view says %q", readable, access.Status)
}
})
}
}
func TestOrganizationAccessOpensOnlyAGrantThatWasBlockedFromTheStart(t *testing.T) {
test := newHarness(t)
sent, candidateID := test.deliveredTo(t)
test.setProfile(t, candidateID, domain.ContactFieldEmail)
test.setTime(sent.DeliveredAt.Add(time.Hour))
test.publish(candidateID, *sent.DeliveredAt)
test.setState(func(state *testState) { state.hidden[[2]uuid.UUID{candidateID, test.organizationID}] = true })
if _, err := test.service.AcceptMine(t.Context(), acceptCommand(candidateID, sent.ID, sent.Version, sent.TermsVersion,
"accept-blocked-access", domain.ContactFieldEmail)); err != nil {
t.Fatalf("AcceptMine() while hidden error = %v", err)
}
requireContactAccess(t, organizationAccess(t, test, sent.ID), domain.InvitationContactAccessClosed)
test.setState(func(state *testState) { delete(state.hidden, [2]uuid.UUID{candidateID, test.organizationID}) })
requireContactAccess(t, organizationAccess(t, test, sent.ID), domain.InvitationContactAccessAvailable, domain.ContactFieldEmail)
}
func TestOrganizationAccessStaysClosedForARevokedGrantAfterItIsVisibleAgain(t *testing.T) {
test := newHarness(t)
sent, candidateID := acceptedForContacts(t, test)
revokedAt := sent.DeliveredAt.Add(2 * time.Hour)
stored := test.transactor.snapshot().grants[sent.ID].Stored()
stored.RevokedAt, stored.RevocationReason = &revokedAt, string(domain.ContactRevocationVisibilityClosed)
revoked, err := domain.RestoreContactGrant(stored)
if err != nil {
t.Fatalf("RestoreContactGrant() error = %v", err)
}
test.setState(func(state *testState) { state.grants[sent.ID] = revoked })
requireContactAccess(t, organizationAccess(t, test, sent.ID), domain.InvitationContactAccessClosed)
// Publishing again and unhiding never reopen a revoked grant.
test.publish(candidateID, revokedAt.Add(time.Hour))
requireContactAccess(t, organizationAccess(t, test, sent.ID), domain.InvitationContactAccessClosed)
}
func TestOrganizationAccessIsNotGrantedForADeclinedOrAnExpiredInvitation(t *testing.T) {
t.Run("declined", func(t *testing.T) {
test := newHarness(t)
sent, candidateID := test.deliveredTo(t)
if _, err := test.service.DeclineMine(t.Context(), declineCommand(candidateID, sent.ID, sent.Version,
"decline-access", domain.InvitationDeclineOther, nil)); err != nil {
t.Fatalf("DeclineMine() error = %v", err)
}
requireContactAccess(t, organizationAccess(t, test, sent.ID), domain.InvitationContactAccessNone)
})
t.Run("expired", func(t *testing.T) {
test := newHarness(t)
sent, candidateID := test.deliveredTo(t)
test.setTime(*sent.ResponseDeadlineAt)
if expired, err := test.service.GetMine(t.Context(), candidateID, sent.ID); err != nil || expired.State != domain.InvitationExpired {
t.Fatalf("GetMine() at the deadline = %v, %v; want expired", expired.State, err)
}
requireContactAccess(t, organizationAccess(t, test, sent.ID), domain.InvitationContactAccessNone)
})
}
func TestOrganizationAccessOfAnotherOrganizationIsNotFound(t *testing.T) {
test := newHarness(t)
sent, _ := acceptedForContacts(t, test)
other := uuid.Must(uuid.NewV7())
if _, err := test.service.Get(t.Context(), test.actorID, other, sent.ID); !errors.Is(err, outbound.ErrOrganizationNotFound) {
t.Fatalf("Get(other organization) error = %v, want not found", err)
}
}
@@ -0,0 +1,153 @@
package invitation
import (
"context"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
const contactsReadLocation = "invitation.Service.ReadContacts"
// ReadContacts returns the contacts that the active grant of one invitation
// allows the organization to read now. Only the owner of the organization
// reads contacts in the MVP. Every other case answers ErrContactGrantNotFound,
// which the caller maps to the same not found: no grant of the invitation, a
// grant of another organization, a revoked grant, a revoked C4 record, and a
// profile that the candidate does not publish or has hidden from the
// organization.
//
// The read checks everything on every call, with no cache. It takes the locks
// in the order of the other candidate-scoped reads: the organization and the
// membership (authorizeOwner), the candidate account, the current C2 record,
// the publication, the C4 record, and the grant. A grant read is the only
// read that records an audit event; it does not consume the card-view quota,
// because the contract does not count contact reads against it.
func (service *Service) ReadContacts(
ctx context.Context,
actorID, organizationID, invitationID uuid.UUID,
) (domain.ContactDisclosure, error) {
if actorID == uuid.Nil || organizationID == uuid.Nil {
return domain.ContactDisclosure{}, fmt.Errorf("%s - actor and organization IDs must be set: %w", contactsReadLocation, ErrForbidden)
}
at, err := service.now(contactsReadLocation)
if err != nil {
return domain.ContactDisclosure{}, err
}
var result domain.ContactDisclosure
err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
var err error
result, err = service.readContactsInTransaction(ctx, unit, actorID, organizationID, invitationID, at)
return err
})
if err != nil {
return domain.ContactDisclosure{}, fmt.Errorf("%s - run transaction: %w", contactsReadLocation, err)
}
return result, nil
}
func (service *Service) readContactsInTransaction(
ctx context.Context,
unit outbound.UnitOfWork,
actorID, organizationID, invitationID uuid.UUID,
at time.Time,
) (domain.ContactDisclosure, error) {
if err := authorizeOwner(ctx, unit, actorID, organizationID, contactsReadLocation); err != nil {
return domain.ContactDisclosure{}, err
}
if invitationID == uuid.Nil {
return domain.ContactDisclosure{}, fmt.Errorf("%s - the nil identifier names no grant: %w", contactsReadLocation, outbound.ErrContactGrantNotFound)
}
// The unlocked read only names the candidate, which never changes for a
// grant, so readableContactGrant can take the visibility locks before the
// grant lock.
grant, err := unit.ContactGrants().GetByInvitation(ctx, organizationID, invitationID)
if err != nil {
return domain.ContactDisclosure{}, fmt.Errorf("%s - read contact grant: %w", contactsReadLocation, err)
}
stored, readable, err := readableContactGrant(ctx, unit, grant, organizationID)
if err != nil {
return domain.ContactDisclosure{}, fmt.Errorf("%s - check contact read: %w", contactsReadLocation, err)
}
if !readable {
return domain.ContactDisclosure{}, fmt.Errorf("%s - the grant does not allow the read now: %w", contactsReadLocation, outbound.ErrContactGrantNotFound)
}
profile, err := unit.CandidateProfiles().Get(ctx, stored.CandidateID())
if err != nil {
return domain.ContactDisclosure{}, fmt.Errorf("%s - read candidate profile: %w", contactsReadLocation, err)
}
disclosure, err := domain.NewContactDisclosure(stored, profile)
if err != nil {
return domain.ContactDisclosure{}, fmt.Errorf("%s - build disclosure: %w", contactsReadLocation, err)
}
access, err := domain.NewCandidateCardAccess(domain.CandidateCardAccessInput{
CandidateID: stored.CandidateID(), OrganizationID: organizationID, ActorID: actorID,
Kind: domain.CandidateCardAccessContactRead, ContactFields: stored.Fields().Fields(), OccurredAt: at,
})
if err != nil {
return domain.ContactDisclosure{}, fmt.Errorf("%s - build access audit: %w", contactsReadLocation, err)
}
if err := unit.PrivacyView().RecordCandidateCardAccess(ctx, access); err != nil {
return domain.ContactDisclosure{}, fmt.Errorf("%s - record access audit: %w", contactsReadLocation, err)
}
return disclosure, nil
}
// readableContactGrant applies the checks that decide whether the organization
// may read the contacts of a grant now. It takes the visibility locks first and
// then the C4 record and the grant, the order that the revocations follow. It
// reports true only for an active grant under a current consent, while the
// organization may read the profile, and it returns the grant as stored under
// those locks. The caller holds the locks until its transaction ends.
func readableContactGrant(
ctx context.Context,
unit outbound.UnitOfWork,
grant domain.ContactGrant,
organizationID uuid.UUID,
) (domain.ContactGrant, bool, error) {
visible, err := lockContactVisibility(ctx, unit, grant.CandidateID(), organizationID)
if err != nil {
return domain.ContactGrant{}, false, fmt.Errorf("lock visibility: %w", err)
}
if !visible {
return domain.ContactGrant{}, false, nil
}
stored, consentCurrent, err := unit.ContactGrants().LockForRead(ctx, grant)
if err != nil {
return domain.ContactGrant{}, false, fmt.Errorf("lock contact grant: %w", err)
}
return stored, consentCurrent && stored.Status() == domain.ContactGrantActive, nil
}
// lockContactVisibility share-locks the candidate account, the current C2
// record, and the publication, in the order of the card reads. It reports
// false when the candidate has no active C2 or the publication is not visible
// to the organization, and it holds the locks until the transaction ends, so a
// hiding or a revocation that commits later waits for the read.
func lockContactVisibility(
ctx context.Context,
unit outbound.UnitOfWork,
candidateID, organizationID uuid.UUID,
) (bool, error) {
repository := unit.PrivacyView()
if err := repository.LockCandidateAccountForView(ctx, candidateID); err != nil {
return false, fmt.Errorf("lock candidate account: %w", err)
}
c2RecordID, err := repository.LockCurrentC2ForView(ctx, candidateID)
if errors.Is(err, outbound.ErrCandidateC2Unavailable) {
return false, nil
}
if err != nil {
return false, fmt.Errorf("lock current C2: %w", err)
}
visible, err := repository.LockVisiblePublicationForView(ctx, organizationID, candidateID, c2RecordID)
if err != nil {
return false, fmt.Errorf("lock visible publication: %w", err)
}
return visible, nil
}
@@ -0,0 +1,205 @@
package invitation
import (
"context"
"errors"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// testPrivacyView is the visibility barrier of the fakes. A published
// publication has one active C2 record, and a hidden organization may not read
// the profile. The database keeps the stamps; these fakes only answer.
type testPrivacyView struct {
outbound.PrivacyViewRepository
state *testState
}
func (unit *testUnit) PrivacyView() outbound.PrivacyViewRepository {
return testPrivacyView{state: unit.state}
}
func (testPrivacyView) LockCandidateAccountForView(context.Context, uuid.UUID) error { return nil }
func (repository testPrivacyView) LockCurrentC2ForView(_ context.Context, candidateID uuid.UUID) (uuid.UUID, error) {
publication, ok := repository.state.publications[candidateID]
if !ok || publication.State() != domain.PublicationPublished {
return uuid.Nil, outbound.ErrCandidateC2Unavailable
}
return publication.ConsentRecordID(), nil
}
func (repository testPrivacyView) LockVisiblePublicationForView(_ context.Context, organizationID, candidateID, _ uuid.UUID) (bool, error) {
publication, ok := repository.state.publications[candidateID]
return ok && publication.State() == domain.PublicationPublished &&
!repository.state.hidden[[2]uuid.UUID{candidateID, organizationID}], nil
}
func (testPrivacyView) RecordCandidateCardAccess(context.Context, domain.CandidateCardAccess) error {
return nil
}
// LockForRead answers from the stored grant and its C4 record, the way the
// database does: the record must be unrevoked for the grant to be current.
func (repository testContactGrants) LockForRead(_ context.Context, grant domain.ContactGrant) (domain.ContactGrant, bool, error) {
stored, ok := repository.state.grants[grant.InvitationID()]
if !ok || stored.ID() != grant.ID() {
return domain.ContactGrant{}, false, outbound.ErrContactGrantNotFound
}
record, ok := repository.state.consentRecords[grant.InvitationID()]
if !ok {
return stored, false, nil
}
_, revoked := record.RevokedAt()
return stored, !revoked, nil
}
// acceptedForContacts delivers an invitation to a published candidate who
// holds an email and a phone number, and accepts it for the email only.
func acceptedForContacts(t *testing.T, test *harness) (domain.OrganizationInvitationView, uuid.UUID) {
t.Helper()
sent, candidateID := test.deliveredTo(t)
test.setProfile(t, candidateID, domain.ContactFieldEmail, domain.ContactFieldPhone)
test.setTime(sent.DeliveredAt.Add(time.Hour))
test.publish(candidateID, *sent.DeliveredAt)
if _, err := test.service.AcceptMine(t.Context(), acceptCommand(candidateID, sent.ID, sent.Version, sent.TermsVersion,
"accept-for-contacts", domain.ContactFieldEmail)); err != nil {
t.Fatalf("AcceptMine() error = %v", err)
}
return sent, candidateID
}
func (test *harness) addMember(t *testing.T, organizationID, actorID uuid.UUID, role domain.OrganizationRole) {
t.Helper()
verified := time.Date(2026, time.October, 9, 9, 0, 0, 0, time.UTC)
test.setState(func(state *testState) {
state.users[actorID] = domain.User{ID: actorID, Scenario: domain.ScenarioEmployer, EmailVerifiedAt: &verified}
membership, err := domain.NewMembership(domain.MembershipInput{
OrganizationID: organizationID, UserID: actorID, Role: role, At: verified,
})
if err != nil {
t.Fatalf("NewMembership() error = %v", err)
}
state.memberships[[2]uuid.UUID{organizationID, actorID}] = membership
})
}
func TestReadContactsReturnsOnlyTheGrantedKindsToTheOwner(t *testing.T) {
test := newHarness(t)
sent, _ := acceptedForContacts(t, test)
disclosure, err := test.service.ReadContacts(t.Context(), test.actorID, test.organizationID, sent.ID)
if err != nil {
t.Fatalf("ReadContacts() error = %v", err)
}
if email, ok := disclosure.Email(); !ok || email != "candidate@example.test" {
t.Fatalf("email = %q, %v; want the confirmed address", email, ok)
}
if _, ok := disclosure.Phone(); ok {
t.Fatal("phone was disclosed although the grant names only the email")
}
if len(disclosure.Fields()) != 1 || disclosure.Fields()[0] != domain.ContactFieldEmail {
t.Fatalf("fields = %v, want the email only", disclosure.Fields())
}
if disclosure.GrantID() != test.transactor.snapshot().grants[sent.ID].ID() {
t.Fatal("the disclosure names another grant than the stored one")
}
}
func TestReadContactsRefusesEveryOtherActorBeforeTheGrant(t *testing.T) {
test := newHarness(t)
sent, candidateID := acceptedForContacts(t, test)
recruiter := uuid.Must(uuid.NewV7())
test.addMember(t, test.organizationID, recruiter, domain.OrganizationRoleRecruiter)
outsider := uuid.Must(uuid.NewV7())
test.addMember(t, uuid.Must(uuid.NewV7()), outsider, domain.OrganizationRoleOwner)
otherOrganization := uuid.Must(uuid.NewV7())
otherOwner := uuid.Must(uuid.NewV7())
test.addMember(t, otherOrganization, otherOwner, domain.OrganizationRoleOwner)
tests := []struct {
name string
actorID uuid.UUID
organizationID uuid.UUID
want error
}{
{"non-owner member of the organization", recruiter, test.organizationID, outbound.ErrOrganizationManagerRequired},
{"candidate account", candidateID, test.organizationID, ErrForbidden},
{"employer without a membership in the organization", outsider, test.organizationID, outbound.ErrOrganizationNotFound},
{"owner of another organization", otherOwner, otherOrganization, outbound.ErrContactGrantNotFound},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
_, err := test.service.ReadContacts(t.Context(), tc.actorID, tc.organizationID, sent.ID)
if !errors.Is(err, tc.want) {
t.Fatalf("ReadContacts() error = %v, want %v", err, tc.want)
}
})
}
}
func TestReadContactsIsClosedWhileTheProfileIsNotReadable(t *testing.T) {
test := newHarness(t)
sent, candidateID := acceptedForContacts(t, test)
publication := test.transactor.snapshot().publications[candidateID]
test.setState(func(state *testState) { state.hidden[[2]uuid.UUID{candidateID, test.organizationID}] = true })
if _, err := test.service.ReadContacts(t.Context(), test.actorID, test.organizationID, sent.ID); !errors.Is(err, outbound.ErrContactGrantNotFound) {
t.Fatalf("ReadContacts() while hidden error = %v, want not found", err)
}
test.setState(func(state *testState) {
delete(state.hidden, [2]uuid.UUID{candidateID, test.organizationID})
delete(state.publications, candidateID)
})
if _, err := test.service.ReadContacts(t.Context(), test.actorID, test.organizationID, sent.ID); !errors.Is(err, outbound.ErrContactGrantNotFound) {
t.Fatalf("ReadContacts() without a publication error = %v, want not found", err)
}
// The same grant is readable again once the profile is visible, which
// shows that the refusals above came from the visibility and not the grant.
test.setState(func(state *testState) { state.publications[candidateID] = publication })
if _, err := test.service.ReadContacts(t.Context(), test.actorID, test.organizationID, sent.ID); err != nil {
t.Fatalf("ReadContacts() after publishing again error = %v", err)
}
}
func TestReadContactsRefusesARevokedGrantOrAnInvitationWithoutOne(t *testing.T) {
test := newHarness(t)
sent, _ := acceptedForContacts(t, test)
grant := test.transactor.snapshot().grants[sent.ID]
stored := grant.Stored()
revokedAt := sent.DeliveredAt.Add(2 * time.Hour)
stored.RevokedAt, stored.RevocationReason = &revokedAt, string(domain.ContactRevocationConsentRevoked)
revoked, err := domain.RestoreContactGrant(stored)
if err != nil {
t.Fatalf("RestoreContactGrant() error = %v", err)
}
test.setState(func(state *testState) { state.grants[sent.ID] = revoked })
if _, err := test.service.ReadContacts(t.Context(), test.actorID, test.organizationID, sent.ID); !errors.Is(err, outbound.ErrContactGrantNotFound) {
t.Fatalf("ReadContacts() of a revoked grant error = %v, want not found", err)
}
delivered, _ := test.deliveredTo(t)
if _, err := test.service.ReadContacts(t.Context(), test.actorID, test.organizationID, delivered.ID); !errors.Is(err, outbound.ErrContactGrantNotFound) {
t.Fatalf("ReadContacts() of a delivered invitation error = %v, want not found", err)
}
for _, invitationID := range []uuid.UUID{uuid.Nil, uuid.Must(uuid.NewV7())} {
if _, err := test.service.ReadContacts(t.Context(), test.actorID, test.organizationID, invitationID); !errors.Is(err, outbound.ErrContactGrantNotFound) {
t.Fatalf("ReadContacts(%v) error = %v, want not found", invitationID, err)
}
}
}
func TestReadContactsRefusesAConsentRecordThatIsRevoked(t *testing.T) {
test := newHarness(t)
sent, _ := acceptedForContacts(t, test)
test.setState(func(state *testState) { delete(state.consentRecords, sent.ID) })
if _, err := test.service.ReadContacts(t.Context(), test.actorID, test.organizationID, sent.ID); !errors.Is(err, outbound.ErrContactGrantNotFound) {
t.Fatalf("ReadContacts() without a current C4 record error = %v, want not found", err)
}
}
+34 -8
View File
@@ -62,13 +62,15 @@ type declineFingerprint struct {
// 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. 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.
// 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 and then only the
// invitation row, never the organization, as for the view.
// 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 {
@@ -146,6 +148,20 @@ func (service *Service) declineInTransaction(
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)
@@ -158,7 +174,9 @@ func (service *Service) declineInTransaction(
// 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.
// 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,
@@ -166,8 +184,16 @@ func (service *Service) declineFound(
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(request.now, current.UpdatedAt())
at := notBefore(now, current.UpdatedAt())
if current.State() == domain.InvitationDeclined {
previous, err := unit.Invitations().GetDecline(ctx, current.OrganizationID(), current.ID())
if err != nil {
+5 -5
View File
@@ -122,7 +122,7 @@ func (service *Service) createInTransaction(
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(invitation)
view, err := service.view(ctx, unit, invitation)
if err != nil {
return domain.OrganizationInvitationView{}, err
}
@@ -300,7 +300,7 @@ func (service *Service) updateInTransaction(
merged := mergeDraft(before, command)
changed := before.ChangedFields(merged)
if len(changed) == 0 {
return service.view(current)
return service.view(ctx, unit, current)
}
if command.ExpectedVersion != current.Version() {
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - compare expected version: %w", updateLocation, domain.ErrInvitationVersionConflict)
@@ -333,7 +333,7 @@ func (service *Service) updateInTransaction(
}
return domain.OrganizationInvitationView{}, fmt.Errorf("%s - save draft: %w", updateLocation, err)
}
return service.view(next)
return service.view(ctx, unit, next)
}
// mergeDraft applies the fields the command sets over the current content.
@@ -407,7 +407,7 @@ func (service *Service) Get(ctx context.Context, actorID, organizationID, invita
if err != nil {
return fmt.Errorf("%s - read invitation: %w", getLocation, err)
}
result, err = service.view(current)
result, err = service.view(ctx, unit, current)
return err
})
if err != nil {
@@ -452,7 +452,7 @@ func (service *Service) List(ctx context.Context, command ListCommand) (Page, er
}
result = Page{Items: make([]domain.OrganizationInvitationView, 0, len(page.Items)), HasMore: page.HasMore}
for _, invitation := range page.Items {
item, err := service.view(invitation)
item, err := service.view(ctx, unit, invitation)
if err != nil {
return err
}
@@ -0,0 +1,166 @@
package invitation
import (
"context"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/inbound"
"lincodex/backend/internal/port/outbound"
)
// ResponseDeadlineJobKind names the scheduled job that expires an invitation
// at its response deadline. The delivery schedules it in its own transaction.
const ResponseDeadlineJobKind = "invitation.response_deadline"
const (
responseDeadlineLocation = "invitation.ResponseDeadlineJob.Handle"
scheduleDeadlineLocation = "invitation.scheduleResponseDeadline"
)
// ResponseDeadlineJob expires a delivered or viewed invitation whose response
// deadline has passed. The job is keyed by its invitation, so a delivery has one
// job, and the job is idempotent: a run that finds the invitation answered or
// expired changes nothing. The expiry creates no consent, no contact grant, and
// no quota change.
type ResponseDeadlineJob struct {
clock func() time.Time
}
// NewResponseDeadlineJob returns the handler of ResponseDeadlineJobKind. A nil
// clock is the process clock.
func NewResponseDeadlineJob(clock func() time.Time) *ResponseDeadlineJob {
if clock == nil {
clock = time.Now
}
return &ResponseDeadlineJob{clock: clock}
}
// JobKind is the stable kind name.
func (*ResponseDeadlineJob) JobKind() string { return ResponseDeadlineJobKind }
// Handle expires the invitation of the job when it still waits for an answer.
// The row is locked before the answer is read, so a candidate command that
// answers at the same moment either wins first, and the job then changes
// nothing, or waits and finds the expiry. The job runs at its due time, which is
// the deadline the invitation stores; a clock that has not reached that deadline
// returns an error, so the job is retried instead of completing unexpired.
func (job *ResponseDeadlineJob) Handle(ctx context.Context, unit outbound.UnitOfWork, scheduled outbound.ClaimedJob) error {
invitationID, err := responseDeadlinePayload(scheduled.Payload)
if err != nil {
return fmt.Errorf("%s - read payload: %w", responseDeadlineLocation, err)
}
current, err := unit.Invitations().GetForDeadline(ctx, invitationID)
if errors.Is(err, outbound.ErrInvitationNotFound) {
return nil
}
if err != nil {
return fmt.Errorf("%s - lock invitation: %w", responseDeadlineLocation, err)
}
if !current.AwaitsAnswer() {
return nil
}
now := job.clock().UTC().Truncate(time.Microsecond)
if !current.ResponseDeadlinePassed(now) {
return fmt.Errorf("%s - the response deadline has not passed by the application clock", responseDeadlineLocation)
}
if _, err := expireDueInvitation(ctx, unit, current, notBefore(now, current.UpdatedAt())); err != nil {
return fmt.Errorf("%s - expire invitation: %w", responseDeadlineLocation, err)
}
return nil
}
// responseDeadlinePayload reads the invitation that a job names. A payload that
// names no invitation can never run, so it is final.
func responseDeadlinePayload(payload json.RawMessage) (uuid.UUID, error) {
var fields struct {
InvitationID string `json:"invitation_id"`
}
if err := json.Unmarshal(payload, &fields); err != nil {
return uuid.Nil, fmt.Errorf("decode payload: %w", inbound.ErrJobRejected)
}
parsed, err := uuid.Parse(fields.InvitationID)
if err != nil || parsed == uuid.Nil {
return uuid.Nil, fmt.Errorf("payload names no invitation: %w", inbound.ErrJobRejected)
}
return parsed, nil
}
// scheduleResponseDeadline schedules the expiry of a delivered invitation at
// its response deadline. It runs in the delivery transaction, so the job exists
// exactly when the delivery committed. The first schedule of the key wins, and
// a key that already exists means the delivery ran twice, which is refused.
func scheduleResponseDeadline(ctx context.Context, unit outbound.UnitOfWork, delivered domain.Invitation) error {
snapshot := delivered.Snapshot()
if snapshot.ResponseDeadlineAt == nil {
return fmt.Errorf("%s - a delivered invitation has a response deadline: %w", scheduleDeadlineLocation, domain.ErrInvalidInvitation)
}
payload, err := json.Marshal(map[string]string{"invitation_id": snapshot.ID.String()})
if err != nil {
return fmt.Errorf("%s - encode payload: %w", scheduleDeadlineLocation, err)
}
job, err := domain.NewScheduledJob(domain.ScheduledJobInput{
Kind: ResponseDeadlineJobKind, Key: snapshot.ID.String(), DueAt: *snapshot.ResponseDeadlineAt, Payload: payload,
})
if err != nil {
return fmt.Errorf("%s - build job: %w", scheduleDeadlineLocation, err)
}
scheduled, err := unit.ScheduledJobs().Schedule(ctx, job)
if err != nil {
return fmt.Errorf("%s - schedule job: %w", scheduleDeadlineLocation, err)
}
if !scheduled {
return fmt.Errorf("%s - the deadline job of the invitation exists already: %w", scheduleDeadlineLocation, domain.ErrInvalidInvitation)
}
return nil
}
// expireDueInvitation stores the expiry of an invitation whose deadline has
// passed at the given time, inside the caller's transaction, and returns the
// invitation as it stands afterwards. The caller holds the row lock. An
// invitation that is not due is returned unchanged.
func expireDueInvitation(
ctx context.Context,
unit outbound.UnitOfWork,
current domain.Invitation,
at time.Time,
) (domain.Invitation, error) {
expired, changed, err := current.Expire(at)
if err != nil {
return domain.Invitation{}, fmt.Errorf("expire invitation: %w", err)
}
if !changed {
return current, nil
}
event, err := expired.ExpiryEvent()
if err != nil {
return domain.Invitation{}, fmt.Errorf("build audit event: %w", err)
}
if err := unit.Invitations().Expire(ctx, current.Version(), expired, event); err != nil {
return domain.Invitation{}, fmt.Errorf("store expiry: %w", err)
}
return expired, nil
}
// settleCandidateEntry applies the due expiry to an invitation that a candidate
// read or command has locked or is about to read, at the time that command
// decided on. A read that found the invitation due must lock it first; the
// caller holds the lock.
func settleCandidateEntry(
ctx context.Context,
unit outbound.UnitOfWork,
entry outbound.CandidateInvitationEntry,
now time.Time,
) (outbound.CandidateInvitationEntry, error) {
current, err := expireDueInvitation(ctx, unit, entry.Invitation, notBefore(now, entry.Invitation.UpdatedAt()))
if err != nil {
return outbound.CandidateInvitationEntry{}, err
}
entry.Invitation = current
return entry, nil
}
@@ -0,0 +1,272 @@
package invitation
import (
"context"
"encoding/json"
"errors"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/inbound"
"lincodex/backend/internal/port/outbound"
)
func (repository testInvitations) GetForDeadline(_ context.Context, invitationID uuid.UUID) (domain.Invitation, error) {
invitation, ok := repository.state.invitations[invitationID]
if !ok {
return domain.Invitation{}, outbound.ErrInvitationNotFound
}
return invitation, nil
}
func (repository testInvitations) Expire(_ context.Context, expectedVersion int64, next domain.Invitation, event domain.InvitationEvent) error {
current, ok := repository.state.invitations[next.ID()]
if !ok || current.Version() != expectedVersion || !current.ExpiryDue(next.UpdatedAt()) {
return outbound.ErrInvitationVersionConflict
}
repository.state.invitations[next.ID()] = next
repository.state.events = append(repository.state.events, event)
return nil
}
func (repository testInvitations) CountPendingNeedInvitations(_ context.Context, organizationID, needID uuid.UUID) (int64, error) {
var count int64
for _, invitation := range repository.state.invitations {
need := invitation.Snapshot().Need
if invitation.OrganizationID() != organizationID || need == nil || need.NeedID != needID {
continue
}
if state := invitation.State(); state == domain.InvitationDelivered || state == domain.InvitationViewed || state == domain.InvitationCounter {
count++
}
}
return count, nil
}
func (repository testInvitations) LatestDeclineTime(_ context.Context, organizationID, candidateID uuid.UUID) (time.Time, bool, error) {
var latest time.Time
found := false
for _, invitation := range repository.state.invitations {
if invitation.OrganizationID() != organizationID || invitation.CandidateID() != candidateID || invitation.State() != domain.InvitationDeclined {
continue
}
if at := *invitation.Snapshot().RespondedAt; !found || at.After(latest) {
latest, found = at, true
}
}
return latest, found, nil
}
// deadlineJob returns the scheduled deadline job of an invitation, which the
// delivery stored in the transaction of the send.
func (test *harness) deadlineJob(t *testing.T, invitationID uuid.UUID) domain.ScheduledJob {
t.Helper()
job, ok := test.transactor.snapshot().jobs[ResponseDeadlineJobKind+"\x00"+invitationID.String()]
if !ok {
t.Fatalf("no deadline job for invitation %s", invitationID)
}
return job
}
// runDeadlineJob runs the handler on a claimed job in its own transaction, as
// the worker does, with the given application clock.
func (test *harness) runDeadlineJob(t *testing.T, claimed outbound.ClaimedJob, clock func() time.Time) error {
t.Helper()
handler := NewResponseDeadlineJob(clock)
return test.transactor.WithinTransaction(t.Context(), func(ctx context.Context, unit outbound.UnitOfWork) error {
return handler.Handle(ctx, unit, claimed)
})
}
// claimOf turns a stored job into the claim that the worker hands to a handler.
func claimOf(job domain.ScheduledJob) outbound.ClaimedJob {
return outbound.ClaimedJob{Kind: job.Kind(), Key: job.Key(), DueAt: job.DueAt(), Payload: job.Payload()}
}
func (test *harness) acceptCommand(candidateID, invitationID uuid.UUID, version int64, key string) AcceptCommand {
return AcceptCommand{
ActorID: candidateID, InvitationID: invitationID, IdempotencyKey: key, ExpectedVersion: version,
TermsVersion: 1, TextVersion: "c4-2026-10-01", Fields: []domain.ContactField{domain.ContactFieldEmail},
}
}
func expiryEvents(state testState) []domain.InvitationEvent {
var events []domain.InvitationEvent
for _, event := range state.events {
if event.Kind == domain.InvitationEventExpired {
events = append(events, event)
}
}
return events
}
func TestDeliveryScheduleTheExpiryJobAtTheResponseDeadline(t *testing.T) {
test := newHarness(t)
sent, _ := test.deliveredTo(t)
job := test.deadlineJob(t, sent.ID)
if job.Kind() != ResponseDeadlineJobKind || job.Key() != sent.ID.String() || !job.DueAt().Equal(*sent.ResponseDeadlineAt) {
t.Fatalf("deadline job = %s/%s due %v, want the invitation key due at its deadline %v",
job.Kind(), job.Key(), job.DueAt(), *sent.ResponseDeadlineAt)
}
var payload map[string]string
if err := json.Unmarshal(job.Payload(), &payload); err != nil || len(payload) != 1 || payload["invitation_id"] != sent.ID.String() {
t.Fatalf("job payload = %s, want only the invitation identifier", job.Payload())
}
}
func TestCandidateReadAtTheDeadlineExpiresTheInvitationOnceWithoutAGrant(t *testing.T) {
test := newHarness(t)
sent, candidate := test.deliveredTo(t)
deadline := *sent.ResponseDeadlineAt
charges := len(test.transactor.snapshot().charged)
test.setTime(deadline.Add(-time.Microsecond))
before, err := test.service.GetMine(t.Context(), candidate, sent.ID)
if err != nil || before.State != domain.InvitationDelivered {
t.Fatalf("GetMine(one microsecond before the deadline) = %v, %v; want delivered", before.State, err)
}
test.setTime(deadline)
expired, err := test.service.GetMine(t.Context(), candidate, sent.ID)
if err != nil || expired.State != domain.InvitationExpired || expired.ExpiryReason == nil || *expired.ExpiryReason != domain.InvitationExpiryTimeout {
t.Fatalf("GetMine(at the deadline) = %v, %v; want expired by the timeout", expired.State, err)
}
if !expired.ResponseDeadlineAt.Equal(deadline) || expired.ContactGrant != nil || expired.ContactConsent != nil {
t.Fatalf("expired view has deadline %v, grant %v, and offer %v; want the deadline and no consent or grant",
expired.ResponseDeadlineAt, expired.ContactGrant, expired.ContactConsent)
}
state := test.transactor.snapshot()
if len(state.grants) != 0 || len(state.consentRecords) != 0 || len(state.charged) != charges {
t.Fatalf("expiry created %d grants and %d consents and charged %d; want no grant, no consent, and the same charges",
len(state.grants), len(state.consentRecords), len(state.charged))
}
events := expiryEvents(state)
if len(events) != 1 || events[0].ActorID != uuid.Nil || events[0].Version != expired.Version {
t.Fatalf("expiry events = %+v, want one system event of the expired version", events)
}
// Later reads show the same invitation and write nothing more.
again, err := test.service.GetMine(t.Context(), candidate, sent.ID)
if err != nil || again.State != domain.InvitationExpired || again.Version != expired.Version || len(expiryEvents(test.transactor.snapshot())) != 1 {
t.Fatalf("second GetMine = %v, %v; want the same expired invitation and no second event", again.State, err)
}
}
func TestAcceptAtTheDeadlineIsRefusedAndStoresTheExpiry(t *testing.T) {
test := newHarness(t)
sent, candidate := test.deliveredTo(t)
test.setTime(*sent.ResponseDeadlineAt)
command := test.acceptCommand(candidate, sent.ID, sent.Version, "accept-late")
if _, err := test.service.AcceptMine(t.Context(), command); !errors.Is(err, ErrAnswerBlocked) {
t.Fatalf("AcceptMine(at the deadline) error = %v, want ErrAnswerBlocked", err)
}
state := test.transactor.snapshot()
if state.invitations[sent.ID].State() != domain.InvitationExpired || len(state.grants) != 0 || len(state.consentRecords) != 0 {
t.Fatalf("late acceptance left state %v with %d grants and %d consents",
state.invitations[sent.ID].State(), len(state.grants), len(state.consentRecords))
}
// The refusal is stored under the key, and the replay refuses the same way.
if _, err := test.service.AcceptMine(t.Context(), command); !errors.Is(err, ErrAnswerBlocked) {
t.Fatalf("AcceptMine(replay) error = %v, want the stored ErrAnswerBlocked", err)
}
}
func TestViewAndDeclineAtTheDeadlineFindTheExpiry(t *testing.T) {
test := newHarness(t)
sent, candidate := test.deliveredTo(t)
test.setTime(*sent.ResponseDeadlineAt)
viewed, err := test.service.ViewMine(t.Context(), candidate, sent.ID)
if err != nil || viewed.State != domain.InvitationExpired {
t.Fatalf("ViewMine(at the deadline) = %v, %v; want the expired invitation", viewed.State, err)
}
declineCommand := DeclineCommand{
ActorID: candidate, InvitationID: sent.ID, IdempotencyKey: "decline-late", ExpectedVersion: viewed.Version,
Choice: domain.InvitationDeclineChoice{Reason: domain.InvitationDeclineOther},
}
if _, err := test.service.DeclineMine(t.Context(), declineCommand); !errors.Is(err, ErrAnswerBlocked) {
t.Fatalf("DeclineMine(expired) error = %v, want ErrAnswerBlocked", err)
}
if declines := len(test.transactor.snapshot().declines); declines != 0 {
t.Fatalf("a late decline stored %d declines", declines)
}
}
func TestResponseDeadlineJobExpiresADueInvitationExactlyOnce(t *testing.T) {
test := newHarness(t)
sent, _ := test.deliveredTo(t)
deadline := *sent.ResponseDeadlineAt
claimed := claimOf(test.deadlineJob(t, sent.ID))
clock := deadline.Add(-time.Second)
now := func() time.Time { return clock }
if err := test.runDeadlineJob(t, claimed, now); err == nil {
t.Fatal("the deadline job completed before the deadline, want a retry")
}
if state := test.transactor.snapshot(); state.invitations[sent.ID].State() != domain.InvitationDelivered {
t.Fatalf("a job before the deadline changed the invitation to %v", state.invitations[sent.ID].State())
}
clock = deadline
if err := test.runDeadlineJob(t, claimed, now); err != nil {
t.Fatalf("deadline job at the deadline error = %v", err)
}
state := test.transactor.snapshot()
if state.invitations[sent.ID].State() != domain.InvitationExpired || len(state.grants) != 0 || len(state.charged) != 1 {
t.Fatalf("job left %v with %d grants and %d charges", state.invitations[sent.ID].State(), len(state.grants), len(state.charged))
}
if events := expiryEvents(state); len(events) != 1 {
t.Fatalf("job wrote %d expiry events, want one", len(events))
}
// A repeat, such as a retry after a crash, finds nothing left to expire.
clock = deadline.Add(time.Hour)
if err := test.runDeadlineJob(t, claimed, now); err != nil {
t.Fatalf("repeated deadline job error = %v", err)
}
if events := expiryEvents(test.transactor.snapshot()); len(events) != 1 {
t.Fatalf("a repeated job wrote %d expiry events, want still one", len(events))
}
}
func TestResponseDeadlineJobLeavesAnAnsweredInvitationAlone(t *testing.T) {
test := newHarness(t)
sent, candidate := test.deliveredTo(t)
deadline := *sent.ResponseDeadlineAt
claimed := claimOf(test.deadlineJob(t, sent.ID))
declined, err := test.service.DeclineMine(t.Context(), DeclineCommand{
ActorID: candidate, InvitationID: sent.ID, IdempotencyKey: "decline-before-deadline", ExpectedVersion: sent.Version,
Choice: domain.InvitationDeclineChoice{Reason: domain.InvitationDeclineOther},
})
if err != nil {
t.Fatalf("DeclineMine() error = %v", err)
}
if err := test.runDeadlineJob(t, claimed, func() time.Time { return deadline }); err != nil {
t.Fatalf("deadline job for a declined invitation error = %v", err)
}
state := test.transactor.snapshot()
if state.invitations[sent.ID].State() != domain.InvitationDeclined || state.invitations[sent.ID].Version() != declined.Version || len(expiryEvents(state)) != 0 {
t.Fatalf("the job changed a declined invitation to %v at version %d", state.invitations[sent.ID].State(), state.invitations[sent.ID].Version())
}
}
func TestResponseDeadlineJobRefusesAPayloadThatNamesNoInvitation(t *testing.T) {
for name, payload := range map[string]json.RawMessage{
"not an object": json.RawMessage(`[1]`),
"no identifier": json.RawMessage(`{}`),
"nil identifier": json.RawMessage(`{"invitation_id":"00000000-0000-0000-0000-000000000000"}`),
} {
t.Run(name, func(t *testing.T) {
test := newHarness(t)
err := test.runDeadlineJob(t, outbound.ClaimedJob{Kind: ResponseDeadlineJobKind, Payload: payload}, time.Now)
if !errors.Is(err, inbound.ErrJobRejected) {
t.Fatalf("Handle(%s) error = %v, want ErrJobRejected", payload, err)
}
})
}
}
@@ -0,0 +1,50 @@
package invitation
import (
"context"
"fmt"
"time"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// sendLimitsReached applies the two send limits of the product policy in force
// at the send: the number of invitations that wait for an answer under the
// need, and the pause of the pair of the organization and the candidate after a
// decline. Both answer the same conflict, so the caller refuses the send with
// one state conflict and says nothing about which limit applied.
//
// The pending count is exact because the caller holds the organization lock:
// every send takes that lock first, and every other change of a waiting
// invitation only removes it from the count. An invitation without a need has
// no need limit, and a direct invitation is bounded by the quota alone.
//
// The pause counts a decline only. The planned no-deal state has no operation
// that produces it, so it has no pause yet.
func (service *Service) sendLimitsReached(
ctx context.Context,
unit outbound.UnitOfWork,
command SendCommand,
current domain.Invitation,
at time.Time,
) (bool, error) {
policy, _, err := effectiveInvitationPolicy(ctx, unit, at, sendLocation)
if err != nil {
return false, err
}
if need := current.Snapshot().Need; need != nil {
pending, err := unit.Invitations().CountPendingNeedInvitations(ctx, command.OrganizationID, need.NeedID)
if err != nil {
return false, fmt.Errorf("%s - count pending invitations of the need: %w", sendLocation, err)
}
if pending >= int64(policy.MaxPendingPerNeed) {
return true, nil
}
}
declinedAt, found, err := unit.Invitations().LatestDeclineTime(ctx, command.OrganizationID, current.CandidateID())
if err != nil {
return false, fmt.Errorf("%s - read the latest decline of the candidate: %w", sendLocation, err)
}
return found && at.Before(declinedAt.Add(policy.RepeatAfterDecline.Duration())), nil
}
@@ -0,0 +1,231 @@
package invitation
import (
"errors"
"fmt"
"sync"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
)
// needDraft creates a draft under the need for a new visible candidate. The
// need is one stored requirements version of the organization.
func (test *harness) needDraft(t *testing.T, need uuid.UUID) domain.OrganizationInvitationView {
t.Helper()
test.transactor.state.needVersions[[3]string{test.organizationID.String(), need.String(), "1"}] = true
handle, _ := test.showCandidate(t)
command := test.createCommand(handle, "create-need-"+uuid.NewString())
command.Need = &domain.InvitationNeedRef{NeedID: need, RequirementsVersion: 1}
view, err := test.service.Create(t.Context(), command)
if err != nil {
t.Fatalf("Create(under the need) error = %v", err)
}
return view
}
func TestSendRefusesTheTwentyFirstWaitingInvitationOfANeed(t *testing.T) {
test := newHarness(t)
test.quotaLeft = 100
need := uuid.Must(uuid.NewV7())
drafts := make([]domain.OrganizationInvitationView, 0, 21)
for range 21 {
drafts = append(drafts, test.needDraft(t, need))
}
for index, draft := range drafts[:20] {
if _, err := test.service.Send(t.Context(), test.sendCommand(draft.ID, draft.Version, fmt.Sprint("send-", index))); err != nil {
t.Fatalf("Send(%d) error = %v, want the twenty waiting invitations to be allowed", index, err)
}
}
last := drafts[20]
if _, err := test.service.Send(t.Context(), test.sendCommand(last.ID, last.Version, "send-over-limit")); !errors.Is(err, ErrSendBlocked) {
t.Fatalf("Send(21st waiting) error = %v, want ErrSendBlocked", err)
}
state := test.transactor.snapshot()
if state.invitations[last.ID].State() != domain.InvitationDraft || len(state.charged) != 20 {
t.Fatalf("a refused send changed the draft to %v or charged %d invitations", state.invitations[last.ID].State(), len(state.charged))
}
// The refusal is stored under its key and replayed.
if _, err := test.service.Send(t.Context(), test.sendCommand(last.ID, last.Version, "send-over-limit")); !errors.Is(err, ErrSendBlocked) {
t.Fatalf("Send(replay of the refusal) error = %v, want ErrSendBlocked", err)
}
}
func TestConcurrentSendsOfTheTwentiethWaitingInvitationLetOnlyOneThrough(t *testing.T) {
test := newHarness(t)
test.quotaLeft = 100
need := uuid.Must(uuid.NewV7())
for index := range 19 {
draft := test.needDraft(t, need)
if _, err := test.service.Send(t.Context(), test.sendCommand(draft.ID, draft.Version, fmt.Sprint("nineteen-", index))); err != nil {
t.Fatalf("Send(%d) error = %v", index, err)
}
}
first, second := test.needDraft(t, need), test.needDraft(t, need)
var group sync.WaitGroup
errs := make([]error, 2)
for index, draft := range []domain.OrganizationInvitationView{first, second} {
group.Go(func() {
_, errs[index] = test.service.Send(t.Context(), test.sendCommand(draft.ID, draft.Version, fmt.Sprint("race-", index)))
})
}
group.Wait()
admitted, refused := 0, 0
for _, err := range errs {
switch {
case err == nil:
admitted++
case errors.Is(err, ErrSendBlocked):
refused++
default:
t.Fatalf("concurrent Send() error = %v", err)
}
}
if admitted != 1 || refused != 1 {
t.Fatalf("admitted %d and refused %d of two sends with nineteen waiting; want one each", admitted, refused)
}
count := 0
for _, draft := range []domain.OrganizationInvitationView{first, second} {
view, err := test.service.Get(t.Context(), test.actorID, test.organizationID, draft.ID)
if err != nil {
t.Fatalf("Get(%s) error = %v", draft.ID, err)
}
if view.State == domain.InvitationDelivered {
count++
}
}
if count != 1 {
t.Fatalf("%d of the two race invitations were delivered; want exactly one", count)
}
}
func TestLeavingTheWaitingStateFreesTheNeedSlotWithoutReturningTheQuota(t *testing.T) {
test := newHarness(t)
test.quotaLeft = 100
need := uuid.Must(uuid.NewV7())
sent := make([]domain.OrganizationInvitationView, 0, 20)
for index := range 20 {
draft := test.needDraft(t, need)
view, err := test.service.Send(t.Context(), test.sendCommand(draft.ID, draft.Version, fmt.Sprint("fill-", index)))
if err != nil {
t.Fatalf("Send(%d) error = %v", index, err)
}
sent = append(sent, view)
}
blocked := test.needDraft(t, need)
if _, err := test.service.Send(t.Context(), test.sendCommand(blocked.ID, blocked.Version, "blocked")); !errors.Is(err, ErrSendBlocked) {
t.Fatalf("Send(full need) error = %v, want ErrSendBlocked", err)
}
// The first invitation expires at its deadline, which frees one place.
deadline := *sent[0].ResponseDeadlineAt
if err := test.runDeadlineJob(t, claimOf(test.deadlineJob(t, sent[0].ID)), func() time.Time { return deadline }); err != nil {
t.Fatalf("deadline job error = %v", err)
}
chargesBefore := len(test.transactor.snapshot().charged)
if view, err := test.service.Send(t.Context(), test.sendCommand(blocked.ID, blocked.Version, "after-expiry")); err != nil || view.State != domain.InvitationDelivered {
t.Fatalf("Send(after one expiry) = %v, %v; want delivered", view.State, err)
}
if chargesAfter := len(test.transactor.snapshot().charged); chargesAfter != chargesBefore+1 {
t.Fatalf("charges went from %d to %d; the expiry must not return quota and the new send must charge once", chargesBefore, chargesAfter)
}
}
func TestPauseAfterADeclineHoldsForThirtyDaysForEveryNeedAndMember(t *testing.T) {
test := newHarness(t)
test.quotaLeft = 100
sent, candidate := test.deliveredTo(t)
declinedAt := sent.DeliveredAt.Add(time.Hour)
test.setTime(declinedAt)
if _, err := test.service.DeclineMine(t.Context(), DeclineCommand{
ActorID: candidate, InvitationID: sent.ID, IdempotencyKey: "decline-pause", ExpectedVersion: sent.Version,
Choice: domain.InvitationDeclineChoice{Reason: domain.InvitationDeclineOther},
}); err != nil {
t.Fatalf("DeclineMine() error = %v", err)
}
// A second owner of the same organization, with another need.
secondOwner := uuid.Must(uuid.NewV7())
verified := declinedAt.Add(-time.Hour)
test.transactor.state.users[secondOwner] = domain.User{ID: secondOwner, Scenario: domain.ScenarioEmployer, EmailVerifiedAt: &verified}
membership, err := domain.NewOwnerMembership(test.organizationID, secondOwner, declinedAt)
if err != nil {
t.Fatalf("NewOwnerMembership() error = %v", err)
}
test.transactor.state.memberships[[2]uuid.UUID{test.organizationID, secondOwner}] = membership
other := uuid.Must(uuid.NewV7())
test.transactor.state.needVersions[[3]string{test.organizationID.String(), other.String(), "1"}] = true
handle, err := test.key.ForOrganization(test.organizationID, candidate)
if err != nil {
t.Fatalf("ForOrganization() error = %v", err)
}
draftOther := func(key string) domain.OrganizationInvitationView {
t.Helper()
command := test.createCommand(handle, key)
command.ActorID = secondOwner
command.Need = &domain.InvitationNeedRef{NeedID: other, RequirementsVersion: 1}
view, err := test.service.Create(t.Context(), command)
if err != nil {
t.Fatalf("Create(%s) error = %v", key, err)
}
return view
}
draft := draftOther("create-pause")
sendAs := func(view domain.OrganizationInvitationView, key string) error {
command := test.sendCommand(view.ID, view.Version, key)
command.ActorID = secondOwner
_, err := test.service.Send(t.Context(), command)
return err
}
test.setTime(declinedAt.Add(29 * 24 * time.Hour))
if err := sendAs(draft, "send-day-29"); !errors.Is(err, ErrSendBlocked) {
t.Fatalf("Send(day 29 after the decline) error = %v, want ErrSendBlocked", err)
}
test.setTime(declinedAt.Add(30 * 24 * time.Hour))
if err := sendAs(draft, "send-day-30"); err != nil {
t.Fatalf("Send(day 30 after the decline) error = %v, want the pause to be over", err)
}
}
func TestPauseAfterADeclineDoesNotHoldAnotherCandidate(t *testing.T) {
test := newHarness(t)
test.quotaLeft = 100
sent, candidate := test.deliveredTo(t)
test.setTime(sent.DeliveredAt.Add(time.Hour))
if _, err := test.service.DeclineMine(t.Context(), DeclineCommand{
ActorID: candidate, InvitationID: sent.ID, IdempotencyKey: "decline-other", ExpectedVersion: sent.Version,
Choice: domain.InvitationDeclineChoice{Reason: domain.InvitationDeclineOther},
}); err != nil {
t.Fatalf("DeclineMine() error = %v", err)
}
next, _, _ := test.draftFor(t, nil)
if _, err := test.service.Send(t.Context(), test.sendCommand(next.ID, next.Version, "send-other-candidate")); err != nil {
t.Fatalf("Send(another candidate) error = %v, want delivered", err)
}
}
// The pause is judged only from declines, so an invitation that expired is
// not a decline and starts no pause.
func TestAnExpiredInvitationStartsNoPause(t *testing.T) {
test := newHarness(t)
test.quotaLeft = 100
sent, candidate := test.deliveredTo(t)
test.setTime(*sent.ResponseDeadlineAt)
if _, err := test.service.GetMine(t.Context(), candidate, sent.ID); err != nil {
t.Fatalf("GetMine(expiry) error = %v", err)
}
next, _, _ := test.draftFor(t, nil)
if _, err := test.service.Send(t.Context(), test.sendCommand(next.ID, next.Version, "send-after-expiry")); err != nil {
t.Fatalf("Send(after an expiry of another invitation) error = %v", err)
}
if _, found, err := (testInvitations{state: &test.transactor.state}).LatestDeclineTime(t.Context(), test.organizationID, candidate); err != nil || found {
t.Fatalf("LatestDeclineTime() = %v, %v; an expiry must not count as a decline", found, err)
}
}
+46 -10
View File
@@ -66,10 +66,11 @@ type sendOutcome struct {
// 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
// version and state, the current visibility of the candidate, the pending limit
// of the need, and the pause after a decline; it then spends one invitation of
// the organization quota, records the delivery with its deadline, the audit
// event, and the expiry job at the deadline, 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) {
@@ -126,8 +127,9 @@ func (service *Service) prepareSend(command SendCommand) (sendRequest, error) {
// 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).
// of a completed send (200), the version (412, not stored), the state, the
// visibility of the candidate, the pending limit, and the pause (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(
@@ -170,23 +172,52 @@ func (service *Service) sendInTransaction(
if current.State() != domain.InvitationDraft {
return service.refuseSend(ctx, unit, command, request, outbound.InvitationSendStateConflict)
}
visible, err := service.candidateStillVisible(ctx, unit, command, current)
at, admitted, err := service.admitSend(ctx, unit, command, current)
if err != nil {
return sendOutcome{}, err
}
if !visible {
if !admitted {
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)
delivered, err := service.deliver(ctx, unit, command, current, at)
if err != nil {
return sendOutcome{}, err
}
return service.completeSend(ctx, unit, request, delivered)
}
// admitSend applies the rules that refuse a send with a state conflict: the
// visibility of the candidate, then the pending limit of the need and the pause
// after a decline. It returns the time of the decision, which the caller uses for
// the delivery, and whether the send is admitted. The decision is made at the time
// the send holds the organization lock, not at the time it started to wait for it.
func (service *Service) admitSend(
ctx context.Context,
unit outbound.UnitOfWork,
command SendCommand,
current domain.Invitation,
) (time.Time, bool, error) {
visible, err := service.candidateStillVisible(ctx, unit, command, current)
if err != nil {
return time.Time{}, false, err
}
if !visible {
return time.Time{}, false, nil
}
at, err := service.now(sendLocation)
if err != nil {
return time.Time{}, false, err
}
limited, err := service.sendLimitsReached(ctx, unit, command, current, at)
if err != nil {
return time.Time{}, false, err
}
return at, !limited, nil
}
// 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
@@ -258,6 +289,11 @@ func (service *Service) deliver(
}
return domain.Invitation{}, fmt.Errorf("%s - store delivery: %w", sendLocation, err)
}
// The expiry at the deadline is scheduled in the delivery transaction, so no
// delivered invitation exists without its job.
if err := scheduleResponseDeadline(ctx, unit, delivered); err != nil {
return domain.Invitation{}, fmt.Errorf("%s - schedule response deadline: %w", sendLocation, err)
}
if err := service.notifier.InvitationDelivered(ctx, unit, delivered); err != nil {
return domain.Invitation{}, fmt.Errorf("%s - record notification: %w", sendLocation, err)
}
@@ -271,7 +307,7 @@ func (service *Service) completeSend(
request sendRequest,
invitation domain.Invitation,
) (sendOutcome, error) {
view, err := service.view(invitation)
view, err := service.view(ctx, unit, invitation)
if err != nil {
return sendOutcome{}, err
}
+17 -7
View File
@@ -142,20 +142,30 @@ func (service *Service) now(location string) (time.Time, error) {
return now, nil
}
// view is the invitation as its organization reads it. The salary indicator
// and the contact access are not derived from the candidate's minimum or from
// a grant yet: the indicator is not_available, the least revealing value, and
// no grant exists before an acceptance.
func (service *Service) view(invitation domain.Invitation) (domain.OrganizationInvitationView, error) {
// 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("invitation.Service.view - derive candidate alias: %w", err)
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: domain.InvitationContactAccessNone,
ContactAccess: access,
}, nil
}
@@ -62,6 +62,8 @@ type testState struct {
// and notified the delivered invitations that were notified.
charged []uuid.UUID
notified []uuid.UUID
// jobs holds the scheduled jobs by kind and key.
jobs map[string]domain.ScheduledJob
}
func newTestState() testState {
@@ -80,6 +82,7 @@ func newTestState() testState {
profiles: map[uuid.UUID]domain.CandidateProfile{},
publications: map[uuid.UUID]domain.Publication{},
hidden: map[[2]uuid.UUID]bool{},
jobs: map[string]domain.ScheduledJob{},
}
}
@@ -136,6 +139,9 @@ func (state testState) clone() testState {
}
cloned.charged = slices.Clone(state.charged)
cloned.notified = slices.Clone(state.notified)
for key, job := range state.jobs {
cloned.jobs[key] = job
}
return cloned
}
@@ -193,6 +199,26 @@ func (unit *testUnit) InvitationSendResults() outbound.InvitationSendResultRepos
func (unit *testUnit) InvitationDeclineResults() outbound.InvitationDeclineResultRepository {
return testInvitations{state: unit.state}
}
func (unit *testUnit) ScheduledJobs() outbound.JobScheduler { return testJobs{state: unit.state} }
// testJobs keeps the scheduled jobs of one transaction: the first schedule of a
// kind and key wins, as in the database.
type testJobs struct {
state *testState
}
func (jobs testJobs) Schedule(_ context.Context, job domain.ScheduledJob) (bool, error) {
key := job.Kind() + "\x00" + job.Key()
if _, exists := jobs.state.jobs[key]; exists {
return false, nil
}
jobs.state.jobs[key] = job
return true, nil
}
func (jobs testJobs) Cancel(context.Context, string, string) (bool, error) {
return false, errors.New("testJobs.Cancel - not used by the invitation usecases")
}
type testUsers struct {
outbound.UserRepository
@@ -542,7 +568,7 @@ func TestCreateStoresADraftForAVisibleCandidateWithTheDefaultPeriod(t *testing.T
}
if view.State != domain.InvitationDraft || view.Version != 1 || view.TermsVersion != 1 || view.ResponsePeriodDays != 7 ||
view.CandidateHandle != handle || view.SalaryFit != domain.InvitationSalaryNotAvailable ||
view.ContactAccess != domain.InvitationContactAccessNone || view.ResponseDeadlineAt != nil {
view.ContactAccess.Status != domain.InvitationContactAccessNone || len(view.ContactAccess.Fields) != 0 || view.ResponseDeadlineAt != nil {
t.Fatalf("created view = %+v, want an unsent version 1 with the default period for the card handle", view.InvitationSnapshot)
}
state := test.transactor.snapshot()
+29 -11
View File
@@ -18,10 +18,11 @@ const (
)
// GetMine reads one invitation delivered to the session candidate with the
// current terms. Reading has no side effect: it never records a view, so a
// prefetch or a cache refresh never changes what the organization sees. A
// draft, an invitation of another candidate, and an unknown identifier are
// not found alike.
// current terms. Reading never records a view, so a prefetch or a cache refresh
// never changes what the organization sees. The one change a read can cause is
// the due expiry: a delivered or viewed invitation read at its deadline or later
// is expired first, and the response shows it. A draft, an invitation of another
// candidate, and an unknown identifier are not found alike.
func (service *Service) GetMine(ctx context.Context, actorID, invitationID uuid.UUID) (domain.CandidateInvitationView, error) {
if actorID == uuid.Nil {
return domain.CandidateInvitationView{}, fmt.Errorf("%s - actor ID must be set: %w", getMineLocation, ErrForbidden)
@@ -39,6 +40,19 @@ func (service *Service) GetMine(ctx context.Context, actorID, invitationID uuid.
if err != nil {
return err
}
if entry.Invitation.ExpiryDue(now) {
// The expiry writes, so the row is locked, read again, and judged at
// the time that the lock is held.
if entry, err = readCandidateEntry(ctx, unit, actorID, invitationID, true); err != nil {
return err
}
if now, err = service.now(getMineLocation); err != nil {
return err
}
if entry, err = settleCandidateEntry(ctx, unit, entry, now); err != nil {
return fmt.Errorf("%s - expire due invitation: %w", getMineLocation, err)
}
}
view, err = service.candidateView(ctx, unit, entry, now)
return err
})
@@ -51,8 +65,9 @@ func (service *Service) GetMine(ctx context.Context, actorID, invitationID uuid.
// ViewMine records that the session candidate opened the terms. A delivered
// invitation moves to viewed with the next version and keeps its deadline;
// every other state, and a view at the deadline or later, changes nothing and
// returns the invitation as it is. The command is idempotent by its effect,
// so it takes neither a key nor an expected version.
// returns the invitation as it is. A due expiry is applied first. The command
// is idempotent by its effect, so it takes neither a key nor an expected
// version.
//
// Locks: only the invitation row, never the organization. A candidate
// command therefore never holds the row while it waits for an organization
@@ -62,12 +77,8 @@ func (service *Service) ViewMine(ctx context.Context, actorID, invitationID uuid
if actorID == uuid.Nil {
return domain.CandidateInvitationView{}, fmt.Errorf("%s - actor ID must be set: %w", viewMineLocation, ErrForbidden)
}
now, err := service.now(viewMineLocation)
if err != nil {
return domain.CandidateInvitationView{}, err
}
var view domain.CandidateInvitationView
err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := authorizeCandidate(ctx, unit, actorID); err != nil {
return err
}
@@ -75,6 +86,13 @@ func (service *Service) ViewMine(ctx context.Context, actorID, invitationID uuid
if err != nil {
return err
}
now, err := service.now(viewMineLocation)
if err != nil {
return err
}
if entry, err = settleCandidateEntry(ctx, unit, entry, now); err != nil {
return fmt.Errorf("%s - expire due invitation: %w", viewMineLocation, err)
}
current := entry.Invitation
viewed, changed, err := current.RecordView(notBefore(now, current.UpdatedAt()))
if err != nil {