feat(notifications): send product notifications with a rights check right before each send
This commit is contained in:
1 parent
a856066316
commit
623d41b969
59 files changed
+4125
-1126
No files matched your search
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -104,28 +105,31 @@ func (repository deliveryRepository) Create(ctx context.Context, delivery domain
|
||||
content := delivery.Content()
|
||||
hash := content.Hash()
|
||||
inserted, err := repository.queries.InsertDelivery(ctx, sqlc.InsertDeliveryParams{
|
||||
ID: pgUUID(delivery.ID()),
|
||||
SourceEventID: pgOptionalUUID(delivery.SourceEventID()),
|
||||
RecipientUserID: pgUUID(delivery.RecipientUserID()),
|
||||
RecipientEmail: delivery.Recipient().Address(),
|
||||
Kind: string(content.Kind()),
|
||||
TemplateVersion: content.TemplateVersion(),
|
||||
Subject: content.Subject(),
|
||||
TextBody: content.Text(),
|
||||
HtmlBody: content.HTML(),
|
||||
ContentSha256: hash[:],
|
||||
Provider: delivery.ProviderAccount().Provider(),
|
||||
ProviderAccount: delivery.ProviderAccount().Account(),
|
||||
IdempotencyKey: delivery.IdempotencyKey(),
|
||||
Status: string(delivery.Status()),
|
||||
AttemptCount: delivery.AttemptCount(),
|
||||
NextAttemptAt: pgZeroableTime(delivery.NextAttemptAt()),
|
||||
LastAttemptAt: pgZeroableTime(delivery.LastAttemptAt()),
|
||||
ProviderMessageID: pgOptionalText(delivery.ProviderMessageID()),
|
||||
EmailTokenID: pgOptionalUUID(delivery.EmailTokenID()),
|
||||
Version: delivery.Version(),
|
||||
CreatedAt: pgTime(delivery.CreatedAt()),
|
||||
UpdatedAt: pgTime(delivery.UpdatedAt()),
|
||||
ID: pgUUID(delivery.ID()),
|
||||
SourceEventID: pgOptionalUUID(delivery.SourceEventID()),
|
||||
RecipientUserID: pgUUID(delivery.RecipientUserID()),
|
||||
RecipientEmail: delivery.Recipient().Address(),
|
||||
Kind: string(content.Kind()),
|
||||
TemplateVersion: content.TemplateVersion(),
|
||||
Subject: content.Subject(),
|
||||
TextBody: content.Text(),
|
||||
HtmlBody: content.HTML(),
|
||||
ContentSha256: hash[:],
|
||||
Provider: delivery.ProviderAccount().Provider(),
|
||||
ProviderAccount: delivery.ProviderAccount().Account(),
|
||||
IdempotencyKey: delivery.IdempotencyKey(),
|
||||
Status: string(delivery.Status()),
|
||||
AttemptCount: delivery.AttemptCount(),
|
||||
NextAttemptAt: pgZeroableTime(delivery.NextAttemptAt()),
|
||||
LastAttemptAt: pgZeroableTime(delivery.LastAttemptAt()),
|
||||
ProviderMessageID: pgOptionalText(delivery.ProviderMessageID()),
|
||||
EmailTokenID: pgOptionalUUID(delivery.EmailTokenID()),
|
||||
SubjectKind: pgOptionalText(string(delivery.Subject().Kind())),
|
||||
SubjectID: pgOptionalUUID(delivery.Subject().ID()),
|
||||
SubjectOrganizationID: pgOptionalUUID(delivery.Subject().OrganizationID()),
|
||||
Version: delivery.Version(),
|
||||
CreatedAt: pgTime(delivery.CreatedAt()),
|
||||
UpdatedAt: pgTime(delivery.UpdatedAt()),
|
||||
})
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("deliveryRepository.Create - insert delivery: %w", mapDeliveryError(err))
|
||||
@@ -142,34 +146,37 @@ func (repository deliveryRepository) Get(ctx context.Context, id uuid.UUID) (dom
|
||||
return domain.Delivery{}, fmt.Errorf("deliveryRepository.Get - select delivery: %w", mapDeliveryError(err))
|
||||
}
|
||||
return deliveryFromRow(sqlc.Delivery{
|
||||
ID: row.ID,
|
||||
SourceEventID: row.SourceEventID,
|
||||
RecipientUserID: row.RecipientUserID,
|
||||
RecipientEmail: row.RecipientEmail,
|
||||
Kind: row.Kind,
|
||||
TemplateVersion: row.TemplateVersion,
|
||||
Subject: row.Subject,
|
||||
TextBody: row.TextBody,
|
||||
HtmlBody: row.HtmlBody,
|
||||
ContentSha256: row.ContentSha256,
|
||||
Provider: row.Provider,
|
||||
ProviderAccount: row.ProviderAccount,
|
||||
IdempotencyKey: row.IdempotencyKey,
|
||||
Status: row.Status,
|
||||
AttemptCount: row.AttemptCount,
|
||||
NextAttemptAt: row.NextAttemptAt,
|
||||
LastAttemptAt: row.LastAttemptAt,
|
||||
ProviderMessageID: row.ProviderMessageID,
|
||||
Version: row.Version,
|
||||
CreatedAt: row.CreatedAt,
|
||||
UpdatedAt: row.UpdatedAt,
|
||||
EmailTokenID: row.EmailTokenID,
|
||||
CancelReason: row.CancelReason,
|
||||
ClaimOwner: row.ClaimOwner,
|
||||
ClaimedUntil: row.ClaimedUntil,
|
||||
FirstSendStartedAt: row.FirstSendStartedAt,
|
||||
FailureCount: row.FailureCount,
|
||||
BodyRedactedAt: row.BodyRedactedAt,
|
||||
ID: row.ID,
|
||||
SourceEventID: row.SourceEventID,
|
||||
RecipientUserID: row.RecipientUserID,
|
||||
RecipientEmail: row.RecipientEmail,
|
||||
Kind: row.Kind,
|
||||
TemplateVersion: row.TemplateVersion,
|
||||
Subject: row.Subject,
|
||||
TextBody: row.TextBody,
|
||||
HtmlBody: row.HtmlBody,
|
||||
ContentSha256: row.ContentSha256,
|
||||
Provider: row.Provider,
|
||||
ProviderAccount: row.ProviderAccount,
|
||||
IdempotencyKey: row.IdempotencyKey,
|
||||
Status: row.Status,
|
||||
AttemptCount: row.AttemptCount,
|
||||
NextAttemptAt: row.NextAttemptAt,
|
||||
LastAttemptAt: row.LastAttemptAt,
|
||||
ProviderMessageID: row.ProviderMessageID,
|
||||
Version: row.Version,
|
||||
CreatedAt: row.CreatedAt,
|
||||
UpdatedAt: row.UpdatedAt,
|
||||
EmailTokenID: row.EmailTokenID,
|
||||
CancelReason: row.CancelReason,
|
||||
ClaimOwner: row.ClaimOwner,
|
||||
ClaimedUntil: row.ClaimedUntil,
|
||||
FirstSendStartedAt: row.FirstSendStartedAt,
|
||||
FailureCount: row.FailureCount,
|
||||
BodyRedactedAt: row.BodyRedactedAt,
|
||||
SubjectKind: row.SubjectKind,
|
||||
SubjectID: row.SubjectID,
|
||||
SubjectOrganizationID: row.SubjectOrganizationID,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -406,6 +413,52 @@ func (repository deliveryRepository) updateState(ctx context.Context, location s
|
||||
return nil
|
||||
}
|
||||
|
||||
// claimKindsBelongToScope reports that every kind is one the lane's claim
|
||||
// statement reads: the product statement has a literal notification predicate,
|
||||
// so it must not be asked for service mail, and the reverse.
|
||||
func claimKindsBelongToScope(scope outbound.ClaimScope, kinds []domain.MailKind) bool {
|
||||
allowed := domain.ServiceMailKinds()
|
||||
if scope == outbound.ClaimScopeNotification {
|
||||
allowed = domain.ProductMailKinds()
|
||||
}
|
||||
for _, kind := range kinds {
|
||||
if !slices.Contains(allowed, kind) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// claimRow runs the claim statement of the claim's lane. The product statement
|
||||
// returns the same columns in the same order, so its row converts to the row of
|
||||
// the service statement; the conversion does not compile if the columns drift.
|
||||
func (repository deliveryRepository) claimRow(ctx context.Context, claim outbound.DeliveryClaim, kinds []string) (sqlc.ClaimDueDeliveryRow, error) {
|
||||
switch claim.Scope {
|
||||
case outbound.ClaimScopeService:
|
||||
return repository.queries.ClaimDueDelivery(ctx, sqlc.ClaimDueDeliveryParams{
|
||||
LeaseOwner: pgUUID(claim.Owner),
|
||||
LeaseSeconds: claim.Lease.Seconds(),
|
||||
Kinds: kinds,
|
||||
Now: pgTime(claim.Now),
|
||||
Provider: claim.Account.Provider(),
|
||||
ProviderAccount: claim.Account.Account(),
|
||||
RebindProvider: claim.RebindProvider,
|
||||
})
|
||||
case outbound.ClaimScopeNotification:
|
||||
product, err := repository.queries.ClaimDueProductDelivery(ctx, sqlc.ClaimDueProductDeliveryParams{
|
||||
LeaseOwner: pgUUID(claim.Owner),
|
||||
LeaseSeconds: claim.Lease.Seconds(),
|
||||
Now: pgTime(claim.Now),
|
||||
Provider: claim.Account.Provider(),
|
||||
ProviderAccount: claim.Account.Account(),
|
||||
RebindProvider: claim.RebindProvider,
|
||||
})
|
||||
return sqlc.ClaimDueDeliveryRow(product), err
|
||||
default:
|
||||
return sqlc.ClaimDueDeliveryRow{}, fmt.Errorf("deliveryRepository.claimRow - unknown claim scope %d: %w", claim.Scope, domain.ErrInvalidDelivery)
|
||||
}
|
||||
}
|
||||
|
||||
func (repository deliveryRepository) ClaimDue(ctx context.Context, claim outbound.DeliveryClaim) (outbound.ClaimedDelivery, error) {
|
||||
const location = "deliveryRepository.ClaimDue"
|
||||
if claim.Owner == uuid.Nil || claim.Account.IsZero() || len(claim.Kinds) == 0 || claim.Now.IsZero() || claim.Lease <= 0 {
|
||||
@@ -418,15 +471,10 @@ func (repository deliveryRepository) ClaimDue(ctx context.Context, claim outboun
|
||||
}
|
||||
kinds = append(kinds, string(kind))
|
||||
}
|
||||
row, err := repository.queries.ClaimDueDelivery(ctx, sqlc.ClaimDueDeliveryParams{
|
||||
LeaseOwner: pgUUID(claim.Owner),
|
||||
LeaseSeconds: claim.Lease.Seconds(),
|
||||
Kinds: kinds,
|
||||
Now: pgTime(claim.Now),
|
||||
Provider: claim.Account.Provider(),
|
||||
ProviderAccount: claim.Account.Account(),
|
||||
RebindProvider: claim.RebindProvider,
|
||||
})
|
||||
if !claimKindsBelongToScope(claim.Scope, claim.Kinds) {
|
||||
return outbound.ClaimedDelivery{}, fmt.Errorf("%s - kinds do not belong to the claim scope: %w", location, domain.ErrInvalidDelivery)
|
||||
}
|
||||
row, err := repository.claimRow(ctx, claim, kinds)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return outbound.ClaimedDelivery{}, outbound.ErrNoDeliveryDue
|
||||
}
|
||||
@@ -434,30 +482,33 @@ func (repository deliveryRepository) ClaimDue(ctx context.Context, claim outboun
|
||||
return outbound.ClaimedDelivery{}, fmt.Errorf("%s - claim due delivery: %w", location, mapDeliveryError(err))
|
||||
}
|
||||
delivery, err := deliveryFromRow(sqlc.Delivery{
|
||||
ID: row.ID,
|
||||
SourceEventID: row.SourceEventID,
|
||||
RecipientUserID: row.RecipientUserID,
|
||||
RecipientEmail: row.RecipientEmail,
|
||||
Kind: row.Kind,
|
||||
TemplateVersion: row.TemplateVersion,
|
||||
Subject: row.Subject,
|
||||
TextBody: row.TextBody,
|
||||
HtmlBody: row.HtmlBody,
|
||||
ContentSha256: row.ContentSha256,
|
||||
Provider: row.Provider,
|
||||
ProviderAccount: row.ProviderAccount,
|
||||
IdempotencyKey: row.IdempotencyKey,
|
||||
Status: row.Status,
|
||||
AttemptCount: row.AttemptCount,
|
||||
NextAttemptAt: row.NextAttemptAt,
|
||||
LastAttemptAt: row.LastAttemptAt,
|
||||
ProviderMessageID: row.ProviderMessageID,
|
||||
EmailTokenID: row.EmailTokenID,
|
||||
CancelReason: row.CancelReason,
|
||||
BodyRedactedAt: row.BodyRedactedAt,
|
||||
Version: row.Version,
|
||||
CreatedAt: row.CreatedAt,
|
||||
UpdatedAt: row.UpdatedAt,
|
||||
ID: row.ID,
|
||||
SourceEventID: row.SourceEventID,
|
||||
RecipientUserID: row.RecipientUserID,
|
||||
RecipientEmail: row.RecipientEmail,
|
||||
Kind: row.Kind,
|
||||
TemplateVersion: row.TemplateVersion,
|
||||
Subject: row.Subject,
|
||||
TextBody: row.TextBody,
|
||||
HtmlBody: row.HtmlBody,
|
||||
ContentSha256: row.ContentSha256,
|
||||
Provider: row.Provider,
|
||||
ProviderAccount: row.ProviderAccount,
|
||||
IdempotencyKey: row.IdempotencyKey,
|
||||
Status: row.Status,
|
||||
AttemptCount: row.AttemptCount,
|
||||
NextAttemptAt: row.NextAttemptAt,
|
||||
LastAttemptAt: row.LastAttemptAt,
|
||||
ProviderMessageID: row.ProviderMessageID,
|
||||
EmailTokenID: row.EmailTokenID,
|
||||
CancelReason: row.CancelReason,
|
||||
BodyRedactedAt: row.BodyRedactedAt,
|
||||
Version: row.Version,
|
||||
CreatedAt: row.CreatedAt,
|
||||
UpdatedAt: row.UpdatedAt,
|
||||
SubjectKind: row.SubjectKind,
|
||||
SubjectID: row.SubjectID,
|
||||
SubjectOrganizationID: row.SubjectOrganizationID,
|
||||
})
|
||||
if err != nil {
|
||||
unreadable := &outbound.UnreadableDeliveryError{DeliveryID: uuid.UUID(row.ID.Bytes), FailureCount: row.FailureCount, Err: err}
|
||||
@@ -575,9 +626,12 @@ func deliveryFromRow(row sqlc.Delivery) (domain.Delivery, error) {
|
||||
return domain.Delivery{}, fmt.Errorf("postgres.deliveryFromRow - decode kind: %w", err)
|
||||
}
|
||||
var content domain.MailContent
|
||||
if row.BodyRedactedAt.Valid {
|
||||
switch {
|
||||
case row.BodyRedactedAt.Valid && kind == domain.MailKindNotification:
|
||||
content, err = domain.RestoreRedactedNotificationContent(row.TemplateVersion, row.Subject, row.ContentSha256)
|
||||
case row.BodyRedactedAt.Valid:
|
||||
content, err = domain.RestoreRedactedMailContent(kind, row.TemplateVersion, row.Subject, row.ContentSha256)
|
||||
} else {
|
||||
default:
|
||||
content, err = domain.RestoreMailContent(kind, row.TemplateVersion, row.Subject, row.TextBody, row.HtmlBody, row.ContentSha256)
|
||||
}
|
||||
if err != nil {
|
||||
@@ -587,12 +641,17 @@ func deliveryFromRow(row sqlc.Delivery) (domain.Delivery, error) {
|
||||
if err != nil {
|
||||
return domain.Delivery{}, fmt.Errorf("postgres.deliveryFromRow - decode provider account: %w", err)
|
||||
}
|
||||
subject, err := domain.RestoreMailSubject(row.SubjectKind.String, optionalUUID(row.SubjectID), optionalUUID(row.SubjectOrganizationID))
|
||||
if err != nil {
|
||||
return domain.Delivery{}, fmt.Errorf("postgres.deliveryFromRow - decode subject: %w", err)
|
||||
}
|
||||
delivery, err := domain.RestoreDelivery(domain.DeliverySnapshot{
|
||||
ID: uuid.UUID(row.ID.Bytes),
|
||||
SourceEventID: optionalUUID(row.SourceEventID),
|
||||
RecipientUserID: uuid.UUID(row.RecipientUserID.Bytes),
|
||||
RecipientAddress: row.RecipientEmail,
|
||||
Content: content,
|
||||
Subject: subject,
|
||||
ProviderAccount: providerAccount,
|
||||
IdempotencyKey: row.IdempotencyKey,
|
||||
Status: domain.DeliveryStatus(row.Status),
|
||||
@@ -654,13 +713,16 @@ func (repository mailRequestRepository) Create(ctx context.Context, request doma
|
||||
return fmt.Errorf("mailRequestRepository.Create - validate request: %w", err)
|
||||
}
|
||||
err := repository.queries.InsertMailRequest(ctx, sqlc.InsertMailRequestParams{
|
||||
ID: pgUUID(request.ID),
|
||||
RecipientUserID: pgUUID(request.RecipientUserID),
|
||||
Kind: string(request.Kind),
|
||||
Subject: request.Notification.Subject,
|
||||
Body: request.Notification.Body,
|
||||
LinkPath: request.Notification.LinkPath,
|
||||
CreatedAt: pgTime(request.CreatedAt),
|
||||
ID: pgUUID(request.ID),
|
||||
RecipientUserID: pgUUID(request.RecipientUserID),
|
||||
Kind: string(request.Kind),
|
||||
Subject: request.Notification.Subject,
|
||||
Body: request.Notification.Body,
|
||||
LinkPath: request.Notification.LinkPath,
|
||||
SubjectKind: pgOptionalText(string(request.Subject.Kind())),
|
||||
SubjectID: pgOptionalUUID(request.Subject.ID()),
|
||||
SubjectOrganizationID: pgOptionalUUID(request.Subject.OrganizationID()),
|
||||
CreatedAt: pgTime(request.CreatedAt),
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("mailRequestRepository.Create - insert mail request: %w", mapDeliveryError(err))
|
||||
@@ -680,11 +742,16 @@ func (repository mailRequestRepository) Lock(ctx context.Context, id uuid.UUID)
|
||||
if err != nil {
|
||||
return domain.MailRequest{}, fmt.Errorf("mailRequestRepository.Lock - decode kind: %w", err)
|
||||
}
|
||||
subject, err := domain.RestoreMailSubject(row.SubjectKind.String, optionalUUID(row.SubjectID), optionalUUID(row.SubjectOrganizationID))
|
||||
if err != nil {
|
||||
return domain.MailRequest{}, fmt.Errorf("mailRequestRepository.Lock - decode subject: %w", err)
|
||||
}
|
||||
request, err := domain.NewMailRequest(domain.MailRequest{
|
||||
ID: uuid.UUID(row.ID.Bytes),
|
||||
RecipientUserID: uuid.UUID(row.RecipientUserID.Bytes),
|
||||
Kind: kind,
|
||||
Notification: domain.NotificationText{Subject: row.Subject, Body: row.Body, LinkPath: row.LinkPath},
|
||||
Subject: subject,
|
||||
CreatedAt: row.CreatedAt.Time,
|
||||
})
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
// NotificationRights is available only inside a transaction: the rights check
|
||||
// reads the standing in the transaction that holds the delivery lock.
|
||||
func (unit *UnitOfWork) NotificationRights() outbound.NotificationRightsReader {
|
||||
return notificationRightsReader{queries: unit.queries}
|
||||
}
|
||||
|
||||
type notificationRightsReader struct {
|
||||
queries *sqlc.Queries
|
||||
}
|
||||
|
||||
var _ outbound.NotificationRightsReader = notificationRightsReader{}
|
||||
|
||||
func (reader notificationRightsReader) InvitationNoticeStanding(
|
||||
ctx context.Context,
|
||||
recipientUserID, invitationID, organizationID uuid.UUID,
|
||||
) (domain.InvitationNoticeStanding, error) {
|
||||
row, err := reader.queries.GetInvitationNoticeStanding(ctx, sqlc.GetInvitationNoticeStandingParams{
|
||||
RecipientUserID: pgUUID(recipientUserID),
|
||||
InvitationID: pgUUID(invitationID),
|
||||
OrganizationID: pgUUID(organizationID),
|
||||
})
|
||||
if err != nil {
|
||||
return domain.InvitationNoticeStanding{}, fmt.Errorf("notificationRightsReader.InvitationNoticeStanding - read standing: %w", mapDeliveryError(err))
|
||||
}
|
||||
return domain.InvitationNoticeStanding{
|
||||
RecipientFound: row.RecipientFound,
|
||||
RecipientEmailVerified: row.RecipientEmailVerified,
|
||||
RecipientEmailKey: row.RecipientEmailKey,
|
||||
InvitationFound: row.InvitationFound,
|
||||
InvitationOrganizationID: optionalUUID(row.InvitationOrganizationID),
|
||||
InvitationState: domain.InvitationState(row.InvitationState),
|
||||
ResponseDeadlineAt: zeroableTime(row.InvitationResponseDeadlineAt),
|
||||
OrganizationHidden: row.OrganizationHidden,
|
||||
PublicationPublished: row.PublicationPublished,
|
||||
}, nil
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -36,6 +36,10 @@ type mailMetrics struct {
|
||||
// per process, not database-wide, so dashboards and alerts aggregate it
|
||||
// with max across instances.
|
||||
senderRunning client.Gauge
|
||||
// notificationSenderRunning is 1 while this process's product notification
|
||||
// loop runs. It is separate from senderRunning, so the service loop's alert
|
||||
// keeps its meaning.
|
||||
notificationSenderRunning client.Gauge
|
||||
// senderCancelled counts deliveries that the sending worker ended without
|
||||
// sending, by cancel reason, a closed set from the domain.
|
||||
senderCancelled *client.CounterVec
|
||||
@@ -100,6 +104,10 @@ func newMailMetrics() mailMetrics {
|
||||
Name: "lincodex_mail_sender_running",
|
||||
Help: "1 while the mail sending loop of this process runs, 0 while it does not, for example with EMAIL_PROVIDER=disabled or after shutdown began.",
|
||||
}),
|
||||
notificationSenderRunning: client.NewGauge(client.GaugeOpts{
|
||||
Name: "lincodex_notification_sender_running",
|
||||
Help: "1 while the product notification sending loop of this process runs, 0 while it does not, for example with EMAIL_PROVIDER=disabled or after shutdown began.",
|
||||
}),
|
||||
}
|
||||
// Every reason exists at zero, so an alert on an increase sees the first
|
||||
// cancellation instead of a new series.
|
||||
@@ -132,7 +140,7 @@ func (mail mailMetrics) collectors() []client.Collector {
|
||||
return []client.Collector{
|
||||
mail.deliveries, mail.oldestDuePendingAge, mail.lastSuccess,
|
||||
mail.quotaUsed, mail.quotaLimit, mail.quotaProviderExhausted,
|
||||
mail.senderRunning, mail.senderCancelled, mail.identityRateLimited,
|
||||
mail.senderRunning, mail.notificationSenderRunning, mail.senderCancelled, mail.identityRateLimited,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -182,6 +190,16 @@ func (metrics *Metrics) SetMailSenderRunning(running bool) {
|
||||
metrics.mail.senderRunning.Set(value)
|
||||
}
|
||||
|
||||
// SetNotificationSenderRunning reports whether this process's product
|
||||
// notification loop runs: 1 from its start until its stop, 0 otherwise.
|
||||
func (metrics *Metrics) SetNotificationSenderRunning(running bool) {
|
||||
value := 0.0
|
||||
if running {
|
||||
value = 1
|
||||
}
|
||||
metrics.mail.notificationSenderRunning.Set(value)
|
||||
}
|
||||
|
||||
// PrepareMailMetricsReads exposes the last success time at 0 when the
|
||||
// sampler starts, so an alert sees a sampler that never reads successfully.
|
||||
func (metrics *Metrics) PrepareMailMetricsReads() {
|
||||
|
||||
@@ -18,6 +18,19 @@ func TestMetricsHandlerExposesWhetherTheMailSenderRuns(t *testing.T) {
|
||||
requireSeries(t, scrape(t, metrics), "lincodex_mail_sender_running 0")
|
||||
}
|
||||
|
||||
func TestMetricsHandlerExposesWhetherTheNotificationSenderRuns(t *testing.T) {
|
||||
metrics := New()
|
||||
// The product loop has its own series, so the service loop's gauge keeps
|
||||
// its meaning when only the product loop runs.
|
||||
requireSeries(t, scrape(t, metrics), "lincodex_notification_sender_running 0")
|
||||
|
||||
metrics.SetNotificationSenderRunning(true)
|
||||
requireSeries(t, scrape(t, metrics), "lincodex_notification_sender_running 1", "lincodex_mail_sender_running 0")
|
||||
|
||||
metrics.SetNotificationSenderRunning(false)
|
||||
requireSeries(t, scrape(t, metrics), "lincodex_notification_sender_running 0")
|
||||
}
|
||||
|
||||
func TestMetricsHandlerCountsCancelledMailByABoundedReason(t *testing.T) {
|
||||
metrics := New()
|
||||
// Every reason exists at zero before the first cancellation.
|
||||
@@ -26,6 +39,9 @@ func TestMetricsHandlerCountsCancelledMailByABoundedReason(t *testing.T) {
|
||||
`lincodex_mail_sender_cancelled_total{reason="content_invalid"} 0`,
|
||||
`lincodex_mail_sender_cancelled_total{reason="processing_failed"} 0`,
|
||||
`lincodex_mail_sender_cancelled_total{reason="token_revoked"} 0`,
|
||||
`lincodex_mail_sender_cancelled_total{reason="rights_revoked"} 0`,
|
||||
`lincodex_mail_sender_cancelled_total{reason="recipient_ineligible"} 0`,
|
||||
`lincodex_mail_sender_cancelled_total{reason="source_closed"} 0`,
|
||||
)
|
||||
metrics.ObserveMailCancelled("content_invalid")
|
||||
metrics.ObserveMailCancelled("content_invalid")
|
||||
|
||||
Reference in new issue
Block a user