Lab3 baseline: HAProxy, replicated stateless API, shared PostgreSQL/Valkey, idempotent messages

This commit is contained in:
Ivan Melnikov
2026-12-02 18:22:57 +03:00
parent 0ab3a341aa
commit e9bf138053
474 changed files with 206416 additions and 16 deletions
+119
View File
@@ -0,0 +1,119 @@
// Package cursor implements the opaque keyset cursor of the contract. A cursor
// carries the last item already returned; the next page asks PostgreSQL for
// rows strictly after (created_at, id). Cursors are bound to the endpoint and,
// for message history, to the chat that issued them.
package cursor
import (
"bytes"
"encoding/base64"
"encoding/json"
"errors"
"io"
"time"
"mtusi.ru/messenger-lab3/internal/model"
"mtusi.ru/messenger-lab3/internal/uuid"
)
const (
ScopeChats = "chats"
ScopeMessages = "messages"
version = 1
maxCursorSize = 512
)
// ErrInvalid is returned for malformed, tampered or out-of-scope cursors. The
// HTTP layer maps it to 400 invalid_request.
var ErrInvalid = errors.New("invalid cursor")
// Cursor is the decoded keyset position.
type Cursor struct {
At time.Time
ID string
ChatID string
}
// Encoding of the wire form. Time is an RFC 3339 timestamp with UTC Z and
// microsecond precision, matching PostgreSQL timestamptz. It is never used as
// an identifier on its own.
type wire struct {
Version int `json:"v"`
Scope string `json:"s"`
ChatID string `json:"c,omitempty"`
Time string `json:"t"`
ID string `json:"i"`
}
// ForChat encodes the position of the last returned chat.
func ForChat(chat model.Chat) string {
return encode(wire{Scope: ScopeChats, Time: chat.CreatedAt.UTC().Format(time.RFC3339Nano), ID: chat.ID})
}
// ForMessage encodes the position of the last returned message.
func ForMessage(message model.Message) string {
return encode(wire{
Scope: ScopeMessages,
ChatID: message.ChatID,
Time: message.CreatedAt.UTC().Format(time.RFC3339Nano),
ID: message.ID,
})
}
// Decode validates a cursor for the expected scope. chatID is required for the
// messages scope and must be empty for the chats scope.
func Decode(raw, scope, chatID string) (Cursor, error) {
if raw == "" || len(raw) > maxCursorSize {
return Cursor{}, ErrInvalid
}
data, err := base64.RawURLEncoding.DecodeString(raw)
if err != nil {
return Cursor{}, ErrInvalid
}
var value wire
decoder := json.NewDecoder(bytes.NewReader(data))
decoder.DisallowUnknownFields()
if err := decoder.Decode(&value); err != nil {
return Cursor{}, ErrInvalid
}
var extra any
if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) {
return Cursor{}, ErrInvalid
}
if value.Version != version || value.Scope != scope {
return Cursor{}, ErrInvalid
}
at, err := time.Parse(time.RFC3339Nano, value.Time)
if err != nil || at.IsZero() || at.Location() != time.UTC {
return Cursor{}, ErrInvalid
}
normalizedID, ok := uuid.Normalize(value.ID)
if !ok || normalizedID != value.ID {
return Cursor{}, ErrInvalid
}
switch scope {
case ScopeChats:
if value.ChatID != "" {
return Cursor{}, ErrInvalid
}
return Cursor{At: at, ID: normalizedID}, nil
case ScopeMessages:
normalizedChat, ok := uuid.Normalize(value.ChatID)
if !ok || normalizedChat != value.ChatID || normalizedChat != chatID {
return Cursor{}, ErrInvalid
}
return Cursor{At: at, ID: normalizedID, ChatID: normalizedChat}, nil
default:
return Cursor{}, ErrInvalid
}
}
func encode(value wire) string {
value.Version = version
data, err := json.Marshal(value)
if err != nil {
panic("encode cursor: " + err.Error())
}
return base64.RawURLEncoding.EncodeToString(data)
}
+97
View File
@@ -0,0 +1,97 @@
package cursor
import (
"encoding/base64"
"encoding/json"
"strings"
"testing"
"time"
"mtusi.ru/messenger-lab3/internal/model"
)
func TestChatCursorRoundTrip(t *testing.T) {
at := time.Date(2026, 11, 30, 12, 34, 56, 123456000, time.UTC)
chat := model.Chat{
ID: "11111111-2222-4333-8444-555555555555",
Title: "chat",
MemberIDs: []string{"11111111-2222-4333-8444-555555555555"},
CreatedAt: model.Time{Time: at},
}
raw := ForChat(chat)
decoded, err := Decode(raw, ScopeChats, "")
if err != nil {
t.Fatalf("Decode: %v", err)
}
if !decoded.At.Equal(at) || decoded.ID != chat.ID || decoded.ChatID != "" {
t.Fatalf("decoded = %+v", decoded)
}
}
func TestMessageCursorIsBoundToChat(t *testing.T) {
at := time.Now().UTC().Truncate(time.Microsecond)
chatID := "11111111-2222-4333-8444-555555555555"
message := model.Message{
ID: "99999999-2222-4333-8444-555555555555",
ChatID: chatID,
SenderID: "11111111-2222-4333-8444-555555555555",
Text: "hello",
CreatedAt: model.Time{Time: at},
}
raw := ForMessage(message)
if _, err := Decode(raw, ScopeMessages, chatID); err != nil {
t.Fatalf("Decode(same chat): %v", err)
}
if _, err := Decode(raw, ScopeMessages, "22222222-2222-4333-8444-555555555555"); err == nil {
t.Fatal("cursor was accepted for another chat")
}
if _, err := Decode(raw, ScopeChats, ""); err == nil {
t.Fatal("message cursor was accepted by the chats scope")
}
}
func TestDecodeRejectsTamperedCursors(t *testing.T) {
at := time.Now().UTC().Truncate(time.Microsecond)
valid := wire{
Version: version,
Scope: ScopeMessages,
ChatID: "11111111-2222-4333-8444-555555555555",
Time: at.Format(time.RFC3339Nano),
ID: "99999999-2222-4333-8444-555555555555",
}
tampered := []wire{
{Version: 2, Scope: valid.Scope, ChatID: valid.ChatID, Time: valid.Time, ID: valid.ID},
{Version: version, Scope: ScopeChats, ChatID: valid.ChatID, Time: valid.Time, ID: valid.ID},
{Version: version, Scope: valid.Scope, ChatID: "", Time: valid.Time, ID: valid.ID},
{Version: version, Scope: valid.Scope, ChatID: "not-a-uuid", Time: valid.Time, ID: valid.ID},
{Version: version, Scope: valid.Scope, ChatID: valid.ChatID, Time: "2026-11-30T12:00:00+03:00", ID: valid.ID},
{Version: version, Scope: valid.Scope, ChatID: valid.ChatID, Time: "yesterday", ID: valid.ID},
{Version: version, Scope: valid.Scope, ChatID: valid.ChatID, Time: valid.Time, ID: "not-a-uuid"},
}
for i, value := range tampered {
data, err := json.Marshal(value)
if err != nil {
t.Fatal(err)
}
raw := base64.RawURLEncoding.EncodeToString(data)
if _, err := Decode(raw, ScopeMessages, valid.ChatID); err == nil {
t.Fatalf("tampered cursor %d was accepted", i)
}
}
withExtra, _ := json.Marshal(map[string]any{
"v": version, "s": ScopeMessages, "c": valid.ChatID,
"t": valid.Time, "i": valid.ID, "x": 1,
})
if _, err := Decode(base64.RawURLEncoding.EncodeToString(withExtra), ScopeMessages, valid.ChatID); err == nil {
t.Fatal("cursor with an unknown field was accepted")
}
}
func TestDecodeRejectsGarbage(t *testing.T) {
for _, raw := range []string{"", "!!!", base64.RawURLEncoding.EncodeToString([]byte("not json")), strings.Repeat("a", 600)} {
if _, err := Decode(raw, ScopeChats, ""); err == nil {
t.Fatalf("Decode accepted %q", raw)
}
}
}