Files
mtusi2026lab4/internal/adapter/memory/repository.go
T

378 lines
7.7 KiB
Go

package memory
import (
"context"
"fmt"
"sync"
"time"
"mtusi2026lab4/internal/application"
"mtusi2026lab4/internal/domain"
)
type memorySession struct {
userID string
expiresAt time.Time
}
type memoryIdempotencyScope struct {
actorID string
method string
canonicalPath string
key string
}
type memoryIdempotencyResult struct {
requestHash [32]byte
message domain.Message
expiresAt time.Time
}
type MemoryRepository struct {
legacy *MemoryStore
mu sync.RWMutex
passwordByUserID map[string]string
userIDByUsername map[string]string
sessionsByHashKey map[[32]byte]memorySession
idempotencyByScope map[memoryIdempotencyScope]memoryIdempotencyResult
}
func NewMemoryRepository(legacy *MemoryStore) *MemoryRepository {
return &MemoryRepository{
legacy: legacy,
passwordByUserID: make(map[string]string),
userIDByUsername: make(map[string]string),
sessionsByHashKey: make(map[[32]byte]memorySession),
idempotencyByScope: make(map[memoryIdempotencyScope]memoryIdempotencyResult),
}
}
func (r *MemoryRepository) CreateUser(
ctx context.Context,
username string,
displayName string,
passwordHash string,
) (domain.User, error) {
if err := ctx.Err(); err != nil {
return domain.User{}, err
}
user, err := r.legacy.CreateUser(username, displayName)
if err != nil {
return domain.User{}, err
}
r.mu.Lock()
r.passwordByUserID[user.ID] = passwordHash
r.userIDByUsername[user.Username] = user.ID
r.mu.Unlock()
return user, nil
}
func (r *MemoryRepository) GetUserByID(
ctx context.Context,
userID string,
) (domain.User, error) {
if err := ctx.Err(); err != nil {
return domain.User{}, err
}
return r.legacy.GetUserByID(userID)
}
func (r *MemoryRepository) GetUserByUsername(
ctx context.Context,
username string,
) (domain.User, string, error) {
if err := ctx.Err(); err != nil {
return domain.User{}, "", err
}
r.mu.RLock()
userID, exists := r.userIDByUsername[username]
passwordHash := r.passwordByUserID[userID]
r.mu.RUnlock()
if !exists {
return domain.User{}, "", ErrNotFound
}
user, err := r.legacy.GetUserByID(userID)
if err != nil {
return domain.User{}, "", err
}
return user, passwordHash, nil
}
func (r *MemoryRepository) CreateChat(
ctx context.Context,
title string,
memberIDs []string,
) (domain.Chat, error) {
if err := ctx.Err(); err != nil {
return domain.Chat{}, err
}
return r.legacy.CreateChat(title, memberIDs)
}
func (r *MemoryRepository) GetChatByID(
ctx context.Context,
chatID string,
callerID string,
) (domain.Chat, error) {
if err := ctx.Err(); err != nil {
return domain.Chat{}, err
}
return r.legacy.GetChatByID(chatID, callerID)
}
func (r *MemoryRepository) GetChatsForUser(
ctx context.Context,
userID string,
limit int,
cursor *domain.ChatCursor,
) ([]domain.Chat, bool, error) {
if err := ctx.Err(); err != nil {
return nil, false, err
}
return r.legacy.GetChatsForUser(userID, limit, cursor)
}
func (r *MemoryRepository) CreateMessageIdempotently(
ctx context.Context,
write application.IdempotentMessageWrite,
) (domain.Message, error) {
if err := ctx.Err(); err != nil {
return domain.Message{}, err
}
scope := memoryIdempotencyScope{
actorID: write.ActorID,
method: write.Method,
canonicalPath: write.CanonicalPath,
key: write.Key,
}
now := time.Now().UTC()
r.mu.Lock()
defer r.mu.Unlock()
if _, err := r.legacy.GetChatByID(write.ChatID, write.ActorID); err != nil {
return domain.Message{}, err
}
for _, attachmentID := range write.AttachmentIDs {
attachment, err := r.legacy.GetAttachmentByID(attachmentID)
if err != nil || attachment.ChatID != write.ChatID {
return domain.Message{}, ErrNotFound
}
if attachment.Status != domain.AttachmentStatusReady {
return domain.Message{}, application.ErrAttachmentNotReady
}
}
if stored, exists := r.idempotencyByScope[scope]; exists {
if stored.expiresAt.After(now) {
if stored.requestHash != write.RequestHash {
return domain.Message{}, application.ErrIdempotencyConflict
}
return stored.message, nil
}
delete(r.idempotencyByScope, scope)
}
message, err := r.legacy.CreateMessage(
write.ChatID,
write.ActorID,
write.Text,
write.AttachmentIDs,
)
if err != nil {
return domain.Message{}, err
}
r.idempotencyByScope[scope] = memoryIdempotencyResult{
requestHash: write.RequestHash,
message: message,
expiresAt: now.Add(write.TTL),
}
return message, nil
}
func (r *MemoryRepository) GetMessages(
ctx context.Context,
chatID string,
callerID string,
limit int,
cursor *domain.MessageCursor,
) ([]domain.Message, bool, error) {
if err := ctx.Err(); err != nil {
return nil, false, err
}
return r.legacy.GetMessages(
chatID,
callerID,
limit,
cursor,
)
}
func (r *MemoryRepository) CreateSession(
ctx context.Context,
tokenHash []byte,
userID string,
expiresAt time.Time,
) error {
if err := ctx.Err(); err != nil {
return err
}
key, err := memoryTokenHashKey(tokenHash)
if err != nil {
return err
}
r.mu.Lock()
r.sessionsByHashKey[key] = memorySession{
userID: userID,
expiresAt: expiresAt,
}
r.mu.Unlock()
return nil
}
func (r *MemoryRepository) GetUserBySession(
ctx context.Context,
tokenHash []byte,
) (domain.User, error) {
if err := ctx.Err(); err != nil {
return domain.User{}, err
}
key, err := memoryTokenHashKey(tokenHash)
if err != nil {
return domain.User{}, ErrNotFound
}
r.mu.RLock()
session, exists := r.sessionsByHashKey[key]
r.mu.RUnlock()
if !exists || !session.expiresAt.After(time.Now().UTC()) {
return domain.User{}, ErrNotFound
}
return r.legacy.GetUserByID(session.userID)
}
func (r *MemoryRepository) DeleteSession(
ctx context.Context,
tokenHash []byte,
) error {
if err := ctx.Err(); err != nil {
return err
}
key, err := memoryTokenHashKey(tokenHash)
if err != nil {
return err
}
r.mu.Lock()
delete(r.sessionsByHashKey, key)
r.mu.Unlock()
return nil
}
func (r *MemoryRepository) CreateAttachment(
ctx context.Context,
attachment domain.Attachment,
) (domain.Attachment, error) {
if err := ctx.Err(); err != nil {
return domain.Attachment{}, err
}
if err := r.legacy.PutAttachment(attachment); err != nil {
return domain.Attachment{}, err
}
return attachment, nil
}
func (r *MemoryRepository) MarkAttachmentReady(
ctx context.Context,
attachmentID string,
updatedAt time.Time,
) (domain.Attachment, error) {
if err := ctx.Err(); err != nil {
return domain.Attachment{}, err
}
return r.legacy.UpdateAttachmentStatus(
attachmentID,
domain.AttachmentStatusReady,
nil,
updatedAt,
)
}
func (r *MemoryRepository) MarkAttachmentFailed(
ctx context.Context,
attachmentID string,
errorCode string,
updatedAt time.Time,
) error {
if err := ctx.Err(); err != nil {
return err
}
_, err := r.legacy.UpdateAttachmentStatus(
attachmentID,
domain.AttachmentStatusFailed,
&errorCode,
updatedAt,
)
return err
}
func (r *MemoryRepository) GetAttachment(
ctx context.Context,
attachmentID string,
callerID string,
) (domain.Attachment, error) {
if err := ctx.Err(); err != nil {
return domain.Attachment{}, err
}
attachment, err := r.legacy.GetAttachmentByID(attachmentID)
if err != nil {
return domain.Attachment{}, err
}
if _, err = r.legacy.GetChatByID(attachment.ChatID, callerID); err != nil {
return domain.Attachment{}, err
}
if attachment.Variants == nil {
attachment.Variants = make([]domain.AttachmentVariant, 0)
}
return attachment, nil
}
func memoryTokenHashKey(tokenHash []byte) ([32]byte, error) {
var key [32]byte
if len(tokenHash) != len(key) {
return key, fmt.Errorf(
"session token hash must contain %d bytes",
len(key),
)
}
copy(key[:], tokenHash)
return key, nil
}
var _ application.Repository = (*MemoryRepository)(nil)