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
}
@@ -0,0 +1,245 @@
package notification
import (
"context"
"errors"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"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,
})
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))
}
if page.Items[0].Content == nil || page.Items[0].ContentUnavailable {
t.Fatalf("visible item = %+v, want current content", page.Items[0])
}
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 resolver.calls != 2 {
t.Fatalf("resolver calls = %d, want one current visibility check per returned item", resolver.calls)
}
}
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,
})
if !errors.Is(err, ErrInboxUnavailable) {
t.Fatalf("List(out-of-scope repository row) error = %v, want ErrInboxUnavailable", err)
}
}
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 {
clockCalls++
if clockCalls == 1 {
return firstRead
}
return secondRead
}
repository := &memoryInboxRepository{entries: []domain.NotificationInboxEntry{entry}}
service := newInboxTestService(t, repository, &memoryInboxResolver{}, clock)
for range 2 {
read, err := service.MarkRead(context.Background(), entry.RecipientUserID(), entry.OrganizationID(), entry.EventID())
if err != nil {
t.Fatalf("MarkRead() error = %v", err)
}
got, isRead := read.ReadAt()
if !isRead || !got.Equal(firstRead.UTC().Truncate(time.Microsecond)) {
t.Fatalf("ReadAt() = %s, %t, want the first read time", got, isRead)
}
}
}
func TestNewInboxContentRejectsExternalOrAmbiguousLinks(t *testing.T) {
t.Parallel()
tests := []struct {
name string
path string
}{
{name: "external URL", path: "https://example.test/invitation"},
{name: "protocol-relative URL", path: "//example.test/invitation"},
{name: "query string", path: "/candidate/invitations?token=secret"},
{name: "fragment", path: "/candidate/invitations#current"},
{name: "backslash", path: `/candidate\\invitations`},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
t.Parallel()
if _, err := NewInboxContent("Приглашение", "Проверьте новое приглашение.", test.path); !errors.Is(err, ErrInboxUnavailable) {
t.Fatalf("NewInboxContent() error = %v, want ErrInboxUnavailable", err)
}
})
}
}
func newInboxTestService(
t *testing.T,
repository outbound.NotificationInboxRepository,
resolver InboxContentResolver,
clock func() time.Time,
) *InboxService {
t.Helper()
service, err := NewInboxService(repository, resolver, clock)
if err != nil {
t.Fatalf("NewInboxService() error = %v", err)
}
return service
}
func inboxTestEntryInput() 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(),
OccurredAt: time.Date(2026, time.October, 8, 12, 0, 0, 0, time.UTC),
}
}
func mustInboxTestEntry(t *testing.T, input domain.NotificationInboxEntryInput) domain.NotificationInboxEntry {
t.Helper()
entry, err := domain.NewNotificationInboxEntry(input)
if err != nil {
t.Fatalf("NewNotificationInboxEntry() error = %v", err)
}
return entry
}
func uuidPointer(value uuid.UUID) *uuid.UUID { return &value }
type memoryInboxRepository struct {
entries []domain.NotificationInboxEntry
ignoreListScope bool
}
func (repository *memoryInboxRepository) Store(_ context.Context, entry domain.NotificationInboxEntry) (bool, error) {
for _, existing := range repository.entries {
if existing.RecipientUserID() != entry.RecipientUserID() || existing.EventID() != entry.EventID() {
continue
}
if !sameInboxEvent(existing, entry) {
return false, outbound.ErrNotificationInboxEventConflict
}
return false, nil
}
repository.entries = append(repository.entries, entry)
return true, nil
}
func (repository *memoryInboxRepository) List(_ context.Context, query outbound.NotificationInboxListQuery) (outbound.NotificationInboxPage, error) {
page := outbound.NotificationInboxPage{}
for _, entry := range repository.entries {
if !repository.ignoreListScope && (entry.RecipientUserID() != query.RecipientUserID || (query.OrganizationID != nil && entry.OrganizationID() != *query.OrganizationID)) {
continue
}
page.Items = append(page.Items, entry)
}
return page, nil
}
func (repository *memoryInboxRepository) MarkRead(
_ context.Context,
recipientUserID 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 {
continue
}
read, err := entry.MarkRead(at)
if err != nil {
return domain.NotificationInboxEntry{}, err
}
repository.entries[index] = read
return read, nil
}
return domain.NotificationInboxEntry{}, outbound.ErrNotificationInboxEntryNotFound
}
func sameInboxEvent(left, right domain.NotificationInboxEntry) bool {
return left.OrganizationID() == right.OrganizationID() && left.EventType() == right.EventType() &&
left.SchemaVersion() == right.SchemaVersion() && left.SourceType() == right.SourceType() &&
left.SourceID() == right.SourceID() && left.OccurredAt().Equal(right.OccurredAt())
}
type memoryInboxResolver struct {
unavailable map[uuid.UUID]bool
calls int
}
func (resolver *memoryInboxResolver) Resolve(_ context.Context, entry domain.NotificationInboxEntry) (InboxContent, error) {
resolver.calls++
if resolver.unavailable[entry.EventID()] {
return InboxContent{}, ErrInboxContentUnavailable
}
return NewInboxContent("Приглашение", "Проверьте новое приглашение.", "/candidate/invitations")
}