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

@@ -0,0 +1,12 @@
-- +goose Up
-- A visibility change of the whole profile closes every active grant of one
-- candidate: the revocation of C2 and the closing of the publication. The
-- existing active index leads with the organization, so it cannot serve that
-- lookup. The index holds no data and only speeds up the closing statement.
CREATE INDEX contact_grants_candidate_active_idx
ON contact_grants (candidate_id)
WHERE revoked_at IS NULL;
-- +goose Down
-- The index holds no data, so a rollback drops only the lookup it provides.
DROP INDEX contact_grants_candidate_active_idx;
@@ -0,0 +1,152 @@
-- +goose Up
-- The pending limit per need, the pause after a decline, and the expiry at the
-- response deadline. A delivered or viewed invitation whose deadline has passed
-- moves to `expired` with the reason `invitation_timeout`. Nothing else changes
-- with it: no consent, no contact grant, and no organization quota is returned.
-- The expiry is written by a scheduled job, which the send schedules for every
-- delivery at its deadline, and by the candidate commands that find the
-- deadline passed. The system performs the expiry, so its audit event names no
-- actor.
ALTER TABLE invitation_events
DROP CONSTRAINT invitation_events_kind_known;
ALTER TABLE invitation_events
ADD CONSTRAINT invitation_events_kind_known CHECK (
kind IN (
'draft_created', 'draft_updated', 'delivered', 'viewed', 'declined',
'accepted', 'expired'
)
);
ALTER TABLE invitation_events
ADD CONSTRAINT invitation_events_expiry_changes_no_field CHECK (
kind <> 'expired' OR cardinality(changed_fields) = 0
);
-- Only the expiry is a server change, so only its event may lack an actor.
ALTER TABLE invitation_events
ALTER COLUMN actor_id DROP NOT NULL;
ALTER TABLE invitation_events
ADD CONSTRAINT invitation_events_system_actor CHECK (
(kind = 'expired') = (actor_id IS NULL)
);
-- Only a delivered or viewed invitation expires, and the expiry is not
-- recorded before the deadline it passed. The application compares the clock
-- with the deadline; this trigger keeps a row changed outside the application
-- from skipping either rule. An expiry without its reason is left to the
-- check constraint invitations_expiry_reason, which runs after this trigger.
-- +goose StatementBegin
CREATE FUNCTION invitations_guard_expiry() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
IF NEW.state = 'expired' AND NEW.expiry_reason IS NOT NULL
AND OLD.state IS DISTINCT FROM NEW.state THEN
IF OLD.state NOT IN ('delivered', 'viewed') THEN
RAISE EXCEPTION USING
ERRCODE = 'integrity_constraint_violation',
CONSTRAINT = 'invitations_expiry_from_pending',
TABLE = 'invitations',
MESSAGE = 'only a delivered or viewed invitation expires';
END IF;
IF NEW.updated_at < OLD.response_deadline_at THEN
RAISE EXCEPTION USING
ERRCODE = 'integrity_constraint_violation',
CONSTRAINT = 'invitations_expiry_after_deadline',
TABLE = 'invitations',
MESSAGE = 'an invitation expires at or after its response deadline';
END IF;
END IF;
RETURN NEW;
END;
$$;
-- +goose StatementEnd
CREATE TRIGGER invitations_guard_expiry
BEFORE UPDATE ON invitations
FOR EACH ROW EXECUTE FUNCTION invitations_guard_expiry();
-- The invitations that wait for an answer under one need of an organization:
-- the pending limit counts them.
CREATE INDEX invitations_pending_need_idx
ON invitations (organization_id, need_id)
WHERE need_id IS NOT NULL AND state IN ('delivered', 'viewed', 'counter');
-- The latest decline of one candidate by one organization, which starts the
-- pause before the next invitation of that pair.
CREATE INDEX invitations_declined_pair_idx
ON invitations (organization_id, candidate_id, responded_at DESC)
WHERE state = 'declined';
-- Invitations delivered before this migration have no deadline job yet. The
-- job's key is the invitation identifier, so the schedule is idempotent, and
-- its due time is the deadline that the invitation already stores.
INSERT INTO scheduled_jobs (
kind,
dedup_key,
payload,
due_at,
available_at,
status,
attempts
)
SELECT
'invitation.response_deadline',
invitations.id::text,
jsonb_build_object('invitation_id', invitations.id::text),
invitations.response_deadline_at AS due_at,
invitations.response_deadline_at AS available_at,
'pending',
0
FROM invitations
WHERE
invitations.state IN ('delivered', 'viewed')
AND invitations.response_deadline_at IS NOT NULL
ON CONFLICT (kind, dedup_key) DO NOTHING;
-- +goose Down
-- A rollback must not hide an expiry that already happened, and it must not
-- leave the deadline jobs without a handler.
-- +goose StatementBegin
DO $$
BEGIN
IF EXISTS (SELECT 1 FROM invitation_events WHERE kind = 'expired')
OR EXISTS (SELECT 1 FROM invitations WHERE state = 'expired') THEN
RAISE EXCEPTION USING
ERRCODE = 'integrity_constraint_violation',
CONSTRAINT = 'invitation_expiries_retained',
TABLE = 'invitation_events',
MESSAGE = 'expired invitations must be resolved before rollback';
END IF;
END;
$$;
-- +goose StatementEnd
DELETE FROM scheduled_jobs WHERE kind = 'invitation.response_deadline';
DROP INDEX invitations_declined_pair_idx;
DROP INDEX invitations_pending_need_idx;
DROP TRIGGER invitations_guard_expiry ON invitations;
DROP FUNCTION invitations_guard_expiry();
ALTER TABLE invitation_events
DROP CONSTRAINT invitation_events_system_actor;
ALTER TABLE invitation_events
ALTER COLUMN actor_id SET NOT NULL;
ALTER TABLE invitation_events
DROP CONSTRAINT invitation_events_expiry_changes_no_field;
ALTER TABLE invitation_events
DROP CONSTRAINT invitation_events_kind_known;
ALTER TABLE invitation_events
ADD CONSTRAINT invitation_events_kind_known CHECK (
kind IN (
'draft_created', 'draft_updated', 'delivered', 'viewed', 'declined',
'accepted'
)
);
+66
View File
@@ -43,3 +43,69 @@ FROM contact_grants
WHERE
organization_id = sqlc.arg(organization_id)
AND source_invitation_id = sqlc.arg(invitation_id);
-- 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.
-- name: LockCurrentContactConsentRecord :one
SELECT consent_records.id
FROM consent_records
WHERE
consent_records.id = sqlc.arg(consent_record_id)
AND consent_records.subject_id = sqlc.arg(candidate_id)
AND consent_records.organization_id = sqlc.arg(organization_id)
AND consent_records.purpose = 'c4'
AND consent_records.revoked_at IS NULL
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.
-- 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 = sqlc.arg(id)
FOR SHARE;
-- 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.
-- name: CloseActiveContactGrants :execrows
WITH targets AS (
SELECT contact_grants.id
FROM contact_grants
WHERE
contact_grants.candidate_id = sqlc.arg(candidate_id)
AND (
sqlc.narg(organization_id)::uuid IS NULL
OR contact_grants.organization_id = sqlc.narg(organization_id)::uuid
)
AND (
sqlc.narg(consent_record_ids)::uuid [] IS NULL
OR contact_grants.consent_record_id = ANY(sqlc.narg(consent_record_ids)::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, sqlc.arg(revoked_at)::timestamptz),
revocation_reason = sqlc.arg(revocation_reason)
FROM targets
WHERE contact_grants.id = targets.id;
@@ -0,0 +1,13 @@
-- 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.
-- name: LatestInvitationDecline :one
SELECT responded_at AS declined_at
FROM invitations
WHERE
organization_id = sqlc.arg(organization_id)
AND candidate_id = sqlc.arg(candidate_id)
AND state = 'declined'
ORDER BY responded_at DESC
LIMIT 1;
+30
View File
@@ -0,0 +1,30 @@
-- 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.
-- name: LockInvitationByID :one
SELECT organization_id
FROM invitations
WHERE id = sqlc.arg(invitation_id)
FOR UPDATE;
-- 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.
-- name: ExpireInvitation :one
UPDATE invitations
SET
state = 'expired',
expiry_reason = 'invitation_timeout',
version = sqlc.arg(next_version),
updated_at = sqlc.arg(expired_at)
WHERE
organization_id = sqlc.arg(organization_id)
AND id = sqlc.arg(invitation_id)
AND state IN ('delivered', 'viewed')
AND version = sqlc.arg(expected_version)
AND response_deadline_at <= sqlc.arg(expired_at)
AND sqlc.arg(next_version)::bigint = sqlc.arg(expected_version)::bigint + 1
RETURNING id;
+11
View File
@@ -0,0 +1,11 @@
-- 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.
-- name: CountPendingNeedInvitations :one
SELECT count(*)::bigint AS pending
FROM invitations
WHERE
organization_id = sqlc.arg(organization_id)
AND need_id = sqlc.arg(need_id)
AND state IN ('delivered', 'viewed', 'counter');