feat(platform): add the notification inbox and deterministic match search
This commit is contained in:
1 parent
5edff21d2d
commit
0b11021b16
169 files changed
+17083
-443
No files matched your search
@@ -4,7 +4,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
@@ -17,6 +17,13 @@ import (
|
||||
|
||||
var (
|
||||
ErrInboxUnavailable = errors.New("notification inbox is unavailable")
|
||||
// ErrInboxForbidden reports an account that may not use the requested
|
||||
// cabinet inbox: a missing or unverified account, or an account of the
|
||||
// other scenario.
|
||||
ErrInboxForbidden = errors.New("notification inbox is forbidden")
|
||||
// ErrInboxEmailNotVerified reports an employer account whose email is not
|
||||
// confirmed; the organization operations answer it as email_not_verified.
|
||||
ErrInboxEmailNotVerified = errors.New("notification inbox requires a confirmed email")
|
||||
// ErrInboxContentUnavailable means the referenced source is missing or its
|
||||
// current visibility no longer permits the original presentation.
|
||||
ErrInboxContentUnavailable = errors.New("notification content is unavailable")
|
||||
@@ -27,6 +34,12 @@ const (
|
||||
maxInboxSummaryRunes = 500
|
||||
)
|
||||
|
||||
// inboxLinkPathPattern is the shape of a content link: a same-origin
|
||||
// absolute path of at most 256 characters from a narrow alphabet, so it has
|
||||
// no query, fragment, escape, dot segment, or backslash. The public contract
|
||||
// states the same pattern.
|
||||
var inboxLinkPathPattern = regexp.MustCompile(`^/[A-Za-z0-9/_-]{0,255}$`)
|
||||
|
||||
// InboxContent is resolved from the current source at read time. It is never
|
||||
// written to notification_inbox_events.
|
||||
type InboxContent struct {
|
||||
@@ -66,26 +79,15 @@ func validInboxText(value string, maxRunes int, allowNewlines bool) bool {
|
||||
}
|
||||
|
||||
func validInboxLinkPath(value string) bool {
|
||||
if !strings.HasPrefix(value, "/") || strings.HasPrefix(value, "//") || strings.ContainsAny(value, "\\?#%") {
|
||||
return false
|
||||
}
|
||||
parsed, err := url.ParseRequestURI(value)
|
||||
if err != nil || parsed.IsAbs() || parsed.Host != "" || parsed.Path != value {
|
||||
return false
|
||||
}
|
||||
for _, segment := range strings.Split(value, "/") {
|
||||
if segment == "." || segment == ".." {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
return inboxLinkPathPattern.MatchString(value) && !strings.HasPrefix(value, "//")
|
||||
}
|
||||
|
||||
// InboxContentResolver reads the current source under its current visibility
|
||||
// rules. It must return ErrInboxContentUnavailable when that source is gone or
|
||||
// no longer safe to present.
|
||||
// rules, inside the read transaction that also authorized the viewer. It must
|
||||
// return ErrInboxContentUnavailable when that source is gone or no longer
|
||||
// safe to present to the recipient.
|
||||
type InboxContentResolver interface {
|
||||
Resolve(ctx context.Context, entry domain.NotificationInboxEntry) (InboxContent, error)
|
||||
Resolve(ctx context.Context, unit outbound.UnitOfWork, entry domain.NotificationInboxEntry) (InboxContent, error)
|
||||
}
|
||||
|
||||
// InboxItem pairs immutable event metadata with content resolved for this
|
||||
@@ -96,9 +98,11 @@ type InboxItem struct {
|
||||
ContentUnavailable bool
|
||||
}
|
||||
|
||||
// InboxListRequest is built from the authenticated recipient and optional
|
||||
// organization context. The organization ID filters items but grants no
|
||||
// authorization by itself.
|
||||
// InboxListRequest is built from the authenticated recipient. A nil
|
||||
// OrganizationID is the candidate cabinet: every organization that sent to
|
||||
// the recipient. A set OrganizationID is the employer cabinet of that
|
||||
// organization and requires the recipient's current active membership. The
|
||||
// organization ID filters items but is never authorization by itself.
|
||||
type InboxListRequest struct {
|
||||
RecipientUserID uuid.UUID
|
||||
OrganizationID *uuid.UUID
|
||||
@@ -106,111 +110,163 @@ type InboxListRequest struct {
|
||||
Limit int32
|
||||
}
|
||||
|
||||
// InboxMarkReadRequest names one inbox item in the same cabinet scope as
|
||||
// InboxListRequest.
|
||||
type InboxMarkReadRequest struct {
|
||||
RecipientUserID uuid.UUID
|
||||
OrganizationID *uuid.UUID
|
||||
EventID uuid.UUID
|
||||
}
|
||||
|
||||
type InboxPage struct {
|
||||
Items []InboxItem
|
||||
HasMore bool
|
||||
}
|
||||
|
||||
// InboxService coordinates recipient-scoped storage and read-time content
|
||||
// resolution. A caller for employer-scoped notices must authorize current
|
||||
// membership before constructing the request; invitation recipients need not
|
||||
// belong to the sender's organization.
|
||||
// InboxService lists and marks the inbox of the authenticated recipient.
|
||||
// Every operation authorizes the recipient for the requested cabinet and
|
||||
// reads the inbox in one transaction, so a membership revoked a moment ago
|
||||
// cannot authorize a later read. The inbox stores references only: the text
|
||||
// of an item is resolved from its current source at each list, so a hiding, a
|
||||
// revoked membership, or a withdrawn source removes the content from every
|
||||
// later read. Mail delivery is a separate concern: an item exists whether or
|
||||
// not any email was sent, and an email failure never blocks it.
|
||||
type InboxService struct {
|
||||
repository outbound.NotificationInboxRepository
|
||||
transactor outbound.Transactor
|
||||
resolver InboxContentResolver
|
||||
clock func() time.Time
|
||||
}
|
||||
|
||||
func NewInboxService(
|
||||
repository outbound.NotificationInboxRepository,
|
||||
transactor outbound.Transactor,
|
||||
resolver InboxContentResolver,
|
||||
clock func() time.Time,
|
||||
) (*InboxService, error) {
|
||||
if repository == nil || resolver == nil || clock == nil {
|
||||
return nil, fmt.Errorf("notification.NewInboxService - repository, resolver, and clock are required: %w", ErrInboxUnavailable)
|
||||
if transactor == nil || resolver == nil || clock == nil {
|
||||
return nil, fmt.Errorf("notification.NewInboxService - transactor, resolver, and clock are required: %w", ErrInboxUnavailable)
|
||||
}
|
||||
return &InboxService{repository: repository, resolver: resolver, clock: clock}, nil
|
||||
return &InboxService{transactor: transactor, resolver: resolver, clock: clock}, nil
|
||||
}
|
||||
|
||||
// StoreInvitationDelivered stores the recipient-specific reference to an
|
||||
// invitation-delivered event. A transaction-bound repository lets a future
|
||||
// event handler commit this row with the invitation state and consumer marker.
|
||||
func (service *InboxService) StoreInvitationDelivered(
|
||||
ctx context.Context,
|
||||
input domain.NotificationInboxEntryInput,
|
||||
) (bool, error) {
|
||||
const location = "InboxService.StoreInvitationDelivered"
|
||||
entry, err := domain.NewNotificationInboxEntry(input)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
created, err := service.repository.Store(ctx, entry)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("%s - store event: %w", location, err)
|
||||
}
|
||||
return created, nil
|
||||
}
|
||||
|
||||
// List resolves each stored reference against its current source. A source
|
||||
// that is missing or no longer visible is returned without source content.
|
||||
// List returns one newest-first page and resolves each stored reference
|
||||
// against its current source. A source that is missing or no longer visible
|
||||
// is returned without content.
|
||||
func (service *InboxService) List(ctx context.Context, request InboxListRequest) (InboxPage, error) {
|
||||
const location = "InboxService.List"
|
||||
if err := validateInboxListRequest(request); err != nil {
|
||||
return InboxPage{}, err
|
||||
}
|
||||
stored, err := service.repository.List(ctx, outbound.NotificationInboxListQuery{
|
||||
RecipientUserID: request.RecipientUserID,
|
||||
OrganizationID: request.OrganizationID,
|
||||
After: request.After,
|
||||
Limit: request.Limit,
|
||||
var page InboxPage
|
||||
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
if err := authorizeInboxViewer(ctx, unit, request.RecipientUserID, request.OrganizationID); err != nil {
|
||||
return err
|
||||
}
|
||||
stored, err := unit.NotificationInbox().List(ctx, outbound.NotificationInboxListQuery{
|
||||
RecipientUserID: request.RecipientUserID,
|
||||
OrganizationID: request.OrganizationID,
|
||||
After: request.After,
|
||||
Limit: request.Limit,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - list recipient events: %w", location, err)
|
||||
}
|
||||
resolved := InboxPage{Items: make([]InboxItem, 0, len(stored.Items)), HasMore: stored.HasMore}
|
||||
for _, entry := range stored.Items {
|
||||
if !inboxEntryMatchesRequest(entry, request) {
|
||||
return fmt.Errorf("%s - repository returned an event outside the recipient scope: %w", location, ErrInboxUnavailable)
|
||||
}
|
||||
item := InboxItem{Entry: entry}
|
||||
content, resolveErr := service.resolver.Resolve(ctx, unit, entry)
|
||||
switch {
|
||||
case errors.Is(resolveErr, ErrInboxContentUnavailable):
|
||||
item.ContentUnavailable = true
|
||||
case resolveErr != nil:
|
||||
return fmt.Errorf("%s - resolve current event content: %w", location, resolveErr)
|
||||
default:
|
||||
item.Content = &content
|
||||
}
|
||||
resolved.Items = append(resolved.Items, item)
|
||||
}
|
||||
page = resolved
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return InboxPage{}, fmt.Errorf("%s - list recipient events: %w", location, err)
|
||||
}
|
||||
page := InboxPage{Items: make([]InboxItem, 0, len(stored.Items)), HasMore: stored.HasMore}
|
||||
for _, entry := range stored.Items {
|
||||
if !inboxEntryMatchesRequest(entry, request) {
|
||||
return InboxPage{}, fmt.Errorf("%s - repository returned an event outside the recipient scope: %w", location, ErrInboxUnavailable)
|
||||
}
|
||||
item := InboxItem{Entry: entry}
|
||||
content, resolveErr := service.resolver.Resolve(ctx, entry)
|
||||
switch {
|
||||
case errors.Is(resolveErr, ErrInboxContentUnavailable):
|
||||
item.ContentUnavailable = true
|
||||
case resolveErr != nil:
|
||||
return InboxPage{}, fmt.Errorf("%s - resolve current event content: %w", location, resolveErr)
|
||||
default:
|
||||
item.Content = &content
|
||||
}
|
||||
page.Items = append(page.Items, item)
|
||||
return InboxPage{}, fmt.Errorf("%s - run transaction: %w", location, err)
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
// MarkRead persists the first read timestamp for one recipient and exact
|
||||
// organization context. The source is not read and no private content is
|
||||
// returned by this command.
|
||||
func (service *InboxService) MarkRead(
|
||||
ctx context.Context,
|
||||
recipientUserID uuid.UUID,
|
||||
organizationID uuid.UUID,
|
||||
eventID uuid.UUID,
|
||||
) (domain.NotificationInboxEntry, error) {
|
||||
// MarkRead persists the first read timestamp of one item of the recipient. A
|
||||
// repeat keeps the first timestamp. The source is not read and no content is
|
||||
// returned. An item of another recipient, of another organization context,
|
||||
// or an unknown item all return outbound.ErrNotificationInboxEntryNotFound.
|
||||
func (service *InboxService) MarkRead(ctx context.Context, request InboxMarkReadRequest) (domain.NotificationInboxEntry, error) {
|
||||
const location = "InboxService.MarkRead"
|
||||
if recipientUserID == uuid.Nil || organizationID == uuid.Nil || eventID == uuid.Nil {
|
||||
return domain.NotificationInboxEntry{}, fmt.Errorf("%s - recipient, organization, and event IDs are required: %w", location, ErrInboxUnavailable)
|
||||
if request.RecipientUserID == uuid.Nil || request.EventID == uuid.Nil ||
|
||||
(request.OrganizationID != nil && *request.OrganizationID == uuid.Nil) {
|
||||
return domain.NotificationInboxEntry{}, fmt.Errorf("%s - recipient and event IDs are required: %w", location, ErrInboxUnavailable)
|
||||
}
|
||||
at := service.clock()
|
||||
if at.IsZero() {
|
||||
return domain.NotificationInboxEntry{}, fmt.Errorf("%s - clock returned zero: %w", location, ErrInboxUnavailable)
|
||||
}
|
||||
entry, err := service.repository.MarkRead(ctx, recipientUserID, organizationID, eventID, at)
|
||||
var entry domain.NotificationInboxEntry
|
||||
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
if err := authorizeInboxViewer(ctx, unit, request.RecipientUserID, request.OrganizationID); err != nil {
|
||||
return err
|
||||
}
|
||||
marked, err := unit.NotificationInbox().MarkRead(ctx, request.RecipientUserID, request.OrganizationID, request.EventID, at)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - mark event read: %w", location, err)
|
||||
}
|
||||
entry = marked
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return domain.NotificationInboxEntry{}, fmt.Errorf("%s - mark event read: %w", location, err)
|
||||
return domain.NotificationInboxEntry{}, fmt.Errorf("%s - run transaction: %w", location, err)
|
||||
}
|
||||
return entry, nil
|
||||
}
|
||||
|
||||
// authorizeInboxViewer checks the account against the requested cabinet. The
|
||||
// candidate cabinet needs a verified candidate account. The employer cabinet
|
||||
// needs an employer account with a verified email (otherwise
|
||||
// ErrInboxEmailNotVerified, like the other organization operations) and an
|
||||
// active membership of any role in the named organization. The membership is
|
||||
// locked FOR SHARE until the transaction ends, like the card reads, so a
|
||||
// revocation cannot commit between this check and the read that follows. A
|
||||
// missing or inactive membership returns outbound.ErrOrganizationNotFound, so
|
||||
// an organization that exists cannot be told from one that does not.
|
||||
func authorizeInboxViewer(ctx context.Context, unit outbound.UnitOfWork, userID uuid.UUID, organizationID *uuid.UUID) error {
|
||||
const location = "notification.authorizeInboxViewer"
|
||||
user, err := unit.Users().GetByID(ctx, userID)
|
||||
if errors.Is(err, outbound.ErrUserNotFound) {
|
||||
return fmt.Errorf("%s - account does not exist: %w", location, ErrInboxForbidden)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - read account: %w", location, err)
|
||||
}
|
||||
if organizationID == nil {
|
||||
if user.Scenario != domain.ScenarioCandidate || !user.EmailVerified() {
|
||||
return fmt.Errorf("%s - the candidate inbox needs a verified candidate account: %w", location, ErrInboxForbidden)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if user.Scenario != domain.ScenarioEmployer {
|
||||
return fmt.Errorf("%s - the organization inbox needs an employer account: %w", location, ErrInboxForbidden)
|
||||
}
|
||||
if !user.EmailVerified() {
|
||||
return fmt.Errorf("%s - email is not verified: %w", location, ErrInboxEmailNotVerified)
|
||||
}
|
||||
if _, err := unit.Organizations().LockActiveMembership(ctx, *organizationID, userID); err != nil {
|
||||
if errors.Is(err, outbound.ErrOrganizationNotFound) {
|
||||
return fmt.Errorf("%s - no active membership: %w", location, outbound.ErrOrganizationNotFound)
|
||||
}
|
||||
return fmt.Errorf("%s - lock active membership: %w", location, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateInboxListRequest(request InboxListRequest) error {
|
||||
const location = "notification.validateInboxListRequest"
|
||||
if request.RecipientUserID == uuid.Nil || request.Limit < 1 || request.Limit > outbound.MaxNotificationInboxPageSize {
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
package notification
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
// InboxSourceResolver resolves the content of the entries of one source
|
||||
// type from the current state of that source, for the entry's recipient. It
|
||||
// returns ErrInboxContentUnavailable when the source is gone or the recipient
|
||||
// may not see it now.
|
||||
type InboxSourceResolver func(ctx context.Context, unit outbound.UnitOfWork, entry domain.NotificationInboxEntry) (InboxContent, error)
|
||||
|
||||
// sourceContentResolver dispatches by source type. A source type without a
|
||||
// resolver is unavailable, never guessed, so a new event type shows nothing
|
||||
// until its resolver is registered.
|
||||
type sourceContentResolver map[domain.NotificationInboxSourceType]InboxSourceResolver
|
||||
|
||||
var _ InboxContentResolver = sourceContentResolver(nil)
|
||||
|
||||
// NewInboxContentResolver combines the resolvers of the source types.
|
||||
func NewInboxContentResolver(resolvers map[domain.NotificationInboxSourceType]InboxSourceResolver) InboxContentResolver {
|
||||
return sourceContentResolver(resolvers)
|
||||
}
|
||||
|
||||
// DefaultInboxSourceResolvers lists the source types that have a resolver
|
||||
// today. The synthetic notice resolver is registered only when
|
||||
// syntheticEnabled is true (development and browser-test stands); a stored
|
||||
// synthetic row is then listed without content. The invitation module adds
|
||||
// domain.NotificationInboxSourceInvitation with its own resolver; the
|
||||
// handler, the table, and the API need no change.
|
||||
func DefaultInboxSourceResolvers(syntheticEnabled bool) map[domain.NotificationInboxSourceType]InboxSourceResolver {
|
||||
resolvers := map[domain.NotificationInboxSourceType]InboxSourceResolver{}
|
||||
if syntheticEnabled {
|
||||
resolvers[domain.NotificationInboxSourceOrganization] = ResolveSyntheticNotice
|
||||
}
|
||||
return resolvers
|
||||
}
|
||||
|
||||
func (resolvers sourceContentResolver) Resolve(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
entry domain.NotificationInboxEntry,
|
||||
) (InboxContent, error) {
|
||||
resolve, ok := resolvers[entry.SourceType()]
|
||||
if !ok {
|
||||
return InboxContent{}, ErrInboxContentUnavailable
|
||||
}
|
||||
return resolve(ctx, unit, entry)
|
||||
}
|
||||
|
||||
const (
|
||||
syntheticNoticeTitle = "Тестовое уведомление"
|
||||
// syntheticNoticeSummary has one verb slot for the organization name.
|
||||
syntheticNoticeSummary = "Организация «%s» отправила проверочное уведомление платформы. Оно создано для проверки доставки и не требует действий."
|
||||
)
|
||||
|
||||
// ResolveSyntheticNotice resolves a synthetic notice. The text is fixed and
|
||||
// names the sending organization by its current name, which is read under the
|
||||
// recipient's current standing: a candidate sees it until they hide the
|
||||
// organization, an employer while they are an active member. Afterwards the
|
||||
// entry stays in the list without content.
|
||||
func ResolveSyntheticNotice(ctx context.Context, unit outbound.UnitOfWork, entry domain.NotificationInboxEntry) (InboxContent, error) {
|
||||
const location = "notification.ResolveSyntheticNotice"
|
||||
name, err := unit.NotificationInbox().OrganizationNameForRecipient(ctx, entry.RecipientUserID(), entry.SourceID())
|
||||
if errors.Is(err, outbound.ErrNotificationInboxSourceNotVisible) {
|
||||
return InboxContent{}, ErrInboxContentUnavailable
|
||||
}
|
||||
if err != nil {
|
||||
return InboxContent{}, fmt.Errorf("%s - read sender organization: %w", location, err)
|
||||
}
|
||||
content, err := NewInboxContent(syntheticNoticeTitle, fmt.Sprintf(syntheticNoticeSummary, name), "")
|
||||
if err != nil {
|
||||
// A stored name that does not fit the presentation is not shown.
|
||||
return InboxContent{}, ErrInboxContentUnavailable
|
||||
}
|
||||
return content, nil
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
package notification
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/inbound"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
func newInboxHandlerFixture(t *testing.T) (*InboxHandler, *inboxFixture, outbound.ConsumedEvent) {
|
||||
t.Helper()
|
||||
fixture := newInboxFixture(t, domain.ScenarioCandidate)
|
||||
payload, err := SyntheticNoticeEventPayload(fixture.user.ID, fixture.organizationID)
|
||||
if err != nil {
|
||||
t.Fatalf("SyntheticNoticeEventPayload() error = %v", err)
|
||||
}
|
||||
event := outbound.ConsumedEvent{
|
||||
EventID: uuid.New(), EventType: string(domain.NotificationInboxSyntheticDelivered), SchemaVersion: 1,
|
||||
AggregateType: SyntheticNoticeAggregateType, AggregateID: uuid.New(), AggregateVersion: SyntheticNoticeAggregateVersion,
|
||||
OccurredAt: time.Date(2026, time.October, 8, 12, 0, 0, 0, time.UTC), Payload: payload,
|
||||
}
|
||||
return NewInboxHandler(slog.New(slog.DiscardHandler), true), fixture, event
|
||||
}
|
||||
|
||||
func TestInboxHandlerStoresOneRowForARepeatedEvent(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
handler, fixture, event := newInboxHandlerFixture(t)
|
||||
if !handler.Handles(event.EventType) || handler.Handles("notification.mail_requested") {
|
||||
t.Fatal("Handles() must accept inbox events only")
|
||||
}
|
||||
for range 2 {
|
||||
if err := handler.Handle(context.Background(), fixture.unit(), event); err != nil {
|
||||
t.Fatalf("Handle() error = %v", err)
|
||||
}
|
||||
}
|
||||
if len(fixture.repository.entries) != 1 {
|
||||
t.Fatalf("stored rows = %d, want one for a repeated event ID", len(fixture.repository.entries))
|
||||
}
|
||||
entry := fixture.repository.entries[0]
|
||||
if entry.EventID() != event.EventID || entry.RecipientUserID() != fixture.user.ID ||
|
||||
entry.OrganizationID() != fixture.organizationID || entry.SourceID() != fixture.organizationID ||
|
||||
entry.SourceType() != domain.NotificationInboxSourceOrganization {
|
||||
t.Fatalf("stored entry = %+v, want the references of the event", entry)
|
||||
}
|
||||
if _, isRead := entry.ReadAt(); isRead {
|
||||
t.Fatal("a delivered row starts as read")
|
||||
}
|
||||
}
|
||||
|
||||
func TestInboxHandlerRejectsEventsThatBreakTheContract(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
mutate func(*outbound.ConsumedEvent, *inboxFixture)
|
||||
}{
|
||||
{name: "schema version", mutate: func(event *outbound.ConsumedEvent, _ *inboxFixture) { event.SchemaVersion = 2 }},
|
||||
{name: "aggregate type", mutate: func(event *outbound.ConsumedEvent, _ *inboxFixture) { event.AggregateType = "mail_request" }},
|
||||
{name: "unknown field", mutate: func(event *outbound.ConsumedEvent, fixture *inboxFixture) {
|
||||
event.Payload = json.RawMessage(`{"recipient_user_id":"` + fixture.user.ID.String() + `","organization_id":"` + fixture.organizationID.String() + `","email":"a@example.test"}`)
|
||||
}},
|
||||
{name: "missing organization", mutate: func(event *outbound.ConsumedEvent, fixture *inboxFixture) {
|
||||
event.Payload = json.RawMessage(`{"recipient_user_id":"` + fixture.user.ID.String() + `"}`)
|
||||
}},
|
||||
{name: "not an object", mutate: func(event *outbound.ConsumedEvent, _ *inboxFixture) { event.Payload = json.RawMessage(`[]`) }},
|
||||
{name: "trailing data", mutate: func(event *outbound.ConsumedEvent, _ *inboxFixture) {
|
||||
event.Payload = append(append(json.RawMessage{}, event.Payload...), []byte(` {}`)...)
|
||||
}},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
handler, fixture, event := newInboxHandlerFixture(t)
|
||||
test.mutate(&event, fixture)
|
||||
err := handler.Handle(context.Background(), fixture.unit(), event)
|
||||
if !errors.Is(err, inbound.ErrEventRejected) {
|
||||
t.Fatalf("Handle() error = %v, want ErrEventRejected", err)
|
||||
}
|
||||
if len(fixture.repository.entries) != 0 {
|
||||
t.Fatal("a rejected event stored a row")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestInboxHandlerRejectsAnEventIDReusedWithOtherMetadata(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
handler, fixture, event := newInboxHandlerFixture(t)
|
||||
if err := handler.Handle(context.Background(), fixture.unit(), event); err != nil {
|
||||
t.Fatalf("Handle(first) error = %v", err)
|
||||
}
|
||||
event.OccurredAt = event.OccurredAt.Add(time.Hour)
|
||||
if err := handler.Handle(context.Background(), fixture.unit(), event); !errors.Is(err, inbound.ErrEventRejected) {
|
||||
t.Fatalf("Handle(changed replay) error = %v, want ErrEventRejected", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInboxHandlerSkipsADeletedRecipientAndKeepsStoreErrorsRetryable(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
handler, fixture, event := newInboxHandlerFixture(t)
|
||||
delete(fixture.users, fixture.user.ID)
|
||||
if err := handler.Handle(context.Background(), fixture.unit(), event); err != nil {
|
||||
t.Fatalf("Handle(deleted recipient) error = %v, want a skip", err)
|
||||
}
|
||||
if len(fixture.repository.entries) != 0 {
|
||||
t.Fatal("a deleted recipient got a row")
|
||||
}
|
||||
|
||||
handler, fixture, event = newInboxHandlerFixture(t)
|
||||
fixture.repository.storeErr = errors.New("connection reset")
|
||||
err := handler.Handle(context.Background(), fixture.unit(), event)
|
||||
if err == nil || errors.Is(err, inbound.ErrEventRejected) {
|
||||
t.Fatalf("Handle(store failure) error = %v, want a retryable error", err)
|
||||
}
|
||||
fixture.repository.storeErr = outbound.ErrNotificationInboxReferenceMissing
|
||||
if err := handler.Handle(context.Background(), fixture.unit(), event); !errors.Is(err, inbound.ErrEventRejected) {
|
||||
t.Fatalf("Handle(missing organization) error = %v, want ErrEventRejected", err)
|
||||
}
|
||||
// A recipient deleted between the check and the insert is not the event's
|
||||
// fault: the attempt is retried, and the retry skips the deleted account.
|
||||
fixture.repository.storeErr = outbound.ErrNotificationInboxRecipientMissing
|
||||
if err := handler.Handle(context.Background(), fixture.unit(), event); err == nil || errors.Is(err, inbound.ErrEventRejected) {
|
||||
t.Fatalf("Handle(vanished recipient) error = %v, want a retryable error", err)
|
||||
}
|
||||
delete(fixture.users, fixture.user.ID)
|
||||
if err := handler.Handle(context.Background(), fixture.unit(), event); err != nil {
|
||||
t.Fatalf("Handle(retry after the recipient vanished) error = %v, want a skip", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInboxHandlerPlugsInInvitationEventsWithTheSameContract(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
handler, fixture, _ := newInboxHandlerFixture(t)
|
||||
invitationID := uuid.New()
|
||||
payload, err := json.Marshal(inboxEventPayload{RecipientUserID: fixture.user.ID, OrganizationID: fixture.organizationID})
|
||||
if err != nil {
|
||||
t.Fatalf("Marshal() error = %v", err)
|
||||
}
|
||||
event := outbound.ConsumedEvent{
|
||||
EventID: uuid.New(), EventType: string(domain.NotificationInboxInvitationDelivered), SchemaVersion: 1,
|
||||
AggregateType: "invitation", AggregateID: invitationID, AggregateVersion: 3,
|
||||
OccurredAt: time.Date(2026, time.October, 8, 12, 0, 0, 0, time.UTC), Payload: payload,
|
||||
}
|
||||
if err := handler.Handle(context.Background(), fixture.unit(), event); err != nil {
|
||||
t.Fatalf("Handle(invitation.delivered) error = %v", err)
|
||||
}
|
||||
entry := fixture.repository.entries[0]
|
||||
if entry.SourceType() != domain.NotificationInboxSourceInvitation || entry.SourceID() != invitationID {
|
||||
t.Fatalf("invitation entry source = %s %s, want the invitation aggregate", entry.SourceType(), entry.SourceID())
|
||||
}
|
||||
}
|
||||
|
||||
func TestInboxHandlerStoresARowWhateverTheStateOfTheAddress(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
// A mail delivery skips an address that is not verified. The inbox is the
|
||||
// delivery state inside the platform and reads no mail state.
|
||||
handler, fixture, event := newInboxHandlerFixture(t)
|
||||
unverified := fixture.user
|
||||
unverified.EmailVerifiedAt = nil
|
||||
fixture.users[unverified.ID] = unverified
|
||||
if err := handler.Handle(context.Background(), fixture.unit(), event); err != nil {
|
||||
t.Fatalf("Handle(unverified address) error = %v", err)
|
||||
}
|
||||
if len(fixture.repository.entries) != 1 {
|
||||
t.Fatalf("stored rows = %d, want 1: an address state must not block a notification", len(fixture.repository.entries))
|
||||
}
|
||||
}
|
||||
|
||||
func TestInboxHandlerIgnoresTheSyntheticEventWhileItIsSwitchedOff(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
_, fixture, event := newInboxHandlerFixture(t)
|
||||
off := NewInboxHandler(slog.New(slog.DiscardHandler), false)
|
||||
if off.Handles(event.EventType) {
|
||||
t.Fatal("the synthetic event is handled while the switch is off")
|
||||
}
|
||||
if !off.Handles(string(domain.NotificationInboxInvitationDelivered)) {
|
||||
t.Fatal("the invitation event must not depend on the synthetic switch")
|
||||
}
|
||||
if err := off.Handle(context.Background(), fixture.unit(), event); !errors.Is(err, inbound.ErrEventRejected) || len(fixture.repository.entries) != 0 {
|
||||
t.Fatalf("Handle(synthetic, off) error = %v, rows = %d, want a rejection and no row", err, len(fixture.repository.entries))
|
||||
}
|
||||
if _, ok := DefaultInboxSourceResolvers(false)[domain.NotificationInboxSourceOrganization]; ok {
|
||||
t.Fatal("the synthetic resolver is registered while the switch is off")
|
||||
}
|
||||
if _, ok := DefaultInboxSourceResolvers(true)[domain.NotificationInboxSourceOrganization]; !ok {
|
||||
t.Fatal("the synthetic resolver is missing while the switch is on")
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package notification
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -12,78 +13,168 @@ import (
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
func TestInboxServiceStoreInvitationDeliveredDeduplicatesRecipientEvent(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
repository := &memoryInboxRepository{}
|
||||
service := newInboxTestService(t, repository, &memoryInboxResolver{}, time.Now)
|
||||
input := inboxTestEntryInput()
|
||||
created, err := service.StoreInvitationDelivered(context.Background(), input)
|
||||
if err != nil || !created {
|
||||
t.Fatalf("StoreInvitationDelivered(first) = %t, %v, want true, nil", created, err)
|
||||
}
|
||||
created, err = service.StoreInvitationDelivered(context.Background(), input)
|
||||
if err != nil || created {
|
||||
t.Fatalf("StoreInvitationDelivered(retry) = %t, %v, want false, nil", created, err)
|
||||
}
|
||||
if len(repository.entries) != 1 {
|
||||
t.Fatalf("stored entries = %d, want one", len(repository.entries))
|
||||
}
|
||||
|
||||
changed := input
|
||||
changed.SourceID = uuid.New()
|
||||
if _, err := service.StoreInvitationDelivered(context.Background(), changed); !errors.Is(err, outbound.ErrNotificationInboxEventConflict) {
|
||||
t.Fatalf("StoreInvitationDelivered(changed replay) error = %v, want ErrNotificationInboxEventConflict", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInboxServiceListRechecksContentAndFallsBackSafely(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
first := mustInboxTestEntry(t, inboxTestEntryInput())
|
||||
secondInput := inboxTestEntryInput()
|
||||
secondInput.RecipientUserID = first.RecipientUserID()
|
||||
secondInput.OrganizationID = first.OrganizationID()
|
||||
secondInput.EventID = uuid.New()
|
||||
second := mustInboxTestEntry(t, secondInput)
|
||||
wrongOrganizationInput := inboxTestEntryInput()
|
||||
wrongOrganizationInput.RecipientUserID = first.RecipientUserID()
|
||||
wrongOrganizationInput.EventID = uuid.New()
|
||||
wrongOrganizationInput.OrganizationID = uuid.New()
|
||||
wrongOrganization := mustInboxTestEntry(t, wrongOrganizationInput)
|
||||
repository := &memoryInboxRepository{entries: []domain.NotificationInboxEntry{first, second, wrongOrganization}}
|
||||
resolver := &memoryInboxResolver{unavailable: map[uuid.UUID]bool{second.EventID(): true}}
|
||||
service := newInboxTestService(t, repository, resolver, time.Now)
|
||||
orgID := first.OrganizationID()
|
||||
page, err := service.List(context.Background(), InboxListRequest{
|
||||
RecipientUserID: first.RecipientUserID(), OrganizationID: &orgID, Limit: 10,
|
||||
})
|
||||
fixture := newInboxFixture(t, domain.ScenarioCandidate)
|
||||
first := fixture.add(t, fixture.entryInput())
|
||||
second := fixture.add(t, fixture.entryInput())
|
||||
fixture.resolver.unavailable[second.EventID()] = true
|
||||
otherRecipient := fixtureEntryInput(uuid.New(), fixture.organizationID)
|
||||
fixture.add(t, otherRecipient)
|
||||
|
||||
page, err := fixture.service.List(context.Background(), InboxListRequest{RecipientUserID: fixture.user.ID, Limit: 10})
|
||||
if err != nil {
|
||||
t.Fatalf("List() error = %v", err)
|
||||
}
|
||||
if len(page.Items) != 2 {
|
||||
t.Fatalf("List() returned %d items, want 2", len(page.Items))
|
||||
t.Fatalf("List() returned %d items, want only the recipient's 2", len(page.Items))
|
||||
}
|
||||
if page.Items[0].Content == nil || page.Items[0].ContentUnavailable {
|
||||
t.Fatalf("visible item = %+v, want current content", page.Items[0])
|
||||
byID := map[uuid.UUID]InboxItem{}
|
||||
for _, item := range page.Items {
|
||||
byID[item.Entry.EventID()] = item
|
||||
}
|
||||
if page.Items[1].Content != nil || !page.Items[1].ContentUnavailable {
|
||||
t.Fatalf("hidden item = %+v, want safe fallback without source content", page.Items[1])
|
||||
if item := byID[first.EventID()]; item.Content == nil || item.ContentUnavailable {
|
||||
t.Fatalf("visible item = %+v, want current content", item)
|
||||
}
|
||||
if resolver.calls != 2 {
|
||||
t.Fatalf("resolver calls = %d, want one current visibility check per returned item", resolver.calls)
|
||||
if item := byID[second.EventID()]; item.Content != nil || !item.ContentUnavailable {
|
||||
t.Fatalf("hidden item = %+v, want safe fallback without source content", item)
|
||||
}
|
||||
if fixture.resolver.calls != 2 {
|
||||
t.Fatalf("resolver calls = %d, want one current visibility check per returned item", fixture.resolver.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInboxServiceAuthorizesTheCabinetInTheReadTransaction(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
t.Run("the candidate inbox refuses an employer", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
fixture := newInboxFixture(t, domain.ScenarioEmployer)
|
||||
_, err := fixture.service.List(context.Background(), InboxListRequest{RecipientUserID: fixture.user.ID, Limit: 10})
|
||||
if !errors.Is(err, ErrInboxForbidden) {
|
||||
t.Fatalf("List(employer in the candidate cabinet) error = %v, want ErrInboxForbidden", err)
|
||||
}
|
||||
if fixture.repository.listCalls != 0 {
|
||||
t.Fatal("the repository was read before the account was authorized")
|
||||
}
|
||||
})
|
||||
t.Run("the organization inbox refuses a candidate", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
fixture := newInboxFixture(t, domain.ScenarioCandidate)
|
||||
_, err := fixture.service.List(context.Background(), InboxListRequest{
|
||||
RecipientUserID: fixture.user.ID, OrganizationID: &fixture.organizationID, Limit: 10,
|
||||
})
|
||||
if !errors.Is(err, ErrInboxForbidden) {
|
||||
t.Fatalf("List(candidate in the organization cabinet) error = %v, want ErrInboxForbidden", err)
|
||||
}
|
||||
})
|
||||
t.Run("an unknown or unverified account is refused", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
fixture := newInboxFixture(t, domain.ScenarioCandidate)
|
||||
if _, err := fixture.service.List(context.Background(), InboxListRequest{RecipientUserID: uuid.New(), Limit: 10}); !errors.Is(err, ErrInboxForbidden) {
|
||||
t.Fatalf("List(unknown account) error = %v, want ErrInboxForbidden", err)
|
||||
}
|
||||
fixture.user.EmailVerifiedAt = nil
|
||||
fixture.users[fixture.user.ID] = fixture.user
|
||||
if _, err := fixture.service.List(context.Background(), InboxListRequest{RecipientUserID: fixture.user.ID, Limit: 10}); !errors.Is(err, ErrInboxForbidden) {
|
||||
t.Fatalf("List(unverified account) error = %v, want ErrInboxForbidden", err)
|
||||
}
|
||||
})
|
||||
t.Run("a revoked membership answers like an unknown organization", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
fixture := newInboxFixture(t, domain.ScenarioEmployer)
|
||||
fixture.addMembership(t, domain.OrganizationRoleOwner, domain.MembershipStateActive)
|
||||
entry := fixture.add(t, fixture.entryInput())
|
||||
request := InboxListRequest{RecipientUserID: fixture.user.ID, OrganizationID: &fixture.organizationID, Limit: 10}
|
||||
page, err := fixture.service.List(context.Background(), request)
|
||||
if err != nil || len(page.Items) != 1 {
|
||||
t.Fatalf("List(active member) = %d items, %v, want 1 item", len(page.Items), err)
|
||||
}
|
||||
fixture.addMembership(t, domain.OrganizationRoleOwner, domain.MembershipStateRemoved)
|
||||
if _, err := fixture.service.List(context.Background(), request); !errors.Is(err, outbound.ErrOrganizationNotFound) {
|
||||
t.Fatalf("List(revoked member) error = %v, want ErrOrganizationNotFound", err)
|
||||
}
|
||||
_, err = fixture.service.MarkRead(context.Background(), InboxMarkReadRequest{
|
||||
RecipientUserID: fixture.user.ID, OrganizationID: &fixture.organizationID, EventID: entry.EventID(),
|
||||
})
|
||||
if !errors.Is(err, outbound.ErrOrganizationNotFound) {
|
||||
t.Fatalf("MarkRead(revoked member) error = %v, want ErrOrganizationNotFound", err)
|
||||
}
|
||||
if _, isRead := fixture.repository.entries[0].ReadAt(); isRead {
|
||||
t.Fatal("a revoked member marked an item read")
|
||||
}
|
||||
unknown := uuid.New()
|
||||
_, err = fixture.service.List(context.Background(), InboxListRequest{RecipientUserID: fixture.user.ID, OrganizationID: &unknown, Limit: 10})
|
||||
if !errors.Is(err, outbound.ErrOrganizationNotFound) {
|
||||
t.Fatalf("List(unknown organization) error = %v, want the same ErrOrganizationNotFound", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestInboxServiceOrganizationCabinetServesEveryRoleItsOwnItems(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
for _, role := range []domain.OrganizationRole{
|
||||
domain.OrganizationRoleOwner, domain.OrganizationRoleRecruiter,
|
||||
domain.OrganizationRoleHiringManager, domain.OrganizationRoleTechnicalExpert,
|
||||
} {
|
||||
t.Run(string(role), func(t *testing.T) {
|
||||
t.Parallel()
|
||||
fixture := newInboxFixture(t, domain.ScenarioEmployer)
|
||||
fixture.addMembership(t, role, domain.MembershipStateActive)
|
||||
own := fixture.add(t, fixture.entryInput())
|
||||
otherMember := fixture.add(t, fixtureEntryInput(uuid.New(), fixture.organizationID))
|
||||
otherOrganization := fixture.add(t, fixtureEntryInput(fixture.user.ID, uuid.New()))
|
||||
|
||||
page, err := fixture.service.List(context.Background(), InboxListRequest{
|
||||
RecipientUserID: fixture.user.ID, OrganizationID: &fixture.organizationID, Limit: 10,
|
||||
})
|
||||
if err != nil || len(page.Items) != 1 || page.Items[0].Entry.EventID() != own.EventID() {
|
||||
t.Fatalf("List(%s) = %d items, %v, want only its own item", role, len(page.Items), err)
|
||||
}
|
||||
if fixture.locks == 0 {
|
||||
t.Fatal("the membership was not locked for the read")
|
||||
}
|
||||
for _, foreign := range []domain.NotificationInboxEntry{otherMember, otherOrganization} {
|
||||
_, err := fixture.service.MarkRead(context.Background(), InboxMarkReadRequest{
|
||||
RecipientUserID: fixture.user.ID, OrganizationID: &fixture.organizationID, EventID: foreign.EventID(),
|
||||
})
|
||||
if !errors.Is(err, outbound.ErrNotificationInboxEntryNotFound) {
|
||||
t.Fatalf("MarkRead(%s, foreign item) error = %v, want ErrNotificationInboxEntryNotFound", role, err)
|
||||
}
|
||||
}
|
||||
if _, err := fixture.service.MarkRead(context.Background(), InboxMarkReadRequest{
|
||||
RecipientUserID: fixture.user.ID, OrganizationID: &fixture.organizationID, EventID: own.EventID(),
|
||||
}); err != nil {
|
||||
t.Fatalf("MarkRead(%s, own item) error = %v", role, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestInboxServiceOrganizationCabinetNeedsAConfirmedEmail(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
fixture := newInboxFixture(t, domain.ScenarioEmployer)
|
||||
fixture.addMembership(t, domain.OrganizationRoleOwner, domain.MembershipStateActive)
|
||||
fixture.user.EmailVerifiedAt = nil
|
||||
fixture.users[fixture.user.ID] = fixture.user
|
||||
_, err := fixture.service.List(context.Background(), InboxListRequest{
|
||||
RecipientUserID: fixture.user.ID, OrganizationID: &fixture.organizationID, Limit: 10,
|
||||
})
|
||||
if !errors.Is(err, ErrInboxEmailNotVerified) {
|
||||
t.Fatalf("List(unverified employer) error = %v, want ErrInboxEmailNotVerified", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInboxServiceListRejectsRepositoryRowsOutsideRecipientScope(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
entry := mustInboxTestEntry(t, inboxTestEntryInput())
|
||||
repository := &memoryInboxRepository{entries: []domain.NotificationInboxEntry{entry}, ignoreListScope: true}
|
||||
service := newInboxTestService(t, repository, &memoryInboxResolver{}, time.Now)
|
||||
_, err := service.List(context.Background(), InboxListRequest{
|
||||
RecipientUserID: uuid.New(), OrganizationID: uuidPointer(entry.OrganizationID()), Limit: 10,
|
||||
})
|
||||
fixture := newInboxFixture(t, domain.ScenarioCandidate)
|
||||
fixture.repository.ignoreListScope = true
|
||||
fixture.add(t, fixtureEntryInput(uuid.New(), fixture.organizationID))
|
||||
_, err := fixture.service.List(context.Background(), InboxListRequest{RecipientUserID: fixture.user.ID, Limit: 10})
|
||||
if !errors.Is(err, ErrInboxUnavailable) {
|
||||
t.Fatalf("List(out-of-scope repository row) error = %v, want ErrInboxUnavailable", err)
|
||||
}
|
||||
@@ -92,21 +183,17 @@ func TestInboxServiceListRejectsRepositoryRowsOutsideRecipientScope(t *testing.T
|
||||
func TestInboxServiceMarkReadPersistsAndKeepsFirstTime(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
entry := mustInboxTestEntry(t, inboxTestEntryInput())
|
||||
firstRead := time.Date(2026, time.October, 8, 13, 0, 0, 1000, time.UTC)
|
||||
secondRead := firstRead.Add(time.Hour)
|
||||
clockCalls := 0
|
||||
clock := func() time.Time {
|
||||
fixture := newInboxFixtureWithClock(t, domain.ScenarioCandidate, func() time.Time {
|
||||
clockCalls++
|
||||
if clockCalls == 1 {
|
||||
return firstRead
|
||||
}
|
||||
return secondRead
|
||||
}
|
||||
repository := &memoryInboxRepository{entries: []domain.NotificationInboxEntry{entry}}
|
||||
service := newInboxTestService(t, repository, &memoryInboxResolver{}, clock)
|
||||
return firstRead.Add(time.Duration(clockCalls-1) * time.Hour)
|
||||
})
|
||||
entry := fixture.add(t, fixture.entryInput())
|
||||
for range 2 {
|
||||
read, err := service.MarkRead(context.Background(), entry.RecipientUserID(), entry.OrganizationID(), entry.EventID())
|
||||
read, err := fixture.service.MarkRead(context.Background(), InboxMarkReadRequest{
|
||||
RecipientUserID: fixture.user.ID, EventID: entry.EventID(),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("MarkRead() error = %v", err)
|
||||
}
|
||||
@@ -117,6 +204,22 @@ func TestInboxServiceMarkReadPersistsAndKeepsFirstTime(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestInboxServiceMarkReadRefusesAnotherRecipientsItem(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
fixture := newInboxFixture(t, domain.ScenarioCandidate)
|
||||
foreign := fixture.add(t, fixtureEntryInput(uuid.New(), fixture.organizationID))
|
||||
_, err := fixture.service.MarkRead(context.Background(), InboxMarkReadRequest{
|
||||
RecipientUserID: fixture.user.ID, EventID: foreign.EventID(),
|
||||
})
|
||||
if !errors.Is(err, outbound.ErrNotificationInboxEntryNotFound) {
|
||||
t.Fatalf("MarkRead(foreign item) error = %v, want ErrNotificationInboxEntryNotFound", err)
|
||||
}
|
||||
if _, isRead := fixture.repository.entries[0].ReadAt(); isRead {
|
||||
t.Fatal("another recipient's item was marked read")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewInboxContentRejectsExternalOrAmbiguousLinks(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
@@ -129,6 +232,9 @@ func TestNewInboxContentRejectsExternalOrAmbiguousLinks(t *testing.T) {
|
||||
{name: "query string", path: "/candidate/invitations?token=secret"},
|
||||
{name: "fragment", path: "/candidate/invitations#current"},
|
||||
{name: "backslash", path: `/candidate\\invitations`},
|
||||
{name: "escape", path: "/candidate/%2e%2e/invitations"},
|
||||
{name: "dot segment", path: "/candidate/../invitations"},
|
||||
{name: "too long", path: "/" + strings.Repeat("a", 300)},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
@@ -138,32 +244,112 @@ func TestNewInboxContentRejectsExternalOrAmbiguousLinks(t *testing.T) {
|
||||
}
|
||||
})
|
||||
}
|
||||
if _, err := NewInboxContent("Приглашение", "Проверьте новое приглашение.", "/candidate/invitations/01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b"); err != nil {
|
||||
t.Fatalf("NewInboxContent(same-origin path) error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func newInboxTestService(
|
||||
t *testing.T,
|
||||
repository outbound.NotificationInboxRepository,
|
||||
resolver InboxContentResolver,
|
||||
clock func() time.Time,
|
||||
) *InboxService {
|
||||
func TestSyntheticNoticeResolverFollowsTheRecipientStanding(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
fixture := newInboxFixture(t, domain.ScenarioCandidate)
|
||||
entry := fixture.add(t, fixture.entryInput())
|
||||
unit := fixture.unit()
|
||||
content, err := ResolveSyntheticNotice(context.Background(), unit, entry)
|
||||
if err != nil {
|
||||
t.Fatalf("ResolveSyntheticNotice(visible) error = %v", err)
|
||||
}
|
||||
if content.Title() != syntheticNoticeTitle || content.LinkPath() != "" || content.Summary() == "" {
|
||||
t.Fatalf("synthetic content = %+v", content)
|
||||
}
|
||||
fixture.repository.organizationName = ""
|
||||
if _, err := ResolveSyntheticNotice(context.Background(), unit, entry); !errors.Is(err, ErrInboxContentUnavailable) {
|
||||
t.Fatalf("ResolveSyntheticNotice(not visible) error = %v, want ErrInboxContentUnavailable", err)
|
||||
}
|
||||
resolvers := NewInboxContentResolver(DefaultInboxSourceResolvers(true))
|
||||
invitation := fixtureEntry(t, domain.NotificationInboxEntryInput{
|
||||
EventID: uuid.New(), RecipientUserID: fixture.user.ID, OrganizationID: fixture.organizationID,
|
||||
EventType: domain.NotificationInboxInvitationDelivered, SchemaVersion: 1,
|
||||
SourceType: domain.NotificationInboxSourceInvitation, SourceID: uuid.New(),
|
||||
OccurredAt: time.Date(2026, time.October, 8, 12, 0, 0, 0, time.UTC),
|
||||
})
|
||||
if _, err := resolvers.Resolve(context.Background(), unit, invitation); !errors.Is(err, ErrInboxContentUnavailable) {
|
||||
t.Fatalf("Resolve(source without a resolver) error = %v, want ErrInboxContentUnavailable", err)
|
||||
}
|
||||
}
|
||||
|
||||
type inboxFixture struct {
|
||||
service *InboxService
|
||||
repository *memoryInboxRepository
|
||||
resolver *memoryInboxResolver
|
||||
users map[uuid.UUID]domain.User
|
||||
memberships map[uuid.UUID]domain.Membership
|
||||
user domain.User
|
||||
organizationID uuid.UUID
|
||||
locks int
|
||||
}
|
||||
|
||||
func newInboxFixture(t *testing.T, scenario domain.Scenario) *inboxFixture {
|
||||
t.Helper()
|
||||
service, err := NewInboxService(repository, resolver, clock)
|
||||
return newInboxFixtureWithClock(t, scenario, time.Now)
|
||||
}
|
||||
|
||||
func newInboxFixtureWithClock(t *testing.T, scenario domain.Scenario, clock func() time.Time) *inboxFixture {
|
||||
t.Helper()
|
||||
verifiedAt := time.Date(2026, time.October, 1, 10, 0, 0, 0, time.UTC)
|
||||
fixture := &inboxFixture{
|
||||
repository: &memoryInboxRepository{organizationName: "Север"},
|
||||
resolver: &memoryInboxResolver{unavailable: map[uuid.UUID]bool{}},
|
||||
users: map[uuid.UUID]domain.User{},
|
||||
memberships: map[uuid.UUID]domain.Membership{},
|
||||
user: domain.User{ID: uuid.New(), Scenario: scenario, EmailVerifiedAt: &verifiedAt},
|
||||
organizationID: uuid.New(),
|
||||
}
|
||||
fixture.users[fixture.user.ID] = fixture.user
|
||||
service, err := NewInboxService(inboxTestTransactor{fixture: fixture}, fixture.resolver, clock)
|
||||
if err != nil {
|
||||
t.Fatalf("NewInboxService() error = %v", err)
|
||||
}
|
||||
return service
|
||||
fixture.service = service
|
||||
return fixture
|
||||
}
|
||||
|
||||
func inboxTestEntryInput() domain.NotificationInboxEntryInput {
|
||||
func (fixture *inboxFixture) unit() outbound.UnitOfWork { return inboxTestUnit{fixture: fixture} }
|
||||
|
||||
func (fixture *inboxFixture) entryInput() domain.NotificationInboxEntryInput {
|
||||
return fixtureEntryInput(fixture.user.ID, fixture.organizationID)
|
||||
}
|
||||
|
||||
func (fixture *inboxFixture) add(t *testing.T, input domain.NotificationInboxEntryInput) domain.NotificationInboxEntry {
|
||||
t.Helper()
|
||||
entry := fixtureEntry(t, input)
|
||||
fixture.repository.entries = append(fixture.repository.entries, entry)
|
||||
return entry
|
||||
}
|
||||
|
||||
func (fixture *inboxFixture) addMembership(t *testing.T, role domain.OrganizationRole, state domain.MembershipState) {
|
||||
t.Helper()
|
||||
now := time.Date(2026, time.October, 1, 10, 0, 0, 0, time.UTC)
|
||||
membership, err := domain.RestoreMembership(domain.StoredMembership{
|
||||
ID: uuid.New(), OrganizationID: fixture.organizationID, UserID: fixture.user.ID,
|
||||
Role: string(role), State: string(state), CreatedAt: now, UpdatedAt: now,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("RestoreMembership() error = %v", err)
|
||||
}
|
||||
fixture.memberships[fixture.user.ID] = membership
|
||||
}
|
||||
|
||||
func fixtureEntryInput(recipientID, organizationID uuid.UUID) domain.NotificationInboxEntryInput {
|
||||
return domain.NotificationInboxEntryInput{
|
||||
EventID: uuid.New(), RecipientUserID: uuid.New(), OrganizationID: uuid.New(),
|
||||
EventType: domain.NotificationInboxInvitationDelivered, SchemaVersion: 1,
|
||||
SourceType: domain.NotificationInboxSourceInvitation, SourceID: uuid.New(),
|
||||
EventID: uuid.New(), RecipientUserID: recipientID, OrganizationID: organizationID,
|
||||
EventType: domain.NotificationInboxSyntheticDelivered, SchemaVersion: 1,
|
||||
SourceType: domain.NotificationInboxSourceOrganization, SourceID: organizationID,
|
||||
OccurredAt: time.Date(2026, time.October, 8, 12, 0, 0, 0, time.UTC),
|
||||
}
|
||||
}
|
||||
|
||||
func mustInboxTestEntry(t *testing.T, input domain.NotificationInboxEntryInput) domain.NotificationInboxEntry {
|
||||
func fixtureEntry(t *testing.T, input domain.NotificationInboxEntryInput) domain.NotificationInboxEntry {
|
||||
t.Helper()
|
||||
entry, err := domain.NewNotificationInboxEntry(input)
|
||||
if err != nil {
|
||||
@@ -172,14 +358,71 @@ func mustInboxTestEntry(t *testing.T, input domain.NotificationInboxEntryInput)
|
||||
return entry
|
||||
}
|
||||
|
||||
func uuidPointer(value uuid.UUID) *uuid.UUID { return &value }
|
||||
type inboxTestTransactor struct{ fixture *inboxFixture }
|
||||
|
||||
func (transactor inboxTestTransactor) WithinTransaction(ctx context.Context, fn func(context.Context, outbound.UnitOfWork) error) error {
|
||||
return fn(ctx, transactor.fixture.unit())
|
||||
}
|
||||
|
||||
type inboxTestUnit struct {
|
||||
outbound.UnitOfWork
|
||||
|
||||
fixture *inboxFixture
|
||||
}
|
||||
|
||||
func (unit inboxTestUnit) Users() outbound.UserRepository {
|
||||
return inboxTestUsers{fixture: unit.fixture}
|
||||
}
|
||||
func (unit inboxTestUnit) Organizations() outbound.OrganizationRepository {
|
||||
return inboxTestOrganizations{fixture: unit.fixture}
|
||||
}
|
||||
func (unit inboxTestUnit) NotificationInbox() outbound.NotificationInboxRepository {
|
||||
return unit.fixture.repository
|
||||
}
|
||||
|
||||
type inboxTestUsers struct {
|
||||
outbound.UserRepository
|
||||
|
||||
fixture *inboxFixture
|
||||
}
|
||||
|
||||
func (repository inboxTestUsers) GetByID(_ context.Context, id uuid.UUID) (domain.User, error) {
|
||||
user, ok := repository.fixture.users[id]
|
||||
if !ok {
|
||||
return domain.User{}, outbound.ErrUserNotFound
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
|
||||
type inboxTestOrganizations struct {
|
||||
outbound.OrganizationRepository
|
||||
|
||||
fixture *inboxFixture
|
||||
}
|
||||
|
||||
// LockActiveMembership answers like the real repository: only an active
|
||||
// membership of the account in the organization is returned.
|
||||
func (repository inboxTestOrganizations) LockActiveMembership(_ context.Context, organizationID, userID uuid.UUID) (domain.Membership, error) {
|
||||
repository.fixture.locks++
|
||||
membership, ok := repository.fixture.memberships[userID]
|
||||
if !ok || membership.OrganizationID() != organizationID || !membership.GrantsAccess() {
|
||||
return domain.Membership{}, outbound.ErrOrganizationNotFound
|
||||
}
|
||||
return membership, nil
|
||||
}
|
||||
|
||||
type memoryInboxRepository struct {
|
||||
entries []domain.NotificationInboxEntry
|
||||
ignoreListScope bool
|
||||
entries []domain.NotificationInboxEntry
|
||||
ignoreListScope bool
|
||||
listCalls int
|
||||
organizationName string
|
||||
storeErr error
|
||||
}
|
||||
|
||||
func (repository *memoryInboxRepository) Store(_ context.Context, entry domain.NotificationInboxEntry) (bool, error) {
|
||||
if repository.storeErr != nil {
|
||||
return false, repository.storeErr
|
||||
}
|
||||
for _, existing := range repository.entries {
|
||||
if existing.RecipientUserID() != entry.RecipientUserID() || existing.EventID() != entry.EventID() {
|
||||
continue
|
||||
@@ -194,6 +437,7 @@ func (repository *memoryInboxRepository) Store(_ context.Context, entry domain.N
|
||||
}
|
||||
|
||||
func (repository *memoryInboxRepository) List(_ context.Context, query outbound.NotificationInboxListQuery) (outbound.NotificationInboxPage, error) {
|
||||
repository.listCalls++
|
||||
page := outbound.NotificationInboxPage{}
|
||||
for _, entry := range repository.entries {
|
||||
if !repository.ignoreListScope && (entry.RecipientUserID() != query.RecipientUserID || (query.OrganizationID != nil && entry.OrganizationID() != *query.OrganizationID)) {
|
||||
@@ -207,12 +451,13 @@ func (repository *memoryInboxRepository) List(_ context.Context, query outbound.
|
||||
func (repository *memoryInboxRepository) MarkRead(
|
||||
_ context.Context,
|
||||
recipientUserID uuid.UUID,
|
||||
organizationID uuid.UUID,
|
||||
organizationID *uuid.UUID,
|
||||
eventID uuid.UUID,
|
||||
at time.Time,
|
||||
) (domain.NotificationInboxEntry, error) {
|
||||
for index, entry := range repository.entries {
|
||||
if entry.RecipientUserID() != recipientUserID || entry.OrganizationID() != organizationID || entry.EventID() != eventID {
|
||||
if entry.RecipientUserID() != recipientUserID || entry.EventID() != eventID ||
|
||||
(organizationID != nil && entry.OrganizationID() != *organizationID) {
|
||||
continue
|
||||
}
|
||||
read, err := entry.MarkRead(at)
|
||||
@@ -225,6 +470,13 @@ func (repository *memoryInboxRepository) MarkRead(
|
||||
return domain.NotificationInboxEntry{}, outbound.ErrNotificationInboxEntryNotFound
|
||||
}
|
||||
|
||||
func (repository *memoryInboxRepository) OrganizationNameForRecipient(context.Context, uuid.UUID, uuid.UUID) (string, error) {
|
||||
if repository.organizationName == "" {
|
||||
return "", outbound.ErrNotificationInboxSourceNotVisible
|
||||
}
|
||||
return repository.organizationName, nil
|
||||
}
|
||||
|
||||
func sameInboxEvent(left, right domain.NotificationInboxEntry) bool {
|
||||
return left.OrganizationID() == right.OrganizationID() && left.EventType() == right.EventType() &&
|
||||
left.SchemaVersion() == right.SchemaVersion() && left.SourceType() == right.SourceType() &&
|
||||
@@ -236,7 +488,7 @@ type memoryInboxResolver struct {
|
||||
calls int
|
||||
}
|
||||
|
||||
func (resolver *memoryInboxResolver) Resolve(_ context.Context, entry domain.NotificationInboxEntry) (InboxContent, error) {
|
||||
func (resolver *memoryInboxResolver) Resolve(_ context.Context, _ outbound.UnitOfWork, entry domain.NotificationInboxEntry) (InboxContent, error) {
|
||||
resolver.calls++
|
||||
if resolver.unavailable[entry.EventID()] {
|
||||
return InboxContent{}, ErrInboxContentUnavailable
|
||||
|
||||
Reference in new issue
Block a user