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