на оценку 3

This commit is contained in:
2026-10-21 13:51:35 +03:00
parent 3f69970b05
commit bd28f1ae26
24 changed files with 1130 additions and 91 deletions
+60 -13
View File
@@ -15,21 +15,36 @@ type memorySession struct {
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
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),
legacy: legacy,
passwordByUserID: make(map[string]string),
userIDByUsername: make(map[string]string),
sessionsByHashKey: make(map[[32]byte]memorySession),
idempotencyByScope: make(map[memoryIdempotencyScope]memoryIdempotencyResult),
}
}
@@ -129,17 +144,49 @@ func (r *MemoryRepository) GetChatsForUser(
return r.legacy.GetChatsForUser(userID, limit, cursor)
}
func (r *MemoryRepository) CreateMessage(
func (r *MemoryRepository) CreateMessageIdempotently(
ctx context.Context,
chatID string,
senderID string,
text string,
write application.IdempotentMessageWrite,
) (domain.Message, error) {
if err := ctx.Err(); err != nil {
return domain.Message{}, err
}
return r.legacy.CreateMessage(chatID, senderID, text)
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
}
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)
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(
+155 -26
View File
@@ -1,33 +1,172 @@
package postgres
import (
"bytes"
"context"
"errors"
"fmt"
"time"
"mtusi2026lab3/internal/application"
"mtusi2026lab3/internal/domain"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
)
func (s *PostgreSQLStore) CreateMessage(
func (s *PostgreSQLStore) CreateMessageIdempotently(
ctx context.Context,
chatID string,
senderID string,
text string,
write application.IdempotentMessageWrite,
) (domain.Message, error) {
queryContext, cancel := s.withTimeout(ctx)
defer cancel()
message := domain.Message{
ID: uuid.NewString(),
ChatID: chatID,
SenderID: senderID,
Text: text,
transaction, err := s.pool.BeginTx(queryContext, pgx.TxOptions{})
if err != nil {
return domain.Message{}, fmt.Errorf("begin idempotent message transaction: %w", err)
}
defer func() { _ = transaction.Rollback(queryContext) }()
var isMember bool
err = transaction.QueryRow(
queryContext,
`
SELECT EXISTS (
SELECT 1
FROM chat_members
WHERE chat_id = $1
AND user_id = $2
)
`,
write.ChatID,
write.ActorID,
).Scan(&isMember)
if err != nil {
return domain.Message{}, fmt.Errorf("check chat membership: %w", err)
}
if !isMember {
return domain.Message{}, ErrNotFound
}
err := s.pool.QueryRow(
_, err = transaction.Exec(
queryContext,
`
DELETE FROM message_idempotency
WHERE user_id = $1
AND method = $2
AND canonical_path = $3
AND idempotency_key = $4
AND expires_at <= CURRENT_TIMESTAMP
`,
write.ActorID,
write.Method,
write.CanonicalPath,
write.Key,
)
if err != nil {
return domain.Message{}, fmt.Errorf("delete expired idempotency key: %w", err)
}
message := domain.Message{
ID: uuid.NewString(),
ChatID: write.ChatID,
SenderID: write.ActorID,
Text: write.Text,
}
var storedHash []byte
var storedMessageID string
err = transaction.QueryRow(
queryContext,
`
INSERT INTO message_idempotency (
user_id,
method,
canonical_path,
idempotency_key,
request_hash,
message_id,
expires_at
)
VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
CURRENT_TIMESTAMP + $7 * INTERVAL '1 second'
)
ON CONFLICT DO NOTHING
RETURNING request_hash, message_id::text
`,
write.ActorID,
write.Method,
write.CanonicalPath,
write.Key,
write.RequestHash[:],
message.ID,
int64(write.TTL/time.Second),
).Scan(&storedHash, &storedMessageID)
if errors.Is(err, pgx.ErrNoRows) {
err = transaction.QueryRow(
queryContext,
`
SELECT request_hash, message_id::text
FROM message_idempotency
WHERE user_id = $1
AND method = $2
AND canonical_path = $3
AND idempotency_key = $4
`,
write.ActorID,
write.Method,
write.CanonicalPath,
write.Key,
).Scan(&storedHash, &storedMessageID)
if err != nil {
return domain.Message{}, fmt.Errorf("read idempotency result: %w", err)
}
if !bytes.Equal(storedHash, write.RequestHash[:]) {
return domain.Message{}, application.ErrIdempotencyConflict
}
err = transaction.QueryRow(
queryContext,
`
SELECT
id::text,
chat_id::text,
sender_id::text,
text,
created_at
FROM messages
WHERE id = $1
`,
storedMessageID,
).Scan(
&message.ID,
&message.ChatID,
&message.SenderID,
&message.Text,
&message.CreatedAt,
)
if err != nil {
return domain.Message{}, fmt.Errorf("read idempotent message: %w", err)
}
if err = transaction.Commit(queryContext); err != nil {
return domain.Message{}, fmt.Errorf("commit idempotency replay: %w", err)
}
return message, nil
}
if err != nil {
return domain.Message{}, fmt.Errorf("claim idempotency key: %w", err)
}
err = transaction.QueryRow(
queryContext,
`
INSERT INTO messages (
@@ -36,14 +175,7 @@ func (s *PostgreSQLStore) CreateMessage(
sender_id,
text
)
SELECT
$1,
$2,
$3,
$4
FROM chat_members
WHERE chat_id = $2
AND user_id = $3
VALUES ($1, $2, $3, $4)
RETURNING created_at
`,
message.ID,
@@ -51,18 +183,15 @@ func (s *PostgreSQLStore) CreateMessage(
message.SenderID,
message.Text,
).Scan(&message.CreatedAt)
if err == nil {
return message, nil
if err != nil {
return domain.Message{}, fmt.Errorf("insert message: %w", err)
}
// INSERT ... SELECT возвращает zero rows, если отправитель
// не является участником указанного чата.
if errors.Is(err, pgx.ErrNoRows) {
return domain.Message{}, ErrNotFound
if err = transaction.Commit(queryContext); err != nil {
return domain.Message{}, fmt.Errorf("commit idempotent message: %w", err)
}
return domain.Message{}, fmt.Errorf("insert message: %w", err)
return message, nil
}
func (s *PostgreSQLStore) GetMessages(
+6 -3
View File
@@ -18,7 +18,10 @@ type CreateChatCommand struct {
}
type SendMessageCommand struct {
ActorID string
ChatID string
Text string
ActorID string
ChatID string
Text string
Method string
CanonicalPath string
IdempotencyKey string
}
+5 -4
View File
@@ -3,8 +3,9 @@ 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")
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")
)
+26 -1
View File
@@ -2,16 +2,41 @@ package application
import (
"context"
"crypto/sha256"
"encoding/json"
"fmt"
"mtusi2026lab3/internal/domain"
)
type canonicalMessageRequest struct {
Text string `json:"text"`
AttachmentIDs []string `json:"attachment_ids"`
}
func (s *Service) SendMessage(ctx context.Context, command SendMessageCommand) (domain.Message, error) {
if err := domain.ValidateMessageText(command.Text); err != nil {
return domain.Message{}, fmt.Errorf("%w: %v", ErrInvalidInput, err)
}
return s.repository.CreateMessage(ctx, command.ChatID, command.ActorID, command.Text)
canonicalBody, err := json.Marshal(canonicalMessageRequest{
Text: command.Text,
AttachmentIDs: make([]string, 0),
})
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,
Method: command.Method,
CanonicalPath: command.CanonicalPath,
Key: command.IdempotencyKey,
RequestHash: sha256.Sum256(canonicalBody),
TTL: s.idempotencyTTL,
})
}
func (s *Service) ListMessages(
+12 -1
View File
@@ -24,8 +24,19 @@ type ChatRepository interface {
GetChatsForUser(ctx context.Context, userID string, limit int, cursor *domain.ChatCursor) ([]domain.Chat, bool, error)
}
type IdempotentMessageWrite struct {
ActorID string
ChatID string
Text string
Method string
CanonicalPath string
Key string
RequestHash [32]byte
TTL time.Duration
}
type MessageRepository interface {
CreateMessage(ctx context.Context, chatID, senderID, text string) (domain.Message, error)
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)
}
+33 -11
View File
@@ -5,14 +5,19 @@ import (
"time"
)
const MinimumIdempotencyTTL = 24 * time.Hour
type ServiceOption func(*Service) error
type Service struct {
repository Repository
cursors *CursorCodec
sessionTTL time.Duration
now func() time.Time
repository Repository
cursors *CursorCodec
sessionTTL time.Duration
idempotencyTTL time.Duration
now func() time.Time
}
func NewService(repository Repository, cursors *CursorCodec, sessionTTL time.Duration) (*Service, error) {
func NewService(repository Repository, cursors *CursorCodec, sessionTTL time.Duration, options ...ServiceOption) (*Service, error) {
if repository == nil {
return nil, fmt.Errorf("repository is required")
}
@@ -22,10 +27,27 @@ func NewService(repository Repository, cursors *CursorCodec, sessionTTL time.Dur
if sessionTTL <= 0 {
return nil, fmt.Errorf("session TTL must be positive")
}
return &Service{
repository: repository,
cursors: cursors,
sessionTTL: sessionTTL,
now: func() time.Time { return time.Now().UTC() },
}, nil
service := &Service{
repository: repository,
cursors: cursors,
sessionTTL: sessionTTL,
idempotencyTTL: MinimumIdempotencyTTL,
now: func() time.Time { return time.Now().UTC() },
}
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
}
}
+47 -2
View File
@@ -5,16 +5,19 @@ import (
"fmt"
"net"
"os"
"regexp"
"strconv"
"strings"
"time"
)
type Config struct {
HTTPHost string
HTTPPort string
HTTPHost string
HTTPPort string
InstanceID string
SessionTTL time.Duration
IdempotencyTTL time.Duration
CursorSigningKey string
DatabaseURL string
@@ -36,6 +39,11 @@ type Config struct {
}
func Load() (Config, error) {
instanceID, err := instanceIDFromEnv()
if err != nil {
return Config{}, err
}
sessionTTL, err := secondsDurationFromEnv(
"SESSION_TTL_SECONDS",
3600,
@@ -44,6 +52,14 @@ func Load() (Config, error) {
return Config{}, err
}
idempotencyTTL, err := secondsDurationFromEnv(
"IDEMPOTENCY_TTL_SECONDS",
86400,
)
if err != nil {
return Config{}, err
}
databaseURL, err := requiredValueOrFile(
"DATABASE_URL",
"DATABASE_URL_FILE",
@@ -158,10 +174,18 @@ func Load() (Config, error) {
)
}
if idempotencyTTL < 24*time.Hour {
return Config{}, errors.New(
"IDEMPOTENCY_TTL_SECONDS must be at least 86400",
)
}
return Config{
HTTPHost: envOrDefault("APP_HOST", "0.0.0.0"),
HTTPPort: envOrDefault("APP_PORT", "8080"),
InstanceID: instanceID,
SessionTTL: sessionTTL,
IdempotencyTTL: idempotencyTTL,
CursorSigningKey: cursorSigningKey,
DatabaseURL: databaseURL,
@@ -183,6 +207,27 @@ func Load() (Config, error) {
}, nil
}
var instanceIDPattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$`)
func instanceIDFromEnv() (string, error) {
instanceID := strings.TrimSpace(os.Getenv("INSTANCE_ID"))
if instanceID == "" {
hostname, err := os.Hostname()
if err != nil {
return "", fmt.Errorf("resolve instance id from hostname: %w", err)
}
instanceID = hostname
}
if !instanceIDPattern.MatchString(instanceID) {
return "", errors.New(
"INSTANCE_ID or hostname must match [A-Za-z0-9][A-Za-z0-9._-]{0,127}",
)
}
return instanceID, nil
}
func (c Config) HTTPAddress() string {
return net.JoinHostPort(c.HTTPHost, c.HTTPPort)
}
+35
View File
@@ -0,0 +1,35 @@
package config
import "testing"
func TestInstanceIDFromEnvironment(t *testing.T) {
t.Setenv("INSTANCE_ID", "api-replica_01")
instanceID, err := instanceIDFromEnv()
if err != nil {
t.Fatal(err)
}
if instanceID != "api-replica_01" {
t.Fatalf("got %q, want api-replica_01", instanceID)
}
}
func TestInstanceIDRejectsUnsafeHeaderValue(t *testing.T) {
t.Setenv("INSTANCE_ID", "api-1\r\nX-Forged: true")
if _, err := instanceIDFromEnv(); err == nil {
t.Fatal("expected unsafe instance ID to be rejected")
}
}
func TestInstanceIDFallsBackToHostname(t *testing.T) {
t.Setenv("INSTANCE_ID", "")
instanceID, err := instanceIDFromEnv()
if err != nil {
t.Fatal(err)
}
if instanceID == "" {
t.Fatal("hostname fallback returned an empty instance ID")
}
}
@@ -3,6 +3,7 @@ package handlers
import (
"errors"
"net/http"
"regexp"
"strings"
"mtusi2026lab3/internal/application"
@@ -14,15 +15,25 @@ import (
"github.com/google/uuid"
)
var idempotencyKeyPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
func (h *Handler) CreateMessage(w http.ResponseWriter, r *http.Request) {
requestID := middleware.GetRequestID(r.Context())
currentUser := middleware.GetCurrentUser(r.Context())
chatID := r.PathValue("chat_id")
if _, err := uuid.Parse(chatID); err != nil {
parsedChatID, err := uuid.Parse(r.PathValue("chat_id"))
if err != nil {
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
"invalid chat_id uuid", requestID)
return
}
chatID := parsedChatID.String()
idempotencyKey := r.Header.Get("Idempotency-Key")
if !idempotencyKeyPattern.MatchString(idempotencyKey) {
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
"Idempotency-Key must match [A-Za-z0-9._:-]{1,128}", requestID)
return
}
var request dto.CreateMessageRequest
if err := decodeJSON(r, &request); err != nil {
@@ -30,8 +41,18 @@ func (h *Handler) CreateMessage(w http.ResponseWriter, r *http.Request) {
return
}
message, err := h.service.SendMessage(r.Context(), application.SendMessageCommand{
ActorID: currentUser.ID, ChatID: chatID, Text: request.Text,
ActorID: currentUser.ID,
ChatID: chatID,
Text: request.Text,
Method: http.MethodPost,
CanonicalPath: "/api/v1/chats/" + chatID + "/messages",
IdempotencyKey: idempotencyKey,
})
if errors.Is(err, application.ErrIdempotencyConflict) {
response.WriteError(w, http.StatusConflict, response.CodeConflict,
"Idempotency-Key is already used for another request", requestID)
return
}
if errors.Is(err, application.ErrInvalidInput) {
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest,
strings.TrimPrefix(err.Error(), application.ErrInvalidInput.Error()+": "), requestID)
@@ -0,0 +1,15 @@
package middleware
import "net/http"
const InstanceIDHeader = "X-Instance-Id"
// InstanceID identifies the process that actually produced the response.
// It must wrap recovery and routing so even errors, health checks and 404/405
// responses carry the same stable process identifier.
func InstanceID(instanceID string, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set(InstanceIDHeader, instanceID)
next.ServeHTTP(w, r)
})
}
@@ -0,0 +1,50 @@
package middleware
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestInstanceIDOnSuccessfulAndNotFoundResponses(t *testing.T) {
mux := http.NewServeMux()
mux.HandleFunc("GET /ok", func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusNoContent)
})
handler := InstanceID("api-01", mux)
for _, test := range []struct {
path string
wantStatus int
}{
{path: "/ok", wantStatus: http.StatusNoContent},
{path: "/missing", wantStatus: http.StatusNotFound},
} {
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, test.path, nil))
if recorder.Code != test.wantStatus {
t.Fatalf("%s: got status %d, want %d", test.path, recorder.Code, test.wantStatus)
}
if got := recorder.Header().Get(InstanceIDHeader); got != "api-01" {
t.Fatalf("%s: got instance ID %q, want api-01", test.path, got)
}
}
}
func TestInstanceIDSurvivesRecoveredPanic(t *testing.T) {
panicking := http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
panic("test panic")
})
handler := InstanceID("api-panic", Recovery(panicking))
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/panic", nil))
if recorder.Code != http.StatusInternalServerError {
t.Fatalf("got status %d, want 500", recorder.Code)
}
if got := recorder.Header().Get(InstanceIDHeader); got != "api-panic" {
t.Fatalf("got instance ID %q, want api-panic", got)
}
}