forked from mtusi2026/mtusi2026lab3
Реализовать lab3 в общем Helm-релизе с Traefik, TLS и HPA
This commit is contained in:
@@ -16,6 +16,8 @@ const (
|
||||
|
||||
// Controller contains settings owned exclusively by the HTTP transport.
|
||||
type Controller struct {
|
||||
// InstanceID identifies this API process to the load balancer diagnostics.
|
||||
InstanceID string
|
||||
// Host is the IP address on which the listener binds.
|
||||
Host string
|
||||
// Port is the TCP port, in the range 1..65535.
|
||||
@@ -85,6 +87,7 @@ func defaultController() *Controller {
|
||||
|
||||
// loadEnvironment applies environment overrides to this configuration section.
|
||||
func (cfg *Controller) loadEnvironment() error {
|
||||
cfg.InstanceID = os.Getenv("INSTANCE_ID")
|
||||
if host, exists := os.LookupEnv("APP_HOST"); exists {
|
||||
cfg.Host = host
|
||||
}
|
||||
|
||||
@@ -8,6 +8,8 @@ import (
|
||||
|
||||
// Persistence contains database, cache and session settings.
|
||||
type Persistence struct {
|
||||
// CursorKey is the shared base64 signing key supplied through a secret.
|
||||
CursorKey string
|
||||
// DatabaseURL identifies the PostgreSQL database.
|
||||
DatabaseURL string
|
||||
// Shards maps stable identities to Valkey addresses.
|
||||
@@ -25,6 +27,7 @@ type Persistence struct {
|
||||
// NewPersistence loads dependency settings separately from HTTP configuration.
|
||||
func NewPersistence() (*Persistence, error) {
|
||||
cfg := &Persistence{
|
||||
CursorKey: os.Getenv("CURSOR_SIGNING_KEY"),
|
||||
DatabaseURL: os.Getenv("DATABASE_URL"),
|
||||
Coordinator: os.Getenv("VALKEY_COORDINATOR"),
|
||||
Shards: make(map[string]string),
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/google/uuid"
|
||||
"go.lab260.ru/fielderr"
|
||||
"go.uber.org/zap"
|
||||
|
||||
@@ -19,6 +20,7 @@ import (
|
||||
// Its configuration is copied at construction and must not change during serving.
|
||||
// Fx manages its listener through Start and Stop.
|
||||
type Controller struct {
|
||||
metrics *httpMetrics
|
||||
log *zap.Logger
|
||||
cfg config.Controller
|
||||
service service.Service
|
||||
@@ -28,6 +30,7 @@ type Controller struct {
|
||||
auth service.Authentication
|
||||
readiness Readiness
|
||||
stopping atomic.Bool
|
||||
instanceID string
|
||||
serveDone chan error
|
||||
}
|
||||
|
||||
@@ -43,6 +46,7 @@ func New(log *zap.Logger, cfg *config.Controller, svc service.Service, registry
|
||||
return nil, fmt.Errorf("HTTP logger, service, error registry and admission limiter are required")
|
||||
}
|
||||
ctrl := &Controller{
|
||||
metrics: newHTTPMetrics(),
|
||||
log: log.Named("controller.http.fiber"),
|
||||
cfg: *cfg,
|
||||
service: svc,
|
||||
@@ -52,6 +56,10 @@ func New(log *zap.Logger, cfg *config.Controller, svc service.Service, registry
|
||||
readiness: readiness,
|
||||
serveDone: make(chan error, 1),
|
||||
}
|
||||
ctrl.instanceID = cfg.InstanceID
|
||||
if ctrl.instanceID == "" {
|
||||
ctrl.instanceID = uuid.NewString()
|
||||
}
|
||||
ctrl.configure()
|
||||
return ctrl, nil
|
||||
}
|
||||
|
||||
@@ -66,6 +66,7 @@ func testController(t *testing.T, change func(*config.Config)) *Controller {
|
||||
// request sends a raw test request and decodes its response.
|
||||
func request(ctrl *Controller, method, path, actor string, body []byte) (int, map[string]any, error) {
|
||||
req := httptest.NewRequest(method, path, bytes.NewReader(body))
|
||||
req.Header.Set("Idempotency-Key", uuid.NewString())
|
||||
if body != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
|
||||
@@ -76,9 +76,10 @@ func (ctrl *Controller) HandleMessagesCreate(ctx *fiber.Ctx) error {
|
||||
return err
|
||||
}
|
||||
message, err := ctrl.service.MessagesCreate(ctx.UserContext(), dto.MessagesCreateRequestDTO{
|
||||
UserID: identity(ctx),
|
||||
ChatID: ctx.Params("chat_id"),
|
||||
Text: request.Text,
|
||||
IdempotencyKey: ctx.Get("Idempotency-Key"),
|
||||
UserID: identity(ctx),
|
||||
ChatID: ctx.Params("chat_id"),
|
||||
Text: request.Text,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/gofiber/fiber/v2/middleware/adaptor"
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"github.com/prometheus/client_golang/prometheus/promhttp"
|
||||
)
|
||||
|
||||
// httpMetrics owns a per-server registry with bounded labels and no user identifiers.
|
||||
type httpMetrics struct {
|
||||
registry *prometheus.Registry
|
||||
requests *prometheus.CounterVec
|
||||
duration *prometheus.HistogramVec
|
||||
active prometheus.Gauge
|
||||
}
|
||||
|
||||
// newHTTPMetrics creates independent collectors so multiple test servers do not share state.
|
||||
func newHTTPMetrics() *httpMetrics {
|
||||
metrics := &httpMetrics{
|
||||
registry: prometheus.NewRegistry(),
|
||||
requests: prometheus.NewCounterVec(prometheus.CounterOpts{Name: "messenger_http_requests_total", Help: "Completed requests by route, method and status class."}, []string{"route", "method", "status_class"}),
|
||||
duration: prometheus.NewHistogramVec(prometheus.HistogramOpts{Name: "messenger_http_duration_seconds", Help: "Completed request latency.", Buckets: prometheus.DefBuckets}, []string{"route", "method"}),
|
||||
active: prometheus.NewGauge(prometheus.GaugeOpts{Name: "messenger_http_in_flight", Help: "Currently executing HTTP requests."}),
|
||||
}
|
||||
metrics.registry.MustRegister(metrics.requests, metrics.duration, metrics.active)
|
||||
return metrics
|
||||
}
|
||||
|
||||
// observe records bounded route patterns, methods and status classes after error handling.
|
||||
func (m *httpMetrics) observe(ctx *fiber.Ctx, elapsed time.Duration) {
|
||||
route := "unmatched"
|
||||
if ctx.Route() != nil && ctx.Route().Path != "/" {
|
||||
route = ctx.Route().Path
|
||||
}
|
||||
method := ctx.Method()
|
||||
switch method {
|
||||
case http.MethodGet, http.MethodPost, http.MethodDelete, http.MethodHead, http.MethodOptions:
|
||||
default:
|
||||
method = "other"
|
||||
}
|
||||
status := "5xx"
|
||||
switch ctx.Response().StatusCode() / 100 {
|
||||
case 2:
|
||||
status = "2xx"
|
||||
case 3:
|
||||
status = "3xx"
|
||||
case 4:
|
||||
status = "4xx"
|
||||
}
|
||||
m.requests.WithLabelValues(route, method, status).Inc()
|
||||
m.duration.WithLabelValues(route, method).Observe(elapsed.Seconds())
|
||||
}
|
||||
|
||||
// handleMetrics exposes this process's Prometheus registry without external backend calls.
|
||||
func (ctrl *Controller) handleMetrics(ctx *fiber.Ctx) error {
|
||||
return adaptor.HTTPHandler(promhttp.HandlerFor(ctrl.metrics.registry, promhttp.HandlerOpts{}))(ctx)
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package fiber
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestMetricsEndpoint exposes completed requests without token or user labels.
|
||||
func TestMetricsEndpoint(t *testing.T) {
|
||||
ctrl := testController(t, nil)
|
||||
call(t, ctrl, http.MethodGet, "/health/live", "", nil, http.StatusOK)
|
||||
resp, err := ctrl.server.Test(httptest.NewRequest(http.MethodGet, "/metrics", nil))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() {
|
||||
_ = resp.Body.Close()
|
||||
}()
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK || !strings.Contains(string(body), "messenger_http_requests_total") || !strings.Contains(string(body), "messenger_http_duration_seconds_bucket") {
|
||||
t.Fatalf("invalid metrics response: status %d", resp.StatusCode)
|
||||
}
|
||||
if resp.Header.Get("X-Instance-Id") == "" {
|
||||
t.Fatal("metrics response lacks instance ID")
|
||||
}
|
||||
}
|
||||
|
||||
// TestInstanceIdentityRemainsStable verifies errors and successes identify the same process.
|
||||
func TestInstanceIdentityRemainsStable(t *testing.T) {
|
||||
ctrl := testController(t, nil)
|
||||
var instance string
|
||||
for _, path := range []string{"/health/live", "/unknown"} {
|
||||
resp, err := ctrl.server.Test(httptest.NewRequest(http.MethodGet, path, nil))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if instance == "" {
|
||||
instance = resp.Header.Get("X-Instance-Id")
|
||||
}
|
||||
if instance == "" || resp.Header.Get("X-Instance-Id") != instance {
|
||||
t.Fatal("unstable instance identity")
|
||||
}
|
||||
if err := resp.Body.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestMissingIdempotencyHeader rejects an otherwise valid authenticated write.
|
||||
func TestMissingIdempotencyHeader(t *testing.T) {
|
||||
ctrl := testController(t, nil)
|
||||
caller := user(t, ctrl)
|
||||
room := chat(t, ctrl, caller)
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/chats/"+room+"/messages", strings.NewReader(`{"text":"valid"}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+caller)
|
||||
resp, err := ctrl.server.Test(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() {
|
||||
_ = resp.Body.Close()
|
||||
}()
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("missing key accepted: %d", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
@@ -16,12 +16,18 @@ import (
|
||||
// request assigns a request identifier, handles errors and logs the completed request.
|
||||
func (ctrl *Controller) request(ctx *fiber.Ctx) error {
|
||||
ctx.Set(headerRequestID, uuid.NewString())
|
||||
ctx.Set("X-Instance-Id", ctrl.instanceID)
|
||||
started := time.Now()
|
||||
ctrl.metrics.active.Inc()
|
||||
defer ctrl.metrics.active.Dec()
|
||||
err := ctx.Next()
|
||||
if err != nil {
|
||||
err = ctrl.handleErr(ctx, err)
|
||||
}
|
||||
ctrl.logRequest(ctx, time.Since(started))
|
||||
if ctx.Path() != "/metrics" {
|
||||
ctrl.metrics.observe(ctx, time.Since(started))
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ package fiber
|
||||
|
||||
// initRoutes registers health endpoints and authenticated application routes.
|
||||
func (ctrl *Controller) initRoutes() {
|
||||
ctrl.server.Get("/metrics", ctrl.handleMetrics)
|
||||
ctrl.server.Get("/health/live", ctrl.handleLive)
|
||||
ctrl.server.Get("/health/ready", ctrl.handleReady)
|
||||
ctrl.server.Use(ctrl.admit)
|
||||
|
||||
@@ -106,3 +106,14 @@ func decodeCursorPosition(payload []byte, resource string) (Position, error) {
|
||||
}
|
||||
return Position{CreatedAt: cursor.Time, ID: cursor.ID}, nil
|
||||
}
|
||||
|
||||
// NewShared creates a codec from the common 256-bit key provisioned to every replica.
|
||||
func NewShared(encoded string) (*Codec, error) {
|
||||
key, err := base64.StdEncoding.DecodeString(encoded)
|
||||
if err != nil || len(key) != cursorSigningKeyBytes {
|
||||
return nil, fmt.Errorf("CURSOR_SIGNING_KEY must encode exactly 32 bytes as base64")
|
||||
}
|
||||
codec := &Codec{}
|
||||
copy(codec.key[:], key)
|
||||
return codec, nil
|
||||
}
|
||||
|
||||
@@ -177,3 +177,36 @@ func encodeFixture(t *testing.T, codec *Codec, resource string) string {
|
||||
}
|
||||
return token
|
||||
}
|
||||
|
||||
// TestSharedCodec verifies a second process can verify the first process's cursor.
|
||||
func TestSharedCodec(t *testing.T) {
|
||||
key := base64.StdEncoding.EncodeToString(make([]byte, 32))
|
||||
first, err := NewShared(key)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
second, err := NewShared(key)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
position := Position{CreatedAt: time.Now().UTC(), ID: uuid.New()}
|
||||
encoded, err := first.Encode("chat", position)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
result, err := second.Decode(encoded, "chat")
|
||||
if err != nil || result != position {
|
||||
t.Fatalf("cross-replica cursor: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSharedCodecRejectsInvalidKey requires a full 256-bit decoded secret.
|
||||
func TestSharedCodecRejectsInvalidKey(t *testing.T) {
|
||||
for _, key := range []string{"", "broken!", base64.StdEncoding.EncodeToString([]byte("short"))} {
|
||||
t.Run(key, func(t *testing.T) {
|
||||
if _, err := NewShared(key); err == nil {
|
||||
t.Fatal("invalid key accepted")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,6 +33,8 @@ type ChatDTO struct {
|
||||
|
||||
// MessageDTO is an immutable message stored in a chat.
|
||||
type MessageDTO struct {
|
||||
// IdempotencyKey identifies a validated retry within the sender and chat scope.
|
||||
IdempotencyKey string
|
||||
// ID is the server-generated message identifier.
|
||||
ID uuid.UUID
|
||||
// ChatID identifies the owning chat.
|
||||
@@ -65,6 +67,8 @@ type ChatsCreateRequestDTO struct {
|
||||
|
||||
// MessagesCreateRequestDTO carries untrusted message creation input.
|
||||
type MessagesCreateRequestDTO struct {
|
||||
// IdempotencyKey identifies a validated retry within the sender and chat scope.
|
||||
IdempotencyKey string
|
||||
// UserID is the authenticated caller identifier, never a supplied sender field.
|
||||
UserID string
|
||||
// ChatID is the raw chat UUID from the route.
|
||||
|
||||
@@ -37,13 +37,28 @@ func prepareChat(request dto.ChatsCreateRequestDTO, caller uuid.UUID) (dto.ChatD
|
||||
|
||||
// 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 !validText(request.Text, maxMessageRunes) {
|
||||
if !validText(request.Text, maxMessageRunes) || !validIdempotencyKey(request.IdempotencyKey) {
|
||||
return dto.MessageDTO{}, service.ErrInvalid
|
||||
}
|
||||
return dto.MessageDTO{
|
||||
ID: uuid.New(),
|
||||
ChatID: chatID,
|
||||
SenderID: sender,
|
||||
Text: request.Text,
|
||||
ID: uuid.New(),
|
||||
ChatID: chatID,
|
||||
SenderID: sender,
|
||||
Text: request.Text,
|
||||
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
|
||||
}
|
||||
|
||||
@@ -29,7 +29,7 @@ func TestService_MessagesCreate(t *testing.T) {
|
||||
return input, nil
|
||||
}
|
||||
svc := newStubService(t, repo)
|
||||
input := dto.MessagesCreateRequestDTO{UserID: actor.String(), ChatID: chat.ID.String(), Text: " Original 👋 "}
|
||||
input := dto.MessagesCreateRequestDTO{IdempotencyKey: "fixture-key", UserID: actor.String(), ChatID: chat.ID.String(), Text: " Original 👋 "}
|
||||
|
||||
// Act.
|
||||
got, err := svc.MessagesCreate(t.Context(), input)
|
||||
@@ -53,7 +53,7 @@ func TestService_MessagesCreate(t *testing.T) {
|
||||
chat := dto.ChatDTO{ID: uuid.New(), MemberIDs: []uuid.UUID{uuid.New()}}
|
||||
allowChatAccess(repo, actor, chat)
|
||||
svc := newStubService(t, repo)
|
||||
input := dto.MessagesCreateRequestDTO{UserID: actor.String(), ChatID: chat.ID.String(), Text: "Valid text"}
|
||||
input := dto.MessagesCreateRequestDTO{IdempotencyKey: "fixture-key", UserID: actor.String(), ChatID: chat.ID.String(), Text: "Valid text"}
|
||||
|
||||
// Act.
|
||||
got, err := svc.MessagesCreate(t.Context(), input)
|
||||
@@ -67,7 +67,7 @@ func TestService_MessagesCreate(t *testing.T) {
|
||||
t.Run("Negative: malformed identity skips storage", func(t *testing.T) {
|
||||
// Arrange.
|
||||
svc := newStubService(t, newStoreStub(t))
|
||||
input := dto.MessagesCreateRequestDTO{UserID: "invalid", ChatID: uuid.NewString(), Text: "text"}
|
||||
input := dto.MessagesCreateRequestDTO{IdempotencyKey: "fixture-key", UserID: "invalid", ChatID: uuid.NewString(), Text: "text"}
|
||||
|
||||
// Act.
|
||||
got, err := svc.MessagesCreate(t.Context(), input)
|
||||
@@ -97,7 +97,7 @@ func TestService_MessagesCreate_InvalidText(t *testing.T) {
|
||||
chat := dto.ChatDTO{ID: uuid.New(), MemberIDs: []uuid.UUID{actor}}
|
||||
allowChatAccess(repo, actor, chat)
|
||||
svc := newStubService(t, repo)
|
||||
input := dto.MessagesCreateRequestDTO{UserID: actor.String(), ChatID: chat.ID.String(), Text: tc.text}
|
||||
input := dto.MessagesCreateRequestDTO{IdempotencyKey: "fixture-key", UserID: actor.String(), ChatID: chat.ID.String(), Text: tc.text}
|
||||
|
||||
// Act.
|
||||
got, err := svc.MessagesCreate(t.Context(), input)
|
||||
@@ -133,7 +133,7 @@ func TestService_MessagesCreate_StoreErrors(t *testing.T) {
|
||||
return dto.MessageDTO{}, tc.cause
|
||||
}
|
||||
svc := newStubService(t, repo)
|
||||
input := dto.MessagesCreateRequestDTO{UserID: actor.String(), ChatID: chat.ID.String(), Text: "Valid text"}
|
||||
input := dto.MessagesCreateRequestDTO{IdempotencyKey: "fixture-key", UserID: actor.String(), ChatID: chat.ID.String(), Text: "Valid text"}
|
||||
|
||||
// Act.
|
||||
got, err := svc.MessagesCreate(t.Context(), input)
|
||||
@@ -145,3 +145,25 @@ func TestService_MessagesCreate_StoreErrors(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 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,51 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/store"
|
||||
)
|
||||
|
||||
// replayMessage serializes one chat and returns an unexpired original response.
|
||||
func replayMessage(ctx context.Context, tx pgx.Tx, message dto.MessageDTO) (dto.MessageDTO, bool, error) {
|
||||
var locked string
|
||||
if err := tx.QueryRow(ctx, "SELECT id FROM chats WHERE id=@chat FOR UPDATE", pgx.StrictNamedArgs{"chat": message.ChatID}).Scan(&locked); err != nil {
|
||||
return dto.MessageDTO{}, false, err
|
||||
}
|
||||
if message.IdempotencyKey == "" {
|
||||
return dto.MessageDTO{}, false, nil
|
||||
}
|
||||
args := pgx.StrictNamedArgs{"user": message.SenderID, "chat": message.ChatID, "key": message.IdempotencyKey}
|
||||
if _, err := tx.Exec(ctx, `DELETE FROM message_idempotency WHERE user_id=@user AND chat_id=@chat AND key=@key AND expires_at<=clock_timestamp()`, args); err != nil {
|
||||
return dto.MessageDTO{}, false, err
|
||||
}
|
||||
var original dto.MessageDTO
|
||||
err := tx.QueryRow(ctx, `SELECT m.id,m.chat_id,m.sender_id,m.text,m.created_at FROM message_idempotency i JOIN messages m ON m.id=i.message_id
|
||||
WHERE i.user_id=@user AND i.chat_id=@chat AND i.key=@key`, args).Scan(&original.ID, &original.ChatID, &original.SenderID, &original.Text, &original.CreatedAt)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return dto.MessageDTO{}, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return dto.MessageDTO{}, false, err
|
||||
}
|
||||
if original.Text != message.Text {
|
||||
return dto.MessageDTO{}, false, store.ErrConflict
|
||||
}
|
||||
return original, true, nil
|
||||
}
|
||||
|
||||
// rememberMessage stores the result in the same transaction as the message insert.
|
||||
func rememberMessage(ctx context.Context, tx pgx.Tx, message dto.MessageDTO) error {
|
||||
if message.IdempotencyKey == "" {
|
||||
return nil
|
||||
}
|
||||
_, err := tx.Exec(ctx, `INSERT INTO message_idempotency(user_id,chat_id,key,message_id,expires_at)
|
||||
VALUES(@user,@chat,@key,@id,clock_timestamp()+interval '24 hours')`, pgx.StrictNamedArgs{
|
||||
"user": message.SenderID, "chat": message.ChatID, "key": message.IdempotencyKey, "id": message.ID,
|
||||
})
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/model/dto"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab3/internal/store"
|
||||
)
|
||||
|
||||
// TestMessageRetryRace verifies concurrent attempts commit exactly one message and replay its response.
|
||||
func TestMessageRetryRace(t *testing.T) {
|
||||
s := testStore(t)
|
||||
user := fixtureUser(t, s)
|
||||
chat := fixtureChat(t, s, user)
|
||||
var wg sync.WaitGroup
|
||||
outcomes := make(chan dto.MessageDTO, 12)
|
||||
failures := make(chan error, 12)
|
||||
for range 12 {
|
||||
wg.Go(func() {
|
||||
message, err := s.CreateMessage(t.Context(), dto.MessageDTO{ID: uuid.New(), ChatID: chat.ID, SenderID: user.ID, Text: "same", IdempotencyKey: "retry"})
|
||||
if err != nil {
|
||||
failures <- err
|
||||
return
|
||||
}
|
||||
outcomes <- message
|
||||
})
|
||||
}
|
||||
wg.Wait()
|
||||
close(failures)
|
||||
close(outcomes)
|
||||
for err := range failures {
|
||||
t.Error(err)
|
||||
}
|
||||
var original dto.MessageDTO
|
||||
for m := range outcomes {
|
||||
if original.ID == uuid.Nil {
|
||||
original = m
|
||||
}
|
||||
if m.ID != original.ID || m.Text != original.Text || !m.CreatedAt.Equal(original.CreatedAt) {
|
||||
t.Fatal("retry returned a different result")
|
||||
}
|
||||
}
|
||||
messages, err := s.Messages(t.Context(), chat.ID, dto.PositionDTO{}, 100)
|
||||
if err != nil || len(messages) != 1 {
|
||||
t.Fatalf("messages=%d error=%v", len(messages), err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestMessageRetryConflict rejects a different body without publishing a second message.
|
||||
func TestMessageRetryConflict(t *testing.T) {
|
||||
s := testStore(t)
|
||||
user := fixtureUser(t, s)
|
||||
chat := fixtureChat(t, s, user)
|
||||
message := dto.MessageDTO{ID: uuid.New(), ChatID: chat.ID, SenderID: user.ID, Text: "first", IdempotencyKey: "retry"}
|
||||
if _, err := s.CreateMessage(t.Context(), message); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
message.ID = uuid.New()
|
||||
message.Text = "different"
|
||||
if _, err := s.CreateMessage(t.Context(), message); !errors.Is(err, store.ErrConflict) {
|
||||
t.Fatalf("expected conflict: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestMessageRetryExpiry permits reuse after the original retention window ends.
|
||||
func TestMessageRetryExpiry(t *testing.T) {
|
||||
s := testStore(t)
|
||||
user := fixtureUser(t, s)
|
||||
chat := fixtureChat(t, s, user)
|
||||
message := dto.MessageDTO{ID: uuid.New(), ChatID: chat.ID, SenderID: user.ID, Text: "first", IdempotencyKey: "retry"}
|
||||
if _, err := s.CreateMessage(t.Context(), message); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.pool.Exec(t.Context(), "UPDATE message_idempotency SET expires_at=clock_timestamp()-interval '1 second'"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
message.ID = uuid.New()
|
||||
message.Text = "new"
|
||||
if result, err := s.CreateMessage(t.Context(), message); err != nil || result.ID != message.ID {
|
||||
t.Fatalf("expired result reused: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestMessageRetryRollback proves failed inserts leave no poisoned idempotency result.
|
||||
func TestMessageRetryRollback(t *testing.T) {
|
||||
s := testStore(t)
|
||||
user := fixtureUser(t, s)
|
||||
chat := fixtureChat(t, s, user)
|
||||
message := dto.MessageDTO{ID: uuid.New(), ChatID: chat.ID, SenderID: uuid.New(), Text: "first", IdempotencyKey: "retry"}
|
||||
if _, err := s.CreateMessage(t.Context(), message); err == nil {
|
||||
t.Fatal("missing sender accepted")
|
||||
}
|
||||
var count int
|
||||
if err := s.pool.QueryRow(t.Context(), "SELECT count(*) FROM message_idempotency").Scan(&count); err != nil || count != 0 {
|
||||
t.Fatalf("failed write stored a result: %d %v", count, err)
|
||||
}
|
||||
message.SenderID = user.ID
|
||||
if _, err := s.CreateMessage(t.Context(), message); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSchemaCheck verifies API schema checks neither create nor upgrade tables.
|
||||
func TestSchemaCheck(t *testing.T) {
|
||||
s := testStore(t)
|
||||
if err := s.CheckSchema(t.Context()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.pool.Exec(t.Context(), "DELETE FROM schema_migrations WHERE version=2"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.CheckSchema(t.Context()); err == nil {
|
||||
t.Fatal("outdated schema accepted")
|
||||
}
|
||||
s.Close()
|
||||
if err := s.CheckSchema(t.Context()); err == nil {
|
||||
t.Fatal("closed connection accepted")
|
||||
}
|
||||
}
|
||||
|
||||
// TestIdempotencyMigrationFailureRollsBackVersion keeps an unsuccessful DDL change out of migration history.
|
||||
func TestIdempotencyMigrationFailureRollsBackVersion(t *testing.T) {
|
||||
s := testStore(t)
|
||||
if _, err := s.pool.Exec(t.Context(), "DELETE FROM schema_migrations WHERE version=2"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// The existing table deliberately conflicts with the pending migration.
|
||||
if err := s.Start(t.Context()); err == nil {
|
||||
t.Fatal("conflicting DDL reported success")
|
||||
}
|
||||
var applied bool
|
||||
if err := s.pool.QueryRow(t.Context(), "SELECT EXISTS(SELECT 1 FROM schema_migrations WHERE version=2)").Scan(&applied); err != nil || applied {
|
||||
t.Fatalf("failed migration marked applied: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -14,14 +14,25 @@ func (s *Store) CreateMessage(ctx context.Context, message dto.MessageDTO) (dto.
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
err := pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error {
|
||||
original, found, err := replayMessage(ctx, tx, message)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if found {
|
||||
message = original
|
||||
return nil
|
||||
}
|
||||
if err := tx.QueryRow(ctx, `UPDATE chats SET last_message_at=GREATEST(clock_timestamp(),last_message_at+interval '1 microsecond')
|
||||
WHERE id=@chat RETURNING last_message_at`, pgx.StrictNamedArgs{"chat": message.ChatID}).Scan(&message.CreatedAt); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := tx.Exec(ctx, `INSERT INTO messages(id,chat_id,sender_id,text,created_at) VALUES(@id,@chat,@sender,@text,@time)`, pgx.StrictNamedArgs{
|
||||
_, err = tx.Exec(ctx, `INSERT INTO messages(id,chat_id,sender_id,text,created_at) VALUES(@id,@chat,@sender,@text,@time)`, pgx.StrictNamedArgs{
|
||||
"id": message.ID, "chat": message.ChatID, "sender": message.SenderID, "text": message.Text, "time": message.CreatedAt,
|
||||
})
|
||||
return err
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return rememberMessage(ctx, tx, message)
|
||||
})
|
||||
return message, normalize(err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
CREATE TABLE message_idempotency (
|
||||
user_id uuid NOT NULL REFERENCES users(id),
|
||||
chat_id uuid NOT NULL REFERENCES chats(id),
|
||||
key text NOT NULL,
|
||||
message_id uuid NOT NULL REFERENCES messages(id),
|
||||
expires_at timestamptz NOT NULL,
|
||||
PRIMARY KEY (user_id,chat_id,key)
|
||||
);
|
||||
CREATE INDEX message_idempotency_expiry ON message_idempotency(expires_at);
|
||||
@@ -22,6 +22,9 @@ import (
|
||||
//go:embed migrations/001_initial.sql
|
||||
var initialMigration string
|
||||
|
||||
//go:embed migrations/002_idempotency.sql
|
||||
var idempotencyMigration string
|
||||
|
||||
const migrationLockID = 202602
|
||||
|
||||
// Options bounds database resource use.
|
||||
@@ -79,14 +82,24 @@ func (s *Store) Start(ctx context.Context) error {
|
||||
if err := tx.QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM schema_migrations WHERE version=1)").Scan(&exists); err != nil {
|
||||
return err
|
||||
}
|
||||
if !exists {
|
||||
if _, err := tx.Exec(ctx, initialMigration); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Exec(ctx, "INSERT INTO schema_migrations(version) VALUES(1)"); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := tx.QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM schema_migrations WHERE version=2)").Scan(&exists); err != nil {
|
||||
return err
|
||||
}
|
||||
if exists {
|
||||
return nil
|
||||
}
|
||||
|
||||
if _, err := tx.Exec(ctx, initialMigration); err != nil {
|
||||
if _, err := tx.Exec(ctx, idempotencyMigration); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := tx.Exec(ctx, "INSERT INTO schema_migrations(version) VALUES(1)")
|
||||
_, err := tx.Exec(ctx, "INSERT INTO schema_migrations(version) VALUES(2)")
|
||||
return err
|
||||
})
|
||||
}
|
||||
@@ -125,3 +138,17 @@ func normalize(err error) error {
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// CheckSchema verifies readiness without allowing API replicas to run DDL.
|
||||
func (s *Store) CheckSchema(ctx context.Context) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
var version int
|
||||
if err := s.pool.QueryRow(ctx, "SELECT COALESCE(max(version),0) FROM schema_migrations").Scan(&version); err != nil {
|
||||
return err
|
||||
}
|
||||
if version != 2 {
|
||||
return fmt.Errorf("database schema version %d; run server migrate", version)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user