chore: checkpoint assessment and inbox integration

This commit is contained in:
TakuyaYagam1 committed 2026-10-08 17:47:30 +03:00
1 parent 88a31ba0d5
commit 5c52fd8b91
31 files changed
+4608 -181

No files matched your search

@@ -0,0 +1,231 @@
package notification
import (
"context"
"errors"
"fmt"
"net/url"
"strings"
"time"
"unicode/utf8"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
var (
ErrInboxUnavailable = errors.New("notification inbox is unavailable")
// ErrInboxContentUnavailable means the referenced source is missing or its
// current visibility no longer permits the original presentation.
ErrInboxContentUnavailable = errors.New("notification content is unavailable")
)
const (
maxInboxTitleRunes = 120
maxInboxSummaryRunes = 500
)
// InboxContent is resolved from the current source at read time. It is never
// written to notification_inbox_events.
type InboxContent struct {
title string
summary string
linkPath string
}
// NewInboxContent validates a small same-origin presentation returned by a
// source resolver after its current visibility checks.
func NewInboxContent(title, summary, linkPath string) (InboxContent, error) {
const location = "notification.NewInboxContent"
if !validInboxText(title, maxInboxTitleRunes, false) || !validInboxText(summary, maxInboxSummaryRunes, true) {
return InboxContent{}, fmt.Errorf("%s - title and summary are invalid: %w", location, ErrInboxUnavailable)
}
if linkPath != "" && !validInboxLinkPath(linkPath) {
return InboxContent{}, fmt.Errorf("%s - link path must be relative and same-origin: %w", location, ErrInboxUnavailable)
}
return InboxContent{title: title, summary: summary, linkPath: linkPath}, nil
}
func (content InboxContent) Title() string { return content.title }
func (content InboxContent) Summary() string { return content.summary }
func (content InboxContent) LinkPath() string { return content.linkPath }
func validInboxText(value string, maxRunes int, allowNewlines bool) bool {
if !utf8.ValidString(value) || value == "" || strings.TrimSpace(value) != value || utf8.RuneCountInString(value) > maxRunes {
return false
}
for _, character := range value {
if character == 0 || (character < 0x20 && !(allowNewlines && (character == '\n' || character == '\t'))) || character == 0x7f {
return false
}
}
return true
}
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
}
// 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.
type InboxContentResolver interface {
Resolve(ctx context.Context, entry domain.NotificationInboxEntry) (InboxContent, error)
}
// InboxItem pairs immutable event metadata with content resolved for this
// read. Content is nil when a safe generic fallback is required.
type InboxItem struct {
Entry domain.NotificationInboxEntry
Content *InboxContent
ContentUnavailable bool
}
// InboxListRequest is built from the authenticated recipient and optional
// organization context. The organization ID filters items but grants no
// authorization by itself.
type InboxListRequest struct {
RecipientUserID uuid.UUID
OrganizationID *uuid.UUID
After *outbound.NotificationInboxPosition
Limit int32
}
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.
type InboxService struct {
repository outbound.NotificationInboxRepository
resolver InboxContentResolver
clock func() time.Time
}
func NewInboxService(
repository outbound.NotificationInboxRepository,
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)
}
return &InboxService{repository: repository, 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.
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,
})
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)
if errors.Is(resolveErr, ErrInboxContentUnavailable) {
item.ContentUnavailable = true
} else if resolveErr != nil {
return InboxPage{}, fmt.Errorf("%s - resolve current event content: %w", location, resolveErr)
} else {
item.Content = &content
}
page.Items = append(page.Items, item)
}
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) {
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)
}
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)
if err != nil {
return domain.NotificationInboxEntry{}, fmt.Errorf("%s - mark event read: %w", location, err)
}
return entry, nil
}
func validateInboxListRequest(request InboxListRequest) error {
const location = "notification.validateInboxListRequest"
if request.RecipientUserID == uuid.Nil || request.Limit < 1 || request.Limit > outbound.MaxNotificationInboxPageSize {
return fmt.Errorf("%s - recipient and a bounded page size are required: %w", location, ErrInboxUnavailable)
}
if request.OrganizationID != nil && *request.OrganizationID == uuid.Nil {
return fmt.Errorf("%s - organization context cannot be zero: %w", location, ErrInboxUnavailable)
}
if request.After != nil && (request.After.EventID == uuid.Nil || request.After.OccurredAt.IsZero()) {
return fmt.Errorf("%s - page position is invalid: %w", location, ErrInboxUnavailable)
}
return nil
}
func inboxEntryMatchesRequest(entry domain.NotificationInboxEntry, request InboxListRequest) bool {
if entry.IsZero() || entry.RecipientUserID() != request.RecipientUserID {
return false
}
return request.OrganizationID == nil || entry.OrganizationID() == *request.OrganizationID
}