forked from mtusi2026/mtusi2026lab6
feat: add bounded observability and verified SLO incident alerts
This commit is contained in:
@@ -0,0 +1,62 @@
|
||||
package production
|
||||
|
||||
import (
|
||||
"context"
|
||||
"slices"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/service"
|
||||
)
|
||||
|
||||
// parseIdentity maps malformed identity values to the authentication error.
|
||||
func parseIdentity(rawID string) (uuid.UUID, error) {
|
||||
id, err := parseID(rawID)
|
||||
if err != nil {
|
||||
return uuid.Nil, service.ErrUnauthorized
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
// requireUserID resolves an existing identity without loading a user profile.
|
||||
func (s *Service) requireUserID(ctx context.Context, rawID string) (uuid.UUID, error) {
|
||||
id, err := parseIdentity(rawID)
|
||||
if err != nil {
|
||||
return uuid.Nil, err
|
||||
}
|
||||
exists, err := s.repo.UsersExist(ctx, []uuid.UUID{id})
|
||||
if err != nil {
|
||||
return uuid.Nil, normalizeStoreError(err)
|
||||
}
|
||||
if !exists {
|
||||
return uuid.Nil, service.ErrUnauthorized
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
// requireChatMember resolves an existing caller and a chat available to that caller.
|
||||
func (s *Service) requireChatMember(ctx context.Context, userID, chatID string) (uuid.UUID, dto.ChatDTO, error) {
|
||||
caller, err := s.requireUserID(ctx, userID)
|
||||
if err != nil {
|
||||
return uuid.Nil, dto.ChatDTO{}, err
|
||||
}
|
||||
chat, err := s.findChat(ctx, chatID)
|
||||
if err != nil {
|
||||
return uuid.Nil, dto.ChatDTO{}, err
|
||||
}
|
||||
if !slices.Contains(chat.MemberIDs, caller) {
|
||||
return uuid.Nil, dto.ChatDTO{}, service.ErrNotFound
|
||||
}
|
||||
return caller, chat, nil
|
||||
}
|
||||
|
||||
// findChat parses a chat identifier and translates storage lookup errors.
|
||||
func (s *Service) findChat(ctx context.Context, rawID string) (dto.ChatDTO, error) {
|
||||
id, err := parseID(rawID)
|
||||
if err != nil {
|
||||
return dto.ChatDTO{}, err
|
||||
}
|
||||
chat, err := s.repo.Chat(ctx, id)
|
||||
return chat, normalizeStoreError(err)
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package production
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/cursor"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto"
|
||||
)
|
||||
|
||||
type cacheFixture struct {
|
||||
profile dto.UserDTO
|
||||
hit bool
|
||||
writes int
|
||||
}
|
||||
|
||||
// GetProfile returns the arranged optional-cache lookup outcome.
|
||||
func (f *cacheFixture) GetProfile(context.Context, uuid.UUID) (dto.UserDTO, bool) {
|
||||
return f.profile, f.hit
|
||||
}
|
||||
|
||||
// PutProfile records successful cache population from authoritative data.
|
||||
func (f *cacheFixture) PutProfile(_ context.Context, user dto.UserDTO) {
|
||||
f.profile = user
|
||||
f.writes++
|
||||
}
|
||||
|
||||
// TestProfileCacheHitAvoidsProfileQuery verifies that the cache has a concrete role.
|
||||
func TestProfileCacheHitAvoidsProfileQuery(t *testing.T) {
|
||||
codec, err := cursor.New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cache := &cacheFixture{profile: dto.UserDTO{ID: uuid.New()}, hit: true}
|
||||
svc, err := NewCached(&storeStub{t: t}, codec, cache)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := svc.UsersGetMe(t.Context(), cache.profile.ID.String())
|
||||
if err != nil || got.ID != cache.profile.ID {
|
||||
t.Fatalf("cache hit ignored: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestProfileCacheMissPopulatesAfterDatabaseRead checks the authoritative fallback.
|
||||
func TestProfileCacheMissPopulatesAfterDatabaseRead(t *testing.T) {
|
||||
codec, err := cursor.New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
id := uuid.New()
|
||||
repo := &storeStub{t: t, user: func(context.Context, uuid.UUID) (dto.UserDTO, error) {
|
||||
return dto.UserDTO{ID: id}, nil
|
||||
}}
|
||||
cache := &cacheFixture{}
|
||||
svc, err := NewCached(repo, codec, cache)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := svc.UsersGetMe(t.Context(), id.String())
|
||||
if err != nil || got.ID != id || cache.writes != 1 {
|
||||
t.Fatalf("fallback failed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCachedServiceRejectsMissingDependencies checks explicit service boundaries.
|
||||
func TestCachedServiceRejectsMissingDependencies(t *testing.T) {
|
||||
t.Run("store", func(t *testing.T) {
|
||||
if _, err := NewCached(nil, nil, &cacheFixture{}); err == nil {
|
||||
t.Fatal("missing store accepted")
|
||||
}
|
||||
})
|
||||
t.Run("cache", func(t *testing.T) {
|
||||
codec, err := cursor.New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := NewCached(&storeStub{t: t}, codec, nil); err == nil {
|
||||
t.Fatal("missing cache accepted")
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package production
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto"
|
||||
)
|
||||
|
||||
// ChatsCreate resolves the caller, validates the proposed chat and persists it atomically.
|
||||
func (s *Service) ChatsCreate(ctx context.Context, request dto.ChatsCreateRequestDTO) (dto.ChatDTO, error) {
|
||||
caller, err := s.requireUserID(ctx, request.UserID)
|
||||
if err != nil {
|
||||
return dto.ChatDTO{}, err
|
||||
}
|
||||
chat, err := prepareChat(request, caller)
|
||||
if err != nil {
|
||||
return dto.ChatDTO{}, err
|
||||
}
|
||||
if err := s.requireExistingMembers(ctx, chat.MemberIDs); err != nil {
|
||||
return dto.ChatDTO{}, err
|
||||
}
|
||||
created, err := s.repo.CreateChat(ctx, chat)
|
||||
return created, normalizeStoreError(err)
|
||||
}
|
||||
|
||||
// ChatsGetByID returns a chat only to a current member, hiding its existence otherwise.
|
||||
func (s *Service) ChatsGetByID(ctx context.Context, userID, chatID string) (dto.ChatDTO, error) {
|
||||
_, chat, err := s.requireChatMember(ctx, userID, chatID)
|
||||
return chat, err
|
||||
}
|
||||
|
||||
// ChatsGetPage authorizes the caller, loads a page and prepares its continuation.
|
||||
func (s *Service) ChatsGetPage(ctx context.Context, request dto.PageRequestDTO) (dto.ChatPageDTO, error) {
|
||||
caller, err := s.requireUserID(ctx, request.UserID)
|
||||
if err != nil {
|
||||
return dto.ChatPageDTO{}, err
|
||||
}
|
||||
page, err := s.parsePage(request, chatListResource(caller))
|
||||
if err != nil {
|
||||
return dto.ChatPageDTO{}, err
|
||||
}
|
||||
items, err := s.repo.Chats(ctx, caller, page.position, page.fetchLimit())
|
||||
if err != nil {
|
||||
return dto.ChatPageDTO{}, normalizeStoreError(err)
|
||||
}
|
||||
return s.chatPage(items, page)
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
package production
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/cursor"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/service"
|
||||
)
|
||||
|
||||
// TestService_ChatsGetPage validates access and pagination before issuing a typed store query.
|
||||
func TestService_ChatsGetPage(t *testing.T) {
|
||||
t.Run("Positive: continuation uses scope, position and lookahead", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
actor := uuid.New()
|
||||
allowIdentity(repo, actor)
|
||||
|
||||
previous := cursor.Position{ID: uuid.New(), CreatedAt: time.Unix(1700000000, 0).UTC()}
|
||||
records := []dto.ChatDTO{
|
||||
{ID: uuid.New(), CreatedAt: time.Unix(1700000001, 0).UTC()},
|
||||
{ID: uuid.New(), CreatedAt: time.Unix(1700000002, 0).UTC()},
|
||||
{ID: uuid.New(), CreatedAt: time.Unix(1700000003, 0).UTC()},
|
||||
}
|
||||
calls := 0
|
||||
repo.chats = func(_ context.Context, id uuid.UUID, position dto.PositionDTO, limit int) ([]dto.ChatDTO, error) {
|
||||
calls++
|
||||
expected := dto.PositionDTO{ID: previous.ID, CreatedAt: previous.CreatedAt}
|
||||
if id != actor || position != expected || limit != 3 {
|
||||
t.Fatalf("wrong page query: id=%s, position=%v, limit=%d", id, position, limit)
|
||||
}
|
||||
return records, nil
|
||||
}
|
||||
svc := newStubService(t, repo)
|
||||
resource := "chats:" + actor.String()
|
||||
token, err := svc.cursors.Encode(resource, previous)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
input := dto.PageRequestDTO{UserID: actor.String(), Limit: "2", Cursor: token}
|
||||
|
||||
// Act.
|
||||
got, err := svc.ChatsGetPage(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if calls != 1 || !reflect.DeepEqual(got.Items, records[:2]) || got.NextCursor == nil {
|
||||
t.Fatalf("calls=%d, page=%+v", calls, got)
|
||||
}
|
||||
position, err := svc.cursors.Decode(*got.NextCursor, resource)
|
||||
expected := cursor.Position{ID: records[1].ID, CreatedAt: records[1].CreatedAt}
|
||||
if err != nil || position != expected {
|
||||
t.Fatalf("next position=%v, want=%v, error=%v", position, expected, err)
|
||||
}
|
||||
|
||||
})
|
||||
|
||||
t.Run("Positive: empty history uses default limit and no continuation", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
actor := uuid.New()
|
||||
allowIdentity(repo, actor)
|
||||
|
||||
calls := 0
|
||||
repo.chats = func(_ context.Context, id uuid.UUID, position dto.PositionDTO, limit int) ([]dto.ChatDTO, error) {
|
||||
calls++
|
||||
if id != actor || position != (dto.PositionDTO{}) || limit != 51 {
|
||||
t.Fatalf("wrong initial page query: id=%s, position=%v, limit=%d", id, position, limit)
|
||||
}
|
||||
return []dto.ChatDTO{}, nil
|
||||
}
|
||||
svc := newStubService(t, repo)
|
||||
input := dto.PageRequestDTO{UserID: actor.String()}
|
||||
|
||||
// Act.
|
||||
got, err := svc.ChatsGetPage(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if calls != 1 || got.Items == nil || len(got.Items) != 0 || got.NextCursor != nil {
|
||||
t.Fatalf("calls=%d, page=%+v", calls, got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: cursor for another resource skips page lookup", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
actor := uuid.New()
|
||||
allowIdentity(repo, actor)
|
||||
|
||||
svc := newStubService(t, repo)
|
||||
token, err := svc.cursors.Encode("another-resource", cursor.Position{ID: uuid.New(), CreatedAt: time.Unix(1700000000, 0).UTC()})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
input := dto.PageRequestDTO{UserID: actor.String(), Cursor: token}
|
||||
|
||||
// Act.
|
||||
got, err := svc.ChatsGetPage(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, service.ErrInvalid) || len(got.Items) != 0 || got.NextCursor != nil {
|
||||
t.Fatalf("page=%+v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: codec failure skips page lookup", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
actor := uuid.New()
|
||||
allowIdentity(repo, actor)
|
||||
|
||||
failure := errors.New("cursor unavailable")
|
||||
svc := newStubService(t, repo)
|
||||
svc.cursors = failingCursor{failure: failure}
|
||||
input := dto.PageRequestDTO{UserID: actor.String(), Cursor: "token"}
|
||||
|
||||
// Act.
|
||||
got, err := svc.ChatsGetPage(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, failure) || len(got.Items) != 0 || got.NextCursor != nil {
|
||||
t.Fatalf("page=%+v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: page storage fails", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
actor := uuid.New()
|
||||
allowIdentity(repo, actor)
|
||||
|
||||
failure := errors.New("page unavailable")
|
||||
repo.chats = func(_ context.Context, _ uuid.UUID, _ dto.PositionDTO, _ int) ([]dto.ChatDTO, error) {
|
||||
return nil, failure
|
||||
}
|
||||
svc := newStubService(t, repo)
|
||||
input := dto.PageRequestDTO{UserID: actor.String()}
|
||||
|
||||
// Act.
|
||||
got, err := svc.ChatsGetPage(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, failure) || len(got.Items) != 0 || got.NextCursor != nil {
|
||||
t.Fatalf("page=%+v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: malformed identity skips all storage", func(t *testing.T) {
|
||||
// Arrange.
|
||||
svc := newStubService(t, newStoreStub(t))
|
||||
input := dto.PageRequestDTO{UserID: "invalid", ChatID: uuid.NewString()}
|
||||
|
||||
// Act.
|
||||
got, err := svc.ChatsGetPage(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, service.ErrUnauthorized) || len(got.Items) != 0 || got.NextCursor != nil {
|
||||
t.Fatalf("page=%+v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestService_ChatsGetPage_InvalidLimit rejects invalid limits before reading stored pages.
|
||||
func TestService_ChatsGetPage_InvalidLimit(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
limit string
|
||||
}{
|
||||
{"Negative: zero limit", "0"},
|
||||
{"Negative: negative limit", "-1"},
|
||||
{"Negative: limit above maximum", "101"},
|
||||
{"Negative: nonnumeric limit", "text"},
|
||||
{"Negative: fractional limit", "1.5"},
|
||||
{"Negative: integer overflow", "99999999999999999999999999"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
actor := uuid.New()
|
||||
allowIdentity(repo, actor)
|
||||
|
||||
svc := newStubService(t, repo)
|
||||
input := dto.PageRequestDTO{UserID: actor.String(), Limit: tc.limit}
|
||||
|
||||
// Act.
|
||||
got, err := svc.ChatsGetPage(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, service.ErrInvalid) || len(got.Items) != 0 || got.NextCursor != nil {
|
||||
t.Fatalf("page=%+v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
package production
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"reflect"
|
||||
"slices"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/service"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/store"
|
||||
)
|
||||
|
||||
// TestService_ChatsCreate checks membership in one batch and persists only validated chats.
|
||||
func TestService_ChatsCreate(t *testing.T) {
|
||||
t.Run("Positive: one membership query and original chat fields", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
actor, other := uuid.New(), uuid.New()
|
||||
var queries [][]uuid.UUID
|
||||
repo.usersExist = func(_ context.Context, ids []uuid.UUID) (bool, error) {
|
||||
queries = append(queries, slices.Clone(ids))
|
||||
return true, nil
|
||||
}
|
||||
var persisted dto.ChatDTO
|
||||
repo.createChat = func(_ context.Context, input dto.ChatDTO) (dto.ChatDTO, error) {
|
||||
persisted = input
|
||||
input.CreatedAt = time.Unix(1700000000, 0).UTC()
|
||||
return input, nil
|
||||
}
|
||||
svc := newStubService(t, repo)
|
||||
input := dto.ChatsCreateRequestDTO{UserID: actor.String(), Title: " Team 👋 ", MemberIDs: []string{actor.String(), other.String()}}
|
||||
|
||||
// Act.
|
||||
got, err := svc.ChatsCreate(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(queries, [][]uuid.UUID{{actor}, {actor, other}}) {
|
||||
t.Fatalf("existence queries=%v", queries)
|
||||
}
|
||||
if persisted.ID == uuid.Nil || persisted.Title != input.Title || !slices.Equal(persisted.MemberIDs, []uuid.UUID{actor, other}) {
|
||||
t.Fatalf("wrong persistence input: %+v", persisted)
|
||||
}
|
||||
if got.ID != persisted.ID || got.CreatedAt.IsZero() || got.Title != input.Title || !slices.Equal(got.MemberIDs, persisted.MemberIDs) {
|
||||
t.Fatalf("wrong returned chat: %+v", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: unknown member prevents persistence", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
actor, missing := uuid.New(), uuid.New()
|
||||
repo.usersExist = func(_ context.Context, ids []uuid.UUID) (bool, error) {
|
||||
return !slices.Contains(ids, missing), nil
|
||||
}
|
||||
svc := newStubService(t, repo)
|
||||
input := dto.ChatsCreateRequestDTO{UserID: actor.String(), Title: "Team", MemberIDs: []string{actor.String(), missing.String()}}
|
||||
|
||||
// Act.
|
||||
got, err := svc.ChatsCreate(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, service.ErrInvalid) || !reflect.DeepEqual(got, dto.ChatDTO{}) {
|
||||
t.Fatalf("result=%+v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: membership lookup failure prevents persistence", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
actor, other := uuid.New(), uuid.New()
|
||||
failure := errors.New("membership unavailable")
|
||||
repo.usersExist = func(_ context.Context, ids []uuid.UUID) (bool, error) {
|
||||
if len(ids) == 1 {
|
||||
return true, nil
|
||||
}
|
||||
return false, failure
|
||||
}
|
||||
svc := newStubService(t, repo)
|
||||
input := dto.ChatsCreateRequestDTO{UserID: actor.String(), Title: "Team", MemberIDs: []string{actor.String(), other.String()}}
|
||||
|
||||
// Act.
|
||||
got, err := svc.ChatsCreate(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, failure) || !reflect.DeepEqual(got, dto.ChatDTO{}) {
|
||||
t.Fatalf("result=%+v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: unknown creator prevents membership and persistence calls", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
repo.usersExist = func(_ context.Context, _ []uuid.UUID) (bool, error) {
|
||||
return false, nil
|
||||
}
|
||||
svc := newStubService(t, repo)
|
||||
actor := uuid.New()
|
||||
input := dto.ChatsCreateRequestDTO{UserID: actor.String(), Title: "Team", MemberIDs: []string{actor.String()}}
|
||||
|
||||
// Act.
|
||||
got, err := svc.ChatsCreate(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, service.ErrUnauthorized) || !reflect.DeepEqual(got, dto.ChatDTO{}) {
|
||||
t.Fatalf("result=%+v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestService_ChatsCreate_InvalidInput rejects malformed chat fields before checking member existence.
|
||||
func TestService_ChatsCreate_InvalidInput(t *testing.T) {
|
||||
actor := uuid.New()
|
||||
cases := []struct {
|
||||
name string
|
||||
title string
|
||||
members []string
|
||||
}{
|
||||
{"Negative: empty member set", "Team", nil},
|
||||
{"Negative: duplicate member", "Team", []string{actor.String(), actor.String()}},
|
||||
{"Negative: caller omitted", "Team", []string{uuid.NewString()}},
|
||||
{"Negative: malformed member ID", "Team", []string{actor.String(), "invalid"}},
|
||||
{"Negative: blank title", " ", []string{actor.String()}},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
calls := 0
|
||||
repo.usersExist = func(_ context.Context, ids []uuid.UUID) (bool, error) {
|
||||
calls++
|
||||
if calls != 1 || !slices.Equal(ids, []uuid.UUID{actor}) {
|
||||
t.Fatalf("unexpected membership check: %v", ids)
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
svc := newStubService(t, repo)
|
||||
input := dto.ChatsCreateRequestDTO{UserID: actor.String(), Title: tc.title, MemberIDs: tc.members}
|
||||
|
||||
// Act.
|
||||
got, err := svc.ChatsCreate(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, service.ErrInvalid) || !reflect.DeepEqual(got, dto.ChatDTO{}) {
|
||||
t.Fatalf("result=%+v, error=%v", got, err)
|
||||
}
|
||||
if calls != 1 {
|
||||
t.Fatalf("identity checks=%d, want=1", calls)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestService_ChatsGetByID authorizes the requested chat and conceals inaccessible records.
|
||||
func TestService_ChatsGetByID(t *testing.T) {
|
||||
t.Run("Positive: member receives the complete chat", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
actor := uuid.New()
|
||||
expected := dto.ChatDTO{ID: uuid.New(), Title: "Team", MemberIDs: []uuid.UUID{actor}, CreatedAt: time.Unix(1700000000, 0).UTC()}
|
||||
allowChatAccess(repo, actor, expected)
|
||||
svc := newStubService(t, repo)
|
||||
|
||||
// Act.
|
||||
got, err := svc.ChatsGetByID(t.Context(), actor.String(), expected.ID.String())
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(got, expected) {
|
||||
t.Fatalf("chat=%+v, want=%+v", got, expected)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: outsider receives no chat details", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
actor := uuid.New()
|
||||
chat := dto.ChatDTO{ID: uuid.New(), Title: "Private", MemberIDs: []uuid.UUID{uuid.New()}}
|
||||
allowChatAccess(repo, actor, chat)
|
||||
svc := newStubService(t, repo)
|
||||
|
||||
// Act.
|
||||
got, err := svc.ChatsGetByID(t.Context(), actor.String(), chat.ID.String())
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, service.ErrNotFound) || !reflect.DeepEqual(got, dto.ChatDTO{}) {
|
||||
t.Fatalf("private chat exposed: %+v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: malformed chat ID skips chat lookup", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
actor := uuid.New()
|
||||
allowIdentity(repo, actor)
|
||||
svc := newStubService(t, repo)
|
||||
|
||||
// Act.
|
||||
got, err := svc.ChatsGetByID(t.Context(), actor.String(), "invalid")
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, service.ErrInvalid) || !reflect.DeepEqual(got, dto.ChatDTO{}) {
|
||||
t.Fatalf("result=%+v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: malformed identity skips storage", func(t *testing.T) {
|
||||
// Arrange.
|
||||
svc := newStubService(t, newStoreStub(t))
|
||||
|
||||
// Act.
|
||||
got, err := svc.ChatsGetByID(t.Context(), "invalid", uuid.NewString())
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, service.ErrUnauthorized) || !reflect.DeepEqual(got, dto.ChatDTO{}) {
|
||||
t.Fatalf("result=%+v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestService_ChatsGetByID_StoreErrors translates missing records and retains unexpected failures.
|
||||
func TestService_ChatsGetByID_StoreErrors(t *testing.T) {
|
||||
failure := errors.New("chat lookup unavailable")
|
||||
cases := []struct {
|
||||
name string
|
||||
cause error
|
||||
want error
|
||||
}{
|
||||
{"Negative: absent chat", store.ErrNotFound, service.ErrNotFound},
|
||||
{"Negative: storage unavailable", failure, failure},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
actor := uuid.New()
|
||||
allowIdentity(repo, actor)
|
||||
repo.chat = func(_ context.Context, _ uuid.UUID) (dto.ChatDTO, error) {
|
||||
return dto.ChatDTO{}, tc.cause
|
||||
}
|
||||
svc := newStubService(t, repo)
|
||||
|
||||
// Act.
|
||||
got, err := svc.ChatsGetByID(t.Context(), actor.String(), uuid.NewString())
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, tc.want) || !reflect.DeepEqual(got, dto.ChatDTO{}) {
|
||||
t.Fatalf("result=%+v, error=%v, want=%v", got, err, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package production
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/service"
|
||||
)
|
||||
|
||||
// PrepareUser validates registration fields and assigns the new user identifier.
|
||||
func PrepareUser(request dto.UsersCreateRequestDTO) (dto.UserDTO, error) {
|
||||
if !validUsername(request.Username) || !validText(request.DisplayName, maxDisplayNameRunes) {
|
||||
return dto.UserDTO{}, service.ErrInvalid
|
||||
}
|
||||
return dto.UserDTO{
|
||||
ID: uuid.New(),
|
||||
Username: request.Username,
|
||||
DisplayName: request.DisplayName,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// prepareChat validates the title and member identifiers before storage access.
|
||||
func prepareChat(request dto.ChatsCreateRequestDTO, caller uuid.UUID) (dto.ChatDTO, error) {
|
||||
if !validText(request.Title, maxChatTitleRunes) {
|
||||
return dto.ChatDTO{}, service.ErrInvalid
|
||||
}
|
||||
members, err := parseMembers(request.MemberIDs, caller)
|
||||
if err != nil {
|
||||
return dto.ChatDTO{}, err
|
||||
}
|
||||
return dto.ChatDTO{
|
||||
ID: uuid.New(),
|
||||
Title: request.Title,
|
||||
MemberIDs: members,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// prepareMessage validates text and creates a record for the authorized sender and chat.
|
||||
func prepareMessage(request dto.MessagesCreateRequestDTO, sender, chatID uuid.UUID) (dto.MessageDTO, error) {
|
||||
if (strings.TrimSpace(request.Text) == "" && len(request.AttachmentIDs) == 0) || !utf8.ValidString(request.Text) || utf8.RuneCountInString(request.Text) > maxMessageRunes || len(request.AttachmentIDs) > 10 || !validIdempotencyKey(request.IdempotencyKey) {
|
||||
return dto.MessageDTO{}, service.ErrInvalid
|
||||
}
|
||||
seen := make(map[string]bool)
|
||||
for _, id := range request.AttachmentIDs {
|
||||
if _, err := parseID(id); err != nil || seen[id] {
|
||||
return dto.MessageDTO{}, service.ErrInvalid
|
||||
}
|
||||
seen[id] = true
|
||||
}
|
||||
return dto.MessageDTO{
|
||||
ID: uuid.New(),
|
||||
ChatID: chatID,
|
||||
SenderID: sender,
|
||||
Text: request.Text,
|
||||
AttachmentIDs: append([]string{}, request.AttachmentIDs...),
|
||||
IdempotencyKey: request.IdempotencyKey,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// validIdempotencyKey accepts only the bounded ASCII alphabet from the contract.
|
||||
func validIdempotencyKey(key string) bool {
|
||||
if len(key) < 1 || len(key) > 128 {
|
||||
return false
|
||||
}
|
||||
for _, c := range key {
|
||||
if c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '.' || c == '_' || c == ':' || c == '-' {
|
||||
continue
|
||||
}
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package production
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/service"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/store"
|
||||
)
|
||||
|
||||
// normalizeStoreError maps expected storage failures to application errors.
|
||||
// Unexpected failures retain their cause for the transport's safe fallback.
|
||||
func normalizeStoreError(err error) error {
|
||||
switch {
|
||||
case errors.Is(err, store.ErrNotFound):
|
||||
return service.ErrNotFound
|
||||
case errors.Is(err, store.ErrConflict):
|
||||
return service.ErrConflict
|
||||
case errors.Is(err, store.ErrCapacity):
|
||||
return service.ErrCapacity
|
||||
default:
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
package production
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/cursor"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto"
|
||||
)
|
||||
|
||||
// storeStub permits only the interactions explicitly arranged by each service scenario.
|
||||
type storeStub struct {
|
||||
t *testing.T
|
||||
createUser func(ctx context.Context, user dto.UserDTO) (dto.UserDTO, error)
|
||||
user func(ctx context.Context, id uuid.UUID) (dto.UserDTO, error)
|
||||
usersExist func(ctx context.Context, ids []uuid.UUID) (bool, error)
|
||||
createChat func(ctx context.Context, chat dto.ChatDTO) (dto.ChatDTO, error)
|
||||
chat func(ctx context.Context, id uuid.UUID) (dto.ChatDTO, error)
|
||||
chats func(ctx context.Context, id uuid.UUID, position dto.PositionDTO, limit int) ([]dto.ChatDTO, error)
|
||||
createMessage func(ctx context.Context, message dto.MessageDTO) (dto.MessageDTO, error)
|
||||
messages func(ctx context.Context, id uuid.UUID, position dto.PositionDTO, limit int) ([]dto.MessageDTO, error)
|
||||
}
|
||||
|
||||
// CreateUser delegates to the arranged behavior and rejects unexpected storage access.
|
||||
func (repo *storeStub) CreateUser(ctx context.Context, user dto.UserDTO) (dto.UserDTO, error) {
|
||||
repo.t.Helper()
|
||||
if repo.createUser == nil {
|
||||
repo.t.Fatalf("unexpected store.CreateUser call")
|
||||
return dto.UserDTO{}, nil
|
||||
}
|
||||
return repo.createUser(ctx, user)
|
||||
}
|
||||
|
||||
// User delegates to the arranged behavior and rejects unexpected storage access.
|
||||
func (repo *storeStub) User(ctx context.Context, id uuid.UUID) (dto.UserDTO, error) {
|
||||
repo.t.Helper()
|
||||
if repo.user == nil {
|
||||
repo.t.Fatalf("unexpected store.User call")
|
||||
return dto.UserDTO{}, nil
|
||||
}
|
||||
return repo.user(ctx, id)
|
||||
}
|
||||
|
||||
// UsersExist delegates to the arranged behavior and rejects unexpected storage access.
|
||||
func (repo *storeStub) UsersExist(ctx context.Context, ids []uuid.UUID) (bool, error) {
|
||||
repo.t.Helper()
|
||||
if repo.usersExist == nil {
|
||||
repo.t.Fatalf("unexpected store.UsersExist call")
|
||||
return false, nil
|
||||
}
|
||||
return repo.usersExist(ctx, ids)
|
||||
}
|
||||
|
||||
// CreateChat delegates to the arranged behavior and rejects unexpected storage access.
|
||||
func (repo *storeStub) CreateChat(ctx context.Context, chat dto.ChatDTO) (dto.ChatDTO, error) {
|
||||
repo.t.Helper()
|
||||
if repo.createChat == nil {
|
||||
repo.t.Fatalf("unexpected store.CreateChat call")
|
||||
return dto.ChatDTO{}, nil
|
||||
}
|
||||
return repo.createChat(ctx, chat)
|
||||
}
|
||||
|
||||
// Chat delegates to the arranged behavior and rejects unexpected storage access.
|
||||
func (repo *storeStub) Chat(ctx context.Context, id uuid.UUID) (dto.ChatDTO, error) {
|
||||
repo.t.Helper()
|
||||
if repo.chat == nil {
|
||||
repo.t.Fatalf("unexpected store.Chat call")
|
||||
return dto.ChatDTO{}, nil
|
||||
}
|
||||
return repo.chat(ctx, id)
|
||||
}
|
||||
|
||||
// Chats delegates to the arranged behavior and rejects unexpected storage access.
|
||||
func (repo *storeStub) Chats(ctx context.Context, id uuid.UUID, position dto.PositionDTO, limit int) ([]dto.ChatDTO, error) {
|
||||
repo.t.Helper()
|
||||
if repo.chats == nil {
|
||||
repo.t.Fatalf("unexpected store.Chats call")
|
||||
return nil, nil
|
||||
}
|
||||
return repo.chats(ctx, id, position, limit)
|
||||
}
|
||||
|
||||
// CreateMessage delegates to the arranged behavior and rejects unexpected storage access.
|
||||
func (repo *storeStub) CreateMessage(ctx context.Context, message dto.MessageDTO) (dto.MessageDTO, error) {
|
||||
repo.t.Helper()
|
||||
if repo.createMessage == nil {
|
||||
repo.t.Fatalf("unexpected store.CreateMessage call")
|
||||
return dto.MessageDTO{}, nil
|
||||
}
|
||||
return repo.createMessage(ctx, message)
|
||||
}
|
||||
|
||||
// Messages delegates to the arranged behavior and rejects unexpected storage access.
|
||||
func (repo *storeStub) Messages(ctx context.Context, id uuid.UUID, position dto.PositionDTO, limit int) ([]dto.MessageDTO, error) {
|
||||
repo.t.Helper()
|
||||
if repo.messages == nil {
|
||||
repo.t.Fatalf("unexpected store.Messages call")
|
||||
return nil, nil
|
||||
}
|
||||
return repo.messages(ctx, id, position, limit)
|
||||
}
|
||||
|
||||
// newStoreStub creates a repository that fails on every unarranged interaction.
|
||||
func newStoreStub(t *testing.T) *storeStub {
|
||||
t.Helper()
|
||||
return &storeStub{t: t}
|
||||
}
|
||||
|
||||
// newStubService composes the service with controlled storage and a real cursor codec.
|
||||
func newStubService(t *testing.T, repo *storeStub) *Service {
|
||||
t.Helper()
|
||||
codec, err := cursor.New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
svc, err := New(repo, codec)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return svc
|
||||
}
|
||||
|
||||
// allowIdentity permits exactly the arranged actor's existence lookup, never a profile read.
|
||||
func allowIdentity(repo *storeStub, actor uuid.UUID) {
|
||||
repo.t.Helper()
|
||||
repo.usersExist = func(_ context.Context, ids []uuid.UUID) (bool, error) {
|
||||
if len(ids) != 1 || ids[0] != actor {
|
||||
repo.t.Fatalf("unexpected identity query: %v", ids)
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
|
||||
// allowChatAccess supplies a typed chat after checking the lookup key at the service boundary.
|
||||
func allowChatAccess(repo *storeStub, actor uuid.UUID, chat dto.ChatDTO) {
|
||||
repo.t.Helper()
|
||||
allowIdentity(repo, actor)
|
||||
repo.chat = func(_ context.Context, id uuid.UUID) (dto.ChatDTO, error) {
|
||||
if id != chat.ID {
|
||||
repo.t.Fatalf("chat queried for %s, want %s", id, chat.ID)
|
||||
}
|
||||
return chat, nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package production
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/service"
|
||||
)
|
||||
|
||||
// parseMembers validates unique member identifiers and requires the caller to be included.
|
||||
func parseMembers(rawIDs []string, caller uuid.UUID) ([]uuid.UUID, error) {
|
||||
if len(rawIDs) == 0 || len(rawIDs) > maxChatMembers {
|
||||
return nil, service.ErrInvalid
|
||||
}
|
||||
members := make([]uuid.UUID, 0, len(rawIDs))
|
||||
seen := make(map[uuid.UUID]bool, len(rawIDs))
|
||||
for _, rawID := range rawIDs {
|
||||
id, err := parseID(rawID)
|
||||
if err != nil || seen[id] {
|
||||
return nil, service.ErrInvalid
|
||||
}
|
||||
seen[id] = true
|
||||
members = append(members, id)
|
||||
}
|
||||
if !seen[caller] {
|
||||
return nil, service.ErrInvalid
|
||||
}
|
||||
return members, nil
|
||||
}
|
||||
|
||||
// requireExistingMembers validates the complete membership set with one storage operation.
|
||||
func (s *Service) requireExistingMembers(ctx context.Context, members []uuid.UUID) error {
|
||||
exists, err := s.repo.UsersExist(ctx, members)
|
||||
if err != nil {
|
||||
return normalizeStoreError(err)
|
||||
}
|
||||
if !exists {
|
||||
return service.ErrInvalid
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package production
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto"
|
||||
)
|
||||
|
||||
// MessagesCreate authorizes the sender, validates the message and stores it atomically.
|
||||
func (s *Service) MessagesCreate(ctx context.Context, request dto.MessagesCreateRequestDTO) (dto.MessageDTO, error) {
|
||||
caller, chat, err := s.requireChatMember(ctx, request.UserID, request.ChatID)
|
||||
if err != nil {
|
||||
return dto.MessageDTO{}, err
|
||||
}
|
||||
message, err := prepareMessage(request, caller, chat.ID)
|
||||
if err != nil {
|
||||
return dto.MessageDTO{}, err
|
||||
}
|
||||
created, err := s.repo.CreateMessage(ctx, message)
|
||||
return created, normalizeStoreError(err)
|
||||
}
|
||||
|
||||
// MessagesGetPage authorizes access, loads history and prepares its continuation.
|
||||
func (s *Service) MessagesGetPage(ctx context.Context, request dto.PageRequestDTO) (dto.MessagePageDTO, error) {
|
||||
_, chat, err := s.requireChatMember(ctx, request.UserID, request.ChatID)
|
||||
if err != nil {
|
||||
return dto.MessagePageDTO{}, err
|
||||
}
|
||||
page, err := s.parsePage(request, messageHistoryResource(chat.ID))
|
||||
if err != nil {
|
||||
return dto.MessagePageDTO{}, err
|
||||
}
|
||||
items, err := s.repo.Messages(ctx, chat.ID, page.position, page.fetchLimit())
|
||||
if err != nil {
|
||||
return dto.MessagePageDTO{}, normalizeStoreError(err)
|
||||
}
|
||||
return s.messagePage(items, page)
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
package production
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/cursor"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/service"
|
||||
)
|
||||
|
||||
// TestService_MessagesGetPage validates access and pagination before issuing a typed store query.
|
||||
func TestService_MessagesGetPage(t *testing.T) {
|
||||
t.Run("Positive: continuation uses scope, position and lookahead", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
actor := uuid.New()
|
||||
chat := dto.ChatDTO{ID: uuid.New(), MemberIDs: []uuid.UUID{actor}}
|
||||
allowChatAccess(repo, actor, chat)
|
||||
|
||||
previous := cursor.Position{ID: uuid.New(), CreatedAt: time.Unix(1700000000, 0).UTC()}
|
||||
records := []dto.MessageDTO{
|
||||
{ID: uuid.New(), CreatedAt: time.Unix(1700000001, 0).UTC()},
|
||||
{ID: uuid.New(), CreatedAt: time.Unix(1700000002, 0).UTC()},
|
||||
{ID: uuid.New(), CreatedAt: time.Unix(1700000003, 0).UTC()},
|
||||
}
|
||||
calls := 0
|
||||
repo.messages = func(_ context.Context, id uuid.UUID, position dto.PositionDTO, limit int) ([]dto.MessageDTO, error) {
|
||||
calls++
|
||||
expected := dto.PositionDTO{ID: previous.ID, CreatedAt: previous.CreatedAt}
|
||||
if id != chat.ID || position != expected || limit != 3 {
|
||||
t.Fatalf("wrong page query: id=%s, position=%v, limit=%d", id, position, limit)
|
||||
}
|
||||
return records, nil
|
||||
}
|
||||
svc := newStubService(t, repo)
|
||||
resource := "messages:" + chat.ID.String()
|
||||
token, err := svc.cursors.Encode(resource, previous)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
input := dto.PageRequestDTO{UserID: actor.String(), ChatID: chat.ID.String(), Limit: "2", Cursor: token}
|
||||
|
||||
// Act.
|
||||
got, err := svc.MessagesGetPage(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if calls != 1 || !reflect.DeepEqual(got.Items, records[:2]) || got.NextCursor == nil {
|
||||
t.Fatalf("calls=%d, page=%+v", calls, got)
|
||||
}
|
||||
position, err := svc.cursors.Decode(*got.NextCursor, resource)
|
||||
expected := cursor.Position{ID: records[1].ID, CreatedAt: records[1].CreatedAt}
|
||||
if err != nil || position != expected {
|
||||
t.Fatalf("next position=%v, want=%v, error=%v", position, expected, err)
|
||||
}
|
||||
|
||||
})
|
||||
|
||||
t.Run("Positive: empty history uses default limit and no continuation", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
actor := uuid.New()
|
||||
chat := dto.ChatDTO{ID: uuid.New(), MemberIDs: []uuid.UUID{actor}}
|
||||
allowChatAccess(repo, actor, chat)
|
||||
|
||||
calls := 0
|
||||
repo.messages = func(_ context.Context, id uuid.UUID, position dto.PositionDTO, limit int) ([]dto.MessageDTO, error) {
|
||||
calls++
|
||||
if id != chat.ID || position != (dto.PositionDTO{}) || limit != 51 {
|
||||
t.Fatalf("wrong initial page query: id=%s, position=%v, limit=%d", id, position, limit)
|
||||
}
|
||||
return []dto.MessageDTO{}, nil
|
||||
}
|
||||
svc := newStubService(t, repo)
|
||||
input := dto.PageRequestDTO{UserID: actor.String(), ChatID: chat.ID.String()}
|
||||
|
||||
// Act.
|
||||
got, err := svc.MessagesGetPage(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if calls != 1 || got.Items == nil || len(got.Items) != 0 || got.NextCursor != nil {
|
||||
t.Fatalf("calls=%d, page=%+v", calls, got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: cursor for another resource skips page lookup", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
actor := uuid.New()
|
||||
chat := dto.ChatDTO{ID: uuid.New(), MemberIDs: []uuid.UUID{actor}}
|
||||
allowChatAccess(repo, actor, chat)
|
||||
|
||||
svc := newStubService(t, repo)
|
||||
token, err := svc.cursors.Encode("another-resource", cursor.Position{ID: uuid.New(), CreatedAt: time.Unix(1700000000, 0).UTC()})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
input := dto.PageRequestDTO{UserID: actor.String(), ChatID: chat.ID.String(), Cursor: token}
|
||||
|
||||
// Act.
|
||||
got, err := svc.MessagesGetPage(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, service.ErrInvalid) || len(got.Items) != 0 || got.NextCursor != nil {
|
||||
t.Fatalf("page=%+v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: codec failure skips page lookup", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
actor := uuid.New()
|
||||
chat := dto.ChatDTO{ID: uuid.New(), MemberIDs: []uuid.UUID{actor}}
|
||||
allowChatAccess(repo, actor, chat)
|
||||
|
||||
failure := errors.New("cursor unavailable")
|
||||
svc := newStubService(t, repo)
|
||||
svc.cursors = failingCursor{failure: failure}
|
||||
input := dto.PageRequestDTO{UserID: actor.String(), ChatID: chat.ID.String(), Cursor: "token"}
|
||||
|
||||
// Act.
|
||||
got, err := svc.MessagesGetPage(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, failure) || len(got.Items) != 0 || got.NextCursor != nil {
|
||||
t.Fatalf("page=%+v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: page storage fails", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
actor := uuid.New()
|
||||
chat := dto.ChatDTO{ID: uuid.New(), MemberIDs: []uuid.UUID{actor}}
|
||||
allowChatAccess(repo, actor, chat)
|
||||
|
||||
failure := errors.New("page unavailable")
|
||||
repo.messages = func(_ context.Context, _ uuid.UUID, _ dto.PositionDTO, _ int) ([]dto.MessageDTO, error) {
|
||||
return nil, failure
|
||||
}
|
||||
svc := newStubService(t, repo)
|
||||
input := dto.PageRequestDTO{UserID: actor.String(), ChatID: chat.ID.String()}
|
||||
|
||||
// Act.
|
||||
got, err := svc.MessagesGetPage(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, failure) || len(got.Items) != 0 || got.NextCursor != nil {
|
||||
t.Fatalf("page=%+v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: malformed identity skips all storage", func(t *testing.T) {
|
||||
// Arrange.
|
||||
svc := newStubService(t, newStoreStub(t))
|
||||
input := dto.PageRequestDTO{UserID: "invalid", ChatID: uuid.NewString()}
|
||||
|
||||
// Act.
|
||||
got, err := svc.MessagesGetPage(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, service.ErrUnauthorized) || len(got.Items) != 0 || got.NextCursor != nil {
|
||||
t.Fatalf("page=%+v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: outsider cannot read message history", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
actor := uuid.New()
|
||||
chat := dto.ChatDTO{ID: uuid.New(), MemberIDs: []uuid.UUID{uuid.New()}}
|
||||
allowChatAccess(repo, actor, chat)
|
||||
svc := newStubService(t, repo)
|
||||
input := dto.PageRequestDTO{UserID: actor.String(), ChatID: chat.ID.String()}
|
||||
|
||||
// Act.
|
||||
got, err := svc.MessagesGetPage(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, service.ErrNotFound) || len(got.Items) != 0 || got.NextCursor != nil {
|
||||
t.Fatalf("page=%+v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestService_MessagesGetPage_InvalidLimit rejects invalid limits before reading stored pages.
|
||||
func TestService_MessagesGetPage_InvalidLimit(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
limit string
|
||||
}{
|
||||
{"Negative: zero limit", "0"},
|
||||
{"Negative: negative limit", "-1"},
|
||||
{"Negative: limit above maximum", "101"},
|
||||
{"Negative: nonnumeric limit", "text"},
|
||||
{"Negative: fractional limit", "1.5"},
|
||||
{"Negative: integer overflow", "99999999999999999999999999"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
actor := uuid.New()
|
||||
chat := dto.ChatDTO{ID: uuid.New(), MemberIDs: []uuid.UUID{actor}}
|
||||
allowChatAccess(repo, actor, chat)
|
||||
|
||||
svc := newStubService(t, repo)
|
||||
input := dto.PageRequestDTO{UserID: actor.String(), ChatID: chat.ID.String(), Limit: tc.limit}
|
||||
|
||||
// Act.
|
||||
got, err := svc.MessagesGetPage(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, service.ErrInvalid) || len(got.Items) != 0 || got.NextCursor != nil {
|
||||
t.Fatalf("page=%+v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
package production
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/service"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/store"
|
||||
)
|
||||
|
||||
// TestService_MessagesCreate authorizes the sender before validating and persisting the message.
|
||||
func TestService_MessagesCreate(t *testing.T) {
|
||||
t.Run("Positive: authenticated sender and original text persisted", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
actor := uuid.New()
|
||||
chat := dto.ChatDTO{ID: uuid.New(), MemberIDs: []uuid.UUID{actor}}
|
||||
allowChatAccess(repo, actor, chat)
|
||||
var persisted dto.MessageDTO
|
||||
repo.createMessage = func(_ context.Context, input dto.MessageDTO) (dto.MessageDTO, error) {
|
||||
persisted = input
|
||||
input.CreatedAt = time.Unix(1700000000, 0).UTC()
|
||||
return input, nil
|
||||
}
|
||||
svc := newStubService(t, repo)
|
||||
input := dto.MessagesCreateRequestDTO{IdempotencyKey: "fixture-key", UserID: actor.String(), ChatID: chat.ID.String(), Text: " Original 👋 "}
|
||||
|
||||
// Act.
|
||||
got, err := svc.MessagesCreate(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if persisted.ID == uuid.Nil || persisted.SenderID != actor || persisted.ChatID != chat.ID || persisted.Text != input.Text {
|
||||
t.Fatalf("wrong persistence input: %+v", persisted)
|
||||
}
|
||||
if got.ID != persisted.ID || got.SenderID != actor || got.ChatID != chat.ID || got.Text != input.Text || got.CreatedAt.IsZero() {
|
||||
t.Fatalf("wrong acknowledgement: %+v", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: outsider cannot persist messages", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
actor := uuid.New()
|
||||
chat := dto.ChatDTO{ID: uuid.New(), MemberIDs: []uuid.UUID{uuid.New()}}
|
||||
allowChatAccess(repo, actor, chat)
|
||||
svc := newStubService(t, repo)
|
||||
input := dto.MessagesCreateRequestDTO{IdempotencyKey: "fixture-key", UserID: actor.String(), ChatID: chat.ID.String(), Text: "Valid text"}
|
||||
|
||||
// Act.
|
||||
got, err := svc.MessagesCreate(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, service.ErrNotFound) || !reflect.DeepEqual(got, dto.MessageDTO{}) {
|
||||
t.Fatalf("result=%+v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: malformed identity skips storage", func(t *testing.T) {
|
||||
// Arrange.
|
||||
svc := newStubService(t, newStoreStub(t))
|
||||
input := dto.MessagesCreateRequestDTO{IdempotencyKey: "fixture-key", UserID: "invalid", ChatID: uuid.NewString(), Text: "text"}
|
||||
|
||||
// Act.
|
||||
got, err := svc.MessagesCreate(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, service.ErrUnauthorized) || !reflect.DeepEqual(got, dto.MessageDTO{}) {
|
||||
t.Fatalf("result=%+v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestService_MessagesCreate_InvalidText refuses invalid text without attempting persistence.
|
||||
func TestService_MessagesCreate_InvalidText(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
text string
|
||||
}{
|
||||
{"Negative: empty text", ""},
|
||||
{"Negative: whitespace only", " \t"},
|
||||
{"Negative: rune limit exceeded", strings.Repeat("界", 4001)},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
actor := uuid.New()
|
||||
chat := dto.ChatDTO{ID: uuid.New(), MemberIDs: []uuid.UUID{actor}}
|
||||
allowChatAccess(repo, actor, chat)
|
||||
svc := newStubService(t, repo)
|
||||
input := dto.MessagesCreateRequestDTO{IdempotencyKey: "fixture-key", UserID: actor.String(), ChatID: chat.ID.String(), Text: tc.text}
|
||||
|
||||
// Act.
|
||||
got, err := svc.MessagesCreate(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, service.ErrInvalid) || !reflect.DeepEqual(got, dto.MessageDTO{}) {
|
||||
t.Fatalf("result=%+v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestService_MessagesCreate_StoreErrors propagates persistence failures without acknowledging a record.
|
||||
func TestService_MessagesCreate_StoreErrors(t *testing.T) {
|
||||
failure := errors.New("write unavailable")
|
||||
cases := []struct {
|
||||
name string
|
||||
cause error
|
||||
want error
|
||||
}{
|
||||
{"Negative: capacity exhausted", store.ErrCapacity, service.ErrCapacity},
|
||||
{"Negative: chat disappeared", store.ErrNotFound, service.ErrNotFound},
|
||||
{"Negative: unexpected write failure", failure, failure},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
actor := uuid.New()
|
||||
chat := dto.ChatDTO{ID: uuid.New(), MemberIDs: []uuid.UUID{actor}}
|
||||
allowChatAccess(repo, actor, chat)
|
||||
repo.createMessage = func(_ context.Context, _ dto.MessageDTO) (dto.MessageDTO, error) {
|
||||
return dto.MessageDTO{}, tc.cause
|
||||
}
|
||||
svc := newStubService(t, repo)
|
||||
input := dto.MessagesCreateRequestDTO{IdempotencyKey: "fixture-key", UserID: actor.String(), ChatID: chat.ID.String(), Text: "Valid text"}
|
||||
|
||||
// Act.
|
||||
got, err := svc.MessagesCreate(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, tc.want) || !reflect.DeepEqual(got, dto.MessageDTO{}) {
|
||||
t.Fatalf("result=%+v, error=%v, want=%v", got, err, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestIdempotencyKeyValidation checks the exact contract alphabet and length independently.
|
||||
func TestIdempotencyKeyValidation(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
key string
|
||||
want bool
|
||||
}{
|
||||
{name: "missing", key: "", want: false},
|
||||
{name: "allowed alphabet", key: "aZ09._:-", want: true},
|
||||
{name: "space", key: "a b", want: false},
|
||||
{name: "unicode", key: "ключ", want: false},
|
||||
{name: "maximum", key: strings.Repeat("a", 128), want: true},
|
||||
{name: "too long", key: strings.Repeat("a", 129), want: false},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
if got := validIdempotencyKey(test.key); got != test.want {
|
||||
t.Fatalf("valid=%v want=%v", got, test.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package production
|
||||
|
||||
import (
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/cursor"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/service"
|
||||
)
|
||||
|
||||
// chatPage adapts the shared page result to the chat response DTO.
|
||||
func (s *Service) chatPage(items []dto.ChatDTO, page pagination) (dto.ChatPageDTO, error) {
|
||||
items, next, err := buildPage(items, page, s.cursors, chatPosition)
|
||||
if err != nil {
|
||||
return dto.ChatPageDTO{}, err
|
||||
}
|
||||
return dto.ChatPageDTO{Items: items, NextCursor: next}, nil
|
||||
}
|
||||
|
||||
// messagePage adapts the shared page result to the message response DTO.
|
||||
func (s *Service) messagePage(items []dto.MessageDTO, page pagination) (dto.MessagePageDTO, error) {
|
||||
items, next, err := buildPage(items, page, s.cursors, messagePosition)
|
||||
if err != nil {
|
||||
return dto.MessagePageDTO{}, err
|
||||
}
|
||||
return dto.MessagePageDTO{Items: items, NextCursor: next}, nil
|
||||
}
|
||||
|
||||
// buildPage trims lookahead and signs the last returned record when more data exists.
|
||||
// The page limit must be validated before calling this helper.
|
||||
func buildPage[T any](items []T, page pagination, codec service.CursorCodec, position func(T) cursor.Position) ([]T, *string, error) {
|
||||
if len(items) <= page.limit {
|
||||
return items, nil, nil
|
||||
}
|
||||
items = items[:page.limit]
|
||||
next, err := codec.Encode(page.resource, position(items[len(items)-1]))
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return items, new(next), nil
|
||||
}
|
||||
|
||||
// chatPosition extracts the stable pagination boundary from a stored chat.
|
||||
func chatPosition(chat dto.ChatDTO) cursor.Position {
|
||||
return cursor.Position{CreatedAt: chat.CreatedAt, ID: chat.ID}
|
||||
}
|
||||
|
||||
// messagePosition extracts the stable pagination boundary from a stored message.
|
||||
func messagePosition(message dto.MessageDTO) cursor.Position {
|
||||
return cursor.Position{CreatedAt: message.CreatedAt, ID: message.ID}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package production
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/cursor"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto"
|
||||
)
|
||||
|
||||
// TestService_messagePage checks boundaries and signs the last returned item, not lookahead.
|
||||
func TestService_messagePage(t *testing.T) {
|
||||
for _, count := range []int{0, 2, 3} {
|
||||
names := map[int]string{0: "Positive: empty page", 2: "Positive: exact limit is final", 3: "Positive: lookahead creates continuation"}
|
||||
t.Run(names[count], func(t *testing.T) {
|
||||
// Arrange.
|
||||
svc := newStubService(t, newStoreStub(t))
|
||||
items := make([]dto.MessageDTO, count)
|
||||
for i := range items {
|
||||
items[i] = dto.MessageDTO{ID: uuid.New(), Text: "message", CreatedAt: time.Unix(int64(i+1), 0).UTC()}
|
||||
}
|
||||
expected := items[:min(count, 2)]
|
||||
|
||||
// Act.
|
||||
page, err := svc.messagePage(items, pagination{limit: 2, resource: "messages:chat"})
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(page.Items, expected) {
|
||||
t.Fatalf("page=%v, want=%v", page.Items, expected)
|
||||
}
|
||||
if count <= 2 {
|
||||
if page.NextCursor != nil {
|
||||
t.Fatal("final page has a continuation")
|
||||
}
|
||||
return
|
||||
}
|
||||
if page.NextCursor == nil {
|
||||
t.Fatal("lookahead did not produce continuation")
|
||||
}
|
||||
decoded, err := svc.cursors.Decode(*page.NextCursor, "messages:chat")
|
||||
want := cursor.Position{ID: items[1].ID, CreatedAt: items[1].CreatedAt}
|
||||
if err != nil || decoded != want {
|
||||
t.Fatalf("cursor=%v, want=%v, error=%v", decoded, want, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package production
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strconv"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/cursor"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/service"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultPageLimit = 50
|
||||
maxPageLimit = 100
|
||||
// Fetching one extra record determines whether to issue a next cursor.
|
||||
pageLookahead = 1
|
||||
)
|
||||
|
||||
type pagination struct {
|
||||
position dto.PositionDTO
|
||||
limit int
|
||||
resource string
|
||||
}
|
||||
|
||||
// parsePage validates the page size and resource-bound cursor.
|
||||
func (s *Service) parsePage(request dto.PageRequestDTO, resource string) (pagination, error) {
|
||||
limit, err := parseLimit(request.Limit)
|
||||
if err != nil {
|
||||
return pagination{}, err
|
||||
}
|
||||
position, err := s.cursors.Decode(request.Cursor, resource)
|
||||
if errors.Is(err, cursor.ErrInvalid) {
|
||||
return pagination{}, service.ErrInvalid
|
||||
}
|
||||
if err != nil {
|
||||
return pagination{}, err
|
||||
}
|
||||
return pagination{
|
||||
position: dto.PositionDTO{CreatedAt: position.CreatedAt, ID: position.ID},
|
||||
limit: limit,
|
||||
resource: resource,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// parseLimit parses a bounded page size or supplies the default.
|
||||
func parseLimit(raw string) (int, error) {
|
||||
if raw == "" {
|
||||
return defaultPageLimit, nil
|
||||
}
|
||||
for _, char := range raw {
|
||||
if char < '0' || char > '9' {
|
||||
return 0, service.ErrInvalid
|
||||
}
|
||||
}
|
||||
limit, err := strconv.Atoi(raw)
|
||||
if err != nil || limit < 1 || limit > maxPageLimit {
|
||||
return 0, service.ErrInvalid
|
||||
}
|
||||
return limit, nil
|
||||
}
|
||||
|
||||
// fetchLimit includes one lookahead record to detect a following page.
|
||||
func (page pagination) fetchLimit() int {
|
||||
return page.limit + pageLookahead
|
||||
}
|
||||
|
||||
// chatListResource scopes a cursor to one user's visible chats.
|
||||
func chatListResource(userID uuid.UUID) string {
|
||||
return "chats:" + userID.String()
|
||||
}
|
||||
|
||||
// messageHistoryResource scopes a cursor to one chat's message history.
|
||||
func messageHistoryResource(chatID uuid.UUID) string {
|
||||
return "messages:" + chatID.String()
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package production
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/cursor"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/service"
|
||||
)
|
||||
|
||||
type failingCursor struct {
|
||||
failure error
|
||||
}
|
||||
|
||||
// Encode injects a signing failure at the service dependency boundary.
|
||||
func (codec failingCursor) Encode(_ string, _ cursor.Position) (string, error) {
|
||||
return "", codec.failure
|
||||
}
|
||||
|
||||
// Decode injects a verification failure at the service dependency boundary.
|
||||
func (codec failingCursor) Decode(_, _ string) (cursor.Position, error) {
|
||||
return cursor.Position{}, codec.failure
|
||||
}
|
||||
|
||||
// TestService_parsePage translates invalid tokens while retaining unexpected dependency failures.
|
||||
func TestService_parsePage(t *testing.T) {
|
||||
failure := errors.New("codec unavailable")
|
||||
cases := []struct {
|
||||
name string
|
||||
cause error
|
||||
want error
|
||||
}{
|
||||
{"Negative: invalid token", cursor.ErrInvalid, service.ErrInvalid},
|
||||
{"Negative: unavailable codec", failure, failure},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
// Arrange.
|
||||
svc := &Service{cursors: failingCursor{failure: tc.cause}}
|
||||
input := dto.PageRequestDTO{Cursor: "supplied-token"}
|
||||
|
||||
// Act.
|
||||
page, err := svc.parsePage(input, "messages:chat")
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, tc.want) {
|
||||
t.Fatalf("error=%v, want=%v", err, tc.want)
|
||||
}
|
||||
if page != (pagination{}) {
|
||||
t.Fatalf("failed cursor produced a page: %+v", page)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestService_messagePage_EncodeFailure returns no partial page when signing fails.
|
||||
func TestService_messagePage_EncodeFailure(t *testing.T) {
|
||||
// Arrange.
|
||||
failure := errors.New("signing unavailable")
|
||||
svc := &Service{cursors: failingCursor{failure: failure}}
|
||||
items := []dto.MessageDTO{{Text: "first"}, {Text: "lookahead"}}
|
||||
|
||||
// Act.
|
||||
page, err := svc.messagePage(items, pagination{limit: 1, resource: "messages:chat"})
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, failure) {
|
||||
t.Fatalf("lost signing failure: %v", err)
|
||||
}
|
||||
if page.Items != nil || page.NextCursor != nil {
|
||||
t.Fatalf("partial page escaped: %+v", page)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
// Package production implements the messenger application operations.
|
||||
package production
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/service"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/store"
|
||||
)
|
||||
|
||||
// Service orchestrates operations through storage and cursor interfaces.
|
||||
type Service struct {
|
||||
repo store.Interface
|
||||
cursors service.CursorCodec
|
||||
cache service.ProfileCache
|
||||
}
|
||||
|
||||
var _ service.Service = (*Service)(nil)
|
||||
|
||||
// New creates an application service using explicitly supplied dependencies.
|
||||
func New(repo store.Interface, cursors service.CursorCodec) (*Service, error) {
|
||||
if repo == nil || cursors == nil {
|
||||
return nil, fmt.Errorf("store and cursor codec are required")
|
||||
}
|
||||
return &Service{repo: repo, cursors: cursors}, nil
|
||||
}
|
||||
|
||||
// NewCached builds the business service with optional immutable-profile caching.
|
||||
func NewCached(repo store.Interface, cursors service.CursorCodec, cache service.ProfileCache) (*Service, error) {
|
||||
instance, err := New(repo, cursors)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if cache == nil {
|
||||
return nil, fmt.Errorf("profile cache is required")
|
||||
}
|
||||
instance.cache = cache
|
||||
return instance, nil
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package production
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/cursor"
|
||||
)
|
||||
|
||||
// TestService_New rejects each missing dependency separately.
|
||||
func TestService_New(t *testing.T) {
|
||||
t.Run("Negative: missing store", func(t *testing.T) {
|
||||
// Arrange.
|
||||
codec, err := cursor.New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Act.
|
||||
svc, err := New(nil, codec)
|
||||
|
||||
// Assert.
|
||||
if err == nil || svc != nil {
|
||||
t.Fatalf("service=%v, error=%v", svc, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: missing codec", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
|
||||
// Act.
|
||||
svc, err := New(repo, nil)
|
||||
|
||||
// Assert.
|
||||
if err == nil || svc != nil {
|
||||
t.Fatalf("service=%v, error=%v", svc, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package production
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/service"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/store"
|
||||
)
|
||||
|
||||
// UsersCreate validates registration and atomically reserves the unique username.
|
||||
func (s *Service) UsersCreate(ctx context.Context, request dto.UsersCreateRequestDTO) (dto.UserDTO, error) {
|
||||
user, err := PrepareUser(request)
|
||||
if err != nil {
|
||||
return dto.UserDTO{}, err
|
||||
}
|
||||
created, err := s.repo.CreateUser(ctx, user)
|
||||
return created, normalizeStoreError(err)
|
||||
}
|
||||
|
||||
// UsersGetMe loads the current user's profile; malformed and missing identities are unauthorized.
|
||||
func (s *Service) UsersGetMe(ctx context.Context, rawID string) (dto.UserDTO, error) {
|
||||
id, err := parseIdentity(rawID)
|
||||
if err != nil {
|
||||
return dto.UserDTO{}, err
|
||||
}
|
||||
if s.cache != nil {
|
||||
if cached, ok := s.cache.GetProfile(ctx, id); ok {
|
||||
return cached, nil
|
||||
}
|
||||
}
|
||||
user, err := s.repo.User(ctx, id)
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
return dto.UserDTO{}, service.ErrUnauthorized
|
||||
}
|
||||
if err == nil && s.cache != nil {
|
||||
s.cache.PutProfile(ctx, user)
|
||||
}
|
||||
return user, normalizeStoreError(err)
|
||||
}
|
||||
|
||||
// UsersCheckIdentity validates the current identity without loading its profile.
|
||||
func (s *Service) UsersCheckIdentity(ctx context.Context, rawID string) error {
|
||||
_, err := s.requireUserID(ctx, rawID)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,289 @@
|
||||
package production
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/service"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/store"
|
||||
)
|
||||
|
||||
// TestService_UsersCreate validates registration before persistence and preserves storage failures.
|
||||
func TestService_UsersCreate(t *testing.T) {
|
||||
t.Run("Positive: validates and persists the original profile", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
expected := dto.UserDTO{Username: "alice", DisplayName: "Алиса 👋", CreatedAt: time.Unix(1700000000, 0).UTC()}
|
||||
calls := 0
|
||||
repo.createUser = func(_ context.Context, input dto.UserDTO) (dto.UserDTO, error) {
|
||||
calls++
|
||||
if input.ID == uuid.Nil || input.Username != expected.Username || input.DisplayName != expected.DisplayName {
|
||||
t.Fatalf("wrong persistence input: %+v", input)
|
||||
}
|
||||
expected.ID = input.ID
|
||||
return expected, nil
|
||||
}
|
||||
svc := newStubService(t, repo)
|
||||
input := dto.UsersCreateRequestDTO{Username: expected.Username, DisplayName: expected.DisplayName}
|
||||
|
||||
// Act.
|
||||
got, err := svc.UsersCreate(t.Context(), input)
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if calls != 1 || got != expected {
|
||||
t.Fatalf("calls=%d, got=%+v, want=%+v", calls, got, expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestService_UsersCreate_InvalidInput refuses malformed registrations without calling storage.
|
||||
func TestService_UsersCreate_InvalidInput(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
input dto.UsersCreateRequestDTO
|
||||
}{
|
||||
{"Negative: short username", dto.UsersCreateRequestDTO{Username: "a", DisplayName: "Alice"}},
|
||||
{"Negative: uppercase username", dto.UsersCreateRequestDTO{Username: "Alice", DisplayName: "Alice"}},
|
||||
{"Negative: blank display name", dto.UsersCreateRequestDTO{Username: "alice", DisplayName: " "}},
|
||||
{"Negative: display name exceeds rune limit", dto.UsersCreateRequestDTO{Username: "alice", DisplayName: strings.Repeat("界", 101)}},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
// Arrange: every store method fails immediately if called.
|
||||
svc := newStubService(t, newStoreStub(t))
|
||||
|
||||
// Act.
|
||||
got, err := svc.UsersCreate(t.Context(), tc.input)
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, service.ErrInvalid) || got != (dto.UserDTO{}) {
|
||||
t.Fatalf("result=%+v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestService_UsersCreate_StoreErrors preserves the application meaning of persistence failures.
|
||||
func TestService_UsersCreate_StoreErrors(t *testing.T) {
|
||||
unexpected := errors.New("storage unavailable")
|
||||
cases := []struct {
|
||||
name string
|
||||
cause error
|
||||
want error
|
||||
}{
|
||||
{"Negative: duplicate username", store.ErrConflict, service.ErrConflict},
|
||||
{"Negative: capacity exhausted", store.ErrCapacity, service.ErrCapacity},
|
||||
{"Negative: unexpected failure", unexpected, unexpected},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
repo.createUser = func(_ context.Context, _ dto.UserDTO) (dto.UserDTO, error) {
|
||||
return dto.UserDTO{}, tc.cause
|
||||
}
|
||||
svc := newStubService(t, repo)
|
||||
|
||||
// Act.
|
||||
got, err := svc.UsersCreate(t.Context(), dto.UsersCreateRequestDTO{Username: "alice", DisplayName: "Alice"})
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, tc.want) || got != (dto.UserDTO{}) {
|
||||
t.Fatalf("result=%+v, error=%v, want=%v", got, err, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestService_UsersGetMe loads only the requested profile and hides unknown identities.
|
||||
func TestService_UsersGetMe(t *testing.T) {
|
||||
t.Run("Positive: returns stored profile", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
expected := dto.UserDTO{ID: uuid.New(), Username: "alice", DisplayName: "Alice", CreatedAt: time.Unix(1700000000, 0).UTC()}
|
||||
calls := 0
|
||||
repo.user = func(_ context.Context, id uuid.UUID) (dto.UserDTO, error) {
|
||||
calls++
|
||||
if id != expected.ID {
|
||||
t.Fatalf("profile queried for %s instead of %s", id, expected.ID)
|
||||
}
|
||||
return expected, nil
|
||||
}
|
||||
svc := newStubService(t, repo)
|
||||
|
||||
// Act.
|
||||
got, err := svc.UsersGetMe(t.Context(), expected.ID.String())
|
||||
|
||||
// Assert.
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if calls != 1 || got != expected {
|
||||
t.Fatalf("calls=%d, got=%+v, want=%+v", calls, got, expected)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: unknown identity", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
repo.user = func(_ context.Context, _ uuid.UUID) (dto.UserDTO, error) {
|
||||
return dto.UserDTO{}, store.ErrNotFound
|
||||
}
|
||||
svc := newStubService(t, repo)
|
||||
wantErr := service.ErrUnauthorized
|
||||
|
||||
// Act.
|
||||
got, err := svc.UsersGetMe(t.Context(), uuid.NewString())
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, wantErr) {
|
||||
t.Fatalf("error=%v, want=%v", err, wantErr)
|
||||
}
|
||||
if got != (dto.UserDTO{}) {
|
||||
t.Fatalf("failed operation returned a profile: %+v", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: storage failure preserved", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
wantErr := errors.New("profile unavailable")
|
||||
repo.user = func(_ context.Context, _ uuid.UUID) (dto.UserDTO, error) {
|
||||
return dto.UserDTO{}, wantErr
|
||||
}
|
||||
svc := newStubService(t, repo)
|
||||
|
||||
// Act.
|
||||
got, err := svc.UsersGetMe(t.Context(), uuid.NewString())
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, wantErr) {
|
||||
t.Fatalf("error=%v, want=%v", err, wantErr)
|
||||
}
|
||||
if got != (dto.UserDTO{}) {
|
||||
t.Fatalf("failed operation returned a profile: %+v", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestService_UsersGetMe_InvalidIdentity rejects malformed identifiers before any store call.
|
||||
func TestService_UsersGetMe_InvalidIdentity(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
raw string
|
||||
}{
|
||||
{"Negative: missing header", ""},
|
||||
{"Negative: short ID", "invalid"},
|
||||
{"Negative: non-UUID characters", strings.Repeat("z", 36)},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
// Arrange.
|
||||
svc := newStubService(t, newStoreStub(t))
|
||||
|
||||
// Act.
|
||||
got, err := svc.UsersGetMe(t.Context(), tc.raw)
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, service.ErrUnauthorized) || got != (dto.UserDTO{}) {
|
||||
t.Fatalf("result=%+v, error=%v", got, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestService_UsersCheckIdentity uses the existence query and never loads a profile.
|
||||
func TestService_UsersCheckIdentity(t *testing.T) {
|
||||
t.Run("Positive: existence check without profile loading", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
id := uuid.New()
|
||||
calls := 0
|
||||
repo.usersExist = func(_ context.Context, ids []uuid.UUID) (bool, error) {
|
||||
calls++
|
||||
if !slices.Equal(ids, []uuid.UUID{id}) {
|
||||
t.Fatalf("queried IDs=%v", ids)
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
svc := newStubService(t, repo)
|
||||
|
||||
// Act.
|
||||
err := svc.UsersCheckIdentity(t.Context(), id.String())
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, nil) || calls != 1 {
|
||||
t.Fatalf("calls=%d, error=%v", calls, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: identity does not exist", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
id := uuid.New()
|
||||
calls := 0
|
||||
repo.usersExist = func(_ context.Context, ids []uuid.UUID) (bool, error) {
|
||||
calls++
|
||||
if !slices.Equal(ids, []uuid.UUID{id}) {
|
||||
t.Fatalf("queried IDs=%v", ids)
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
svc := newStubService(t, repo)
|
||||
|
||||
// Act.
|
||||
err := svc.UsersCheckIdentity(t.Context(), id.String())
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, service.ErrUnauthorized) || calls != 1 {
|
||||
t.Fatalf("calls=%d, error=%v", calls, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: existence lookup fails", func(t *testing.T) {
|
||||
// Arrange.
|
||||
repo := newStoreStub(t)
|
||||
id := uuid.New()
|
||||
calls := 0
|
||||
failure := errors.New("identity unavailable")
|
||||
repo.usersExist = func(_ context.Context, ids []uuid.UUID) (bool, error) {
|
||||
calls++
|
||||
if !slices.Equal(ids, []uuid.UUID{id}) {
|
||||
t.Fatalf("queried IDs=%v", ids)
|
||||
}
|
||||
return false, failure
|
||||
}
|
||||
svc := newStubService(t, repo)
|
||||
|
||||
// Act.
|
||||
err := svc.UsersCheckIdentity(t.Context(), id.String())
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, failure) || calls != 1 {
|
||||
t.Fatalf("calls=%d, error=%v", calls, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Negative: malformed identity skips storage", func(t *testing.T) {
|
||||
// Arrange.
|
||||
svc := newStubService(t, newStoreStub(t))
|
||||
|
||||
// Act.
|
||||
err := svc.UsersCheckIdentity(t.Context(), "invalid")
|
||||
|
||||
// Assert.
|
||||
if !errors.Is(err, service.ErrUnauthorized) {
|
||||
t.Fatalf("error=%v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package production
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/service"
|
||||
)
|
||||
|
||||
// These bounds come from the mandatory lab1 OpenAPI schema.
|
||||
const (
|
||||
minUsernameLength = 3
|
||||
maxUsernameLength = 32
|
||||
maxDisplayNameRunes = 100
|
||||
maxChatTitleRunes = 100
|
||||
maxChatMembers = 100
|
||||
maxMessageRunes = 4000
|
||||
canonicalUUIDLength = len("00000000-0000-0000-0000-000000000000")
|
||||
)
|
||||
|
||||
// validText checks that text is nonblank and within its Unicode length limit.
|
||||
func validText(value string, maxRunes int) bool {
|
||||
return utf8.ValidString(value) && strings.TrimSpace(value) != "" && utf8.RuneCountInString(value) <= maxRunes
|
||||
}
|
||||
|
||||
// validUsername checks the username length and permitted ASCII characters.
|
||||
func validUsername(value string) bool {
|
||||
if len(value) < minUsernameLength || len(value) > maxUsernameLength {
|
||||
return false
|
||||
}
|
||||
for _, char := range value {
|
||||
if (char < 'a' || char > 'z') && (char < '0' || char > '9') && char != '_' {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// parseID parses a canonical UUID or returns a validation error.
|
||||
func parseID(value string) (uuid.UUID, error) {
|
||||
if len(value) != canonicalUUIDLength {
|
||||
return uuid.Nil, service.ErrInvalid
|
||||
}
|
||||
id, err := uuid.Parse(value)
|
||||
if err != nil {
|
||||
return uuid.Nil, service.ErrInvalid
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
Reference in New Issue
Block a user