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

@@ -14035,8 +14035,8 @@ func (s *Server) handleSearchOrganizationMatchesRequest(args [1]string, argsEsca
// answer per need (`delivered`, `viewed`, `counter`) and the 30-day pause for the pair of the
// organization and the candidate after a decline or a no deal, regardless of the member or the need,
// both with 409 state_conflict; and the rolling weekly quota of the organization, with 429 and
// Retry-After. The organization quota is enforced; the pending limit and the pause are planned and are
// not checked yet.
// Retry-After. The organization quota, the pending limit, and the pause after a decline are enforced;
// the pause after a no deal is planned, because no operation produces the state `no_deal` yet.
//
// Repeats return the same result: a retry with the same Idempotency-Key replays the stored response,
// and a send of an invitation that was already sent answers 200 with the invitation in its current
@@ -1725,8 +1725,8 @@ type Handler interface {
// answer per need (`delivered`, `viewed`, `counter`) and the 30-day pause for the pair of the
// organization and the candidate after a decline or a no deal, regardless of the member or the need,
// both with 409 state_conflict; and the rolling weekly quota of the organization, with 429 and
// Retry-After. The organization quota is enforced; the pending limit and the pause are planned and are
// not checked yet.
// Retry-After. The organization quota, the pending limit, and the pause after a decline are enforced;
// the pause after a no deal is planned, because no operation produces the state `no_deal` yet.
//
// Repeats return the same result: a retry with the same Idempotency-Key replays the stored response,
// and a send of an invitation that was already sent answers 200 with the invitation in its current
@@ -1916,8 +1916,8 @@ func (UnimplementedHandler) SearchOrganizationMatches(ctx context.Context, req M
// answer per need (`delivered`, `viewed`, `counter`) and the 30-day pause for the pair of the
// organization and the candidate after a decline or a no deal, regardless of the member or the need,
// both with 409 state_conflict; and the rolling weekly quota of the organization, with 429 and
// Retry-After. The organization quota is enforced; the pending limit and the pause are planned and are
// not checked yet.
// Retry-After. The organization quota, the pending limit, and the pause after a decline are enforced;
// the pause after a no deal is planned, because no operation produces the state `no_deal` yet.
//
// Repeats return the same result: a retry with the same Idempotency-Key replays the stored response,
// and a send of an invitation that was already sent answers 200 with the invitation in its current
@@ -0,0 +1,91 @@
package v1
import (
"context"
"errors"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/adapter/primary/http/problem"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
func (handler *Handler) GetOrganizationInvitationContacts(ctx context.Context, params api.GetOrganizationInvitationContactsParams) (api.GetOrganizationInvitationContactsRes, error) {
if handler.invitation == nil {
return handler.UnimplementedHandler.GetOrganizationInvitationContacts(ctx, params)
}
return handler.invitation.GetOrganizationInvitationContacts(ctx, params)
}
// GetOrganizationInvitationContacts serves the only operation that returns
// contact values. The company middleware has already checked the session, the
// owner membership, and the path, and the usecase repeats the owner check in
// its transaction. Every failure of the grant read answers the same not found,
// so the response never tells which condition applies.
func (handler *InvitationHandler) GetOrganizationInvitationContacts(
ctx context.Context,
params api.GetOrganizationInvitationContactsParams,
) (api.GetOrganizationInvitationContactsRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.GetOrganizationInvitationContactsUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
disclosure, err := handler.operations.ReadContacts(ctx, principal.UserID, params.OrgID, params.InvitationID)
if err != nil {
return contactsReadFailure(ctx, err)
}
return &api.ContactDisclosureHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: contactDisclosureResponse(disclosure)}, nil
}
func contactsReadFailure(ctx context.Context, err error) (api.GetOrganizationInvitationContactsRes, error) {
// A missing grant is the not found of the contract. It is handled before the
// shared classification, which treats an unexpected missing grant as a
// storage defect on the other invitation paths.
if errors.Is(err, outbound.ErrContactGrantNotFound) {
return (*api.GetOrganizationInvitationContactsNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
}
switch classifyInvitationError(err) {
case invitationFailureForbidden:
return (*api.GetOrganizationInvitationContactsForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case invitationFailureNotFound:
return (*api.GetOrganizationInvitationContactsNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
case invitationFailureKeyReused, invitationFailureBadKey, invitationFailureInvalid,
invitationFailureVersionConflict, invitationFailureStateConflict, invitationFailureOther:
return nil, err
}
return nil, err
}
// contactDisclosureResponse maps the disclosure field by field. A kind that the
// grant does not cover, or that the profile no longer holds, is null.
func contactDisclosureResponse(disclosure domain.ContactDisclosure) api.ContactDisclosure {
fields := make([]api.ContactFieldKind, 0, len(disclosure.Fields()))
for _, field := range disclosure.Fields() {
fields = append(fields, api.ContactFieldKind(field))
}
response := api.ContactDisclosure{
InvitationID: disclosure.InvitationID(), GrantID: disclosure.GrantID(),
Fields: fields, GrantedAt: api.Timestamp(disclosure.GrantedAt()),
}
if value, present := disclosure.FullName(); present {
response.FullName = api.NewNilContactFullName(api.ContactFullName(value))
} else {
response.FullName.SetToNull()
}
if value, present := disclosure.Email(); present {
response.Email = api.NewNilEmailAddress(api.EmailAddress(value))
} else {
response.Email.SetToNull()
}
if value, present := disclosure.Phone(); present {
response.Phone = api.NewNilContactPhoneNumber(api.ContactPhoneNumber(value))
} else {
response.Phone.SetToNull()
}
if value, present := disclosure.Telegram(); present {
response.Telegram = api.NewNilContactTelegramUsername(api.ContactTelegramUsername(value))
} else {
response.Telegram.SetToNull()
}
return response
}
@@ -31,6 +31,7 @@ type InvitationOperations interface {
ViewMine(ctx context.Context, actorID, invitationID uuid.UUID) (domain.CandidateInvitationView, error)
DeclineMine(ctx context.Context, command invitationusecase.DeclineCommand) (domain.CandidateInvitationView, error)
AcceptMine(ctx context.Context, command invitationusecase.AcceptCommand) (domain.CandidateInvitationView, error)
ReadContacts(ctx context.Context, actorID, organizationID, invitationID uuid.UUID) (domain.ContactDisclosure, error)
}
// InvitationHandler serves the organization side of invitation drafts and
@@ -590,10 +591,14 @@ func nullableTimestamp(value *time.Time) api.NilTimestamp {
return response
}
func invitationContactAccessResponse(access domain.InvitationContactAccess) api.InvitationContactAccess {
// No contact grant exists before an acceptance, so no kind of contact is
// listed and no contact value is ever part of this response.
return api.InvitationContactAccess{Status: api.InvitationContactAccessState(access), Fields: []api.ContactFieldKind{}}
func invitationContactAccessResponse(access domain.InvitationContactAccessView) api.InvitationContactAccess {
// The usecase lists kinds only while the access is available. The kinds
// name the contact read; no contact value is ever part of this response.
fields := make([]api.ContactFieldKind, 0, len(access.Fields))
for _, field := range access.Fields {
fields = append(fields, api.ContactFieldKind(field))
}
return api.InvitationContactAccess{Status: api.InvitationContactAccessState(access.Status), Fields: fields}
}
func organizationInvitationResponse(view domain.OrganizationInvitationView) api.OrganizationInvitation {
@@ -83,7 +83,8 @@ func TestInvitationResponseNeverCarriesACandidateIdentifierOrAContact(t *testing
}
view := domain.OrganizationInvitationView{
InvitationSnapshot: draft.Snapshot(), CandidateHandle: "cv1_" + strings.Repeat("A", 43),
SalaryFit: domain.InvitationSalaryNotAvailable, ContactAccess: domain.InvitationContactAccessNone,
SalaryFit: domain.InvitationSalaryNotAvailable,
ContactAccess: domain.NewInvitationContactAccessView(domain.InvitationContactAccessNone, nil),
}
for name, response := range map[string]any{
"invitation": organizationInvitationResponse(view),
@@ -94,6 +94,9 @@ func (effects consentRevocationEffects) Apply(
return fmt.Errorf("consentRevocationEffects.Apply - close publication: %w", err)
}
}
if err := effects.closeContactGrants(ctx, revocation, records); err != nil {
return fmt.Errorf("consentRevocationEffects.Apply - close contact grants: %w", err)
}
if err := effects.appendRevocationIntent(ctx, revocation, records); err != nil {
return fmt.Errorf("consentRevocationEffects.Apply - append outbox intent: %w", err)
}
@@ -145,6 +148,42 @@ func (effects consentRevocationEffects) closePublication(
return nil
}
// closeContactGrants closes the grants that the revoked consent gave. A C2
// revocation closes every grant of the candidate, because it closes the
// profile for every organization, whether or not a publication row exists. A
// C4 revocation closes the grants of its organization that name the revoked
// records, so the grants of other organizations and other invitations stay.
func (effects consentRevocationEffects) closeContactGrants(
ctx context.Context,
revocation domain.ConsentRevocation,
records []domain.ConsentRecord,
) error {
const location = "consentRevocationEffects.closeContactGrants"
switch revocation.Purpose() {
case domain.ConsentPurposePublication:
return closeActiveContactGrants(ctx, effects.queries, contactGrantClosure{
candidateID: revocation.SubjectID(), reason: domain.ContactRevocationVisibilityClosed,
at: revocation.RevokedAt(),
})
case domain.ConsentPurposeContactDisclosure:
recordIDs := make([]uuid.UUID, 0, len(records))
for _, record := range records {
recordIDs = append(recordIDs, record.ID())
}
if len(recordIDs) == 0 {
return fmt.Errorf("%s - revoked C4 record IDs are required: %w", location, domain.ErrInvalidConsent)
}
return closeActiveContactGrants(ctx, effects.queries, contactGrantClosure{
candidateID: revocation.SubjectID(), organizationID: revocation.OrganizationID(),
consentRecordIDs: recordIDs, reason: domain.ContactRevocationConsentRevoked, at: revocation.RevokedAt(),
})
case domain.ConsentPurposePersonalData, domain.ConsentPurposeAutoCategorization, domain.ConsentPurposeFSPImport:
// These purposes never gave a contact grant, so their revocation closes none.
return nil
}
return fmt.Errorf("%s - purpose %q has no grant rule: %w", location, revocation.Purpose(), domain.ErrInvalidConsent)
}
type consentRevocationPayload struct {
RevocationID uuid.UUID `json:"revocation_id"`
RecordID uuid.UUID `json:"record_id"`
@@ -0,0 +1,56 @@
package postgres
import (
"context"
"fmt"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgtype"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
)
// contactGrantClosure names the active grants that one change closes. The
// caller runs it in the transaction of the change, so the grants and the change
// commit or roll back together.
type contactGrantClosure struct {
candidateID uuid.UUID
// organizationID limits the closure to one organization. Nil closes every
// organization of the candidate.
organizationID uuid.UUID
// consentRecordIDs limits the closure to the grants that these C4 records
// gave. Nil applies no record filter.
consentRecordIDs []uuid.UUID
reason domain.ContactRevocationReason
at time.Time
}
// closeActiveContactGrants stamps the active grants of the closure with its
// reason and time. A grant already closed keeps its first stamp, and the
// revocation time is never earlier than the grant time, as the grant requires.
func closeActiveContactGrants(ctx context.Context, queries *sqlc.Queries, closure contactGrantClosure) error {
const location = "postgres.closeActiveContactGrants"
if closure.candidateID == uuid.Nil || closure.at.IsZero() || closure.reason == "" {
return fmt.Errorf("%s - candidate, time, and reason are required: %w", location, domain.ErrInvalidContactGrant)
}
params := sqlc.CloseActiveContactGrantsParams{
RevokedAt: pgTime(closure.at),
RevocationReason: pgtype.Text{String: string(closure.reason), Valid: true},
CandidateID: pgUUID(closure.candidateID),
}
if closure.organizationID != uuid.Nil {
params.OrganizationID = pgUUID(closure.organizationID)
}
if closure.consentRecordIDs != nil {
params.ConsentRecordIds = make([]pgtype.UUID, 0, len(closure.consentRecordIDs))
for _, id := range closure.consentRecordIDs {
params.ConsentRecordIds = append(params.ConsentRecordIds, pgUUID(id))
}
}
if _, err := queries.CloseActiveContactGrants(ctx, params); err != nil {
return fmt.Errorf("%s - close active grants: %w", location, markTransactionConflict(sanitizeConnectError(err)))
}
return nil
}
@@ -207,3 +207,48 @@ func storedContactGrantRow(row sqlc.ContactGrant) (domain.StoredContactGrant, er
}
return stored, nil
}
// LockForRead locks the C4 record before the grant, the order of the consent
// revocation, so a read and a revocation of the same consent cannot wait for
// each other in opposite orders. The locked grant is restored through the
// domain like GetByInvitation, and it must still name the grant that was read.
func (repository contactGrantRepository) LockForRead(
ctx context.Context,
grant domain.ContactGrant,
) (domain.ContactGrant, bool, error) {
const location = "contactGrantRepository.LockForRead"
if grant.IsZero() {
return domain.ContactGrant{}, false, fmt.Errorf("%s - grant must be built by the domain: %w", location, domain.ErrInvalidContactGrant)
}
consentCurrent := true
_, err := repository.queries.LockCurrentContactConsentRecord(ctx, sqlc.LockCurrentContactConsentRecordParams{
ConsentRecordID: pgUUID(grant.ConsentRecordID()), CandidateID: pgUUID(grant.CandidateID()),
OrganizationID: pgUUID(grant.OrganizationID()),
})
switch {
case errors.Is(err, pgx.ErrNoRows):
consentCurrent = false
case err != nil:
return domain.ContactGrant{}, false, fmt.Errorf("%s - lock consent C4 record: %w", location, mapInvitationError(err))
}
row, err := repository.queries.LockContactGrant(ctx, pgUUID(grant.ID()))
if errors.Is(err, pgx.ErrNoRows) {
return domain.ContactGrant{}, false, fmt.Errorf("%s - lock contact grant: %w", location, outbound.ErrContactGrantNotFound)
}
if err != nil {
return domain.ContactGrant{}, false, fmt.Errorf("%s - lock contact grant: %w", location, mapInvitationError(err))
}
stored, err := storedContactGrantRow(row)
if err != nil {
return domain.ContactGrant{}, false, fmt.Errorf("%s - read stored grant: %w", location, err)
}
current, err := domain.RestoreContactGrant(stored)
if err != nil {
return domain.ContactGrant{}, false, fmt.Errorf("%s - restore contact grant: %w", location, err)
}
if current.OrganizationID() != grant.OrganizationID() || current.CandidateID() != grant.CandidateID() ||
current.InvitationID() != grant.InvitationID() || current.ConsentRecordID() != grant.ConsentRecordID() {
return domain.ContactGrant{}, false, fmt.Errorf("%s - locked grant has another scope: %w", location, domain.ErrInvalidContactGrant)
}
return current, consentCurrent, nil
}
@@ -0,0 +1,115 @@
package postgres
import (
"context"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// CountPendingNeedInvitations counts the waiting invitations of one need. The
// count is only exact under the organization lock, which the caller holds.
func (repository invitationRepository) CountPendingNeedInvitations(
ctx context.Context,
organizationID, needID uuid.UUID,
) (int64, error) {
const location = "invitationRepository.CountPendingNeedInvitations"
if organizationID == uuid.Nil || needID == uuid.Nil {
return 0, fmt.Errorf("%s - organization and need IDs must be set: %w", location, domain.ErrInvalidInvitation)
}
count, err := repository.queries.CountPendingNeedInvitations(ctx, sqlc.CountPendingNeedInvitationsParams{
OrganizationID: pgUUID(organizationID), NeedID: pgUUID(needID),
})
if err != nil {
return 0, fmt.Errorf("%s - count pending invitations: %w", location, mapInvitationError(err))
}
return count, nil
}
// LatestDeclineTime reads the latest decline of the pair of the organization
// and the candidate. It reports false when the pair has none.
func (repository invitationRepository) LatestDeclineTime(
ctx context.Context,
organizationID, candidateID uuid.UUID,
) (time.Time, bool, error) {
const location = "invitationRepository.LatestDeclineTime"
if organizationID == uuid.Nil || candidateID == uuid.Nil {
return time.Time{}, false, fmt.Errorf("%s - organization and candidate IDs must be set: %w", location, domain.ErrInvalidInvitation)
}
declinedAt, err := repository.queries.LatestInvitationDecline(ctx, sqlc.LatestInvitationDeclineParams{
OrganizationID: pgUUID(organizationID), CandidateID: pgUUID(candidateID),
})
if errors.Is(err, pgx.ErrNoRows) {
return time.Time{}, false, nil
}
if err != nil {
return time.Time{}, false, fmt.Errorf("%s - read latest decline: %w", location, mapInvitationError(err))
}
if !declinedAt.Valid {
return time.Time{}, false, fmt.Errorf("%s - declined invitation has no answer time: %w", location, domain.ErrInvalidInvitation)
}
return declinedAt.Time.UTC(), true, nil
}
// GetForDeadline locks the invitation row first and reads it with its scope
// afterwards, as the other locking reads of invitations do.
func (repository invitationRepository) GetForDeadline(
ctx context.Context,
invitationID uuid.UUID,
) (domain.Invitation, error) {
const location = "invitationRepository.GetForDeadline"
if invitationID == uuid.Nil {
return domain.Invitation{}, fmt.Errorf("%s - invitation ID must be set: %w", location, domain.ErrInvalidInvitation)
}
organizationID, err := repository.queries.LockInvitationByID(ctx, pgUUID(invitationID))
if err != nil {
return domain.Invitation{}, fmt.Errorf("%s - lock invitation: %w", location, mapInvitationNoRows(err))
}
if !organizationID.Valid {
return domain.Invitation{}, fmt.Errorf("%s - invitation has no organization: %w", location, domain.ErrInvalidInvitation)
}
invitation, err := repository.Get(ctx, uuid.UUID(organizationID.Bytes), invitationID)
if err != nil {
return domain.Invitation{}, fmt.Errorf("%s - read locked invitation: %w", location, err)
}
return invitation, nil
}
// Expire stores the expired version. The conditional update is the
// compare-and-swap that makes the expiry idempotent: a row that another
// transaction already answered or expired, or whose deadline has not passed at
// the expiry time, matches nothing and the caller learns of the conflict.
func (repository invitationRepository) Expire(
ctx context.Context,
expectedVersion int64,
next domain.Invitation,
event domain.InvitationEvent,
) error {
const location = "invitationRepository.Expire"
stored := next.Stored()
if expectedVersion < 1 || stored.Version != expectedVersion+1 || stored.State != string(domain.InvitationExpired) ||
stored.ExpiryReason == nil || event.Kind != domain.InvitationEventExpired {
return fmt.Errorf("%s - the next version must be the expiry that follows the expected one: %w", location, domain.ErrInvalidInvitation)
}
if err := repository.insertEventPrerequisites(location, next, event, stored.Version); err != nil {
return err
}
_, err := repository.queries.ExpireInvitation(ctx, sqlc.ExpireInvitationParams{
NextVersion: stored.Version, ExpiredAt: pgTime(stored.UpdatedAt), OrganizationID: pgUUID(stored.OrganizationID),
InvitationID: pgUUID(stored.ID), ExpectedVersion: expectedVersion,
})
if errors.Is(err, pgx.ErrNoRows) {
return fmt.Errorf("%s - expire invitation: %w", location, outbound.ErrInvitationVersionConflict)
}
if err != nil {
return fmt.Errorf("%s - expire invitation: %w", location, mapInvitationError(err))
}
return repository.insertEvent(ctx, location, event)
}
@@ -268,15 +268,17 @@ func (repository invitationRepository) GetCreationResult(
}
// insertEventPrerequisites checks that the audit event describes the version
// that the caller is about to store.
// that the caller is about to store. Only the server's expiry has no actor.
func (repository invitationRepository) insertEventPrerequisites(
location string,
invitation domain.Invitation,
event domain.InvitationEvent,
version int64,
) error {
actorMissing := event.ActorID == uuid.Nil
if event.ID == uuid.Nil || event.InvitationID != invitation.ID() || event.OrganizationID != invitation.OrganizationID() ||
event.Version != version || event.TermsVersion != invitation.TermsVersion() || event.ActorID == uuid.Nil ||
event.Version != version || event.TermsVersion != invitation.TermsVersion() ||
actorMissing != (event.Kind == domain.InvitationEventExpired) ||
!validStoredInvitationTime(event.OccurredAt) {
return fmt.Errorf("%s - the audit event does not describe the stored version: %w", location, domain.ErrInvalidInvitation)
}
@@ -311,9 +313,14 @@ func (repository invitationRepository) insertEvent(ctx context.Context, location
fields = append(fields, string(field))
}
slices.Sort(fields)
// The expiry is the server's own change, so its event has no actor.
actor := pgtype.UUID{}
if event.ActorID != uuid.Nil {
actor = pgUUID(event.ActorID)
}
if err := repository.queries.InsertInvitationEvent(ctx, sqlc.InsertInvitationEventParams{
ID: pgUUID(event.ID), InvitationID: pgUUID(event.InvitationID), OrganizationID: pgUUID(event.OrganizationID),
Version: event.Version, TermsVersion: event.TermsVersion, Kind: string(event.Kind), ActorID: pgUUID(event.ActorID),
Version: event.Version, TermsVersion: event.TermsVersion, Kind: string(event.Kind), ActorID: actor,
ChangedFields: fields, OccurredAt: pgTime(event.OccurredAt),
}); err != nil {
return fmt.Errorf("%s - record audit event: %w", location, mapInvitationError(err))
@@ -17,15 +17,28 @@ import (
var _ outbound.PrivacyViewRepository = privacyCohortRepository{}
// CurrentFields stays closed until invitation grants have transaction-bound
// persistence. The C4 ledger alone does not identify a live invitation grant.
// CurrentFields stays closed. The card-handle contact read has no contract
// operation; contact values are read only through the invitation grant of
// GetOrganizationInvitationContacts, which locks its own grant and C4 record.
func (privacyCohortRepository) CurrentFields(context.Context, uuid.UUID, uuid.UUID) (domain.ContactFieldSet, error) {
return domain.ContactFieldSet{}, outbound.ErrContactAccessClosed
}
func (privacyCohortRepository) CloseForVisibility(context.Context, uuid.UUID, uuid.UUID, time.Time) error {
// No C4 contact-grant persistence exists in this release. Contact reads are
// closed by default, so there is no persisted grant to reactivate later.
// CloseForVisibility closes the active grants of the candidate, or of one
// organization when organizationID is set, with the reason visibility_closed.
// The publication and the hiding call it in their own transactions.
func (repository privacyCohortRepository) CloseForVisibility(
ctx context.Context,
candidateID, organizationID uuid.UUID,
at time.Time,
) error {
const location = "privacyCohortRepository.CloseForVisibility"
if err := closeActiveContactGrants(ctx, repository.queries, contactGrantClosure{
candidateID: candidateID, organizationID: organizationID,
reason: domain.ContactRevocationVisibilityClosed, at: at,
}); err != nil {
return fmt.Errorf("%s - close contact grants: %w", location, err)
}
return nil
}
@@ -11,6 +11,60 @@ import (
"github.com/jackc/pgx/v5/pgtype"
)
const closeActiveContactGrants = `-- name: CloseActiveContactGrants :execrows
WITH targets AS (
SELECT contact_grants.id
FROM contact_grants
WHERE
contact_grants.candidate_id = $3
AND (
$4::uuid IS NULL
OR contact_grants.organization_id = $4::uuid
)
AND (
$5::uuid [] IS NULL
OR contact_grants.consent_record_id = ANY($5::uuid [])
)
AND contact_grants.revoked_at IS NULL
ORDER BY contact_grants.id
FOR NO KEY UPDATE
)
UPDATE contact_grants
SET
revoked_at = greatest(contact_grants.granted_at, $1::timestamptz),
revocation_reason = $2
FROM targets
WHERE contact_grants.id = targets.id
`
type CloseActiveContactGrantsParams struct {
RevokedAt pgtype.Timestamptz
RevocationReason pgtype.Text
CandidateID pgtype.UUID
OrganizationID pgtype.UUID
ConsentRecordIds []pgtype.UUID
}
// Closes the active grants of one candidate with one reason. A nil organization
// closes every organization of the candidate, and a non-nil list of consent
// records closes only the grants that those records gave. The grant rows are
// locked in identifier order, so two closures that overlap take their locks in
// the same order. The revocation time never precedes the grant time, which the
// grant checks. A grant that is already closed keeps its first stamp.
func (q *Queries) CloseActiveContactGrants(ctx context.Context, arg CloseActiveContactGrantsParams) (int64, error) {
result, err := q.db.Exec(ctx, closeActiveContactGrants,
arg.RevokedAt,
arg.RevocationReason,
arg.CandidateID,
arg.OrganizationID,
arg.ConsentRecordIds,
)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const getContactGrantByInvitation = `-- name: GetContactGrantByInvitation :one
SELECT
id,
@@ -109,3 +163,72 @@ func (q *Queries) InsertContactGrant(ctx context.Context, arg InsertContactGrant
)
return err
}
const lockContactGrant = `-- name: LockContactGrant :one
SELECT
id,
organization_id,
candidate_id,
source_invitation_id,
consent_record_id,
terms_version,
fields,
consent_text_version,
granted_at,
revoked_at,
revocation_reason
FROM contact_grants
WHERE id = $1
FOR SHARE
`
// Share-locks one grant for the duration of a contact read and returns its
// stored state. The caller decides whether the state still allows the read.
func (q *Queries) LockContactGrant(ctx context.Context, id pgtype.UUID) (ContactGrant, error) {
row := q.db.QueryRow(ctx, lockContactGrant, id)
var i ContactGrant
err := row.Scan(
&i.ID,
&i.OrganizationID,
&i.CandidateID,
&i.SourceInvitationID,
&i.ConsentRecordID,
&i.TermsVersion,
&i.Fields,
&i.ConsentTextVersion,
&i.GrantedAt,
&i.RevokedAt,
&i.RevocationReason,
)
return i, err
}
const lockCurrentContactConsentRecord = `-- name: LockCurrentContactConsentRecord :one
SELECT consent_records.id
FROM consent_records
WHERE
consent_records.id = $1
AND consent_records.subject_id = $2
AND consent_records.organization_id = $3
AND consent_records.purpose = 'c4'
AND consent_records.revoked_at IS NULL
FOR SHARE
`
type LockCurrentContactConsentRecordParams struct {
ConsentRecordID pgtype.UUID
CandidateID pgtype.UUID
OrganizationID pgtype.UUID
}
// Share-locks the consent C4 record of a grant for the duration of a contact
// read. The read locks the record before the grant, the order that a C4
// revocation follows when it stamps the record and then closes its grants. No
// row means the record is revoked or belongs to another scope, which closes
// the read.
func (q *Queries) LockCurrentContactConsentRecord(ctx context.Context, arg LockCurrentContactConsentRecordParams) (pgtype.UUID, error) {
row := q.db.QueryRow(ctx, lockCurrentContactConsentRecord, arg.ConsentRecordID, arg.CandidateID, arg.OrganizationID)
var id pgtype.UUID
err := row.Scan(&id)
return id, err
}
@@ -0,0 +1,39 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: invitation_cooldowns.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const latestInvitationDecline = `-- name: LatestInvitationDecline :one
SELECT responded_at AS declined_at
FROM invitations
WHERE
organization_id = $1
AND candidate_id = $2
AND state = 'declined'
ORDER BY responded_at DESC
LIMIT 1
`
type LatestInvitationDeclineParams struct {
OrganizationID pgtype.UUID
CandidateID pgtype.UUID
}
// The time of the latest decline of one candidate by one organization, across
// every need and every member of the organization. The pause that follows it is
// applied by the send, from the policy in force. A candidate without a decline
// finds no row.
func (q *Queries) LatestInvitationDecline(ctx context.Context, arg LatestInvitationDeclineParams) (pgtype.Timestamptz, error) {
row := q.db.QueryRow(ctx, latestInvitationDecline, arg.OrganizationID, arg.CandidateID)
var declined_at pgtype.Timestamptz
err := row.Scan(&declined_at)
return declined_at, err
}
@@ -0,0 +1,73 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: invitation_expiry.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const expireInvitation = `-- name: ExpireInvitation :one
UPDATE invitations
SET
state = 'expired',
expiry_reason = 'invitation_timeout',
version = $1,
updated_at = $2
WHERE
organization_id = $3
AND id = $4
AND state IN ('delivered', 'viewed')
AND version = $5
AND response_deadline_at <= $2
AND $1::bigint = $5::bigint + 1
RETURNING id
`
type ExpireInvitationParams struct {
NextVersion int64
ExpiredAt pgtype.Timestamptz
OrganizationID pgtype.UUID
InvitationID pgtype.UUID
ExpectedVersion int64
}
// The compare-and-swap of the expiry: it applies only to a delivered or viewed
// invitation at the version the caller read, whose deadline has passed at the
// expiry time. It keeps the deadline, the terms, and every answer field, and it
// sets the timeout reason. No row is returned when it lost a race or the
// deadline has not passed.
func (q *Queries) ExpireInvitation(ctx context.Context, arg ExpireInvitationParams) (pgtype.UUID, error) {
row := q.db.QueryRow(ctx, expireInvitation,
arg.NextVersion,
arg.ExpiredAt,
arg.OrganizationID,
arg.InvitationID,
arg.ExpectedVersion,
)
var id pgtype.UUID
err := row.Scan(&id)
return id, err
}
const lockInvitationByID = `-- name: LockInvitationByID :one
SELECT organization_id
FROM invitations
WHERE id = $1
FOR UPDATE
`
// Takes the row lock of one invitation by its identifier alone. Only the
// response deadline job reads an invitation without an organization or a
// candidate of the request; it reads the organization from this row and then
// reads the locked invitation with its scope.
func (q *Queries) LockInvitationByID(ctx context.Context, invitationID pgtype.UUID) (pgtype.UUID, error) {
row := q.db.QueryRow(ctx, lockInvitationByID, invitationID)
var organization_id pgtype.UUID
err := row.Scan(&organization_id)
return organization_id, err
}
@@ -0,0 +1,37 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: invitation_pending.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const countPendingNeedInvitations = `-- name: CountPendingNeedInvitations :one
SELECT count(*)::bigint AS pending
FROM invitations
WHERE
organization_id = $1
AND need_id = $2
AND state IN ('delivered', 'viewed', 'counter')
`
type CountPendingNeedInvitationsParams struct {
OrganizationID pgtype.UUID
NeedID pgtype.UUID
}
// Counts the invitations of one organization need that wait for an answer:
// delivered, viewed, or the planned counter offer. The send counts them under
// the organization lock, which every send takes first, so no other send can
// add a waiting invitation between the count and its own delivery.
func (q *Queries) CountPendingNeedInvitations(ctx context.Context, arg CountPendingNeedInvitationsParams) (int64, error) {
row := q.db.QueryRow(ctx, countPendingNeedInvitations, arg.OrganizationID, arg.NeedID)
var pending int64
err := row.Scan(&pending)
return pending, err
}
@@ -114,6 +114,13 @@ type Querier interface {
// jobs belong to kinds without a handler in the claiming process, an index
// on (kind, available_at, id) is the next step.
ClaimScheduledJobs(ctx context.Context, arg ClaimScheduledJobsParams) ([]ClaimScheduledJobsRow, error)
// Closes the active grants of one candidate with one reason. A nil organization
// closes every organization of the candidate, and a non-nil list of consent
// records closes only the grants that those records gave. The grant rows are
// locked in identifier order, so two closures that overlap take their locks in
// the same order. The revocation time never precedes the grant time, which the
// grant checks. A grant that is already closed keeps its first stamp.
CloseActiveContactGrants(ctx context.Context, arg CloseActiveContactGrantsParams) (int64, error)
// Completes a job in the transaction of its handler effect. The guard is
// the lease owner and the attempt, so a worker that lost its lease cannot
// complete the job.
@@ -147,6 +154,11 @@ type Querier interface {
// row stays attributed to the organization that consumed it.
CountCompanyInvitationQuotaHoldingWindow(ctx context.Context, arg CountCompanyInvitationQuotaHoldingWindowParams) (CountCompanyInvitationQuotaHoldingWindowRow, error)
CountCompanyInvitationQuotaWindow(ctx context.Context, arg CountCompanyInvitationQuotaWindowParams) (CountCompanyInvitationQuotaWindowRow, error)
// Counts the invitations of one organization need that wait for an answer:
// delivered, viewed, or the planned counter offer. The send counts them under
// the organization lock, which every send takes first, so no other send can
// add a waiting invitation between the count and its own delivery.
CountPendingNeedInvitations(ctx context.Context, arg CountPendingNeedInvitationsParams) (int64, error)
// Counts the families of a category that have at least one published
// version, however many versions each has.
CountPublishedAssessmentFamilies(ctx context.Context, category string) (int32, error)
@@ -235,6 +247,12 @@ type Querier interface {
// for the first transaction and then inserts nothing. Existing rows are
// neither changed nor locked here.
EnsureMailQuotaRows(ctx context.Context, arg EnsureMailQuotaRowsParams) error
// The compare-and-swap of the expiry: it applies only to a delivered or viewed
// invitation at the version the caller read, whose deadline has passed at the
// expiry time. It keeps the deadline, the terms, and every answer field, and it
// sets the timeout reason. No row is returned when it lost a race or the
// deadline has not passed.
ExpireInvitation(ctx context.Context, arg ExpireInvitationParams) (pgtype.UUID, error)
// Records a failed attempt after its handler transaction rolled back: the
// job waits for its retry at retry_at (status failed) or is dead, with a
// NULL retry_at. due_at keeps the deadline. The same guard as the
@@ -576,6 +594,11 @@ type Querier interface {
// version number of a stored snapshot whose own requirements version is that
// number, so a later edit that only renamed the need is not accepted.
InvitationNeedVersionExists(ctx context.Context, arg InvitationNeedVersionExistsParams) (bool, error)
// The time of the latest decline of one candidate by one organization, across
// every need and every member of the organization. The pause that follows it is
// applied by the send, from the policy in force. A candidate without a decline
// finds no row.
LatestInvitationDecline(ctx context.Context, arg LatestInvitationDeclineParams) (pgtype.Timestamptz, error)
// Read the latest serialized event so a temporarily regressing application
// clock cannot make the next request fall before an event already counted.
LatestSupportCaseRequestEvent(ctx context.Context, ownerID pgtype.UUID) (pgtype.Timestamptz, error)
@@ -793,6 +816,9 @@ type Querier interface {
// transaction. The result carries the holding, whose pool an E0 organization
// shares; the caller locks that holding right after this lock.
LockCompanyQuotaOrganizationFirst(ctx context.Context, organizationID pgtype.UUID) (LockCompanyQuotaOrganizationFirstRow, error)
// Share-locks one grant for the duration of a contact read and returns its
// stored state. The caller decides whether the state still allows the read.
LockContactGrant(ctx context.Context, id pgtype.UUID) (ContactGrant, error)
// Lock the current C2 before locking the publication. C2 revocation updates
// this row before it locks the publication, so preserving this order avoids
// a lock inversion and makes the current consent stable through the read.
@@ -809,6 +835,12 @@ type Querier interface {
// Keeps the current C3 grant stable through a real assessment transaction.
// Revocation updates this row and therefore waits until the caller commits.
LockCurrentConsentForUse(ctx context.Context, subjectID pgtype.UUID) (LockCurrentConsentForUseRow, error)
// Share-locks the consent C4 record of a grant for the duration of a contact
// read. The read locks the record before the grant, the order that a C4
// revocation follows when it stamps the record and then closes its grants. No
// row means the record is revoked or belongs to another scope, which closes
// the read.
LockCurrentContactConsentRecord(ctx context.Context, arg LockCurrentContactConsentRecordParams) (pgtype.UUID, error)
// Takes the row lock of one invitation. It is a statement of its own, ahead of
// ReadInvitation, because a locking read that joins the terms table is
// re-checked against the new row version after a wait and then pairs the
@@ -816,6 +848,11 @@ type Querier interface {
// finds nothing. Once the lock is held, the following read sees the committed
// state and no writer can change it.
LockInvitation(ctx context.Context, arg LockInvitationParams) (pgtype.UUID, error)
// Takes the row lock of one invitation by its identifier alone. Only the
// response deadline job reads an invitation without an organization or a
// candidate of the request; it reads the organization from this row and then
// reads the locked invitation with its scope.
LockInvitationByID(ctx context.Context, invitationID pgtype.UUID) (pgtype.UUID, error)
// Locks the listed window rows until the transaction ends, in
// (period_kind, period_start) order, the same order for every caller, and
// returns their usage. Under READ COMMITTED a waiting caller reads the usage
+8 -3
View File
@@ -11,6 +11,7 @@ import (
"lincodex/backend/internal/adapter/secondary/prometheus"
"lincodex/backend/internal/port/inbound"
"lincodex/backend/internal/usecase/assessment"
"lincodex/backend/internal/usecase/invitation"
"lincodex/backend/internal/worker/jobrunner"
"lincodex/backend/internal/worker/retry"
)
@@ -32,10 +33,14 @@ var _ jobrunner.Metrics = (*prometheus.Metrics)(nil)
// jobHandlers lists the scheduled job handlers, one per kind. A product
// module adds its handler here, and the worker then claims jobs of that kind
// with the next deployment. Jobs of a kind without a handler wait in the
// database. The only kind now is the computation of the assessment review
// band, which can never block or change a result.
// database. The kinds are the computation of the assessment review band, which
// can never block or change a result, and the expiry of an invitation at its
// response deadline.
func jobHandlers(logger *slog.Logger) []inbound.JobHandler {
return []inbound.JobHandler{assessment.NewSignalReviewJob(logger)}
return []inbound.JobHandler{
assessment.NewSignalReviewJob(logger),
invitation.NewResponseDeadlineJob(time.Now),
}
}
func newJobWorker(
+8 -3
View File
@@ -4,6 +4,7 @@ import (
"context"
"log/slog"
"net/http"
"slices"
"strings"
"testing"
"time"
@@ -55,10 +56,14 @@ func TestBuildJobWorkerSkipsWithoutWork(t *testing.T) {
}
}
func TestBootstrapRegistersTheReviewJobKind(t *testing.T) {
func TestBootstrapRegistersTheProductJobKinds(t *testing.T) {
handlers := jobHandlers(slog.New(slog.DiscardHandler))
if len(handlers) != 1 || handlers[0].JobKind() != "assessment.signal_review" {
t.Fatalf("jobHandlers() = %v; update the documentation when the registered job kinds change", handlers)
kinds := make([]string, 0, len(handlers))
for _, handler := range handlers {
kinds = append(kinds, handler.JobKind())
}
if !slices.Equal(kinds, []string{"assessment.signal_review", "invitation.response_deadline"}) {
t.Fatalf("jobHandlers() kinds = %v; update the documentation when the registered job kinds change", kinds)
}
}
@@ -0,0 +1,112 @@
package domain
import (
"fmt"
"log/slog"
"slices"
"time"
"github.com/google/uuid"
)
const redactedContactDisclosure = "[redacted contact disclosure]"
// ContactDisclosure holds the contact values that one active grant allows an
// organization to read now. It is the only domain value that carries contact
// values, so it redacts itself in fmt and slog output. It names no candidate
// and no organization: the caller already knows both from its own request.
type ContactDisclosure struct {
invitationID uuid.UUID
grantID uuid.UUID
fields []ContactField
grantedAt time.Time
fullName *string
email *string
phone *string
telegram *string
}
// NewContactDisclosure builds the values of an active grant from the profile.
// Only the kinds of the grant are read, and a kind yields its value only when
// the profile holds it as a confirmed claim, so a suggestion that nobody
// confirmed is never disclosed. A kind the profile no longer holds stays nil.
func NewContactDisclosure(grant ContactGrant, profile CandidateProfile) (ContactDisclosure, error) {
const location = "domain.NewContactDisclosure"
if grant.IsZero() || grant.Status() != ContactGrantActive {
return ContactDisclosure{}, fmt.Errorf("%s - only an active grant discloses contacts: %w", location, ErrInvalidContactGrant)
}
content := profile.Content()
disclosure := ContactDisclosure{
invitationID: grant.InvitationID(), grantID: grant.ID(),
fields: grant.Fields().Fields(), grantedAt: grant.GrantedAt(),
}
for _, field := range disclosure.fields {
switch field {
case ContactFieldFullName:
disclosure.fullName = confirmedContactValue(content.FullName())
case ContactFieldEmail:
disclosure.email = confirmedContactValue(content.Email())
case ContactFieldPhone:
disclosure.phone = confirmedContactValue(content.Phone())
case ContactFieldTelegram:
disclosure.telegram = confirmedContactValue(content.Telegram())
}
}
return disclosure, nil
}
// confirmedContactValue returns the value of a claim the candidate confirmed,
// and nil for a missing claim or an unconfirmed suggestion.
func confirmedContactValue(claim ProfileClaim[string], present bool) *string {
if !present || claim.Status() != ProfileClaimConfirmed {
return nil
}
value := claim.Value()
return &value
}
// InvitationID is the invitation whose acceptance created the grant.
func (disclosure ContactDisclosure) InvitationID() uuid.UUID { return disclosure.invitationID }
// GrantID is the grant that allowed the read.
func (disclosure ContactDisclosure) GrantID() uuid.UUID { return disclosure.grantID }
// Fields are the kinds that the grant covers, in canonical order.
func (disclosure ContactDisclosure) Fields() []ContactField { return slices.Clone(disclosure.fields) }
// GrantedAt is the time of the consent that the grant stores.
func (disclosure ContactDisclosure) GrantedAt() time.Time { return disclosure.grantedAt }
// FullName returns the full name and whether it is disclosed.
func (disclosure ContactDisclosure) FullName() (string, bool) {
return valueOfContact(disclosure.fullName)
}
// Email returns the email address and whether it is disclosed.
func (disclosure ContactDisclosure) Email() (string, bool) { return valueOfContact(disclosure.email) }
// Phone returns the phone number and whether it is disclosed.
func (disclosure ContactDisclosure) Phone() (string, bool) { return valueOfContact(disclosure.phone) }
// Telegram returns the Telegram username and whether it is disclosed.
func (disclosure ContactDisclosure) Telegram() (string, bool) {
return valueOfContact(disclosure.telegram)
}
func valueOfContact(value *string) (string, bool) {
if value == nil {
return "", false
}
return *value, true
}
func (disclosure ContactDisclosure) String() string { return redactedContactDisclosure }
func (disclosure ContactDisclosure) GoString() string { return redactedContactDisclosure }
func (disclosure ContactDisclosure) Format(state fmt.State, _ rune) {
writeRedacted(state, redactedContactDisclosure)
}
// LogValue carries the grant identifier and the number of kinds only.
func (disclosure ContactDisclosure) LogValue() slog.Value {
return slog.GroupValue(slog.String("grant_id", disclosure.grantID.String()), slog.Int("fields", len(disclosure.fields)))
}
@@ -0,0 +1,172 @@
package domain
import (
"errors"
"fmt"
"strings"
"testing"
"time"
"github.com/google/uuid"
)
func TestNewContactDisclosureReadsOnlyTheGrantedConfirmedKinds(t *testing.T) {
now := time.Date(2026, time.October, 9, 10, 0, 0, 0, time.UTC)
candidateID, organizationID, invitationID := uuid.Must(uuid.NewV7()), uuid.Must(uuid.NewV7()), uuid.Must(uuid.NewV7())
profile := contactTestProfile(t, candidateID, now, map[string]ProfileClaimInput[string]{
"full_name": {Value: "Test Candidate", Status: ProfileClaimConfirmed},
"phone": {Value: "+70000000000", Status: ProfileClaimConfirmed},
"telegram": {Value: "@candidate_test", Status: ProfileClaimConfirmed},
})
grant := contactTestGrant(t, candidateID, organizationID, invitationID, now, "email", "phone", "telegram")
disclosure, err := NewContactDisclosure(grant, profile)
if err != nil {
t.Fatalf("NewContactDisclosure() error = %v", err)
}
if disclosure.InvitationID() != invitationID || disclosure.GrantID() != grant.ID() || !disclosure.GrantedAt().Equal(now) {
t.Fatalf("disclosure identity = %v %v %v, want the grant's", disclosure.InvitationID(), disclosure.GrantID(), disclosure.GrantedAt())
}
if !equalContactFields(disclosure.Fields(), ContactFieldEmail, ContactFieldPhone, ContactFieldTelegram) {
t.Fatalf("fields = %v, want the grant's three kinds", disclosure.Fields())
}
// The profile holds no email, so the granted email has no value.
if value, ok := disclosure.Email(); ok || value != "" {
t.Fatalf("email = %q, %v; want no value for a kind the profile does not hold", value, ok)
}
if value, ok := disclosure.Phone(); !ok || value != "+70000000000" {
t.Fatalf("phone = %q, %v; want the confirmed number", value, ok)
}
if value, ok := disclosure.Telegram(); !ok || value != "@candidate_test" {
t.Fatalf("telegram = %q, %v; want the confirmed name", value, ok)
}
// The full name is held but not granted, so it stays undisclosed.
if value, ok := disclosure.FullName(); ok || value != "" {
t.Fatalf("full name = %q, %v; want none because the grant does not cover it", value, ok)
}
}
func TestConfirmedContactValueIgnoresUnconfirmedSuggestions(t *testing.T) {
source, err := RestoreProfileClaimSource(ProfileOriginImported, ProfileClaimTrustLevel, "", "extractor-1", time.Time{})
if err != nil {
t.Fatalf("RestoreProfileClaimSource() error = %v", err)
}
suggestion, err := RestoreProfileClaim("candidate@example.test", ProfileClaimExtracted, source)
if err != nil {
t.Fatalf("RestoreProfileClaim() error = %v", err)
}
if value := confirmedContactValue(suggestion, true); value != nil {
t.Fatalf("confirmedContactValue(suggestion) = %q, want nil", *value)
}
if value := confirmedContactValue(suggestion, false); value != nil {
t.Fatal("confirmedContactValue(missing claim) returned a value")
}
}
func TestNewContactDisclosureRefusesAGrantThatIsNotActive(t *testing.T) {
now := time.Date(2026, time.October, 9, 10, 0, 0, 0, time.UTC)
candidateID, organizationID, invitationID := uuid.Must(uuid.NewV7()), uuid.Must(uuid.NewV7()), uuid.Must(uuid.NewV7())
profile := contactTestProfile(t, candidateID, now, map[string]ProfileClaimInput[string]{
"email": {Value: "candidate@example.test", Status: ProfileClaimConfirmed},
})
grant := contactTestGrant(t, candidateID, organizationID, invitationID, now, "email")
stored := grant.Stored()
revokedAt := now.Add(time.Hour)
stored.RevokedAt, stored.RevocationReason = &revokedAt, string(ContactRevocationVisibilityClosed)
revoked, err := RestoreContactGrant(stored)
if err != nil {
t.Fatalf("RestoreContactGrant() error = %v", err)
}
if _, err := NewContactDisclosure(revoked, profile); !errors.Is(err, ErrInvalidContactGrant) {
t.Fatalf("NewContactDisclosure(revoked) error = %v, want ErrInvalidContactGrant", err)
}
if _, err := NewContactDisclosure(ContactGrant{}, profile); !errors.Is(err, ErrInvalidContactGrant) {
t.Fatalf("NewContactDisclosure(zero) error = %v, want ErrInvalidContactGrant", err)
}
}
func TestContactDisclosureRedactsItsValuesInFormatting(t *testing.T) {
now := time.Date(2026, time.October, 9, 10, 0, 0, 0, time.UTC)
candidateID, organizationID, invitationID := uuid.Must(uuid.NewV7()), uuid.Must(uuid.NewV7()), uuid.Must(uuid.NewV7())
profile := contactTestProfile(t, candidateID, now, map[string]ProfileClaimInput[string]{
"phone": {Value: "+70000000001", Status: ProfileClaimConfirmed},
})
disclosure, err := NewContactDisclosure(contactTestGrant(t, candidateID, organizationID, invitationID, now, "phone"), profile)
if err != nil {
t.Fatalf("NewContactDisclosure() error = %v", err)
}
for _, rendered := range []string{
fmt.Sprint(disclosure), fmt.Sprintf("%+v", disclosure), fmt.Sprintf("%#v", disclosure),
} {
if strings.Contains(rendered, "+70000000001") || strings.Contains(rendered, candidateID.String()) {
t.Fatalf("formatted disclosure leaks a value or the candidate: %q", rendered)
}
}
}
// contactTestGrant builds an active grant of the kinds, as the acceptance does.
func contactTestGrant(t *testing.T, candidateID, organizationID, invitationID uuid.UUID, at time.Time, kinds ...string) ContactGrant {
t.Helper()
grant, err := RestoreContactGrant(StoredContactGrant{
ID: uuid.Must(uuid.NewV7()), OrganizationID: organizationID, CandidateID: candidateID,
InvitationID: invitationID, ConsentRecordID: uuid.Must(uuid.NewV7()), TermsVersion: 1,
Fields: canonicalKinds(kinds...), ConsentTextVersion: "c4-2026-10-01", GrantedAt: at,
})
if err != nil {
t.Fatalf("RestoreContactGrant() error = %v", err)
}
return grant
}
// contactTestProfile builds a profile whose claims have the given statuses.
func contactTestProfile(t *testing.T, candidateID uuid.UUID, at time.Time, claims map[string]ProfileClaimInput[string]) CandidateProfile {
t.Helper()
var input CandidateProfileInput
for kind, claim := range claims {
switch kind {
case "full_name":
input.FullName = &claim
case "email":
input.Email = &claim
case "phone":
input.Phone = &claim
case "telegram":
input.Telegram = &claim
}
}
empty, err := EmptyCandidateProfile(candidateID)
if err != nil {
t.Fatalf("EmptyCandidateProfile() error = %v", err)
}
profile, _, err := empty.Replace(input, 0, at)
if err != nil {
t.Fatalf("Replace() error = %v", err)
}
return profile
}
// canonicalKinds returns the kinds in the order of the stored form.
func canonicalKinds(kinds ...string) []string {
order := []string{"full_name", "email", "phone", "telegram"}
var canonical []string
for _, kind := range order {
for _, given := range kinds {
if given == kind {
canonical = append(canonical, kind)
}
}
}
return canonical
}
func equalContactFields(got []ContactField, want ...ContactField) bool {
if len(got) != len(want) {
return false
}
for index := range got {
if got[index] != want[index] {
return false
}
}
return true
}
+2 -1
View File
@@ -17,7 +17,8 @@ var (
)
// ContactRevocationReason says why a contact grant was revoked. It is shown
// only to the candidate. The revocation itself belongs to a later operation.
// only to the candidate. The consent revocation and the visibility changes
// stamp it in the transaction of the change; a stamp is never cleared.
type ContactRevocationReason string
const (
+25 -6
View File
@@ -459,6 +459,26 @@ const (
InvitationContactAccessClosed InvitationContactAccess = "closed"
)
// InvitationContactAccessView is the contact access of the organization through
// one invitation. Fields are the kinds that the contact read returns while the
// status is available; the other states list none. It never holds a contact
// value, and it names no reason, because the organization is not told one.
type InvitationContactAccessView struct {
Status InvitationContactAccess `json:"status"`
Fields []ContactField `json:"fields"`
}
// NewInvitationContactAccessView builds the view of a status. Fields are kept
// only for an available access, and the list is never nil, so it serializes as
// an empty array.
func NewInvitationContactAccessView(status InvitationContactAccess, fields []ContactField) InvitationContactAccessView {
view := InvitationContactAccessView{Status: status, Fields: []ContactField{}}
if status == InvitationContactAccessAvailable {
view.Fields = append(view.Fields, fields...)
}
return view
}
// InvitationSnapshot is the serializable part of an invitation that an
// organization may read. It has no candidate identifier, so it cannot reveal
// who the invitation is for.
@@ -500,15 +520,14 @@ func (invitation Invitation) Snapshot() InvitationSnapshot {
// OrganizationInvitationView is an invitation as its organization reads it:
// the snapshot, the organization-scoped alias of the candidate, the coarse
// salary indicator, and the state of the contact access without any contact
// value. It also serves as the stored original response of an idempotent
// create.
// salary indicator, and the contact access without any contact value. It also
// serves as the stored original response of an idempotent create or send.
type OrganizationInvitationView struct {
InvitationSnapshot
CandidateHandle string `json:"candidate_handle"`
SalaryFit InvitationSalaryFit `json:"salary_fit"`
ContactAccess InvitationContactAccess `json:"contact_access"`
CandidateHandle string `json:"candidate_handle"`
SalaryFit InvitationSalaryFit `json:"salary_fit"`
ContactAccess InvitationContactAccessView `json:"contact_access"`
}
func (invitation Invitation) String() string { return redactedInvitation }
@@ -0,0 +1,74 @@
package domain
import (
"fmt"
"time"
"github.com/google/uuid"
)
// InvitationEventExpired is the audit event of an expiry that the server made
// at the response deadline. No candidate or organization acted, so the event
// names no actor and no field.
const InvitationEventExpired InvitationEventKind = "expired"
// AwaitsAnswer reports the states in which the candidate's answer is still
// open: a delivered or a viewed invitation. The planned counter offer is not
// among them, because no operation produces it yet.
func (invitation Invitation) AwaitsAnswer() bool {
return invitation.IsDelivered() && (invitation.State() == InvitationDelivered || invitation.State() == InvitationViewed)
}
// ExpiryDue reports whether the invitation still awaits an answer at the time
// and its response deadline has passed. At the deadline or later the answer is
// late, so the expiry is due.
func (invitation Invitation) ExpiryDue(at time.Time) bool {
return invitation.AwaitsAnswer() && invitation.ResponseDeadlinePassed(at)
}
// Expire returns the next version in the terminal state expired with the
// timeout reason, when the invitation is due at the time. An invitation that is
// not due, because it is answered, expired, or its deadline has not passed yet,
// is returned as it is with changed false. The expiry keeps the deadline, the
// terms, and the answer fields. It creates no consent and no contact grant, and
// it never returns a weekly quota or a pending slot that the organization
// spent: the pending limit counts only the invitations that still wait.
func (invitation Invitation) Expire(at time.Time) (Invitation, bool, error) {
const location = "Invitation.Expire"
if !validInvitationTime(at) || at.Before(invitation.record.UpdatedAt) {
return Invitation{}, false, fmt.Errorf("%s - expiry time must be set and not before the last change: %w", location, ErrInvalidInvitation)
}
if !invitation.ExpiryDue(at) {
return invitation, false, nil
}
at = at.UTC()
next := invitation.Stored()
reason := string(InvitationExpiryTimeout)
next.State = string(InvitationExpired)
next.ExpiryReason = &reason
next.Version++
next.UpdatedAt = at
expired, err := RestoreInvitation(next)
if err != nil {
return Invitation{}, false, fmt.Errorf("%s - restore expired invitation: %w", location, err)
}
return expired, true, nil
}
// ExpiryEvent builds the audit event of the expired version this invitation has
// just reached. The event has no actor, because the server made the change.
func (invitation Invitation) ExpiryEvent() (InvitationEvent, error) {
const location = "Invitation.ExpiryEvent"
if invitation.State() != InvitationExpired {
return InvitationEvent{}, fmt.Errorf("%s - the invitation must be expired: %w", location, ErrInvalidInvitation)
}
id, err := uuid.NewV7()
if err != nil {
return InvitationEvent{}, fmt.Errorf("%s - generate event ID: %w", location, err)
}
return InvitationEvent{
ID: id, InvitationID: invitation.record.ID, OrganizationID: invitation.record.OrganizationID,
Version: invitation.record.Version, TermsVersion: invitation.record.TermsVersion, Kind: InvitationEventExpired,
ActorID: uuid.Nil, ChangedFields: []InvitationChangedField{}, OccurredAt: invitation.record.UpdatedAt,
}, nil
}
@@ -0,0 +1,86 @@
package domain
import (
"errors"
"testing"
"time"
"github.com/google/uuid"
)
func TestExpireMovesADueInvitationToTheTimeoutReasonAndKeepsItsDeadline(t *testing.T) {
delivered, _ := deliveredTestInvitation(t)
deadline := *delivered.Snapshot().ResponseDeadlineAt
viewed, _, err := delivered.RecordView(delivered.UpdatedAt().Add(time.Minute))
if err != nil {
t.Fatalf("RecordView() error = %v", err)
}
for name, invitation := range map[string]Invitation{"delivered": delivered, "viewed": viewed} {
t.Run(name, func(t *testing.T) {
expired, changed, err := invitation.Expire(deadline)
if err != nil || !changed {
t.Fatalf("Expire(at the deadline) = %v, %v; want a change", changed, err)
}
snapshot := expired.Snapshot()
if snapshot.State != InvitationExpired || snapshot.ExpiryReason == nil || *snapshot.ExpiryReason != InvitationExpiryTimeout ||
snapshot.Version != invitation.Version()+1 || snapshot.TermsVersion != invitation.TermsVersion() ||
!snapshot.ResponseDeadlineAt.Equal(deadline) || !snapshot.UpdatedAt.Equal(deadline) ||
snapshot.RespondedAt != nil || !snapshot.DeliveredAt.Equal(*invitation.Snapshot().DeliveredAt) {
t.Fatalf("expired = %+v, want the next version expired by the timeout with the same deadline and terms", snapshot)
}
event, err := expired.ExpiryEvent()
if err != nil {
t.Fatalf("ExpiryEvent() error = %v", err)
}
if event.Kind != InvitationEventExpired || event.ActorID != uuid.Nil ||
event.Version != snapshot.Version || len(event.ChangedFields) != 0 || !event.OccurredAt.Equal(deadline) {
t.Fatalf("ExpiryEvent() = %+v, want one system event of the expired version", event)
}
})
}
}
func TestExpireLeavesAnInvitationAloneBeforeItsDeadlineAndAfterAnAnswer(t *testing.T) {
delivered, _ := deliveredTestInvitation(t)
deadline := *delivered.Snapshot().ResponseDeadlineAt
expiring := deadline.Add(-time.Microsecond)
declined, _, err := delivered.Decline(InvitationDeclineChoice{Reason: InvitationDeclineOther}, expiring)
if err != nil {
t.Fatalf("Decline() error = %v", err)
}
accepted := withState(t, delivered, InvitationAccepted, func(stored *StoredInvitation) {
responded := expiring
stored.RespondedAt = &responded
})
for name, test := range map[string]struct {
invitation Invitation
at time.Time
}{
"one microsecond before the deadline": {delivered, expiring},
"declined after the deadline": {declined, deadline.Add(time.Hour)},
"accepted after the deadline": {accepted, deadline.Add(time.Hour)},
} {
t.Run(name, func(t *testing.T) {
unchanged, changed, err := test.invitation.Expire(test.at)
if err != nil || changed || unchanged.Version() != test.invitation.Version() || unchanged.State() != test.invitation.State() {
t.Fatalf("Expire() = %v, %v, %v; want the invitation unchanged", unchanged.State(), changed, err)
}
})
}
}
func TestExpireRefusesATimeBeforeTheLastChange(t *testing.T) {
delivered, _ := deliveredTestInvitation(t)
if _, _, err := delivered.Expire(delivered.UpdatedAt().Add(-time.Second)); !errors.Is(err, ErrInvalidInvitation) {
t.Fatalf("Expire(before the last change) error = %v, want ErrInvalidInvitation", err)
}
}
func TestExpiryEventRequiresAnExpiredInvitation(t *testing.T) {
delivered, _ := deliveredTestInvitation(t)
if _, err := delivered.ExpiryEvent(); !errors.Is(err, ErrInvalidInvitation) {
t.Fatalf("ExpiryEvent(delivered) error = %v, want ErrInvalidInvitation", err)
}
}
+11 -13
View File
@@ -57,25 +57,23 @@ type AccountDeletionRequests interface {
CreateOrGet(ctx context.Context, request domain.AccountDeletionRequest) (record domain.AccountDeletionRequest, created bool, err error)
}
// ConsentRevocationEffects applies every currently available local privacy
// change and records downstream revocation intents in the same transaction as
// the ledger stamps. Future C2 and C4 grant adapters must bind each downstream
// grant to its source consent record ID and synchronously close grants for
// revoked record IDs before returning; a later consent record may create a
// new grant, but must never reactivate an older record's grant. Future C5
// readers and importers must check the current consent ledger before reading
// ConsentRevocationEffects applies every local privacy change of a revocation
// and records downstream revocation intents in the same transaction as the
// ledger stamps. The local grants are closed synchronously there: a C4
// revocation closes the grants that name the revoked records, and a C2
// revocation closes every grant of the candidate. A later consent record may
// create a new grant, but must never reactivate an older record's grant. Future
// C5 readers and importers must check the current consent ledger before reading
// or synchronizing data and fail closed on a missing grant or ledger error.
// An outbox event communicates a committed change; it is never an
// authorization check and cannot make a revoked grant current again. This
// release has no external FSP or downstream contact-grant adapter, so those
// external effects are not claimed as complete.
type ConsentRevocationEffects interface {
// Apply synchronously closes and records a C2 publication when present,
// then appends one bounded durable outbox intent per affected consent record
// with its stored scope. It must not truncate or omit affected records. A
// future local C2/C4 grant adapter must implement record-bound closure in
// this same UnitOfWork before the outbox intent is appended. An empty record
// set is not a valid call.
// Apply closes the local grants and the C2 publication when present, in the
// caller's transaction, then appends one bounded durable outbox intent per
// affected consent record with its stored scope. It must not truncate or
// omit affected records. An empty record set is not a valid call.
Apply(ctx context.Context, revocation domain.ConsentRevocation, records []domain.ConsentRecord) error
}
@@ -16,14 +16,25 @@ var ErrContactGrantNotFound = errors.New("contact grant not found")
// ContactGrantRepository stores the contact grants of accepted invitations. A
// grant is created in the acceptance transaction next to its consent C4
// record; it is never updated here, and a read is always scoped by the
// organization.
// record. Its revocation stamp is set only by the consent revocation and the
// visibility changes, through the closing statements of the postgres adapter.
// A read is always scoped by the organization.
type ContactGrantRepository interface {
// Create inserts the grant in the surrounding transaction. The database
// checks that the grant agrees with its consent record and invitation.
Create(ctx context.Context, grant domain.ContactGrant) error
// GetByInvitation returns the grant of one invitation of one organization,
// or ErrContactGrantNotFound.
// or ErrContactGrantNotFound. It takes no lock, so its result is only a
// starting point: a contact read locks the grant with LockForRead before it
// decides.
GetByInvitation(ctx context.Context, organizationID, invitationID uuid.UUID) (domain.ContactGrant, error)
// LockForRead share-locks the consent C4 record and then the grant that
// grant names, in that order, and returns the grant as stored now. The
// boolean reports whether the C4 record is still unrevoked. Both locks
// last until the surrounding transaction ends, so a revocation that commits
// first is seen here, and a revocation that waits closes the grant after the
// read. It returns ErrContactGrantNotFound when the grant has no row.
LockForRead(ctx context.Context, grant domain.ContactGrant) (domain.ContactGrant, bool, error)
}
@@ -144,6 +144,29 @@ type InvitationRepository interface {
// expectedVersion, at its terms version, or before its deadline. The consent
// C4 and the contact grant are stored by the caller in the same transaction.
Accept(ctx context.Context, expectedVersion int64, next domain.Invitation, event domain.InvitationEvent) error
// CountPendingNeedInvitations counts the invitations of the organization
// under the need that wait for an answer: delivered, viewed, or counter.
// The caller holds the organization lock, which every send takes first.
CountPendingNeedInvitations(ctx context.Context, organizationID, needID uuid.UUID) (int64, error)
// LatestDeclineTime returns the time of the latest decline of the candidate
// by the organization, across its needs and members. It reports false when
// the pair has no decline.
LatestDeclineTime(ctx context.Context, organizationID, candidateID uuid.UUID) (time.Time, bool, error)
// GetForDeadline locks the row of an invitation by its identifier alone and
// returns it, or ErrInvitationNotFound. Only the response deadline job reads
// an invitation without the organization or the candidate of a request.
GetForDeadline(ctx context.Context, invitationID uuid.UUID) (domain.Invitation, error)
// Expire moves a delivered or viewed invitation from expectedVersion to the
// expired version of next, when its deadline has passed at the expiry time
// of next, and records the audit event. It returns
// ErrInvitationVersionConflict when the stored row is not waiting for an
// answer at expectedVersion or its deadline has not passed. Nothing else
// changes: no consent, grant, or quota is written or returned.
Expire(ctx context.Context, expectedVersion int64, next domain.Invitation, event domain.InvitationEvent) error
}
// InvitationCreationResultRepository stores the original response of a
+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 {