feat(notifications): send product notifications with a rights check right before each send

This commit is contained in:
shira committed 2026-10-09 20:38:39 +03:00
1 parent a856066316
commit 623d41b969
59 files changed
+4125 -1126

No files matched your search

@@ -162,14 +162,14 @@ SET
claim_owner = NULL,
claimed_until = NULL,
text_body = CASE
WHEN deliveries.kind IN ('verification', 'password_reset') THEN '' ELSE deliveries.text_body
WHEN deliveries.kind IN ('verification', 'password_reset', 'notification') THEN '' ELSE deliveries.text_body
END,
html_body = CASE
WHEN deliveries.kind IN ('verification', 'password_reset') THEN '' ELSE deliveries.html_body
WHEN deliveries.kind IN ('verification', 'password_reset', 'notification') THEN '' ELSE deliveries.html_body
END,
body_redacted_at = CASE
WHEN
deliveries.kind IN ('verification', 'password_reset')
deliveries.kind IN ('verification', 'password_reset', 'notification')
THEN greatest(deliveries.updated_at, $1::timestamptz)
ELSE deliveries.body_redacted_at
END,
@@ -279,6 +279,9 @@ RETURNING
claimed.version,
claimed.created_at,
claimed.updated_at,
claimed.subject_kind,
claimed.subject_id,
claimed.subject_organization_id,
candidate.previous_claimed_until,
candidate.since_first_send_seconds,
candidate.manual_retry_pending,
@@ -323,6 +326,9 @@ type ClaimDueDeliveryRow struct {
Version int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
SubjectKind pgtype.Text
SubjectID pgtype.UUID
SubjectOrganizationID pgtype.UUID
PreviousClaimedUntil pgtype.Timestamptz
SinceFirstSendSeconds float64
ManualRetryPending pgtype.Bool
@@ -392,6 +398,203 @@ func (q *Queries) ClaimDueDelivery(ctx context.Context, arg ClaimDueDeliveryPara
&i.Version,
&i.CreatedAt,
&i.UpdatedAt,
&i.SubjectKind,
&i.SubjectID,
&i.SubjectOrganizationID,
&i.PreviousClaimedUntil,
&i.SinceFirstSendSeconds,
&i.ManualRetryPending,
&i.ManualRetryCycleStarted,
&i.SendStartUnsettled,
&i.HasUncertainAttempt,
)
return i, err
}
const claimDueProductDelivery = `-- name: ClaimDueProductDelivery :one
WITH candidate AS (
SELECT
due.id,
due.claimed_until AS previous_claimed_until,
coalesce(
extract(EPOCH FROM clock_timestamp() - due.first_send_started_at),
-1
)::float8 AS since_first_send_seconds,
(due.manual_retry_authorized_at IS NOT NULL AND due.manual_retry_started_at IS NULL)
AS manual_retry_pending,
(due.manual_retry_started_at IS NOT NULL)::boolean AS manual_retry_cycle_started,
(
due.send_started_attempt_count IS NOT NULL
AND due.send_started_attempt_count = due.attempt_count
)::boolean AS send_start_unsettled,
EXISTS (
SELECT 1
FROM delivery_attempts AS prior_attempt
WHERE prior_attempt.delivery_id = due.id
AND prior_attempt.outcome = 'unknown'
)::boolean AS has_uncertain_attempt
FROM deliveries AS due
WHERE
due.kind = 'notification'
AND due.status IN ('pending', 'waiting_quota', 'unknown')
AND due.next_attempt_at IS NOT NULL
AND due.next_attempt_at <= $3::timestamptz
AND (
(
due.provider = $4
AND due.provider_account = $5
)
OR (
due.provider = $6::text
AND due.attempt_count = 0
)
)
AND (
due.claim_owner IS NULL
OR due.claimed_until <= clock_timestamp()
)
ORDER BY due.next_attempt_at, due.id
LIMIT 1
FOR UPDATE SKIP LOCKED
)
UPDATE deliveries AS claimed
SET
claim_owner = $1::uuid,
claimed_until = clock_timestamp()
+ make_interval(secs => $2::float8)
FROM candidate
WHERE claimed.id = candidate.id
RETURNING
claimed.id,
claimed.source_event_id,
claimed.recipient_user_id,
claimed.recipient_email,
claimed.kind,
claimed.template_version,
claimed.subject,
claimed.text_body,
claimed.html_body,
claimed.content_sha256,
claimed.provider,
claimed.provider_account,
claimed.idempotency_key,
claimed.status,
claimed.attempt_count,
claimed.next_attempt_at,
claimed.last_attempt_at,
claimed.provider_message_id,
claimed.email_token_id,
claimed.cancel_reason,
claimed.body_redacted_at,
claimed.failure_count,
claimed.version,
claimed.created_at,
claimed.updated_at,
claimed.subject_kind,
claimed.subject_id,
claimed.subject_organization_id,
candidate.previous_claimed_until,
candidate.since_first_send_seconds,
candidate.manual_retry_pending,
candidate.manual_retry_cycle_started,
candidate.send_start_unsettled,
candidate.has_uncertain_attempt
`
type ClaimDueProductDeliveryParams struct {
LeaseOwner pgtype.UUID
LeaseSeconds float64
Now pgtype.Timestamptz
Provider string
ProviderAccount string
RebindProvider string
}
type ClaimDueProductDeliveryRow struct {
ID pgtype.UUID
SourceEventID pgtype.UUID
RecipientUserID pgtype.UUID
RecipientEmail string
Kind string
TemplateVersion string
Subject string
TextBody string
HtmlBody string
ContentSha256 []byte
Provider string
ProviderAccount string
IdempotencyKey string
Status string
AttemptCount int32
NextAttemptAt pgtype.Timestamptz
LastAttemptAt pgtype.Timestamptz
ProviderMessageID pgtype.Text
EmailTokenID pgtype.UUID
CancelReason pgtype.Text
BodyRedactedAt pgtype.Timestamptz
FailureCount int32
Version int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
SubjectKind pgtype.Text
SubjectID pgtype.UUID
SubjectOrganizationID pgtype.UUID
PreviousClaimedUntil pgtype.Timestamptz
SinceFirstSendSeconds float64
ManualRetryPending pgtype.Bool
ManualRetryCycleStarted bool
SendStartUnsettled bool
HasUncertainAttempt bool
}
// Claims the most overdue product notification, under the same rules as
// ClaimDueDelivery: a lease in the database clock, the configured provider
// account or a rebind of a delivery before its first attempt, and no live
// lease. It reads deliveries_product_due_idx, whose predicate repeats the
// literal kind below, so the backlog of service mail never enters the scan.
// A notification is claimed here whatever its subject; the sending worker
// checks the subject's rights after the claim and cancels a notice whose
// basis no longer holds.
func (q *Queries) ClaimDueProductDelivery(ctx context.Context, arg ClaimDueProductDeliveryParams) (ClaimDueProductDeliveryRow, error) {
row := q.db.QueryRow(ctx, claimDueProductDelivery,
arg.LeaseOwner,
arg.LeaseSeconds,
arg.Now,
arg.Provider,
arg.ProviderAccount,
arg.RebindProvider,
)
var i ClaimDueProductDeliveryRow
err := row.Scan(
&i.ID,
&i.SourceEventID,
&i.RecipientUserID,
&i.RecipientEmail,
&i.Kind,
&i.TemplateVersion,
&i.Subject,
&i.TextBody,
&i.HtmlBody,
&i.ContentSha256,
&i.Provider,
&i.ProviderAccount,
&i.IdempotencyKey,
&i.Status,
&i.AttemptCount,
&i.NextAttemptAt,
&i.LastAttemptAt,
&i.ProviderMessageID,
&i.EmailTokenID,
&i.CancelReason,
&i.BodyRedactedAt,
&i.FailureCount,
&i.Version,
&i.CreatedAt,
&i.UpdatedAt,
&i.SubjectKind,
&i.SubjectID,
&i.SubjectOrganizationID,
&i.PreviousClaimedUntil,
&i.SinceFirstSendSeconds,
&i.ManualRetryPending,
@@ -444,40 +647,46 @@ SELECT
claimed_until,
first_send_started_at,
failure_count,
body_redacted_at
body_redacted_at,
subject_kind,
subject_id,
subject_organization_id
FROM deliveries
WHERE id = $1
`
type GetDeliveryByIDRow struct {
ID pgtype.UUID
SourceEventID pgtype.UUID
RecipientUserID pgtype.UUID
RecipientEmail string
Kind string
TemplateVersion string
Subject string
TextBody string
HtmlBody string
ContentSha256 []byte
Provider string
ProviderAccount string
IdempotencyKey string
Status string
AttemptCount int32
NextAttemptAt pgtype.Timestamptz
LastAttemptAt pgtype.Timestamptz
ProviderMessageID pgtype.Text
Version int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
EmailTokenID pgtype.UUID
CancelReason pgtype.Text
ClaimOwner pgtype.UUID
ClaimedUntil pgtype.Timestamptz
FirstSendStartedAt pgtype.Timestamptz
FailureCount int32
BodyRedactedAt pgtype.Timestamptz
ID pgtype.UUID
SourceEventID pgtype.UUID
RecipientUserID pgtype.UUID
RecipientEmail string
Kind string
TemplateVersion string
Subject string
TextBody string
HtmlBody string
ContentSha256 []byte
Provider string
ProviderAccount string
IdempotencyKey string
Status string
AttemptCount int32
NextAttemptAt pgtype.Timestamptz
LastAttemptAt pgtype.Timestamptz
ProviderMessageID pgtype.Text
Version int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
EmailTokenID pgtype.UUID
CancelReason pgtype.Text
ClaimOwner pgtype.UUID
ClaimedUntil pgtype.Timestamptz
FirstSendStartedAt pgtype.Timestamptz
FailureCount int32
BodyRedactedAt pgtype.Timestamptz
SubjectKind pgtype.Text
SubjectID pgtype.UUID
SubjectOrganizationID pgtype.UUID
}
func (q *Queries) GetDeliveryByID(ctx context.Context, id pgtype.UUID) (GetDeliveryByIDRow, error) {
@@ -512,6 +721,9 @@ func (q *Queries) GetDeliveryByID(ctx context.Context, id pgtype.UUID) (GetDeliv
&i.FirstSendStartedAt,
&i.FailureCount,
&i.BodyRedactedAt,
&i.SubjectKind,
&i.SubjectID,
&i.SubjectOrganizationID,
)
return i, err
}
@@ -730,6 +942,9 @@ INSERT INTO deliveries (
last_attempt_at,
provider_message_id,
email_token_id,
subject_kind,
subject_id,
subject_organization_id,
version,
created_at,
updated_at
@@ -755,34 +970,40 @@ INSERT INTO deliveries (
$19,
$20,
$21,
$22
$22,
$23,
$24,
$25
)
ON CONFLICT (id) DO NOTHING
`
type InsertDeliveryParams struct {
ID pgtype.UUID
SourceEventID pgtype.UUID
RecipientUserID pgtype.UUID
RecipientEmail string
Kind string
TemplateVersion string
Subject string
TextBody string
HtmlBody string
ContentSha256 []byte
Provider string
ProviderAccount string
IdempotencyKey string
Status string
AttemptCount int32
NextAttemptAt pgtype.Timestamptz
LastAttemptAt pgtype.Timestamptz
ProviderMessageID pgtype.Text
EmailTokenID pgtype.UUID
Version int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
ID pgtype.UUID
SourceEventID pgtype.UUID
RecipientUserID pgtype.UUID
RecipientEmail string
Kind string
TemplateVersion string
Subject string
TextBody string
HtmlBody string
ContentSha256 []byte
Provider string
ProviderAccount string
IdempotencyKey string
Status string
AttemptCount int32
NextAttemptAt pgtype.Timestamptz
LastAttemptAt pgtype.Timestamptz
ProviderMessageID pgtype.Text
EmailTokenID pgtype.UUID
SubjectKind pgtype.Text
SubjectID pgtype.UUID
SubjectOrganizationID pgtype.UUID
Version int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
// Stores a new delivery. A delivery with the same ID already exists when the
@@ -811,6 +1032,9 @@ func (q *Queries) InsertDelivery(ctx context.Context, arg InsertDeliveryParams)
arg.LastAttemptAt,
arg.ProviderMessageID,
arg.EmailTokenID,
arg.SubjectKind,
arg.SubjectID,
arg.SubjectOrganizationID,
arg.Version,
arg.CreatedAt,
arg.UpdatedAt,
@@ -829,6 +1053,9 @@ INSERT INTO mail_requests (
subject,
body,
link_path,
subject_kind,
subject_id,
subject_organization_id,
created_at
) VALUES (
$1,
@@ -837,18 +1064,24 @@ INSERT INTO mail_requests (
$4,
$5,
$6,
$7
$7,
$8,
$9,
$10
)
`
type InsertMailRequestParams struct {
ID pgtype.UUID
RecipientUserID pgtype.UUID
Kind string
Subject string
Body string
LinkPath string
CreatedAt pgtype.Timestamptz
ID pgtype.UUID
RecipientUserID pgtype.UUID
Kind string
Subject string
Body string
LinkPath string
SubjectKind pgtype.Text
SubjectID pgtype.UUID
SubjectOrganizationID pgtype.UUID
CreatedAt pgtype.Timestamptz
}
func (q *Queries) InsertMailRequest(ctx context.Context, arg InsertMailRequestParams) error {
@@ -859,6 +1092,9 @@ func (q *Queries) InsertMailRequest(ctx context.Context, arg InsertMailRequestPa
arg.Subject,
arg.Body,
arg.LinkPath,
arg.SubjectKind,
arg.SubjectID,
arg.SubjectOrganizationID,
arg.CreatedAt,
)
return err
@@ -945,20 +1181,36 @@ SELECT
subject,
body,
link_path,
subject_kind,
subject_id,
subject_organization_id,
created_at
FROM mail_requests
WHERE id = $1
FOR UPDATE
`
type LockMailRequestRow struct {
ID pgtype.UUID
RecipientUserID pgtype.UUID
Kind string
Subject string
Body string
LinkPath string
SubjectKind pgtype.Text
SubjectID pgtype.UUID
SubjectOrganizationID pgtype.UUID
CreatedAt pgtype.Timestamptz
}
// Locks a request for the consumer transaction that turns it into a
// delivery. A concurrent consumer of the same request waits here and then
// finds the row deleted. The account cleanup and the cascade from users take
// the same row lock, so a request is never converted for an account whose
// deletion is in progress without one of the two transactions waiting.
func (q *Queries) LockMailRequest(ctx context.Context, id pgtype.UUID) (MailRequest, error) {
func (q *Queries) LockMailRequest(ctx context.Context, id pgtype.UUID) (LockMailRequestRow, error) {
row := q.db.QueryRow(ctx, lockMailRequest, id)
var i MailRequest
var i LockMailRequestRow
err := row.Scan(
&i.ID,
&i.RecipientUserID,
@@ -966,6 +1218,9 @@ func (q *Queries) LockMailRequest(ctx context.Context, id pgtype.UUID) (MailRequ
&i.Subject,
&i.Body,
&i.LinkPath,
&i.SubjectKind,
&i.SubjectID,
&i.SubjectOrganizationID,
&i.CreatedAt,
)
return i, err
@@ -1181,7 +1436,7 @@ SET
WHEN
$1::boolean
AND deliveries.failure_count + 1 >= $2::integer
AND deliveries.kind IN ('verification', 'password_reset')
AND deliveries.kind IN ('verification', 'password_reset', 'notification')
THEN ''
ELSE deliveries.text_body
END,
@@ -1189,7 +1444,7 @@ SET
WHEN
$1::boolean
AND deliveries.failure_count + 1 >= $2::integer
AND deliveries.kind IN ('verification', 'password_reset')
AND deliveries.kind IN ('verification', 'password_reset', 'notification')
THEN ''
ELSE deliveries.html_body
END,
@@ -1197,7 +1452,7 @@ SET
WHEN
$1::boolean
AND deliveries.failure_count + 1 >= $2::integer
AND deliveries.kind IN ('verification', 'password_reset')
AND deliveries.kind IN ('verification', 'password_reset', 'notification')
THEN greatest(deliveries.updated_at, $4::timestamptz)
ELSE deliveries.body_redacted_at
END,
@@ -1328,21 +1583,21 @@ SET
text_body = CASE
WHEN
$1::text = 'cancelled'
AND deliveries.kind IN ('verification', 'password_reset')
AND deliveries.kind IN ('verification', 'password_reset', 'notification')
THEN ''
ELSE deliveries.text_body
END,
html_body = CASE
WHEN
$1::text = 'cancelled'
AND deliveries.kind IN ('verification', 'password_reset')
AND deliveries.kind IN ('verification', 'password_reset', 'notification')
THEN ''
ELSE deliveries.html_body
END,
body_redacted_at = CASE
WHEN
$1::text = 'cancelled'
AND deliveries.kind IN ('verification', 'password_reset')
AND deliveries.kind IN ('verification', 'password_reset', 'notification')
THEN $7
ELSE deliveries.body_redacted_at
END,
@@ -532,6 +532,12 @@ type Delivery struct {
ManualRetryStartedAt pgtype.Timestamptz
// Attempt count when the latest provider call started. Equality with attempt_count means its result was not recorded; a greater attempt_count means a provider result was stored after that send-start.
SendStartedAttemptCount pgtype.Int4
// The kind of record a notification is about; set only for a notification, NULL when it names none. The product sending worker re-checks its rights before the send.
SubjectKind pgtype.Text
// The record a notification is about; an opaque ID, never an address or a contact.
SubjectID pgtype.UUID
// The organization the subject record belongs to.
SubjectOrganizationID pgtype.UUID
}
type DeliveryAttempt struct {
@@ -702,6 +708,12 @@ type MailRequest struct {
Body string
LinkPath string
CreatedAt pgtype.Timestamptz
// The kind of record the notification is about, NULL when it names none; the sending worker checks the rights of that kind.
SubjectKind pgtype.Text
// The record the notification is about, for example the invitation; an opaque ID, never an address or a contact.
SubjectID pgtype.UUID
// The organization the subject record belongs to, for example the organization that sent the invitation.
SubjectOrganizationID pgtype.UUID
}
type Membership struct {
@@ -0,0 +1,86 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: notification_rights.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const getInvitationNoticeStanding = `-- name: GetInvitationNoticeStanding :one
SELECT
(recipient.id IS NOT NULL)::boolean AS recipient_found,
coalesce(recipient.email_verified_at IS NOT NULL, false)::boolean AS recipient_email_verified,
coalesce(recipient.email_normalized, '')::text AS recipient_email_key,
(invitation.id IS NOT NULL)::boolean AS invitation_found,
invitation.organization_id AS invitation_organization_id,
coalesce(invitation.state, '')::text AS invitation_state,
invitation.response_deadline_at AS invitation_response_deadline_at,
EXISTS (
SELECT 1
FROM candidate_hidden_organizations AS hidden
WHERE
hidden.user_id = $1
AND hidden.organization_id = $2
)::boolean AS organization_hidden,
EXISTS (
SELECT 1
FROM candidate_effective_publications AS publication
WHERE publication.user_id = $1
)::boolean AS publication_published
FROM (SELECT $1::uuid AS user_id) AS target
LEFT JOIN users AS recipient
ON recipient.id = target.user_id
LEFT JOIN invitations AS invitation
ON invitation.id = $3
AND invitation.candidate_id = target.user_id
AND invitation.organization_id = $2
`
type GetInvitationNoticeStandingParams struct {
RecipientUserID pgtype.UUID
OrganizationID pgtype.UUID
InvitationID pgtype.UUID
}
type GetInvitationNoticeStandingRow struct {
RecipientFound bool
RecipientEmailVerified bool
RecipientEmailKey string
InvitationFound bool
InvitationOrganizationID pgtype.UUID
InvitationState string
InvitationResponseDeadlineAt pgtype.Timestamptz
OrganizationHidden bool
PublicationPublished bool
}
// Reads the standing of an invitation notice in one statement, for the rights
// check before the send. The recipient is matched by ID; the invitation must
// be addressed to that recipient and belong to the organization of the
// subject, otherwise it is not found. It reads no address and no contact:
// the recipient address is returned only as its comparison key. The hiding
// is the candidate's own current state. The publication is read through the
// effective view, so a publication whose C2 consent was revoked does not count
// as current. A missing account or invitation gives false flags and NULL
// columns.
func (q *Queries) GetInvitationNoticeStanding(ctx context.Context, arg GetInvitationNoticeStandingParams) (GetInvitationNoticeStandingRow, error) {
row := q.db.QueryRow(ctx, getInvitationNoticeStanding, arg.RecipientUserID, arg.OrganizationID, arg.InvitationID)
var i GetInvitationNoticeStandingRow
err := row.Scan(
&i.RecipientFound,
&i.RecipientEmailVerified,
&i.RecipientEmailKey,
&i.InvitationFound,
&i.InvitationOrganizationID,
&i.InvitationState,
&i.InvitationResponseDeadlineAt,
&i.OrganizationHidden,
&i.PublicationPublished,
)
return i, err
}
@@ -99,6 +99,15 @@ type Querier interface {
// now is the application clock. Unknown deliveries without a scheduled retry
// and quota waits with an unknown reset wait for an operator.
ClaimDueDelivery(ctx context.Context, arg ClaimDueDeliveryParams) (ClaimDueDeliveryRow, error)
// Claims the most overdue product notification, under the same rules as
// ClaimDueDelivery: a lease in the database clock, the configured provider
// account or a rebind of a delivery before its first attempt, and no live
// lease. It reads deliveries_product_due_idx, whose predicate repeats the
// literal kind below, so the backlog of service mail never enters the scan.
// A notification is claimed here whatever its subject; the sending worker
// checks the subject's rights after the claim and cancels a notice whose
// basis no longer holds.
ClaimDueProductDelivery(ctx context.Context, arg ClaimDueProductDeliveryParams) (ClaimDueProductDeliveryRow, error)
// Claims up to batch_limit jobs of the listed kinds in one statement: jobs
// whose available_at has passed, and running jobs whose lease expired
// because their worker stopped without finishing them. Rows that another
@@ -343,6 +352,16 @@ type Querier interface {
GetInvitationAcceptResult(ctx context.Context, scopeHash []byte) (GetInvitationAcceptResultRow, error)
GetInvitationCreationResult(ctx context.Context, scopeHash []byte) (string, error)
GetInvitationDeclineResult(ctx context.Context, scopeHash []byte) (GetInvitationDeclineResultRow, error)
// Reads the standing of an invitation notice in one statement, for the rights
// check before the send. The recipient is matched by ID; the invitation must
// be addressed to that recipient and belong to the organization of the
// subject, otherwise it is not found. It reads no address and no contact:
// the recipient address is returned only as its comparison key. The hiding
// is the candidate's own current state. The publication is read through the
// effective view, so a publication whose C2 consent was revoked does not count
// as current. A missing account or invitation gives false flags and NULL
// columns.
GetInvitationNoticeStanding(ctx context.Context, arg GetInvitationNoticeStandingParams) (GetInvitationNoticeStandingRow, error)
GetInvitationSendResult(ctx context.Context, scopeHash []byte) (GetInvitationSendResultRow, error)
// The caller holds the attempt row lock, so the last mark is stable.
GetLastAssessmentOriginMark(ctx context.Context, attemptID pgtype.UUID) (AssessmentAttemptOriginMark, error)
@@ -864,7 +883,7 @@ type Querier interface {
// finds the row deleted. The account cleanup and the cascade from users take
// the same row lock, so a request is never converted for an account whose
// deletion is in progress without one of the two transactions waiting.
LockMailRequest(ctx context.Context, id pgtype.UUID) (MailRequest, error)
LockMailRequest(ctx context.Context, id pgtype.UUID) (LockMailRequestRow, error)
// Locks the next relay batch. For each aggregate only its earliest unpublished
// event (lowest aggregate_version, then position) qualifies, so a relay never
// holds a later version while an earlier one is still pending, whether that