на оценку 4
Skeleton contracts / contracts (pull_request) Canceled after 0s

This commit is contained in:
2026-11-22 23:33:11 +03:00
parent 20afc2c790
commit cc41f601e3
207 changed files with 22098 additions and 120 deletions
@@ -0,0 +1,67 @@
package application
import (
"context"
"fmt"
"io"
"mtusi2026lab7/internal/domain"
)
type AttachmentDownload struct {
Body io.ReadCloser
ContentType string
Filename string
SizeBytes int64
}
func (s *Service) GetAttachment(ctx context.Context, attachmentID, actorID string) (domain.Attachment, error) {
return s.repository.GetAttachment(ctx, attachmentID, actorID)
}
func (s *Service) DownloadAttachment(ctx context.Context, attachmentID, actorID, variantName string) (AttachmentDownload, error) {
attachment, err := s.repository.GetAttachment(ctx, attachmentID, actorID)
if err != nil {
return AttachmentDownload{}, err
}
if attachment.Status != domain.AttachmentStatusReady {
return AttachmentDownload{}, ErrAttachmentNotReady
}
if s.objectStore == nil {
return AttachmentDownload{}, ErrStorageUnavailable
}
if variantName == "" {
variantName = "original"
}
key := attachment.ObjectKey
contentType := attachment.ContentType
sizeBytes := attachment.SizeBytes
filename := attachment.Filename
if variantName != "original" {
found := false
for _, variant := range attachment.Variants {
if variant.Name == variantName {
key = variant.ObjectKey
contentType = variant.ContentType
sizeBytes = variant.SizeBytes
filename = variant.Name + ".jpg"
found = true
break
}
}
if !found {
return AttachmentDownload{}, domain.ErrNotFound
}
}
object, err := s.objectStore.Get(ctx, key)
if err != nil {
return AttachmentDownload{}, fmt.Errorf("%w: get object", ErrStorageUnavailable)
}
if object.Body == nil || object.SizeBytes != sizeBytes {
if object.Body != nil {
_ = object.Body.Close()
}
return AttachmentDownload{}, fmt.Errorf("%w: object metadata mismatch", ErrStorageUnavailable)
}
return AttachmentDownload{Body: object.Body, ContentType: contentType, Filename: filename, SizeBytes: sizeBytes}, nil
}
+182
View File
@@ -0,0 +1,182 @@
package application
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"image"
_ "image/jpeg"
_ "image/png"
"io"
"os"
"mtusi2026lab7/internal/domain"
"github.com/google/uuid"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/propagation"
)
const currentAttachmentPipelineVersion = 1
func (s *Service) UploadAttachment(ctx context.Context, command UploadAttachmentCommand) (domain.Attachment, error) {
if s.objectStore == nil {
return domain.Attachment{}, ErrStorageUnavailable
}
queueRepository, ok := s.repository.(AttachmentQueueRepository)
if !ok {
return domain.Attachment{}, fmt.Errorf("attachment queue repository is not configured")
}
if command.Body == nil {
return domain.Attachment{}, fmt.Errorf("%w: attachment body is required", ErrInvalidInput)
}
if err := domain.ValidateAttachmentFilename(command.Filename); err != nil {
return domain.Attachment{}, fmt.Errorf("%w: %v", ErrInvalidInput, err)
}
if err := domain.ValidateAttachmentContentType(command.DeclaredContentType); err != nil {
return domain.Attachment{}, fmt.Errorf("%w: %v", ErrUnsupportedMediaType, err)
}
if _, err := s.repository.GetChatByID(ctx, command.ChatID, command.ActorID); err != nil {
return domain.Attachment{}, err
}
if err := acquireAttachmentSlot(ctx, s.attachmentUploadSlots); err != nil {
return domain.Attachment{}, fmt.Errorf("%w: wait for upload capacity", ErrStorageUnavailable)
}
defer releaseAttachmentSlot(s.attachmentUploadSlots)
stagedFile, err := os.CreateTemp("", "mtusi-attachment-*")
if err != nil {
return domain.Attachment{}, fmt.Errorf("create bounded upload staging file: %w", err)
}
stagedPath := stagedFile.Name()
defer func() {
_ = stagedFile.Close()
_ = os.Remove(stagedPath)
}()
hasher := sha256.New()
sizeBytes, err := io.Copy(io.MultiWriter(stagedFile, hasher), io.LimitReader(command.Body, domain.MaxAttachmentSizeBytes+1))
if err != nil {
return domain.Attachment{}, fmt.Errorf("%w: read attachment body", ErrInvalidInput)
}
if sizeBytes > domain.MaxAttachmentSizeBytes {
return domain.Attachment{}, ErrPayloadTooLarge
}
if _, err = stagedFile.Seek(0, io.SeekStart); err != nil {
return domain.Attachment{}, fmt.Errorf("rewind staged attachment: %w", err)
}
imageConfig, format, err := image.DecodeConfig(stagedFile)
if err != nil {
return domain.Attachment{}, fmt.Errorf("%w: decode image header", ErrInvalidImage)
}
actualContentType, supported := contentTypeForImageFormat(format)
if !supported || actualContentType != command.DeclaredContentType {
return domain.Attachment{}, ErrUnsupportedMediaType
}
if imageConfig.Width < 1 || imageConfig.Height < 1 {
return domain.Attachment{}, ErrInvalidImage
}
if int64(imageConfig.Width) > int64(domain.MaxAttachmentPixels)/int64(imageConfig.Height) {
return domain.Attachment{}, ErrPayloadTooLarge
}
sha256Hex := hex.EncodeToString(hasher.Sum(nil))
if err = domain.ValidateReadyAttachmentMetadata(command.Filename, actualContentType, sizeBytes, sha256Hex, imageConfig.Width, imageConfig.Height); err != nil {
return domain.Attachment{}, fmt.Errorf("%w: %v", ErrInvalidImage, err)
}
if _, err = stagedFile.Seek(0, io.SeekStart); err != nil {
return domain.Attachment{}, fmt.Errorf("rewind staged attachment for validation: %w", err)
}
if err = s.validateCompleteImage(ctx, stagedFile); err != nil {
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
return domain.Attachment{}, fmt.Errorf("%w: wait for image decoder", ErrStorageUnavailable)
}
return domain.Attachment{}, fmt.Errorf("%w: decode complete image", ErrInvalidImage)
}
now := s.now().UTC()
attachmentID := uuid.NewString()
attachment := domain.Attachment{
ID: attachmentID,
ChatID: command.ChatID,
OwnerID: command.ActorID,
Filename: command.Filename,
ObjectKey: "attachments/" + command.ChatID + "/" + attachmentID + "/original",
StagingKey: "staging/" + attachmentID + "/original",
ContentType: actualContentType,
SizeBytes: sizeBytes,
SHA256: sha256Hex,
Width: imageConfig.Width,
Height: imageConfig.Height,
PipelineVersion: currentAttachmentPipelineVersion,
Status: domain.AttachmentStatusQueued,
Variants: make([]domain.AttachmentVariant, 0),
CreatedAt: now,
UpdatedAt: now,
}
if _, err = stagedFile.Seek(0, io.SeekStart); err != nil {
return domain.Attachment{}, fmt.Errorf("rewind staged attachment for storage: %w", err)
}
if err = s.objectStore.Put(ctx, ObjectPut{Key: attachment.StagingKey, ContentType: attachment.ContentType, SizeBytes: attachment.SizeBytes, Body: stagedFile}); err != nil {
return domain.Attachment{}, fmt.Errorf("%w: put durable staging object", ErrStorageUnavailable)
}
traceCarrier := propagation.MapCarrier{}
otel.GetTextMapPropagator().Inject(ctx, traceCarrier)
job := domain.AttachmentJob{
SchemaVersion: 1,
JobID: uuid.NewString(),
Type: domain.AttachmentJobType,
AttachmentID: attachment.ID,
PipelineVersion: attachment.PipelineVersion,
Attempt: 1,
MaxAttempts: s.jobMaxAttempts,
Status: domain.AttachmentJobQueued,
AvailableAt: now,
CreatedAt: now,
UpdatedAt: now,
TraceParent: traceCarrier.Get("traceparent"),
TraceState: traceCarrier.Get("tracestate"),
}
attachment, err = queueRepository.CreateQueuedAttachment(ctx, attachment, job)
if err != nil {
// A failed COMMIT response is ambiguous. Preserve staging so a committed
// job can still finish and an uncommitted orphan can be retained/cleaned.
return domain.Attachment{}, fmt.Errorf("persist queued attachment: %w", err)
}
if attachment.Variants == nil {
attachment.Variants = make([]domain.AttachmentVariant, 0)
}
return attachment, nil
}
func acquireAttachmentSlot(ctx context.Context, slots chan struct{}) error {
select {
case slots <- struct{}{}:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
func releaseAttachmentSlot(slots chan struct{}) { <-slots }
func (s *Service) validateCompleteImage(ctx context.Context, body io.Reader) error {
if err := acquireAttachmentSlot(ctx, s.attachmentDecodeSlots); err != nil {
return err
}
defer releaseAttachmentSlot(s.attachmentDecodeSlots)
_, _, err := image.Decode(body)
return err
}
func contentTypeForImageFormat(format string) (string, bool) {
switch format {
case "png":
return "image/png", true
case "jpeg":
return "image/jpeg", true
default:
return "", false
}
}
+155
View File
@@ -0,0 +1,155 @@
package application_test
import (
"bytes"
"context"
"errors"
"image"
"image/color"
"image/png"
"io"
"sync"
"testing"
"time"
"mtusi2026lab7/internal/adapter/memory"
. "mtusi2026lab7/internal/application"
"mtusi2026lab7/internal/domain"
)
type fakeObjectStore struct {
mu sync.Mutex
objects map[string][]byte
putError error
}
func newFakeObjectStore() *fakeObjectStore { return &fakeObjectStore{objects: make(map[string][]byte)} }
func (store *fakeObjectStore) Put(_ context.Context, object ObjectPut) error {
if store.putError != nil {
return store.putError
}
payload, err := io.ReadAll(object.Body)
if err != nil {
return err
}
store.mu.Lock()
store.objects[object.Key] = payload
store.mu.Unlock()
return nil
}
func (store *fakeObjectStore) Get(_ context.Context, key string) (ObjectContent, error) {
store.mu.Lock()
defer store.mu.Unlock()
payload, ok := store.objects[key]
if !ok {
return ObjectContent{}, errors.New("not found")
}
return ObjectContent{Body: io.NopCloser(bytes.NewReader(payload)), SizeBytes: int64(len(payload))}, nil
}
func (store *fakeObjectStore) Delete(_ context.Context, key string) error {
store.mu.Lock()
delete(store.objects, key)
store.mu.Unlock()
return nil
}
type interruptedReader struct{}
func (interruptedReader) Read([]byte) (int, error) { return 0, errors.New("injected read failure") }
func newAttachmentService(t *testing.T, objects ObjectStore) (*Service, string, string) {
t.Helper()
legacy := memory.NewMemoryStore()
repository := memory.NewMemoryRepository(legacy)
user, err := repository.CreateUser(context.Background(), "uploader", "Uploader", "hash")
if err != nil {
t.Fatal(err)
}
chat, err := repository.CreateChat(context.Background(), "Images", []string{user.ID})
if err != nil {
t.Fatal(err)
}
codec, err := NewCursorCodec("attachment-test-key-with-more-than-thirty-two-bytes")
if err != nil {
t.Fatal(err)
}
service, err := NewService(repository, codec, time.Hour, WithObjectStore(objects), WithJobMaxAttempts(5))
if err != nil {
t.Fatal(err)
}
return service, user.ID, chat.ID
}
func testPNG(t *testing.T) []byte {
t.Helper()
var payload bytes.Buffer
img := image.NewRGBA(image.Rect(0, 0, 320, 200))
img.Set(0, 0, color.RGBA{R: 255, A: 255})
if err := png.Encode(&payload, img); err != nil {
t.Fatal(err)
}
return payload.Bytes()
}
func TestUploadAttachmentDurablyQueuesStagingObject(t *testing.T) {
objects := newFakeObjectStore()
service, actorID, chatID := newAttachmentService(t, objects)
payload := testPNG(t)
attachment, err := service.UploadAttachment(context.Background(), UploadAttachmentCommand{
ActorID: actorID, ChatID: chatID, Filename: "photo.png",
DeclaredContentType: "image/png", Body: bytes.NewReader(payload),
})
if err != nil {
t.Fatal(err)
}
if attachment.Status != domain.AttachmentStatusQueued {
t.Fatalf("status=%s, want queued", attachment.Status)
}
if attachment.StagingKey == "" || attachment.ObjectKey == attachment.StagingKey {
t.Fatalf("staging/final keys are not separated: %+v", attachment)
}
objects.mu.Lock()
staged := append([]byte(nil), objects.objects[attachment.StagingKey]...)
objects.mu.Unlock()
if !bytes.Equal(staged, payload) {
t.Fatal("durable staging bytes differ")
}
}
func TestUploadAttachmentRejectsInvalidInputBeforeStaging(t *testing.T) {
objects := newFakeObjectStore()
service, actorID, chatID := newAttachmentService(t, objects)
cases := []struct {
name string
command UploadAttachmentCommand
target error
}{
{"unsafe filename", UploadAttachmentCommand{ActorID: actorID, ChatID: chatID, Filename: "../x.png", DeclaredContentType: "image/png", Body: bytes.NewReader(testPNG(t))}, ErrInvalidInput},
{"mime", UploadAttachmentCommand{ActorID: actorID, ChatID: chatID, Filename: "x.png", DeclaredContentType: "image/jpeg", Body: bytes.NewReader(testPNG(t))}, ErrUnsupportedMediaType},
{"corrupt", UploadAttachmentCommand{ActorID: actorID, ChatID: chatID, Filename: "x.png", DeclaredContentType: "image/png", Body: bytes.NewReader([]byte("broken"))}, ErrInvalidImage},
{"interrupted", UploadAttachmentCommand{ActorID: actorID, ChatID: chatID, Filename: "x.png", DeclaredContentType: "image/png", Body: interruptedReader{}}, ErrInvalidInput},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if _, err := service.UploadAttachment(context.Background(), tc.command); !errors.Is(err, tc.target) {
t.Fatalf("error=%v, want %v", err, tc.target)
}
})
}
objects.mu.Lock()
count := len(objects.objects)
objects.mu.Unlock()
if count != 0 {
t.Fatalf("invalid requests staged %d objects", count)
}
}
func TestUploadAttachmentStorageFailureDoesNotCreateQueuedMetadata(t *testing.T) {
objects := newFakeObjectStore()
objects.putError = errors.New("storage down")
service, actorID, chatID := newAttachmentService(t, objects)
_, err := service.UploadAttachment(context.Background(), UploadAttachmentCommand{ActorID: actorID, ChatID: chatID, Filename: "x.png", DeclaredContentType: "image/png", Body: bytes.NewReader(testPNG(t))})
if !errors.Is(err, ErrStorageUnavailable) {
t.Fatalf("error=%v, want storage unavailable", err)
}
}
+55
View File
@@ -0,0 +1,55 @@
package application
import (
"context"
"fmt"
"mtusi2026lab7/internal/domain"
)
func (s *Service) CreateChat(ctx context.Context, command CreateChatCommand) (domain.Chat, error) {
if err := domain.ValidateChatInput(command.Title, command.MemberIDs, command.ActorID); err != nil {
return domain.Chat{}, fmt.Errorf("%w: %v", ErrInvalidInput, err)
}
return s.repository.CreateChat(ctx, command.Title, command.MemberIDs)
}
func (s *Service) GetChat(ctx context.Context, actorID, chatID string) (domain.Chat, error) {
return s.repository.GetChatByID(ctx, chatID, actorID)
}
func (s *Service) ListChats(
ctx context.Context,
actorID string,
limit int,
cursorToken string,
) (domain.ChatPage, error) {
var cursor *domain.ChatCursor
if cursorToken != "" {
decoded, err := s.cursors.DecodeChat(cursorToken, actorID)
if err != nil {
return domain.ChatPage{}, ErrInvalidCursor
}
cursor = decoded
}
items, hasMore, err := s.repository.GetChatsForUser(ctx, actorID, limit, cursor)
if err != nil {
return domain.ChatPage{}, err
}
page := domain.ChatPage{Items: items}
if page.Items == nil {
page.Items = make([]domain.Chat, 0)
}
if hasMore {
last := page.Items[len(page.Items)-1]
next, encodeErr := s.cursors.EncodeChat(domain.ChatCursor{
CreatedAt: last.CreatedAt, ChatID: last.ID, UserID: actorID,
})
if encodeErr != nil {
return domain.ChatPage{}, encodeErr
}
page.NextCursor = &next
}
return page, nil
}
+38
View File
@@ -0,0 +1,38 @@
package application
import "io"
type CreateUserCommand struct {
Username string
DisplayName string
Password string
}
type CreateSessionCommand struct {
Username string
Password string
}
type CreateChatCommand struct {
ActorID string
Title string
MemberIDs []string
}
type SendMessageCommand struct {
ActorID string
ChatID string
Text string
AttachmentIDs []string
Method string
CanonicalPath string
IdempotencyKey string
}
type UploadAttachmentCommand struct {
ActorID string
ChatID string
Filename string
DeclaredContentType string
Body io.Reader
}
+121
View File
@@ -0,0 +1,121 @@
package application
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
"strings"
"time"
"mtusi2026lab7/internal/domain"
"github.com/google/uuid"
)
const cursorVersion = 1
type CursorCodec struct {
key []byte
}
type cursorPayload struct {
Version int `json:"v"`
Kind string `json:"kind"`
CreatedAt string `json:"created_at"`
ID string `json:"id"`
ScopeID string `json:"scope_id"`
}
func NewCursorCodec(key string) (*CursorCodec, error) {
if len(key) < 32 {
return nil, fmt.Errorf("cursor signing key must contain at least 32 bytes")
}
return &CursorCodec{key: []byte(key)}, nil
}
func (c *CursorCodec) EncodeChat(cursor domain.ChatCursor) (string, error) {
return c.encode(cursorPayload{
Version: cursorVersion, Kind: "chat", CreatedAt: cursor.CreatedAt.UTC().Format(time.RFC3339Nano),
ID: cursor.ChatID, ScopeID: cursor.UserID,
})
}
func (c *CursorCodec) DecodeChat(token, expectedUserID string) (*domain.ChatCursor, error) {
payload, err := c.decode(token, "chat", expectedUserID)
if err != nil {
return nil, err
}
return &domain.ChatCursor{CreatedAt: payload.createdAt, ChatID: payload.id, UserID: payload.scopeID}, nil
}
func (c *CursorCodec) EncodeMessage(cursor domain.MessageCursor) (string, error) {
return c.encode(cursorPayload{
Version: cursorVersion, Kind: "message", CreatedAt: cursor.CreatedAt.UTC().Format(time.RFC3339Nano),
ID: cursor.MessageID, ScopeID: cursor.ChatID,
})
}
func (c *CursorCodec) DecodeMessage(token, expectedChatID string) (*domain.MessageCursor, error) {
payload, err := c.decode(token, "message", expectedChatID)
if err != nil {
return nil, err
}
return &domain.MessageCursor{CreatedAt: payload.createdAt, MessageID: payload.id, ChatID: payload.scopeID}, nil
}
func (c *CursorCodec) encode(payload cursorPayload) (string, error) {
encodedPayload, err := json.Marshal(payload)
if err != nil {
return "", fmt.Errorf("encode cursor payload: %w", err)
}
mac := hmac.New(sha256.New, c.key)
_, _ = mac.Write(encodedPayload)
return base64.RawURLEncoding.EncodeToString(encodedPayload) + "." +
base64.RawURLEncoding.EncodeToString(mac.Sum(nil)), nil
}
type decodedCursor struct {
createdAt time.Time
id string
scopeID string
}
func (c *CursorCodec) decode(token, expectedKind, expectedScopeID string) (decodedCursor, error) {
parts := strings.Split(token, ".")
if len(parts) != 2 {
return decodedCursor{}, ErrInvalidCursor
}
payloadBytes, err := base64.RawURLEncoding.DecodeString(parts[0])
if err != nil {
return decodedCursor{}, ErrInvalidCursor
}
signature, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil {
return decodedCursor{}, ErrInvalidCursor
}
mac := hmac.New(sha256.New, c.key)
_, _ = mac.Write(payloadBytes)
if !hmac.Equal(signature, mac.Sum(nil)) {
return decodedCursor{}, ErrInvalidCursor
}
var payload cursorPayload
if err = json.Unmarshal(payloadBytes, &payload); err != nil ||
payload.Version != cursorVersion || payload.Kind != expectedKind ||
payload.ScopeID != expectedScopeID {
return decodedCursor{}, ErrInvalidCursor
}
createdAt, err := time.Parse(time.RFC3339Nano, payload.CreatedAt)
if err != nil {
return decodedCursor{}, ErrInvalidCursor
}
if _, err = uuid.Parse(payload.ID); err != nil {
return decodedCursor{}, ErrInvalidCursor
}
if _, err = uuid.Parse(payload.ScopeID); err != nil {
return decodedCursor{}, ErrInvalidCursor
}
return decodedCursor{createdAt: createdAt.UTC(), id: payload.ID, scopeID: payload.ScopeID}, nil
}
+96
View File
@@ -0,0 +1,96 @@
package application
import (
"encoding/base64"
"errors"
"strings"
"testing"
"time"
"mtusi2026lab7/internal/domain"
)
const cursorTestKey = "cursor-test-key-with-more-than-thirty-two-bytes"
func TestCursorCodecRoundTrip(t *testing.T) {
codec, err := NewCursorCodec(cursorTestKey)
if err != nil {
t.Fatal(err)
}
expected := domain.MessageCursor{
CreatedAt: time.Date(2026, 10, 18, 12, 30, 0, 123, time.UTC),
MessageID: "42eea32e-d9b5-4bc6-b4fc-94e9b0477adf",
ChatID: "9fa3f49c-e62e-4209-8414-d6d5f69805bf",
}
token, err := codec.EncodeMessage(expected)
if err != nil {
t.Fatal(err)
}
actual, err := codec.DecodeMessage(token, expected.ChatID)
if err != nil {
t.Fatal(err)
}
if *actual != expected {
t.Fatalf("cursor changed after round trip: got %#v, want %#v", *actual, expected)
}
}
func TestCursorCodecRejectsTamperingAndWrongScope(t *testing.T) {
codec, err := NewCursorCodec(cursorTestKey)
if err != nil {
t.Fatal(err)
}
token, err := codec.EncodeChat(domain.ChatCursor{
CreatedAt: time.Now().UTC(),
ChatID: "42eea32e-d9b5-4bc6-b4fc-94e9b0477adf",
UserID: "9fa3f49c-e62e-4209-8414-d6d5f69805bf",
})
if err != nil {
t.Fatal(err)
}
parts := strings.Split(token, ".")
signature, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil {
t.Fatal(err)
}
signature[0] ^= 1
tampered := parts[0] + "." + base64.RawURLEncoding.EncodeToString(signature)
if _, err = codec.DecodeChat(tampered, "9fa3f49c-e62e-4209-8414-d6d5f69805bf"); !errors.Is(err, ErrInvalidCursor) {
t.Fatalf("tampered cursor: got %v, want ErrInvalidCursor", err)
}
if _, err = codec.DecodeChat(token, "e6ca4af0-69ed-4784-8ce0-ee035299fe08"); !errors.Is(err, ErrInvalidCursor) {
t.Fatalf("wrong scope: got %v, want ErrInvalidCursor", err)
}
if _, err = codec.DecodeMessage(token, "9fa3f49c-e62e-4209-8414-d6d5f69805bf"); !errors.Is(err, ErrInvalidCursor) {
t.Fatalf("wrong cursor kind: got %v, want ErrInvalidCursor", err)
}
}
func TestCursorCodecRequiresStrongSharedKey(t *testing.T) {
if _, err := NewCursorCodec("too-short"); err == nil {
t.Fatal("expected short cursor signing key to be rejected")
}
}
func TestCursorCodecRejectsSignedInvalidFieldTypesBeforeSQL(t *testing.T) {
codec, err := NewCursorCodec(cursorTestKey)
if err != nil {
t.Fatal(err)
}
chatID := "9fa3f49c-e62e-4209-8414-d6d5f69805bf"
validMessageID := "42eea32e-d9b5-4bc6-b4fc-94e9b0477adf"
testCases := []cursorPayload{
{Version: cursorVersion, Kind: "message", CreatedAt: "not-a-time", ID: validMessageID, ScopeID: chatID},
{Version: cursorVersion, Kind: "message", CreatedAt: time.Now().UTC().Format(time.RFC3339Nano), ID: "not-a-uuid", ScopeID: chatID},
}
for _, payload := range testCases {
token, encodeErr := codec.encode(payload)
if encodeErr != nil {
t.Fatal(encodeErr)
}
if _, decodeErr := codec.DecodeMessage(token, chatID); !errors.Is(decodeErr, ErrInvalidCursor) {
t.Fatalf("invalid signed cursor returned %v, want ErrInvalidCursor", decodeErr)
}
}
}
+16
View File
@@ -0,0 +1,16 @@
package application
import "errors"
var (
ErrInvalidCursor = errors.New("invalid cursor")
ErrInvalidCredentials = errors.New("invalid credentials")
ErrInvalidInput = errors.New("invalid input")
ErrCredentialState = errors.New("invalid stored credential state")
ErrIdempotencyConflict = errors.New("idempotency key is already used for another request")
ErrAttachmentNotReady = errors.New("attachment is not ready")
ErrPayloadTooLarge = errors.New("payload too large")
ErrUnsupportedMediaType = errors.New("unsupported media type")
ErrInvalidImage = errors.New("invalid image")
ErrStorageUnavailable = errors.New("object storage unavailable")
)
+88
View File
@@ -0,0 +1,88 @@
package application
import (
"context"
"crypto/sha256"
"encoding/json"
"fmt"
"mtusi2026lab7/internal/domain"
"github.com/google/uuid"
)
type canonicalMessageRequest struct {
Text string `json:"text"`
AttachmentIDs []string `json:"attachment_ids"`
}
func (s *Service) SendMessage(ctx context.Context, command SendMessageCommand) (domain.Message, error) {
attachmentIDs := append([]string(nil), command.AttachmentIDs...)
if attachmentIDs == nil {
attachmentIDs = make([]string, 0)
}
if err := domain.ValidateMessageInput(command.Text, attachmentIDs); err != nil {
return domain.Message{}, fmt.Errorf("%w: %v", ErrInvalidInput, err)
}
for index, attachmentID := range attachmentIDs {
attachmentIDs[index] = uuid.MustParse(attachmentID).String()
}
canonicalBody, err := json.Marshal(canonicalMessageRequest{
Text: command.Text,
AttachmentIDs: attachmentIDs,
})
if err != nil {
return domain.Message{}, fmt.Errorf("canonicalize message request: %w", err)
}
return s.repository.CreateMessageIdempotently(ctx, IdempotentMessageWrite{
ActorID: command.ActorID,
ChatID: command.ChatID,
Text: command.Text,
AttachmentIDs: attachmentIDs,
Method: command.Method,
CanonicalPath: command.CanonicalPath,
Key: command.IdempotencyKey,
RequestHash: sha256.Sum256(canonicalBody),
TTL: s.idempotencyTTL,
})
}
func (s *Service) ListMessages(
ctx context.Context,
actorID string,
chatID string,
limit int,
cursorToken string,
) (domain.MessagePage, error) {
var cursor *domain.MessageCursor
if cursorToken != "" {
decoded, err := s.cursors.DecodeMessage(cursorToken, chatID)
if err != nil {
return domain.MessagePage{}, ErrInvalidCursor
}
cursor = decoded
}
items, hasMore, err := s.repository.GetMessages(ctx, chatID, actorID, limit, cursor)
if err != nil {
return domain.MessagePage{}, err
}
page := domain.MessagePage{Items: items}
if page.Items == nil {
page.Items = make([]domain.Message, 0)
}
if hasMore {
last := page.Items[len(page.Items)-1]
next, encodeErr := s.cursors.EncodeMessage(domain.MessageCursor{
CreatedAt: last.CreatedAt, MessageID: last.ID, ChatID: chatID,
})
if encodeErr != nil {
return domain.MessagePage{}, encodeErr
}
page.NextCursor = &next
}
return page, nil
}
+81
View File
@@ -0,0 +1,81 @@
package application
import (
"context"
"io"
"time"
"mtusi2026lab7/internal/domain"
)
type UserRepository interface {
CreateUser(ctx context.Context, username, displayName, passwordHash string) (domain.User, error)
GetUserByUsername(ctx context.Context, username string) (domain.User, string, error)
UpdatePasswordHash(ctx context.Context, userID, previousHash, newHash string) error
}
type SessionRepository interface {
CreateSession(ctx context.Context, tokenHash []byte, userID string, expiresAt time.Time) error
GetUserBySession(ctx context.Context, tokenHash []byte) (domain.User, error)
DeleteSession(ctx context.Context, tokenHash []byte) error
}
type ChatRepository interface {
CreateChat(ctx context.Context, title string, memberIDs []string) (domain.Chat, error)
GetChatByID(ctx context.Context, chatID, callerID string) (domain.Chat, error)
GetChatsForUser(ctx context.Context, userID string, limit int, cursor *domain.ChatCursor) ([]domain.Chat, bool, error)
}
type IdempotentMessageWrite struct {
ActorID string
ChatID string
Text string
AttachmentIDs []string
Method string
CanonicalPath string
Key string
RequestHash [32]byte
TTL time.Duration
}
type MessageRepository interface {
CreateMessageIdempotently(ctx context.Context, write IdempotentMessageWrite) (domain.Message, error)
GetMessages(ctx context.Context, chatID, callerID string, limit int, cursor *domain.MessageCursor) ([]domain.Message, bool, error)
}
type AttachmentRepository interface {
CreateAttachment(ctx context.Context, attachment domain.Attachment) (domain.Attachment, error)
MarkAttachmentReady(ctx context.Context, attachmentID string, updatedAt time.Time) (domain.Attachment, error)
MarkAttachmentFailed(ctx context.Context, attachmentID, errorCode string, updatedAt time.Time) error
GetAttachment(ctx context.Context, attachmentID, callerID string) (domain.Attachment, error)
}
type AttachmentQueueRepository interface {
CreateQueuedAttachment(ctx context.Context, attachment domain.Attachment, job domain.AttachmentJob) (domain.Attachment, error)
}
type Repository interface {
UserRepository
SessionRepository
ChatRepository
MessageRepository
AttachmentRepository
}
type ObjectPut struct {
Key string
ContentType string
SizeBytes int64
Body io.Reader
}
type ObjectContent struct {
Body io.ReadCloser
SizeBytes int64
}
type ObjectStore interface {
Put(ctx context.Context, object ObjectPut) error
Get(ctx context.Context, key string) (ObjectContent, error)
Delete(ctx context.Context, key string) error
}
+86
View File
@@ -0,0 +1,86 @@
package application
import (
"fmt"
"time"
)
const MinimumIdempotencyTTL = 24 * time.Hour
const defaultAttachmentCleanupTimeout = time.Second
const defaultAttachmentUploadConcurrency = 4
const defaultAttachmentDecodeConcurrency = 1
const defaultJobMaxAttempts = 5
type ServiceOption func(*Service) error
type Service struct {
repository Repository
cursors *CursorCodec
sessionTTL time.Duration
idempotencyTTL time.Duration
now func() time.Time
objectStore ObjectStore
attachmentCleanupTimeout time.Duration
attachmentUploadSlots chan struct{}
attachmentDecodeSlots chan struct{}
jobMaxAttempts int
}
func NewService(repository Repository, cursors *CursorCodec, sessionTTL time.Duration, options ...ServiceOption) (*Service, error) {
if repository == nil {
return nil, fmt.Errorf("repository is required")
}
if cursors == nil {
return nil, fmt.Errorf("cursor codec is required")
}
if sessionTTL <= 0 {
return nil, fmt.Errorf("session TTL must be positive")
}
service := &Service{
repository: repository,
cursors: cursors,
sessionTTL: sessionTTL,
idempotencyTTL: MinimumIdempotencyTTL,
now: func() time.Time { return time.Now().UTC() },
attachmentCleanupTimeout: defaultAttachmentCleanupTimeout,
attachmentUploadSlots: make(chan struct{}, defaultAttachmentUploadConcurrency),
attachmentDecodeSlots: make(chan struct{}, defaultAttachmentDecodeConcurrency),
jobMaxAttempts: defaultJobMaxAttempts,
}
for _, option := range options {
if err := option(service); err != nil {
return nil, err
}
}
return service, nil
}
func WithIdempotencyTTL(ttl time.Duration) ServiceOption {
return func(service *Service) error {
if ttl < MinimumIdempotencyTTL {
return fmt.Errorf("idempotency TTL must be at least %s", MinimumIdempotencyTTL)
}
service.idempotencyTTL = ttl
return nil
}
}
func WithObjectStore(objectStore ObjectStore) ServiceOption {
return func(service *Service) error {
if objectStore == nil {
return fmt.Errorf("object store is required")
}
service.objectStore = objectStore
return nil
}
}
func WithJobMaxAttempts(attempts int) ServiceOption {
return func(service *Service) error {
if attempts < 1 {
return fmt.Errorf("job max attempts must be positive")
}
service.jobMaxAttempts = attempts
return nil
}
}
+70
View File
@@ -0,0 +1,70 @@
package application
import (
"context"
"errors"
"fmt"
"mtusi2026lab7/internal/domain"
"mtusi2026lab7/internal/security"
)
const dummyPasswordHash = "$argon2id$v=19$m=19456,t=2,p=1$" +
"AAAAAAAAAAAAAAAAAAAAAA$" +
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
func (s *Service) CreateSession(ctx context.Context, command CreateSessionCommand) (domain.Session, error) {
user, passwordHash, err := s.repository.GetUserByUsername(ctx, command.Username)
userNotFound := errors.Is(err, domain.ErrNotFound)
if userNotFound {
passwordHash = dummyPasswordHash
} else if err != nil {
return domain.Session{}, err
}
passwordMatches, verifyErr := security.VerifyPassword(command.Password, passwordHash)
if verifyErr != nil {
return domain.Session{}, fmt.Errorf("%w: %v", ErrCredentialState, verifyErr)
}
if userNotFound || !passwordMatches {
return domain.Session{}, ErrInvalidCredentials
}
needsRehash, rehashErr := security.NeedsPasswordRehash(passwordHash)
if rehashErr != nil {
return domain.Session{}, fmt.Errorf("%w: password hash policy", ErrCredentialState)
}
if needsRehash {
newHash, hashErr := security.HashPassword(command.Password)
if hashErr != nil {
return domain.Session{}, fmt.Errorf("%w: password rehash", ErrCredentialState)
}
if updateErr := s.repository.UpdatePasswordHash(ctx, user.ID, passwordHash, newHash); updateErr != nil {
return domain.Session{}, fmt.Errorf("%w: password rehash update", ErrCredentialState)
}
}
token, tokenHash, err := security.GenerateSessionToken()
if err != nil {
return domain.Session{}, fmt.Errorf("generate session token: %w", err)
}
expiresAt := s.now().Add(s.sessionTTL)
if err = s.repository.CreateSession(ctx, tokenHash, user.ID, expiresAt); err != nil {
return domain.Session{}, err
}
return domain.Session{
Token: token, TokenType: "Bearer", ExpiresAt: expiresAt, User: user,
}, nil
}
func (s *Service) Authenticate(ctx context.Context, token string) (domain.User, []byte, error) {
tokenHash := security.HashSessionToken(token)
user, err := s.repository.GetUserBySession(ctx, tokenHash)
if err != nil {
return domain.User{}, nil, err
}
return user, tokenHash, nil
}
func (s *Service) DeleteSession(ctx context.Context, tokenHash []byte) error {
return s.repository.DeleteSession(ctx, tokenHash)
}
+29
View File
@@ -0,0 +1,29 @@
package application
import (
"context"
"fmt"
"mtusi2026lab7/internal/domain"
"mtusi2026lab7/internal/security"
)
func (s *Service) CreateUser(ctx context.Context, command CreateUserCommand) (domain.User, error) {
if err := domain.ValidateUser(command.Username, command.DisplayName); err != nil {
return domain.User{}, fmt.Errorf("%w: %v", ErrInvalidInput, err)
}
if err := security.ValidatePassword(command.Password); err != nil {
return domain.User{}, fmt.Errorf("%w: %v", ErrInvalidInput, err)
}
passwordHash, err := security.HashPassword(command.Password)
if err != nil {
return domain.User{}, fmt.Errorf("hash password: %w", err)
}
return s.repository.CreateUser(
ctx,
command.Username,
command.DisplayName,
passwordHash,
)
}