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,