214 lines
9.0 KiB
Go
214 lines
9.0 KiB
Go
package notification
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"log/slog"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"lincodex/backend/internal/domain"
|
|
"lincodex/backend/internal/port/inbound"
|
|
"lincodex/backend/internal/port/outbound"
|
|
)
|
|
|
|
// InboxConsumerName names the consumer group and scopes deduplication of the
|
|
// inbox handler. Renaming it makes the consumer process every retained event
|
|
// again; the inbox key keeps the rows unique, but do not rename it lightly.
|
|
const InboxConsumerName = "notification_inbox"
|
|
|
|
// inboxPayloadSchemaVersion is the only supported schema version of the
|
|
// inbox events. Version 1 is inboxEventPayload.
|
|
const inboxPayloadSchemaVersion = 1
|
|
|
|
// inboxEventPayload is version 1 of the payload of every event the inbox
|
|
// stores. It names the recipient and the organization context and nothing
|
|
// else: the text is resolved from the source when the inbox is read, so
|
|
// neither the outbox nor the event bus keeps content that could outlive a
|
|
// revocation.
|
|
type inboxEventPayload struct {
|
|
RecipientUserID uuid.UUID `json:"recipient_user_id"`
|
|
OrganizationID uuid.UUID `json:"organization_id"`
|
|
}
|
|
|
|
// inboxProjection describes how one event type becomes an inbox row: the
|
|
// aggregate the event must come from and where the content source is.
|
|
type inboxProjection struct {
|
|
aggregateType string
|
|
// source returns the source record of the content for a decoded event.
|
|
source func(event outbound.ConsumedEvent, payload inboxEventPayload) uuid.UUID
|
|
}
|
|
|
|
// inboxProjections is the allowlist of events the inbox stores. A producer
|
|
// plugs in by appending an event of one of these types in its own
|
|
// transaction; adding a type here also needs the same pair in
|
|
// domain.NotificationInboxSourceFor, the CHECK constraint of the table, and a
|
|
// content resolver for its source type.
|
|
//
|
|
// - invitation.delivered: the aggregate is the invitation, which is also
|
|
// the source. Invitations are a later module; the projection and the
|
|
// payload contract are fixed here so that it needs no inbox change.
|
|
// - notification.synthetic_delivered: a synthetic event for tests and
|
|
// probes. Its aggregate is a one-off notice and its source is the
|
|
// organization of the payload.
|
|
var inboxProjections = map[domain.NotificationInboxEventType]inboxProjection{
|
|
domain.NotificationInboxInvitationDelivered: {
|
|
aggregateType: "invitation",
|
|
source: func(event outbound.ConsumedEvent, _ inboxEventPayload) uuid.UUID {
|
|
return event.AggregateID
|
|
},
|
|
},
|
|
domain.NotificationInboxSyntheticDelivered: {
|
|
aggregateType: SyntheticNoticeAggregateType,
|
|
source: func(_ outbound.ConsumedEvent, payload inboxEventPayload) uuid.UUID {
|
|
return payload.OrganizationID
|
|
},
|
|
},
|
|
}
|
|
|
|
// SyntheticNoticeAggregateType is the aggregate type of a synthetic inbox
|
|
// event. Every notice is its own aggregate at version 1.
|
|
const SyntheticNoticeAggregateType = "synthetic_notice"
|
|
|
|
// SyntheticNoticeAggregateVersion is the version of a synthetic notice.
|
|
const SyntheticNoticeAggregateVersion = 1
|
|
|
|
// SyntheticNoticeEventPayload builds the version 1 payload of a synthetic
|
|
// inbox event for the outbox. It is the single writer of the contract that
|
|
// the inbox handler reads.
|
|
func SyntheticNoticeEventPayload(recipientUserID, organizationID uuid.UUID) ([]byte, error) {
|
|
payload, err := json.Marshal(inboxEventPayload{RecipientUserID: recipientUserID, OrganizationID: organizationID})
|
|
if err != nil {
|
|
return nil, fmt.Errorf("notification.SyntheticNoticeEventPayload - encode payload: %w", err)
|
|
}
|
|
return payload, nil
|
|
}
|
|
|
|
// InboxHandler stores one inbox row for each inbox event, in the consumer
|
|
// transaction that records the event as processed. The row key is the
|
|
// recipient and the event ID, so a repeated delivery, a replayed dead letter,
|
|
// or a renamed consumer still stores one row, and a redelivery that changed
|
|
// the immutable metadata is refused instead of overwritten.
|
|
//
|
|
// The inbox is the in-platform delivery state of a notification: a stored row
|
|
// means delivered. Nothing here reads mail state, so an unverified address, a
|
|
// missing mail provider, or a failed email never blocks a notification.
|
|
type InboxHandler struct {
|
|
logger *slog.Logger
|
|
syntheticEnabled bool
|
|
}
|
|
|
|
var _ inbound.EventHandler = (*InboxHandler)(nil)
|
|
|
|
// NewInboxHandler creates the handler. The synthetic event type is handled
|
|
// only when syntheticEnabled is true, which a development or browser-test
|
|
// stand sets; otherwise such an event is acknowledged and ignored.
|
|
func NewInboxHandler(logger *slog.Logger, syntheticEnabled bool) *InboxHandler {
|
|
return &InboxHandler{logger: logger, syntheticEnabled: syntheticEnabled}
|
|
}
|
|
|
|
func (*InboxHandler) ConsumerName() string { return InboxConsumerName }
|
|
|
|
func (handler *InboxHandler) Handles(eventType string) bool {
|
|
return handler.handles(domain.NotificationInboxEventType(eventType))
|
|
}
|
|
|
|
func (handler *InboxHandler) handles(eventType domain.NotificationInboxEventType) bool {
|
|
if eventType == domain.NotificationInboxSyntheticDelivered && !handler.syntheticEnabled {
|
|
return false
|
|
}
|
|
_, known := inboxProjections[eventType]
|
|
return known
|
|
}
|
|
|
|
// Handle turns the event into an inbox row:
|
|
//
|
|
// - A payload or envelope that breaks the contract, a recipient or
|
|
// organization that does not exist, or an event ID that already holds
|
|
// different metadata is rejected for good (inbound.ErrEventRejected).
|
|
// - A recipient account that was deleted is skipped: its private inbox
|
|
// went with it. An account deleted between the check and the insert
|
|
// aborts the insert; the error is returned for a retry, and the retry
|
|
// finds the account gone and skips.
|
|
// - Storage errors, including a recipient that disappeared, are returned
|
|
// for a retry.
|
|
//
|
|
// Errors and logs carry event IDs, never the payload.
|
|
func (handler *InboxHandler) Handle(ctx context.Context, unit outbound.UnitOfWork, event outbound.ConsumedEvent) error {
|
|
const location = "InboxHandler.Handle"
|
|
eventType := domain.NotificationInboxEventType(event.EventType)
|
|
projection := inboxProjections[eventType]
|
|
if !handler.handles(eventType) {
|
|
return fmt.Errorf("%s - event type is not an inbox event: %w", location, inbound.ErrEventRejected)
|
|
}
|
|
payload, err := decodeInboxPayload(event, projection)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if _, err := unit.Users().GetByID(ctx, payload.RecipientUserID); err != nil {
|
|
if errors.Is(err, outbound.ErrUserNotFound) {
|
|
handler.logger.InfoContext(ctx, "inbox event skipped because the recipient account does not exist",
|
|
slog.String("event_id", event.EventID.String()))
|
|
return nil
|
|
}
|
|
return fmt.Errorf("%s - read recipient account: %w", location, err)
|
|
}
|
|
sourceType, _ := domain.NotificationInboxSourceFor(eventType)
|
|
entry, err := domain.NewNotificationInboxEntry(domain.NotificationInboxEntryInput{
|
|
EventID: event.EventID,
|
|
RecipientUserID: payload.RecipientUserID,
|
|
OrganizationID: payload.OrganizationID,
|
|
EventType: eventType,
|
|
SchemaVersion: event.SchemaVersion,
|
|
SourceType: sourceType,
|
|
SourceID: projection.source(event, payload),
|
|
OccurredAt: event.OccurredAt,
|
|
})
|
|
if err != nil {
|
|
return fmt.Errorf("%s - build inbox entry: %w: %w", location, inbound.ErrEventRejected, err)
|
|
}
|
|
if _, err := unit.NotificationInbox().Store(ctx, entry); err != nil {
|
|
// A vanished recipient (ErrNotificationInboxRecipientMissing) is not
|
|
// the event's fault: it is retried and then skipped above.
|
|
if errors.Is(err, outbound.ErrNotificationInboxEventConflict) || errors.Is(err, outbound.ErrNotificationInboxReferenceMissing) {
|
|
return fmt.Errorf("%s - store inbox entry: %w: %w", location, inbound.ErrEventRejected, err)
|
|
}
|
|
return fmt.Errorf("%s - store inbox entry: %w", location, err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// decodeInboxPayload checks the envelope and the version 1 payload. Errors
|
|
// name the broken rule and never quote the payload.
|
|
func decodeInboxPayload(event outbound.ConsumedEvent, projection inboxProjection) (inboxEventPayload, error) {
|
|
const location = "notification.decodeInboxPayload"
|
|
rejected := func(reason string) error {
|
|
return fmt.Errorf("%s - %s: %w", location, reason, inbound.ErrEventRejected)
|
|
}
|
|
if event.SchemaVersion != inboxPayloadSchemaVersion {
|
|
return inboxEventPayload{}, rejected(fmt.Sprintf("schema version %d is not supported", event.SchemaVersion))
|
|
}
|
|
if event.AggregateType != projection.aggregateType || event.AggregateID == uuid.Nil {
|
|
return inboxEventPayload{}, rejected("aggregate does not match the event type")
|
|
}
|
|
var payload inboxEventPayload
|
|
decoder := json.NewDecoder(bytes.NewReader(event.Payload))
|
|
decoder.DisallowUnknownFields()
|
|
// The decoder error can quote a fragment of the payload, so it is not
|
|
// wrapped. A second value after the object is refused as well.
|
|
if err := decoder.Decode(&payload); err != nil {
|
|
return inboxEventPayload{}, rejected("payload is not a valid inbox event")
|
|
}
|
|
if _, err := decoder.Token(); !errors.Is(err, io.EOF) {
|
|
return inboxEventPayload{}, rejected("payload has data after the inbox event")
|
|
}
|
|
if payload.RecipientUserID == uuid.Nil || payload.OrganizationID == uuid.Nil {
|
|
return inboxEventPayload{}, rejected("recipient and organization IDs are required")
|
|
}
|
|
return payload, nil
|
|
}
|