package notification import ( "bytes" "context" "encoding/json" "errors" "fmt" "io" "log/slog" "time" "github.com/google/uuid" "lincodex/backend/internal/domain" "lincodex/backend/internal/port/inbound" "lincodex/backend/internal/port/outbound" "lincodex/backend/internal/usecase/notification/mailtemplate" ) // DeliveryConsumerName names the consumer group and scopes deduplication. // Renaming it makes the consumer process every retained request again; the // delivery IDs then keep the deliveries unique, but do not rename it lightly. const DeliveryConsumerName = "notification_delivery" // DeliveryHandler creates one Delivery for each notification.mail_requested // event, in the consumer transaction that records the event as processed. // // The delivery ID is the request ID, so a duplicate event, a replayed dead // letter, or a renamed consumer maps to the same delivery. The content is // rendered once, here, and stored; a later template version does not change // it. The request row is deleted in the same transaction, so its text lives // only as long as it is needed. type DeliveryHandler struct { renderer NotificationRenderer providerAccount domain.MailProviderAccount clock func() time.Time logger *slog.Logger } var _ inbound.EventHandler = (*DeliveryHandler)(nil) // NewDeliveryHandler pins new deliveries to providerAccount, the transport // and account configured when the event is handled. clock is the // application clock for the creation time. func NewDeliveryHandler( renderer NotificationRenderer, providerAccount domain.MailProviderAccount, clock func() time.Time, logger *slog.Logger, ) *DeliveryHandler { return &DeliveryHandler{renderer: renderer, providerAccount: providerAccount, clock: clock, logger: logger} } func (*DeliveryHandler) ConsumerName() string { return DeliveryConsumerName } func (*DeliveryHandler) Handles(eventType string) bool { return eventType == MailRequestedEventType } // Handle turns the request into a delivery: // // - A request that breaks the event contract, data the template refuses, // or an existing delivery under the same ID for another recipient or // kind is rejected for good (inbound.ErrEventRejected). // - A request that no longer exists, because it was already turned into a // delivery or its account was deleted, is skipped. // - A notification to an account whose address is not verified is skipped // and its request deleted: notifications go only to confirmed addresses. // - Storage errors are returned for a retry. That includes an account // deleted after it was read, which aborts the insert; the retry then // finds the request gone with the account and skips it. // // Errors and logs carry the delivery and event IDs, never the address or // the notification text. func (handler *DeliveryHandler) Handle(ctx context.Context, unit outbound.UnitOfWork, event outbound.ConsumedEvent) error { const location = "DeliveryHandler.Handle" payload, err := decodeMailRequest(event) if err != nil { return err } request, err := unit.MailRequests().Lock(ctx, payload.MailRequestID) if errors.Is(err, outbound.ErrMailRequestNotFound) { handler.logSkip(ctx, "mail request skipped because it was already handled or its account was deleted", event) return nil } if err != nil { return fmt.Errorf("%s - lock mail request: %w", location, err) } if string(request.Kind) != payload.Kind { return fmt.Errorf("%s - event kind does not match the stored request: %w", location, inbound.ErrEventRejected) } recipient, err := unit.Users().GetByID(ctx, request.RecipientUserID) if errors.Is(err, outbound.ErrUserNotFound) { // The foreign key deletes a request with its account, so this is a // defensive branch. handler.logSkip(ctx, "mail request skipped because the recipient account does not exist", event) return handler.finish(ctx, unit, request.ID) } if err != nil { return fmt.Errorf("%s - read recipient account: %w", location, err) } if recipient.EmailVerifiedAt == nil { handler.logSkip(ctx, "notification skipped because the recipient address is not verified", event) return handler.finish(ctx, unit, request.ID) } content, err := handler.renderer.RenderNotification(mailtemplate.NotificationData{ Subject: request.Notification.Subject, Body: request.Notification.Body, LinkPath: request.Notification.LinkPath, }) if errors.Is(err, mailtemplate.ErrInvalidTemplateData) || errors.Is(err, domain.ErrInvalidMailContent) { return fmt.Errorf("%s - render notification: %w: %w", location, inbound.ErrEventRejected, err) } if err != nil { return fmt.Errorf("%s - render notification: %w", location, err) } delivery, err := domain.NewDelivery(domain.NewDeliveryInput{ ID: request.ID, SourceEventID: event.EventID, RecipientUserID: recipient.ID, Recipient: recipient.Email, Content: content, ProviderAccount: handler.providerAccount, CreatedAt: handler.clock(), }) if err != nil { return fmt.Errorf("%s - build delivery: %w: %w", location, inbound.ErrEventRejected, err) } created, err := unit.Deliveries().Create(ctx, delivery) if err != nil { return fmt.Errorf("%s - store delivery: %w", location, err) } if !created { if err := checkExistingDelivery(ctx, unit, request); err != nil { return err } } return handler.finish(ctx, unit, request.ID) } // checkExistingDelivery accepts a delivery stored earlier under the request // ID only when it is for the same recipient and kind; its content stays as // stored. func checkExistingDelivery(ctx context.Context, unit outbound.UnitOfWork, request domain.MailRequest) error { const location = "notification.checkExistingDelivery" existing, err := unit.Deliveries().Get(ctx, request.ID) if err != nil { return fmt.Errorf("%s - read existing delivery: %w", location, err) } if existing.RecipientUserID() != request.RecipientUserID || existing.Kind() != request.Kind { return fmt.Errorf("%s - a delivery for another recipient or kind has the request ID: %w", location, inbound.ErrEventRejected) } return nil } // finish deletes the handled request in the consumer transaction. func (handler *DeliveryHandler) finish(ctx context.Context, unit outbound.UnitOfWork, requestID uuid.UUID) error { if err := unit.MailRequests().Delete(ctx, requestID); err != nil { return fmt.Errorf("DeliveryHandler.finish - delete mail request: %w", err) } return nil } func (handler *DeliveryHandler) logSkip(ctx context.Context, message string, event outbound.ConsumedEvent) { handler.logger.InfoContext(ctx, message, slog.String("delivery_id", event.AggregateID.String()), slog.String("event_id", event.EventID.String())) } // decodeMailRequest checks the envelope and payload of a version 1 request. // Errors name the broken rule and never quote the payload. func decodeMailRequest(event outbound.ConsumedEvent) (mailRequestedPayload, error) { const location = "notification.decodeMailRequest" rejected := func(reason string) error { return fmt.Errorf("%s - %s: %w", location, reason, inbound.ErrEventRejected) } if event.SchemaVersion != mailRequestedSchemaVersion { return mailRequestedPayload{}, rejected(fmt.Sprintf("schema version %d is not supported", event.SchemaVersion)) } if event.AggregateType != mailRequestAggregateType || event.AggregateID == uuid.Nil { return mailRequestedPayload{}, rejected("aggregate must be a mail_request with an ID") } var payload mailRequestedPayload decoder := json.NewDecoder(bytes.NewReader(event.Payload)) // 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 mailRequestedPayload{}, rejected("payload is not a valid mail request") } if _, err := decoder.Token(); !errors.Is(err, io.EOF) { return mailRequestedPayload{}, rejected("payload has data after the mail request") } switch { case payload.MailRequestID != event.AggregateID: return mailRequestedPayload{}, rejected("mail_request_id must equal the aggregate ID") case payload.Kind != string(domain.MailKindNotification): return mailRequestedPayload{}, rejected("kind must be notification in schema version 1") } return payload, nil }