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
@@ -170,6 +170,19 @@ const (
|
||||
// again and again for a reason of its own, so it stopped trying and left
|
||||
// the row to an operator.
|
||||
DeliveryCancelProcessingFailed DeliveryCancelReason = "processing_failed"
|
||||
// DeliveryCancelRightsRevoked: a notification's basis no longer holds
|
||||
// when it is about to be sent. The organization is hidden from the
|
||||
// candidate, the candidate withdrew publication (C2), or the invitation
|
||||
// was answered, expired, or passed its deadline (see
|
||||
// Delivery.CheckInvitationNotice).
|
||||
DeliveryCancelRightsRevoked DeliveryCancelReason = "rights_revoked"
|
||||
// DeliveryCancelRecipientIneligible: the recipient account is gone or its
|
||||
// address is not verified, so a notification may not go to it.
|
||||
DeliveryCancelRecipientIneligible DeliveryCancelReason = "recipient_ineligible"
|
||||
// DeliveryCancelSourceClosed: the record a notification is about does not
|
||||
// exist, belongs to another organization, or the notification names no
|
||||
// record at all, so there is no right to check.
|
||||
DeliveryCancelSourceClosed DeliveryCancelReason = "source_closed"
|
||||
)
|
||||
|
||||
// DeliveryCancelReasons lists every cancel reason, for metrics that expose
|
||||
@@ -179,7 +192,8 @@ func DeliveryCancelReasons() []DeliveryCancelReason {
|
||||
DeliveryCancelTokenMissing, DeliveryCancelTokenPurposeMismatch, DeliveryCancelTokenOwnerMismatch,
|
||||
DeliveryCancelTokenConsumed, DeliveryCancelTokenRevoked, DeliveryCancelTokenExpired,
|
||||
DeliveryCancelAccountNotCurrent, DeliveryCancelRecipientMismatch, DeliveryCancelContentInvalid,
|
||||
DeliveryCancelProcessingFailed,
|
||||
DeliveryCancelProcessingFailed, DeliveryCancelRightsRevoked, DeliveryCancelRecipientIneligible,
|
||||
DeliveryCancelSourceClosed,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -189,7 +203,8 @@ func ParseDeliveryCancelReason(value string) (DeliveryCancelReason, error) {
|
||||
case DeliveryCancelTokenMissing, DeliveryCancelTokenPurposeMismatch, DeliveryCancelTokenOwnerMismatch,
|
||||
DeliveryCancelTokenConsumed, DeliveryCancelTokenRevoked, DeliveryCancelTokenExpired,
|
||||
DeliveryCancelAccountNotCurrent, DeliveryCancelRecipientMismatch, DeliveryCancelContentInvalid,
|
||||
DeliveryCancelProcessingFailed:
|
||||
DeliveryCancelProcessingFailed, DeliveryCancelRightsRevoked, DeliveryCancelRecipientIneligible,
|
||||
DeliveryCancelSourceClosed:
|
||||
return reason, nil
|
||||
default:
|
||||
return "", invalidDelivery("domain.ParseDeliveryCancelReason", "unknown cancel reason")
|
||||
@@ -239,6 +254,7 @@ type Delivery struct {
|
||||
recipientUserID uuid.UUID
|
||||
recipient EmailAddress
|
||||
content MailContent
|
||||
subject MailSubject
|
||||
providerAccount MailProviderAccount
|
||||
idempotencyKey string
|
||||
status DeliveryStatus
|
||||
@@ -271,7 +287,11 @@ type NewDeliveryInput struct {
|
||||
// the worker with the reason token_missing. It must be uuid.Nil for a
|
||||
// notification.
|
||||
EmailTokenID uuid.UUID
|
||||
CreatedAt time.Time
|
||||
// Subject names the record a notification is about; the sending worker
|
||||
// checks its rights before the send. Only a notification may name one, and
|
||||
// the zero value names none.
|
||||
Subject MailSubject
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
// NewDelivery validates input and returns a pending delivery that is due at
|
||||
@@ -293,6 +313,8 @@ func NewDelivery(input NewDeliveryInput) (Delivery, error) {
|
||||
return Delivery{}, invalidDelivery(location, "creation time must be set")
|
||||
case input.EmailTokenID != uuid.Nil && !input.Content.Kind().CarriesBearerToken():
|
||||
return Delivery{}, invalidDelivery(location, "only a delivery of a token kind is bound to a token")
|
||||
case !input.Subject.IsZero() && input.Content.Kind() != MailKindNotification:
|
||||
return Delivery{}, invalidDelivery(location, "only a notification names a subject")
|
||||
}
|
||||
return Delivery{
|
||||
id: input.ID,
|
||||
@@ -300,6 +322,7 @@ func NewDelivery(input NewDeliveryInput) (Delivery, error) {
|
||||
recipientUserID: input.RecipientUserID,
|
||||
recipient: input.Recipient,
|
||||
content: input.Content,
|
||||
subject: input.Subject,
|
||||
providerAccount: input.ProviderAccount,
|
||||
emailTokenID: input.EmailTokenID,
|
||||
idempotencyKey: deliveryIdempotencyKeyPrefix + input.ID.String(),
|
||||
@@ -329,9 +352,11 @@ type DeliverySnapshot struct {
|
||||
EmailTokenID uuid.UUID
|
||||
// CancelReason is set exactly for a cancelled delivery.
|
||||
CancelReason DeliveryCancelReason
|
||||
Version int64
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
// Subject is the zero value for a delivery without a subject.
|
||||
Subject MailSubject
|
||||
Version int64
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
// RestoreDelivery rebuilds a stored delivery and checks the invariants that
|
||||
@@ -362,6 +387,7 @@ func RestoreDelivery(snapshot DeliverySnapshot) (Delivery, error) {
|
||||
recipientUserID: snapshot.RecipientUserID,
|
||||
recipient: recipient,
|
||||
content: snapshot.Content,
|
||||
subject: snapshot.Subject,
|
||||
providerAccount: snapshot.ProviderAccount,
|
||||
idempotencyKey: snapshot.IdempotencyKey,
|
||||
status: snapshot.Status,
|
||||
@@ -408,6 +434,8 @@ func checkCancellationAndBinding(location string, snapshot DeliverySnapshot) err
|
||||
return invalidDelivery(location, "cancel reason must be set exactly for a cancelled delivery")
|
||||
case snapshot.EmailTokenID != uuid.Nil && !snapshot.Content.Kind().CarriesBearerToken():
|
||||
return invalidDelivery(location, "only a delivery of a token kind is bound to a token")
|
||||
case !snapshot.Subject.IsZero() && snapshot.Content.Kind() != MailKindNotification:
|
||||
return invalidDelivery(location, "only a notification names a subject")
|
||||
}
|
||||
if snapshot.CancelReason != "" {
|
||||
if _, err := ParseDeliveryCancelReason(string(snapshot.CancelReason)); err != nil {
|
||||
@@ -440,6 +468,9 @@ func (delivery Delivery) RecipientUserID() uuid.UUID { return delivery.recipient
|
||||
// only to send the message; never log it.
|
||||
func (delivery Delivery) Recipient() EmailAddress { return delivery.recipient }
|
||||
|
||||
// Subject is the record a notification is about; zero for other deliveries.
|
||||
func (delivery Delivery) Subject() MailSubject { return delivery.subject }
|
||||
|
||||
func (delivery Delivery) Kind() MailKind { return delivery.content.Kind() }
|
||||
|
||||
func (delivery Delivery) Content() MailContent { return delivery.content }
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// InvitationNoticeStanding is what the rights check of an invitation notice
|
||||
// reads about its recipient and its source at the time of the send. It holds
|
||||
// no address and no contact: the recipient address enters only as the
|
||||
// normalized key that the delivery is compared with.
|
||||
type InvitationNoticeStanding struct {
|
||||
RecipientFound bool
|
||||
RecipientEmailVerified bool
|
||||
// RecipientEmailKey is the normalized address of the account now.
|
||||
RecipientEmailKey string
|
||||
InvitationFound bool
|
||||
InvitationOrganizationID uuid.UUID
|
||||
InvitationState InvitationState
|
||||
// ResponseDeadlineAt is zero when the invitation was never delivered.
|
||||
ResponseDeadlineAt time.Time
|
||||
// OrganizationHidden reports that the recipient hid the sending
|
||||
// organization.
|
||||
OrganizationHidden bool
|
||||
// PublicationPublished reports that the recipient's publication (C2) is
|
||||
// current, which is the state an invitation was sent under.
|
||||
PublicationPublished bool
|
||||
}
|
||||
|
||||
// CheckInvitationNotice decides whether the notice about an invitation may still
|
||||
// be sent at the given time, and returns the cancel reason when it may not. An
|
||||
// empty reason means that the notice is sendable. The checks run in this order
|
||||
// and the first failure decides:
|
||||
//
|
||||
// 1. the delivery names an invitation subject;
|
||||
// 2. the recipient account exists and its address is verified;
|
||||
// 3. the address of the delivery is still the address of the account;
|
||||
// 4. the invitation exists and belongs to the organization of the subject;
|
||||
// 5. the invitation still awaits an answer (delivered or viewed) and its
|
||||
// response deadline has not passed;
|
||||
// 6. the recipient has not hidden the sending organization, and the
|
||||
// recipient's publication (C2) is current.
|
||||
//
|
||||
// The notice declares no allowed fields. Its body is fixed text that names
|
||||
// neither the organization nor the terms, and it carries no contact, so no
|
||||
// field consent (C4) applies. A future notice that carries any candidate field
|
||||
// or contact must add that field's consent check here, and must not put a
|
||||
// contact into the mail at all: contacts are read on request, and every read
|
||||
// re-checks the grant.
|
||||
//
|
||||
// The check is a snapshot taken in the sending transaction. A change after it
|
||||
// and before the provider call still lets the notice go, which is the same
|
||||
// rule as for service mail.
|
||||
func (delivery Delivery) CheckInvitationNotice(standing InvitationNoticeStanding, at time.Time) DeliveryCancelReason {
|
||||
subject := delivery.Subject()
|
||||
awaitsAnswer := standing.InvitationState == InvitationDelivered || standing.InvitationState == InvitationViewed
|
||||
switch {
|
||||
case subject.Kind() != MailSubjectInvitation:
|
||||
return DeliveryCancelSourceClosed
|
||||
case !standing.RecipientFound || !standing.RecipientEmailVerified:
|
||||
return DeliveryCancelRecipientIneligible
|
||||
case standing.RecipientEmailKey != delivery.Recipient().Normalized():
|
||||
return DeliveryCancelRecipientMismatch
|
||||
case !standing.InvitationFound || standing.InvitationOrganizationID != subject.OrganizationID():
|
||||
return DeliveryCancelSourceClosed
|
||||
case !awaitsAnswer || !at.Before(standing.ResponseDeadlineAt):
|
||||
return DeliveryCancelRightsRevoked
|
||||
case standing.OrganizationHidden || !standing.PublicationPublished:
|
||||
return DeliveryCancelRightsRevoked
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
var (
|
||||
testInvitationID = uuid.MustParse("01926f3a-7c00-7000-8000-0000000000c1")
|
||||
testSenderOrganizationID = uuid.MustParse("01926f3a-7c00-7000-8000-0000000000c3")
|
||||
)
|
||||
|
||||
// newInvitationNotice is a notification to the test recipient that names an
|
||||
// invitation of the test organization.
|
||||
func newInvitationNotice(t *testing.T) Delivery {
|
||||
t.Helper()
|
||||
content, err := NewMailContent(MailKindNotification, "notification.v1", "Новое приглашение от работодателя", "Работодатель отправил вам приглашение\n", "")
|
||||
if err != nil {
|
||||
t.Fatalf("NewMailContent() error = %v", err)
|
||||
}
|
||||
subject, err := NewInvitationMailSubject(testInvitationID, testSenderOrganizationID)
|
||||
if err != nil {
|
||||
t.Fatalf("NewInvitationMailSubject() error = %v", err)
|
||||
}
|
||||
input := testDeliveryInput(t)
|
||||
input.Content = content
|
||||
input.Subject = subject
|
||||
delivery, err := NewDelivery(input)
|
||||
if err != nil {
|
||||
t.Fatalf("NewDelivery() error = %v", err)
|
||||
}
|
||||
return delivery
|
||||
}
|
||||
|
||||
// currentInvitationStanding is the standing of a notice that may be sent: the
|
||||
// address is verified and unchanged, the invitation awaits an answer before its
|
||||
// deadline, and the candidate neither hid the organization nor withdrew
|
||||
// publication.
|
||||
func currentInvitationStanding(delivery Delivery) InvitationNoticeStanding {
|
||||
return InvitationNoticeStanding{
|
||||
RecipientFound: true,
|
||||
RecipientEmailVerified: true,
|
||||
RecipientEmailKey: delivery.Recipient().Normalized(),
|
||||
InvitationFound: true,
|
||||
InvitationOrganizationID: testSenderOrganizationID,
|
||||
InvitationState: InvitationDelivered,
|
||||
ResponseDeadlineAt: after(7 * 24 * 60),
|
||||
PublicationPublished: true,
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckInvitationNoticeAllowsAnInvitationThatStillAwaitsAnswer(t *testing.T) {
|
||||
delivery := newInvitationNotice(t)
|
||||
for _, state := range []InvitationState{InvitationDelivered, InvitationViewed} {
|
||||
standing := currentInvitationStanding(delivery)
|
||||
standing.InvitationState = state
|
||||
if reason := delivery.CheckInvitationNotice(standing, after(1)); reason != "" {
|
||||
t.Fatalf("CheckInvitationNotice(%s) = %q for an open invitation, want it sendable", state, reason)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The first failed rule decides, so each row changes one fact from the current
|
||||
// standing and names the reason that fact must give.
|
||||
func TestCheckInvitationNoticeNamesTheReasonOfTheFirstFailedRule(t *testing.T) {
|
||||
delivery := newInvitationNotice(t)
|
||||
deadline := currentInvitationStanding(delivery).ResponseDeadlineAt
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
change func(*InvitationNoticeStanding)
|
||||
at int
|
||||
want DeliveryCancelReason
|
||||
}{
|
||||
{"the account is gone", func(s *InvitationNoticeStanding) { s.RecipientFound = false }, 1, DeliveryCancelRecipientIneligible},
|
||||
{"the address is not verified", func(s *InvitationNoticeStanding) { s.RecipientEmailVerified = false }, 1, DeliveryCancelRecipientIneligible},
|
||||
{"the address changed", func(s *InvitationNoticeStanding) { s.RecipientEmailKey = "other@example.com" }, 1, DeliveryCancelRecipientMismatch},
|
||||
{"the invitation is gone", func(s *InvitationNoticeStanding) { s.InvitationFound = false }, 1, DeliveryCancelSourceClosed},
|
||||
{"the invitation belongs to another organization", func(s *InvitationNoticeStanding) {
|
||||
s.InvitationOrganizationID = uuid.MustParse("01926f3a-7c00-7000-8000-0000000000c9")
|
||||
}, 1, DeliveryCancelSourceClosed},
|
||||
{"the candidate declined", func(s *InvitationNoticeStanding) { s.InvitationState = InvitationDeclined }, 1, DeliveryCancelRightsRevoked},
|
||||
{"the candidate accepted", func(s *InvitationNoticeStanding) { s.InvitationState = InvitationAccepted }, 1, DeliveryCancelRightsRevoked},
|
||||
{"the invitation expired", func(s *InvitationNoticeStanding) { s.InvitationState = InvitationExpired }, 1, DeliveryCancelRightsRevoked},
|
||||
{"the deadline has passed", func(*InvitationNoticeStanding) {}, 7*24*60 + 1, DeliveryCancelRightsRevoked},
|
||||
{"the deadline is reached", func(*InvitationNoticeStanding) {}, 7 * 24 * 60, DeliveryCancelRightsRevoked},
|
||||
{"the invitation was never delivered", func(s *InvitationNoticeStanding) {
|
||||
s.ResponseDeadlineAt = deadline
|
||||
s.InvitationState = InvitationDraft
|
||||
}, 1, DeliveryCancelRightsRevoked},
|
||||
{"the candidate hid the organization", func(s *InvitationNoticeStanding) { s.OrganizationHidden = true }, 1, DeliveryCancelRightsRevoked},
|
||||
{"the candidate withdrew publication", func(s *InvitationNoticeStanding) { s.PublicationPublished = false }, 1, DeliveryCancelRightsRevoked},
|
||||
{"an unverified address outranks a hidden organization", func(s *InvitationNoticeStanding) {
|
||||
s.RecipientEmailVerified = false
|
||||
s.OrganizationHidden = true
|
||||
}, 1, DeliveryCancelRecipientIneligible},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
standing := currentInvitationStanding(delivery)
|
||||
test.change(&standing)
|
||||
if got := delivery.CheckInvitationNotice(standing, after(test.at)); got != test.want {
|
||||
t.Fatalf("CheckInvitationNotice() = %q, want %q", got, test.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckInvitationNoticeRefusesAMailThatNamesNoInvitation(t *testing.T) {
|
||||
content, err := NewMailContent(MailKindNotification, "notification.v1", "Уведомление", "Текст\n", "")
|
||||
if err != nil {
|
||||
t.Fatalf("NewMailContent() error = %v", err)
|
||||
}
|
||||
input := testDeliveryInput(t)
|
||||
input.Content = content
|
||||
delivery, err := NewDelivery(input)
|
||||
if err != nil {
|
||||
t.Fatalf("NewDelivery() error = %v", err)
|
||||
}
|
||||
if reason := delivery.CheckInvitationNotice(currentInvitationStanding(delivery), after(1)); reason != DeliveryCancelSourceClosed {
|
||||
t.Fatalf("CheckInvitationNotice() = %q for a notice without a subject, want source_closed", reason)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewMailSubjectNamesOnlyKnownRecords(t *testing.T) {
|
||||
if _, err := NewInvitationMailSubject(uuid.Nil, testSenderOrganizationID); !errors.Is(err, ErrInvalidMailSubject) {
|
||||
t.Fatalf("NewInvitationMailSubject(nil invitation) error = %v, want ErrInvalidMailSubject", err)
|
||||
}
|
||||
if _, err := NewInvitationMailSubject(testInvitationID, uuid.Nil); !errors.Is(err, ErrInvalidMailSubject) {
|
||||
t.Fatalf("NewInvitationMailSubject(nil organization) error = %v, want ErrInvalidMailSubject", err)
|
||||
}
|
||||
if subject, err := RestoreMailSubject("", uuid.Nil, uuid.Nil); err != nil || !subject.IsZero() {
|
||||
t.Fatalf("RestoreMailSubject(empty) = %v, %v; want the zero subject", subject, err)
|
||||
}
|
||||
if _, err := RestoreMailSubject("contract", testInvitationID, testSenderOrganizationID); !errors.Is(err, ErrInvalidMailSubject) {
|
||||
t.Fatalf("RestoreMailSubject(unknown kind) error = %v, want ErrInvalidMailSubject", err)
|
||||
}
|
||||
subject, err := NewInvitationMailSubject(testInvitationID, testSenderOrganizationID)
|
||||
if err != nil {
|
||||
t.Fatalf("NewInvitationMailSubject() error = %v", err)
|
||||
}
|
||||
if text := subject.String(); text != "[mail subject invitation]" {
|
||||
t.Fatalf("String() = %q; the identifiers must stay out of printed values", text)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOnlyANotificationNamesASubject(t *testing.T) {
|
||||
subject, err := NewInvitationMailSubject(testInvitationID, testSenderOrganizationID)
|
||||
if err != nil {
|
||||
t.Fatalf("NewInvitationMailSubject() error = %v", err)
|
||||
}
|
||||
input := testDeliveryInput(t)
|
||||
input.Subject = subject
|
||||
if _, err := NewDelivery(input); !errors.Is(err, ErrInvalidDelivery) {
|
||||
t.Fatalf("NewDelivery(verification with subject) error = %v, want ErrInvalidDelivery", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRightsCancelReasonsAreKnownAndExposed(t *testing.T) {
|
||||
for _, value := range []string{"rights_revoked", "recipient_ineligible", "source_closed"} {
|
||||
reason, err := ParseDeliveryCancelReason(value)
|
||||
if err != nil {
|
||||
t.Fatalf("ParseDeliveryCancelReason(%q) error = %v", value, err)
|
||||
}
|
||||
listed := false
|
||||
for _, known := range DeliveryCancelReasons() {
|
||||
listed = listed || known == reason
|
||||
}
|
||||
if !listed {
|
||||
t.Fatalf("%q is parsed but missing from DeliveryCancelReasons, so its metric series would not exist at zero", value)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -58,14 +58,20 @@ func ParseMailKind(value string) (MailKind, error) {
|
||||
}
|
||||
|
||||
// ServiceMailKinds lists the kinds of service identity mail, the kinds the
|
||||
// sending worker claims and sends. Notifications are not among them until
|
||||
// their sending is connected. The delivery metrics of due mail,
|
||||
// the sending worker, and the due index of the deliveries table follow this
|
||||
// list; changing it changes the predicate of deliveries_due_idx too.
|
||||
// service sending worker claims and sends. The delivery metrics of due mail
|
||||
// and the due index of the deliveries table follow this list; changing it
|
||||
// changes the predicate of deliveries_due_idx too.
|
||||
func ServiceMailKinds() []MailKind {
|
||||
return []MailKind{MailKindVerification, MailKindPasswordReset}
|
||||
}
|
||||
|
||||
// ProductMailKinds lists the kinds of product notifications, the kinds the
|
||||
// notification sending worker claims. Its claim has its own partial index,
|
||||
// deliveries_product_due_idx, which follows this list.
|
||||
func ProductMailKinds() []MailKind {
|
||||
return []MailKind{MailKindNotification}
|
||||
}
|
||||
|
||||
// IsServiceMail reports a kind of service identity mail.
|
||||
func (kind MailKind) IsServiceMail() bool { return kind.CarriesBearerToken() }
|
||||
|
||||
@@ -173,6 +179,17 @@ func RestoreRedactedMailContent(kind MailKind, templateVersion, subject string,
|
||||
if _, err := ParseMailKind(string(kind)); err != nil || !kind.CarriesBearerToken() {
|
||||
return MailContent{}, invalidMailContent("only a token mail has redacted content")
|
||||
}
|
||||
return restoreRedactedContent(location, kind, templateVersion, subject, hash)
|
||||
}
|
||||
|
||||
// RestoreRedactedNotificationContent rebuilds the content of a notification
|
||||
// whose bodies were cleared when it was cancelled. Like a redacted token mail,
|
||||
// it keeps the subject and the hash and can never be sent.
|
||||
func RestoreRedactedNotificationContent(templateVersion, subject string, hash []byte) (MailContent, error) {
|
||||
return restoreRedactedContent("domain.RestoreRedactedNotificationContent", MailKindNotification, templateVersion, subject, hash)
|
||||
}
|
||||
|
||||
func restoreRedactedContent(location string, kind MailKind, templateVersion, subject string, hash []byte) (MailContent, error) {
|
||||
if !mailTemplateVersionPattern.MatchString(templateVersion) || !strings.HasPrefix(templateVersion, string(kind)+".v") ||
|
||||
strings.TrimSpace(subject) == "" || utf8.RuneCountInString(subject) > maxMailSubjectRunes {
|
||||
return MailContent{}, fmt.Errorf("%s - stored version or subject is invalid: %w", location, ErrInvalidMailContent)
|
||||
|
||||
@@ -44,6 +44,22 @@ func NewMailQuotaLimits(daily, monthly int64) (MailQuotaLimits, error) {
|
||||
|
||||
func (limits MailQuotaLimits) IsZero() bool { return limits.daily == 0 }
|
||||
|
||||
// WithReserve returns the limits that a sender may use when daily and monthly
|
||||
// recipients stay free for other mail. Each window keeps its own reserve, so
|
||||
// the result is checked window by window; it may not keep the rule that the
|
||||
// daily limit does not exceed the monthly one, which the configuration keeps.
|
||||
// A reserve must be zero or more and leave at least one recipient per window.
|
||||
func (limits MailQuotaLimits) WithReserve(daily, monthly int64) (MailQuotaLimits, error) {
|
||||
const location = "domain.MailQuotaLimits.WithReserve"
|
||||
switch {
|
||||
case daily < 0 || monthly < 0:
|
||||
return MailQuotaLimits{}, fmt.Errorf("%s - reserves must not be negative: %w", location, ErrInvalidMailQuota)
|
||||
case daily >= limits.daily || monthly >= limits.monthly:
|
||||
return MailQuotaLimits{}, fmt.Errorf("%s - a reserve must leave room in its window: %w", location, ErrInvalidMailQuota)
|
||||
}
|
||||
return MailQuotaLimits{daily: limits.daily - daily, monthly: limits.monthly - monthly}, nil
|
||||
}
|
||||
|
||||
func (limits MailQuotaLimits) Daily() int64 { return limits.daily }
|
||||
|
||||
func (limits MailQuotaLimits) Monthly() int64 { return limits.monthly }
|
||||
|
||||
@@ -118,3 +118,36 @@ func TestNewMailQuotaLimits(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestWithReserveLeavesEachWindowItsOwnShare(t *testing.T) {
|
||||
limits, err := NewMailQuotaLimits(100, 3000)
|
||||
if err != nil {
|
||||
t.Fatalf("NewMailQuotaLimits() error = %v", err)
|
||||
}
|
||||
admission, err := limits.WithReserve(20, 600)
|
||||
if err != nil {
|
||||
t.Fatalf("WithReserve(20, 600) error = %v", err)
|
||||
}
|
||||
if admission.Daily() != 80 || admission.Monthly() != 2400 {
|
||||
t.Fatalf("admission = %d a day and %d a month, want 80 and 2400", admission.Daily(), admission.Monthly())
|
||||
}
|
||||
if unchanged, err := limits.WithReserve(0, 0); err != nil || unchanged.Daily() != 100 || unchanged.Monthly() != 3000 {
|
||||
t.Fatalf("WithReserve(0, 0) = %+v, %v; want the limits unchanged", unchanged, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWithReserveRefusesAReserveThatLeavesNoRoom(t *testing.T) {
|
||||
limits, err := NewMailQuotaLimits(100, 3000)
|
||||
if err != nil {
|
||||
t.Fatalf("NewMailQuotaLimits() error = %v", err)
|
||||
}
|
||||
for name, reserve := range map[string][2]int64{
|
||||
"a daily reserve equal to the limit": {100, 0},
|
||||
"a monthly reserve above the limit": {0, 3001},
|
||||
"a negative reserve": {-1, 0},
|
||||
} {
|
||||
if _, err := limits.WithReserve(reserve[0], reserve[1]); !errors.Is(err, ErrInvalidMailQuota) {
|
||||
t.Fatalf("%s: WithReserve() error = %v, want ErrInvalidMailQuota", name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -60,7 +60,11 @@ type MailRequest struct {
|
||||
RecipientUserID uuid.UUID
|
||||
Kind MailKind
|
||||
Notification NotificationText
|
||||
CreatedAt time.Time
|
||||
// Subject names the record the notification is about. It is copied to the
|
||||
// delivery, whose sending worker checks its rights; the zero value names
|
||||
// none.
|
||||
Subject MailSubject
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
// NewMailRequest checks the storage rules of a request. Only notification
|
||||
@@ -68,7 +72,6 @@ type MailRequest struct {
|
||||
// transaction that issues the token. Whether the text renders is checked by
|
||||
// the template, not here.
|
||||
func NewMailRequest(request MailRequest) (MailRequest, error) {
|
||||
text := request.Notification
|
||||
switch {
|
||||
case request.ID == uuid.Nil || request.RecipientUserID == uuid.Nil:
|
||||
return MailRequest{}, invalidMailRequest("request and recipient user IDs must not be nil")
|
||||
@@ -76,17 +79,30 @@ func NewMailRequest(request MailRequest) (MailRequest, error) {
|
||||
return MailRequest{}, invalidMailRequest("only notification mail can be requested")
|
||||
case request.CreatedAt.IsZero():
|
||||
return MailRequest{}, invalidMailRequest("creation time must be set")
|
||||
case !request.Subject.IsZero() && request.Subject.Kind() != MailSubjectInvitation:
|
||||
return MailRequest{}, invalidMailRequest("the subject kind is unknown")
|
||||
}
|
||||
if err := checkMailRequestText(request.Notification); err != nil {
|
||||
return MailRequest{}, err
|
||||
}
|
||||
return request, nil
|
||||
}
|
||||
|
||||
// checkMailRequestText bounds and checks the raw text of a request, before the
|
||||
// template normalizes it.
|
||||
func checkMailRequestText(text NotificationText) error {
|
||||
switch {
|
||||
case !utf8.ValidString(text.Subject) || !utf8.ValidString(text.Body) || !utf8.ValidString(text.LinkPath):
|
||||
return MailRequest{}, invalidMailRequest("text must be valid UTF-8")
|
||||
return invalidMailRequest("text must be valid UTF-8")
|
||||
// PostgreSQL text cannot store NUL.
|
||||
case strings.ContainsRune(text.Subject, 0) || strings.ContainsRune(text.Body, 0) || strings.ContainsRune(text.LinkPath, 0):
|
||||
return MailRequest{}, invalidMailRequest("text must not contain NUL characters")
|
||||
return invalidMailRequest("text must not contain NUL characters")
|
||||
case utf8.RuneCountInString(text.Subject) > maxMailRequestSubjectRunes ||
|
||||
utf8.RuneCountInString(text.Body) > maxMailRequestBodyRunes ||
|
||||
len(text.LinkPath) > maxMailRequestLinkPathSize:
|
||||
return MailRequest{}, invalidMailRequest("subject, body, or link path is too long")
|
||||
return invalidMailRequest("subject, body, or link path is too long")
|
||||
}
|
||||
return request, nil
|
||||
return nil
|
||||
}
|
||||
|
||||
// LogValue carries the IDs and kind only.
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// ErrInvalidMailSubject reports a subject that names no record or breaks the
|
||||
// rule of its kind. Errors name the rule, never an identifier.
|
||||
var ErrInvalidMailSubject = errors.New("invalid mail subject")
|
||||
|
||||
// MailSubjectKind names the kind of record a notification is about. The
|
||||
// values are stored, and each one has a rights checker in the sending usecase.
|
||||
type MailSubjectKind string
|
||||
|
||||
const (
|
||||
// MailSubjectInvitation is an invitation addressed to the recipient. The
|
||||
// subject ID is the invitation and the organization is its sender.
|
||||
MailSubjectInvitation MailSubjectKind = "invitation"
|
||||
)
|
||||
|
||||
// MailSubject links a notification to the record whose rights must still hold
|
||||
// when the mail is sent. The sending worker re-checks those rights before the
|
||||
// transport is called, so a notification that outlives its basis is cancelled
|
||||
// instead of sent. The zero value names no subject; the worker then has no
|
||||
// rights to check and cancels the notification with source_closed.
|
||||
type MailSubject struct {
|
||||
kind MailSubjectKind
|
||||
id uuid.UUID
|
||||
organizationID uuid.UUID
|
||||
}
|
||||
|
||||
// NewInvitationMailSubject names an invitation and the organization that sent
|
||||
// it. Both IDs must be set.
|
||||
func NewInvitationMailSubject(invitationID, organizationID uuid.UUID) (MailSubject, error) {
|
||||
if invitationID == uuid.Nil || organizationID == uuid.Nil {
|
||||
return MailSubject{}, fmt.Errorf("domain.NewInvitationMailSubject - invitation and organization IDs must be set: %w", ErrInvalidMailSubject)
|
||||
}
|
||||
return MailSubject{kind: MailSubjectInvitation, id: invitationID, organizationID: organizationID}, nil
|
||||
}
|
||||
|
||||
// RestoreMailSubject rebuilds a stored subject. A kind of "" with nil IDs is
|
||||
// the zero subject; any other combination must be a complete known subject.
|
||||
func RestoreMailSubject(kind string, id, organizationID uuid.UUID) (MailSubject, error) {
|
||||
if kind == "" && id == uuid.Nil && organizationID == uuid.Nil {
|
||||
return MailSubject{}, nil
|
||||
}
|
||||
switch MailSubjectKind(kind) {
|
||||
case MailSubjectInvitation:
|
||||
return NewInvitationMailSubject(id, organizationID)
|
||||
default:
|
||||
return MailSubject{}, fmt.Errorf("domain.RestoreMailSubject - unknown subject kind: %w", ErrInvalidMailSubject)
|
||||
}
|
||||
}
|
||||
|
||||
// IsZero reports a subject that names nothing.
|
||||
func (subject MailSubject) IsZero() bool { return subject.kind == "" }
|
||||
|
||||
func (subject MailSubject) Kind() MailSubjectKind { return subject.kind }
|
||||
|
||||
// ID is the identifier of the subject record.
|
||||
func (subject MailSubject) ID() uuid.UUID { return subject.id }
|
||||
|
||||
// OrganizationID is the organization the subject record belongs to.
|
||||
func (subject MailSubject) OrganizationID() uuid.UUID { return subject.organizationID }
|
||||
|
||||
// String shows the kind only; the identifiers stay out of printed values.
|
||||
func (subject MailSubject) String() string {
|
||||
if subject.IsZero() {
|
||||
return "[empty mail subject]"
|
||||
}
|
||||
return fmt.Sprintf("[mail subject %s]", subject.kind)
|
||||
}
|
||||
|
||||
func (subject MailSubject) GoString() string { return subject.String() }
|
||||
|
||||
// LogValue carries the kind only.
|
||||
func (subject MailSubject) LogValue() slog.Value {
|
||||
return slog.StringValue(string(subject.kind))
|
||||
}
|
||||
Reference in new issue
Block a user