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

@@ -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