feat(platform): add the notification inbox and deterministic match search

This commit is contained in:
shira committed 2026-10-09 13:14:46 +03:00
1 parent 5edff21d2d
commit 0b11021b16
169 files changed
+17083 -443

No files matched your search

+142 -86
View File
@@ -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 {