feat(app) lab2 prepared for mr

This commit is contained in:
imadev
2026-10-23 18:55:20 +03:00
parent 1db3953226
commit f6e74247fd
57 changed files with 2367 additions and 660 deletions
+29 -43
View File
@@ -2,59 +2,43 @@ package internal
import (
"errors"
"time"
"gitflic.ru/project/bulla-max/mtusi2026lab1/internal/chats"
"gitflic.ru/project/bulla-max/mtusi2026lab1/internal/common"
"gitflic.ru/project/bulla-max/mtusi2026lab1/internal/health"
"gitflic.ru/project/bulla-max/mtusi2026lab1/internal/messages"
"gitflic.ru/project/bulla-max/mtusi2026lab1/internal/storage"
"gitflic.ru/project/bulla-max/mtusi2026lab1/internal/users"
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/auth"
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/chats"
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/common"
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/config"
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/health"
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/messages"
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/session"
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/store"
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/users"
"github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/middleware/recover"
"github.com/gofiber/fiber/v3/middleware/requestid"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgxpool"
)
func SignalGracefulShutdown() {
health.SignalShutdown()
}
func authMiddleware(c fiber.Ctx) error {
userIDStr := c.Get("X-User-Id")
if userIDStr == "" {
return common.SendError(c, fiber.StatusUnauthorized,
common.ErrorCodeUnauthorized, "X-User-Id header is required")
}
func New(cfg config.Config, pool *pgxpool.Pool, sessions *session.Store) *fiber.App {
st := store.New(pool, cfg.DBTimeout)
userID, err := uuid.Parse(userIDStr)
if err != nil {
return common.SendError(c, fiber.StatusBadRequest,
common.ErrorCodeInvalidRequest, "X-User-Id must be a valid UUID")
}
var exists bool
err = storage.GlobalStore.View(func(tx storage.ReadOnlyTx) error {
_, exists = tx.GetUser(userID)
return nil
})
if err != nil || !exists {
return common.SendError(c, fiber.StatusUnauthorized,
common.ErrorCodeUnauthorized, "user not found")
}
c.Locals("userID", userID)
return c.Next()
}
func GetApp() *fiber.App {
app := fiber.New(fiber.Config{
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 60 * time.Second,
BodyLimit: 1 * 1024 * 1024,
ErrorHandler: func(c fiber.Ctx, err error) error {
if appErr, ok := errors.AsType[*common.AppError](err); ok {
var appErr *common.AppError
if errors.As(err, &appErr) {
return common.SendError(c, appErr.Status, appErr.Code, appErr.Message)
}
if fiberErr, ok := errors.AsType[*fiber.Error](err); ok {
var fiberErr *fiber.Error
if errors.As(err, &fiberErr) {
return common.SendError(c, fiberErr.Code,
common.ErrorCodeFromStatus(fiberErr.Code), fiberErr.Message)
}
@@ -67,16 +51,18 @@ func GetApp() *fiber.App {
app.Use(recover.New())
app.Use(requestid.New())
health.RegisterRoutes(app.Group("/health"))
health.RegisterRoutes(app.Group("/health"), st, sessions)
api := app.Group("/api/v1")
users.RegisterPublicRoutes(api)
users.RegisterPublicRoutes(api, st)
auth.RegisterPublicRoutes(api, st, sessions)
protected := api.Group("")
protected.Use(authMiddleware)
users.RegisterRoutes(protected)
chats.RegisterRoutes(protected)
messages.RegisterRoutes(protected)
protected.Use(auth.BearerAuth(sessions))
auth.RegisterRoutes(protected, st, sessions)
users.RegisterRoutes(protected, st)
chats.RegisterRoutes(protected, st)
messages.RegisterRoutes(protected, st)
return app
}
+132
View File
@@ -0,0 +1,132 @@
package auth
import (
"encoding/base64"
"errors"
"strings"
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/common"
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/model"
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/session"
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/store"
"github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/log"
)
const basicChallenge = `Basic realm="messenger", charset="UTF-8"`
const bearerChallenge = `Bearer realm="messenger"`
type Handler struct {
store *store.Store
sessions *session.Store
}
func NewHandler(st *store.Store, sessions *session.Store) *Handler {
return &Handler{store: st, sessions: sessions}
}
// AGENT: CreateSession is the only endpoint that accepts Basic auth. It reads
// no JSON body and returns the same 401 for an unknown user and a wrong
// password, so the response does not reveal which usernames exist.
func (h *Handler) CreateSession(c fiber.Ctx) error {
username, password, ok := parseBasic(c.Get(fiber.HeaderAuthorization))
if !ok {
return common.SendChallenge(c, basicChallenge, "invalid credentials")
}
user, err := h.store.GetUserByUsername(c.Context(), username)
if err != nil {
if common.IsCode(err, common.ErrorCodeNotFound) {
return common.SendChallenge(c, basicChallenge, "invalid credentials")
}
return common.SendAppError(c, err)
}
valid, err := VerifyPassword(user.PasswordHash, password)
if err != nil || !valid {
return common.SendChallenge(c, basicChallenge, "invalid credentials")
}
token, expiresAt, err := h.sessions.Create(c.Context(), user.ID)
if err != nil {
log.Errorf("create session: %v", err)
return common.SendError(c, fiber.StatusServiceUnavailable,
common.ErrorCodeUnavailable, "session store unavailable")
}
return c.Status(fiber.StatusCreated).JSON(model.Session{
Token: token,
TokenType: "Bearer",
ExpiresAt: common.RFCFormTime(expiresAt),
User: user,
})
}
// RevokeSession deletes the current token. The middleware has already proven
// that the token exists, so a repeated DELETE is a 401, not a 204.
func (h *Handler) RevokeSession(c fiber.Ctx) error {
token, _ := c.Locals(sessionTokenLocal).(string)
if token == "" {
return common.SendChallenge(c, bearerChallenge, "authentication required")
}
if err := h.sessions.Revoke(c.Context(), token); err != nil {
log.Errorf("revoke session: %v", err)
return common.SendError(c, fiber.StatusServiceUnavailable,
common.ErrorCodeUnavailable, "session store unavailable")
}
return c.SendStatus(fiber.StatusNoContent)
}
const sessionTokenLocal = "sessionToken"
// BearerAuth accepts only an opaque Bearer token. X-User-Id is deliberately
// never read: with lab 2 it can neither create nor override an identity.
func BearerAuth(sessions *session.Store) fiber.Handler {
return func(c fiber.Ctx) error {
header := strings.TrimSpace(c.Get(fiber.HeaderAuthorization))
scheme, token, found := strings.Cut(header, " ")
token = strings.TrimSpace(token)
if !found || !strings.EqualFold(scheme, "Bearer") || token == "" || strings.ContainsAny(token, " \t") {
return common.SendChallenge(c, bearerChallenge, "authentication required")
}
userID, err := sessions.Lookup(c.Context(), token)
if err != nil {
if errors.Is(err, session.ErrNotFound) {
return common.SendChallenge(c, bearerChallenge, "session expired or revoked")
}
// AGENT: A dead Redis must not degrade to "anonymous allowed".
// Protected calls get a bounded 503 instead of a 401 or a bypass.
log.Errorf("session lookup: %v", err)
return common.SendError(c, fiber.StatusServiceUnavailable,
common.ErrorCodeUnavailable, "session store unavailable")
}
c.Locals("userID", userID)
c.Locals(sessionTokenLocal, token)
return c.Next()
}
}
func parseBasic(header string) (string, string, bool) {
scheme, encoded, found := strings.Cut(strings.TrimSpace(header), " ")
if !found || !strings.EqualFold(scheme, "Basic") || encoded == "" {
return "", "", false
}
decoded, err := base64.StdEncoding.DecodeString(encoded)
if err != nil {
if decoded, err = base64.RawStdEncoding.DecodeString(encoded); err != nil {
return "", "", false
}
}
// RFC 7617: split at the first colon; a colon is legal inside the password.
username, password, found := strings.Cut(string(decoded), ":")
if !found || username == "" || password == "" {
return "", "", false
}
return username, password, true
}
+72
View File
@@ -0,0 +1,72 @@
// AGENT: Argon2id is used instead of bcrypt because the contract allows 128
// Unicode code points and bcrypt silently truncates at 72 bytes. Salt and
// parameters are stored inside the encoded hash string.
package auth
import (
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"errors"
"fmt"
"strings"
"golang.org/x/crypto/argon2"
)
const (
argonMemory = 64 * 1024
argonIterations = 2
argonParallelism = 4
argonKeyLength = 32
argonSaltLength = 16
)
var ErrInvalidHash = errors.New("invalid password hash")
func HashPassword(password string) (string, error) {
salt := make([]byte, argonSaltLength)
if _, err := rand.Read(salt); err != nil {
return "", fmt.Errorf("generate salt: %w", err)
}
key := argon2.IDKey([]byte(password), salt, argonIterations, argonMemory, argonParallelism, argonKeyLength)
return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
argon2.Version, argonMemory, argonIterations, argonParallelism,
base64.RawStdEncoding.EncodeToString(salt),
base64.RawStdEncoding.EncodeToString(key)), nil
}
// VerifyPassword recomputes the digest with the stored parameters and compares
// in constant time.
func VerifyPassword(encoded, password string) (bool, error) {
parts := strings.Split(encoded, "$")
if len(parts) != 6 || parts[1] != "argon2id" {
return false, ErrInvalidHash
}
var version int
if _, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil || version != argon2.Version {
return false, ErrInvalidHash
}
var memory uint32
var iterations uint32
var parallelism uint8
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &memory, &iterations, &parallelism); err != nil {
return false, ErrInvalidHash
}
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
if err != nil {
return false, ErrInvalidHash
}
expected, err := base64.RawStdEncoding.DecodeString(parts[5])
if err != nil {
return false, ErrInvalidHash
}
actual := argon2.IDKey([]byte(password), salt, iterations, memory, parallelism, uint32(len(expected)))
return subtle.ConstantTimeCompare(actual, expected) == 1, nil
}
+46
View File
@@ -0,0 +1,46 @@
package auth
import (
"strings"
"testing"
)
func TestPasswordRoundTripPreservesFullRange(t *testing.T) {
passwords := []string{
"simple-password-123",
"colon:inside:password",
"пароль-с-кириллицей-12",
strings.Repeat("😀", 128),
}
for _, password := range passwords {
hash, err := HashPassword(password)
if err != nil {
t.Fatalf("HashPassword: %v", err)
}
ok, err := VerifyPassword(hash, password)
if err != nil || !ok {
t.Fatalf("VerifyPassword rejected the correct password (ok=%v err=%v)", ok, err)
}
ok, err = VerifyPassword(hash, password+"x")
if err != nil || ok {
t.Fatalf("VerifyPassword accepted a different password (ok=%v err=%v)", ok, err)
}
}
}
func TestPasswordHashIsSalted(t *testing.T) {
first, err := HashPassword("same-password-123")
if err != nil {
t.Fatal(err)
}
second, err := HashPassword("same-password-123")
if err != nil {
t.Fatal(err)
}
if first == second {
t.Fatal("two hashes of the same password are identical")
}
if _, err := VerifyPassword("not-a-hash", "same-password-123"); err == nil {
t.Fatal("invalid encoded hash was accepted")
}
}
+17
View File
@@ -0,0 +1,17 @@
package auth
import (
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/session"
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/store"
"github.com/gofiber/fiber/v3"
)
func RegisterPublicRoutes(router fiber.Router, st *store.Store, sessions *session.Store) {
handler := NewHandler(st, sessions)
router.Post("/auth/sessions", handler.CreateSession)
}
func RegisterRoutes(router fiber.Router, st *store.Store, sessions *session.Store) {
handler := NewHandler(st, sessions)
router.Delete("/auth/sessions/current", handler.RevokeSession)
}
-9
View File
@@ -1,9 +0,0 @@
package chats
import "gitflic.ru/project/bulla-max/mtusi2026lab1/internal/common"
var (
ErrChatNotFound = common.NotFound("chat not found")
ErrInvalidChatID = common.BadRequest("invalid chat_id format")
ErrMemberNotFound = common.BadRequest("member_id refers to non-existent user")
)
+24 -44
View File
@@ -1,13 +1,26 @@
package chats
import (
"gitflic.ru/project/bulla-max/mtusi2026lab1/internal/common"
"gitflic.ru/project/bulla-max/mtusi2026lab1/internal/storage"
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/common"
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/store"
"github.com/gofiber/fiber/v3"
"github.com/google/uuid"
)
func createChat(c fiber.Ctx) error {
type Handler struct {
store *store.Store
}
func NewHandler(st *store.Store) *Handler {
return &Handler{store: st}
}
type CreateChatRequest struct {
Title string `json:"title" validate:"required"`
MemberIDs []uuid.UUID `json:"member_ids" validate:"required"`
}
func (h *Handler) CreateChat(c fiber.Ctx) error {
userID := c.Locals("userID").(uuid.UUID)
var req CreateChatRequest
@@ -18,24 +31,11 @@ func createChat(c fiber.Ctx) error {
if msg := common.ValidateChatTitle(req.Title); msg != "" {
return common.SendError(c, fiber.StatusBadRequest, common.ErrorCodeInvalidRequest, msg)
}
if msg := common.ValidateMemberIDs(req.MemberIDs, userID); msg != "" {
return common.SendError(c, fiber.StatusBadRequest, common.ErrorCodeInvalidRequest, msg)
}
var chat Chat
err := storage.GlobalStore.Update(func(tx storage.Tx) error {
for _, memberID := range req.MemberIDs {
if _, ok := tx.GetUser(memberID); !ok {
return ErrMemberNotFound
}
}
chat = NewChat(req)
tx.CreateChat(chat)
return nil
})
chat, err := h.store.CreateChat(c.Context(), req.Title, req.MemberIDs)
if err != nil {
return common.SendAppError(c, err)
}
@@ -43,7 +43,7 @@ func createChat(c fiber.Ctx) error {
return c.Status(fiber.StatusCreated).JSON(chat)
}
func listChats(c fiber.Ctx) error {
func (h *Handler) ListChats(c fiber.Ctx) error {
userID := c.Locals("userID").(uuid.UUID)
limit, err := common.ParseLimit(c, 50)
@@ -55,19 +55,12 @@ func listChats(c fiber.Ctx) error {
if err != nil {
return common.SendAppError(c, err)
}
if cursor != nil && userID != cursor.ContextID {
if cursor != nil && cursor.ContextID != userID {
return common.SendError(c, fiber.StatusBadRequest,
common.ErrorCodeInvalidRequest, "bad cursor value")
}
var page *common.PaginatedResponse[storage.Entity]
err = storage.GlobalStore.View(func(tx storage.ReadOnlyTx) error {
found, fetchErr := tx.GetUserChats(userID, limit, cursor)
page = found
return fetchErr
})
page, err := h.store.ListChats(c.Context(), userID, limit, cursor)
if err != nil {
return common.SendAppError(c, err)
}
@@ -75,29 +68,16 @@ func listChats(c fiber.Ctx) error {
return c.JSON(page)
}
func getChat(c fiber.Ctx) error {
func (h *Handler) GetChat(c fiber.Ctx) error {
userID := c.Locals("userID").(uuid.UUID)
chatID, err := uuid.Parse(c.Params("chat_id"))
if err != nil {
return common.SendAppError(c, ErrInvalidChatID)
return common.SendError(c, fiber.StatusBadRequest,
common.ErrorCodeInvalidRequest, "invalid chat_id format")
}
var chat storage.ChatEntity
err = storage.GlobalStore.View(func(tx storage.ReadOnlyTx) error {
if !tx.IsMember(userID, chatID) {
return ErrChatNotFound
}
found, ok := tx.GetChat(chatID)
if !ok {
return ErrChatNotFound
}
chat = found
return nil
})
chat, err := h.store.GetChatForUser(c.Context(), userID, chatID)
if err != nil {
return common.SendAppError(c, err)
}
-41
View File
@@ -1,41 +0,0 @@
package chats
import (
"time"
"gitflic.ru/project/bulla-max/mtusi2026lab1/internal/common"
"github.com/google/uuid"
)
type Chat struct {
ID uuid.UUID `json:"id"`
Title string `json:"title"`
MemberIDs []uuid.UUID `json:"member_ids"`
CreatedAt common.RFCFormTime `json:"created_at"`
}
type CreateChatRequest struct {
Title string `json:"title" validate:"required"`
MemberIDs []uuid.UUID `json:"member_ids" validate:"required"`
}
func NewChat(req CreateChatRequest) Chat {
return Chat{
ID: uuid.New(),
Title: req.Title,
MemberIDs: req.MemberIDs,
CreatedAt: common.NowUTC(),
}
}
func (c Chat) GetID() uuid.UUID {
return c.ID
}
func (c Chat) GetCreatedAt() time.Time {
return time.Time(c.CreatedAt)
}
func (c Chat) GetMemberIDs() []uuid.UUID {
return c.MemberIDs
}
+9 -5
View File
@@ -1,9 +1,13 @@
package chats
import "github.com/gofiber/fiber/v3"
import (
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/store"
"github.com/gofiber/fiber/v3"
)
func RegisterRoutes(router fiber.Router) {
router.Post("/chats", createChat)
router.Get("/chats", listChats)
router.Get("/chats/:chat_id", getChat)
func RegisterRoutes(router fiber.Router, st *store.Store) {
handler := NewHandler(st)
router.Post("/chats", handler.CreateChat)
router.Get("/chats", handler.ListChats)
router.Get("/chats/:chat_id", handler.GetChat)
}
+22 -1
View File
@@ -4,6 +4,7 @@ import (
"errors"
"github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/middleware/requestid"
)
const (
@@ -80,6 +81,16 @@ func Internal() *AppError {
return NewAppError(fiber.StatusInternalServerError, ErrorCodeInternal, "Internal server error")
}
func Unavailable(message string) *AppError {
return NewAppError(fiber.StatusServiceUnavailable, ErrorCodeUnavailable, message)
}
// IsCode reports whether err is an AppError with the given contract code.
func IsCode(err error, code string) bool {
var appErr *AppError
return errors.As(err, &appErr) && appErr.Code == code
}
func ErrorCodeFromStatus(status int) string {
switch status {
case fiber.StatusBadRequest:
@@ -104,7 +115,10 @@ func ErrorCodeFromStatus(status int) string {
}
func getRequestID(c fiber.Ctx) string {
return string(c.Response().Header.Peek("X-Request-Id"))
if id := string(c.Response().Header.Peek("X-Request-Id")); id != "" {
return id
}
return requestid.FromContext(c)
}
func SendError(c fiber.Ctx, status int, code, message string) error {
@@ -120,3 +134,10 @@ func SendAppError(c fiber.Ctx, err error) error {
return SendError(c, fiber.StatusInternalServerError,
ErrorCodeInternal, "Internal server error")
}
// SendChallenge emits a 401 with the WWW-Authenticate value required by the
// contract: Basic for login, Bearer for every protected endpoint.
func SendChallenge(c fiber.Ctx, challenge, message string) error {
c.Set(fiber.HeaderWWWAuthenticate, challenge)
return SendError(c, fiber.StatusUnauthorized, ErrorCodeUnauthorized, message)
}
+45 -135
View File
@@ -2,7 +2,7 @@ package common
import (
"encoding/base64"
"sort"
"strconv"
"strings"
"time"
@@ -10,189 +10,99 @@ import (
"github.com/google/uuid"
)
// CursorKeyCtx is the opaque keyset position: (created_at, id) plus the
// resource/user the cursor belongs to. ContextID stops a cursor from one chat
// or user list being replayed against another.
type CursorKeyCtx struct {
Time time.Time
ID uuid.UUID
ContextID uuid.UUID
}
type cursorKey struct {
time time.Time
id uuid.UUID
}
type CreatedAtIDable interface {
GetCreatedAt() time.Time
GetID() uuid.UUID
}
type PaginatedResponse[T any] struct {
type Page[T any] struct {
Items []T `json:"items"`
NextCursor *string `json:"next_cursor"`
}
func ParseLimit(c fiber.Ctx, defaultLimit int) (int, error) {
limitStr, exists := c.Queries()["limit"]
if limitStr == "" {
if !exists {
return defaultLimit, nil
}
if !exists {
return defaultLimit, nil
}
if strings.TrimSpace(limitStr) == "" {
return 0, BadRequest("limit param declared but empty")
}
limit, ok := validateLimitStr(limitStr)
if !ok {
limit, err := strconv.Atoi(limitStr)
if err != nil || limit < 1 || limit > 100 {
return 0, BadRequest("limit must be an integer between 1 and 100")
}
return limit, nil
}
func ParseCursor(c fiber.Ctx) (*CursorKeyCtx, error) {
cursorStr, exists := c.Queries()["cursor"]
if cursorStr == "" {
if !exists {
return nil, nil
}
if !exists {
return nil, nil
}
if strings.TrimSpace(cursorStr) == "" {
return nil, BadRequest("cursor param declared but empty")
}
cursor := DecodeCursor(cursorStr)
if cursor == nil {
cursor, ok := DecodeCursor(cursorStr)
if !ok {
return nil, BadRequest("invalid cursor format")
}
return cursor, nil
}
func Paginate[T CreatedAtIDable](
items []T,
limit int,
cursor *CursorKeyCtx,
contextID uuid.UUID,
) (*PaginatedResponse[T], error) {
enforceOrder(items)
start := 0
if cursor != nil {
key := cursorKey{time: cursor.Time, id: cursor.ID}
position, found := findAfter(items, key)
if !found {
return nil, BadRequest("cursor invalid")
}
if position == -1 {
position = len(items)
}
start = position
}
end := start + limit
if end > len(items) {
end = len(items)
}
page := items[start:end]
if page == nil {
page = []T{}
}
var nextCursor *string
if end < len(items) {
last := items[end-1]
encoded := encodeCursor(CursorKeyCtx{
Time: last.GetCreatedAt(),
ID: last.GetID(),
ContextID: contextID,
})
nextCursor = &encoded
}
return &PaginatedResponse[T]{
Items: page,
NextCursor: nextCursor,
}, nil
}
func encodeCursor(key CursorKeyCtx) string {
timeStr := key.Time.UTC().Format(time.RFC3339Nano)
raw := timeStr + "|" + key.ID.String() + "|" + key.ContextID.String()
func EncodeCursor(key CursorKeyCtx) string {
raw := key.Time.UTC().Format(time.RFC3339Nano) + "|" + key.ID.String() + "|" + key.ContextID.String()
return base64.RawURLEncoding.EncodeToString([]byte(raw))
}
func DecodeCursor(cursor string) *CursorKeyCtx {
func DecodeCursor(cursor string) (*CursorKeyCtx, bool) {
data, err := base64.RawURLEncoding.DecodeString(cursor)
if err != nil {
return nil
return nil, false
}
parts := strings.SplitN(string(data), "|", 3)
if len(parts) != 3 {
return nil
return nil, false
}
parsedTime, err := time.Parse(time.RFC3339Nano, parts[0])
if err != nil {
return nil
return nil, false
}
parsedID, err := uuid.Parse(parts[1])
if err != nil {
return nil
return nil, false
}
parsedContextID, err := uuid.Parse(parts[2])
parsedContext, err := uuid.Parse(parts[2])
if err != nil {
return nil, false
}
return &CursorKeyCtx{Time: parsedTime, ID: parsedID, ContextID: parsedContext}, true
}
// NextCursor returns a cursor pointing at the last item of a page when more
// rows exist. limit+1 rows are fetched by the store, so a non-nil cursor means
// the next page is known to be non-empty at read time.
func NextCursor[T interface {
GetID() uuid.UUID
GetCreatedAt() time.Time
}](items []T, hasMore bool, contextID uuid.UUID) *string {
if !hasMore || len(items) == 0 {
return nil
}
return &CursorKeyCtx{
Time: parsedTime,
ID: parsedID,
ContextID: parsedContextID,
}
}
func findAfter[T CreatedAtIDable](items []T, key cursorKey) (position int, keyFound bool) {
for i, item := range items {
itemKey := keyOf(item)
if itemKey == key {
keyFound = true
}
if after(itemKey, key) {
return i, true
}
}
return -1, keyFound
}
func keyOf(item CreatedAtIDable) cursorKey {
return cursorKey{
time: item.GetCreatedAt(),
id: item.GetID(),
}
}
func after(a, b cursorKey) bool {
if !a.time.Equal(b.time) {
return a.time.After(b.time)
}
return a.id.String() > b.id.String()
}
func enforceOrder[T CreatedAtIDable](items []T) {
sort.Slice(items, func(i, j int) bool {
return after(keyOf(items[j]), keyOf(items[i]))
last := items[len(items)-1]
encoded := EncodeCursor(CursorKeyCtx{
Time: last.GetCreatedAt(),
ID: last.GetID(),
ContextID: contextID,
})
return &encoded
}
+49
View File
@@ -0,0 +1,49 @@
package common
import (
"testing"
"time"
"github.com/google/uuid"
)
func TestCursorRoundTrip(t *testing.T) {
want := CursorKeyCtx{
Time: time.Date(2026, 10, 20, 12, 30, 45, 123456789, time.UTC),
ID: uuid.MustParse("11111111-1111-4111-8111-111111111111"),
ContextID: uuid.MustParse("22222222-2222-4222-8222-222222222222"),
}
encoded := EncodeCursor(want)
got, ok := DecodeCursor(encoded)
if !ok {
t.Fatal("cursor did not decode")
}
if !got.Time.Equal(want.Time) || got.ID != want.ID || got.ContextID != want.ContextID {
t.Fatalf("cursor round trip changed the key: %+v", got)
}
for _, invalid := range []string{"not-base64!", "", "aGVsbG8"} {
if _, ok := DecodeCursor(invalid); ok {
t.Fatalf("invalid cursor %q was accepted", invalid)
}
}
}
func TestValidatePasswordRange(t *testing.T) {
cases := []struct {
password string
valid bool
}{
{"short", false},
{"12345678901", false},
{"123456789012", true},
{"пароль-из-двенадцати", true},
{"😀", false},
}
for _, tc := range cases {
if got := ValidatePassword(tc.password) == ""; got != tc.valid {
t.Fatalf("ValidatePassword(%q) valid=%v, want %v", tc.password, got, tc.valid)
}
}
}
+13 -2
View File
@@ -34,7 +34,7 @@ func BindJSON(c fiber.Ctx, req any) error {
decoder.DisallowUnknownFields()
if err := decoder.Decode(req); err != nil {
return BadRequest(err.Error())
return BadRequest("invalid JSON body")
}
var extra json.RawMessage
@@ -43,7 +43,7 @@ func BindJSON(c fiber.Ctx, req any) error {
}
if err := validate.Struct(req); err != nil {
return BadRequest("field validation failed: " + err.Error())
return BadRequest("field validation failed")
}
return nil
@@ -74,6 +74,17 @@ func ValidateCreateUser(username, displayName string) string {
return ""
}
// ValidatePassword enforces the contract range in Unicode code points. The
// upper bound matters: bcrypt would silently truncate, which is why this
// project uses Argon2id instead.
func ValidatePassword(password string) string {
if !strLenBetween(password, 12, 128) {
return "password must be between 12 and 128 Unicode code points"
}
return ""
}
func ValidateChatTitle(title string) string {
if blank(title) {
return "title must not be empty or only whitespace"
+107
View File
@@ -0,0 +1,107 @@
// AGENT: All runtime configuration is read here so every other package receives
// explicit values instead of calling os.Getenv. Values are compatible with
// .env.example and support the *_FILE convention used by Compose secrets.
package config
import (
"fmt"
"os"
"strconv"
"strings"
"time"
)
type Config struct {
Host string
Port string
SessionTTL time.Duration
DatabaseURL string
CacheURL string
DBMaxConns int32
DBTimeout time.Duration
RedisTimeout time.Duration
StartupWait time.Duration
}
func Load() (Config, error) {
cfg := Config{
Host: envOr("APP_HOST", "0.0.0.0"),
Port: envOr("APP_PORT", "8080"),
DBMaxConns: 10,
DBTimeout: 5 * time.Second,
RedisTimeout: 2 * time.Second,
StartupWait: 30 * time.Second,
}
ttlSeconds, err := strconv.Atoi(envOr("SESSION_TTL_SECONDS", "3600"))
if err != nil || ttlSeconds < 1 {
return cfg, fmt.Errorf("SESSION_TTL_SECONDS must be a positive integer")
}
cfg.SessionTTL = time.Duration(ttlSeconds) * time.Second
if value := envOr("DB_POOL_MAX_CONNS", ""); value != "" {
n, convErr := strconv.Atoi(value)
if convErr != nil || n < 1 || n > 100 {
return cfg, fmt.Errorf("DB_POOL_MAX_CONNS must be an integer between 1 and 100")
}
cfg.DBMaxConns = int32(n)
}
cfg.DatabaseURL, err = secret("DATABASE_URL")
if err != nil {
return cfg, err
}
if cfg.DatabaseURL == "" {
return cfg, fmt.Errorf("DATABASE_URL or DATABASE_URL_FILE is required")
}
cfg.CacheURL, err = secret("CACHE_URL")
if err != nil {
return cfg, err
}
if cfg.CacheURL == "" {
cfg.CacheURL, err = secret("REDIS_URL")
if err != nil {
return cfg, err
}
}
if cfg.CacheURL == "" {
return cfg, fmt.Errorf("CACHE_URL or CACHE_URL_FILE is required")
}
if value := strings.ToLower(envOr("SESSION_STORE", "redis")); value != "redis" {
return cfg, fmt.Errorf("SESSION_STORE must be redis (got %q)", value)
}
return cfg, nil
}
func envOr(name, fallback string) string {
if value := os.Getenv(name); value != "" {
return value
}
return fallback
}
func secret(name string) (string, error) {
if value := os.Getenv(name); value != "" {
return value, nil
}
path := os.Getenv(name + "_FILE")
if path == "" {
return "", nil
}
data, err := os.ReadFile(path)
if err != nil {
return "", fmt.Errorf("read %s_FILE: %w", name, err)
}
value := strings.TrimSpace(string(data))
if value == "" {
return "", fmt.Errorf("%s_FILE is empty", name)
}
return value, nil
}
+127
View File
@@ -0,0 +1,127 @@
// AGENT: A tiny migration runner instead of a framework: one advisory lock,
// one schema_migrations row per file, each file in its own transaction.
package database
import (
"context"
"embed"
"fmt"
"io/fs"
"sort"
"time"
"github.com/jackc/pgx/v5/pgxpool"
)
//go:embed migrations/*.sql
var migrationFiles embed.FS
const migrationLockID int64 = 728_2026
func Connect(ctx context.Context, url string, maxConns int32, wait time.Duration) (*pgxpool.Pool, error) {
cfg, err := pgxpool.ParseConfig(url)
if err != nil {
return nil, fmt.Errorf("parse DATABASE_URL: %w", err)
}
cfg.MaxConns = maxConns
cfg.MinConns = 1
cfg.MaxConnLifetime = 30 * time.Minute
cfg.MaxConnIdleTime = 5 * time.Minute
cfg.HealthCheckPeriod = 30 * time.Second
cfg.ConnConfig.ConnectTimeout = 3 * time.Second
pool, err := pgxpool.NewWithConfig(ctx, cfg)
if err != nil {
return nil, fmt.Errorf("create pool: %w", err)
}
// AGENT: Compose may start the API while PostgreSQL is still booting. A bounded
// retry keeps the container from crash-looping without hiding a permanent error.
deadline := time.Now().Add(wait)
for {
pingCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
err = pool.Ping(pingCtx)
cancel()
if err == nil {
return pool, nil
}
if time.Now().After(deadline) || ctx.Err() != nil {
pool.Close()
return nil, fmt.Errorf("postgres is not reachable: %w", err)
}
time.Sleep(500 * time.Millisecond)
}
}
func Migrate(ctx context.Context, pool *pgxpool.Pool) error {
conn, err := pool.Acquire(ctx)
if err != nil {
return fmt.Errorf("acquire migration connection: %w", err)
}
defer conn.Release()
if _, err = conn.Exec(ctx, "SELECT pg_advisory_lock($1)", migrationLockID); err != nil {
return fmt.Errorf("acquire migration lock: %w", err)
}
defer func() {
unlockCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
_, _ = conn.Exec(unlockCtx, "SELECT pg_advisory_unlock($1)", migrationLockID)
}()
if _, err = conn.Exec(ctx, `
CREATE TABLE IF NOT EXISTS schema_migrations (
version text PRIMARY KEY,
applied_at timestamptz NOT NULL DEFAULT now()
)`); err != nil {
return fmt.Errorf("create schema_migrations: %w", err)
}
entries, err := fs.ReadDir(migrationFiles, "migrations")
if err != nil {
return fmt.Errorf("read embedded migrations: %w", err)
}
sort.Slice(entries, func(i, j int) bool { return entries[i].Name() < entries[j].Name() })
for _, entry := range entries {
if entry.IsDir() {
continue
}
var applied bool
if err = conn.QueryRow(ctx,
"SELECT EXISTS(SELECT 1 FROM schema_migrations WHERE version = $1)", entry.Name(),
).Scan(&applied); err != nil {
return fmt.Errorf("check migration %s: %w", entry.Name(), err)
}
if applied {
continue
}
body, readErr := migrationFiles.ReadFile("migrations/" + entry.Name())
if readErr != nil {
return fmt.Errorf("read migration %s: %w", entry.Name(), readErr)
}
tx, beginErr := conn.Begin(ctx)
if beginErr != nil {
return fmt.Errorf("begin migration %s: %w", entry.Name(), beginErr)
}
if _, execErr := tx.Exec(ctx, string(body)); execErr != nil {
_ = tx.Rollback(ctx)
return fmt.Errorf("apply migration %s: %w", entry.Name(), execErr)
}
if _, insertErr := tx.Exec(ctx,
"INSERT INTO schema_migrations (version) VALUES ($1)", entry.Name(),
); insertErr != nil {
_ = tx.Rollback(ctx)
return fmt.Errorf("record migration %s: %w", entry.Name(), insertErr)
}
if commitErr := tx.Commit(ctx); commitErr != nil {
return fmt.Errorf("commit migration %s: %w", entry.Name(), commitErr)
}
}
return nil
}
@@ -0,0 +1,46 @@
-- AGENT: Single versioned baseline migration for lab 2. The application records
-- applied versions in schema_migrations, so rerunning it never duplicates rows.
-- The unique username constraint is the authoritative defence against the
-- concurrent-registration race, not a SELECT followed by an INSERT.
CREATE TABLE IF NOT EXISTS users (
id uuid PRIMARY KEY,
username text NOT NULL,
display_name text NOT NULL,
password_hash text NOT NULL,
created_at timestamptz NOT NULL,
CONSTRAINT users_username_key UNIQUE (username),
CONSTRAINT users_username_format CHECK (username ~ '^[a-z0-9_]{3,32}$'),
CONSTRAINT users_display_name_len CHECK (char_length(display_name) BETWEEN 1 AND 100)
);
CREATE TABLE IF NOT EXISTS chats (
id uuid PRIMARY KEY,
title text NOT NULL,
created_at timestamptz NOT NULL,
CONSTRAINT chats_title_len CHECK (char_length(title) BETWEEN 1 AND 100)
);
CREATE TABLE IF NOT EXISTS chat_members (
chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
user_id uuid NOT NULL REFERENCES users(id) ON DELETE RESTRICT,
PRIMARY KEY (chat_id, user_id)
);
CREATE INDEX IF NOT EXISTS chat_members_user_idx
ON chat_members (user_id, chat_id);
CREATE TABLE IF NOT EXISTS messages (
id uuid PRIMARY KEY,
chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
sender_id uuid NOT NULL REFERENCES users(id) ON DELETE RESTRICT,
text text NOT NULL,
created_at timestamptz NOT NULL,
CONSTRAINT messages_text_len CHECK (char_length(text) BETWEEN 1 AND 4000)
);
-- AGENT: This composite index matches the only history predicate and sort order:
-- (chat_id, created_at, id). It lets each keyset page seek directly to the cursor
-- instead of scanning the chat history from the beginning.
CREATE INDEX IF NOT EXISTS messages_chat_created_id_idx
ON messages (chat_id, created_at, id);
+35 -7
View File
@@ -3,25 +3,53 @@ package health
import (
"sync/atomic"
"gitflic.ru/project/bulla-max/mtusi2026lab1/internal/common"
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/common"
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/session"
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/store"
"github.com/gofiber/fiber/v3"
)
type Handler struct {
store *store.Store
sessions *session.Store
}
func NewHandler(st *store.Store, sessions *session.Store) *Handler {
return &Handler{store: st, sessions: sessions}
}
var shuttingDown atomic.Bool
func SignalShutdown() {
shuttingDown.Store(true)
}
func live(c fiber.Ctx) error {
return c.JSON(fiber.Map{"status": "ok"})
type Status struct {
Status string `json:"status"`
}
func ready(c fiber.Ctx) error {
func (h *Handler) Live(c fiber.Ctx) error {
return c.JSON(Status{Status: "ok"})
}
// Ready answers whether the synchronous mandatory path can be served. Both
// PostgreSQL and Redis are critical here: business data and sessions live in
// them respectively.
func (h *Handler) Ready(c fiber.Ctx) error {
if shuttingDown.Load() {
return common.SendError(c, fiber.StatusInternalServerError,
common.ErrorCodeInternal, "app currently shutting down")
return common.SendError(c, fiber.StatusServiceUnavailable,
common.ErrorCodeUnavailable, "service is shutting down")
}
return c.JSON(fiber.Map{"status": "ok"})
if err := h.store.Ping(c.Context()); err != nil {
return common.SendError(c, fiber.StatusServiceUnavailable,
common.ErrorCodeUnavailable, "database unavailable")
}
if err := h.sessions.Ping(c.Context()); err != nil {
return common.SendError(c, fiber.StatusServiceUnavailable,
common.ErrorCodeUnavailable, "session store unavailable")
}
return c.JSON(Status{Status: "ok"})
}
+9 -4
View File
@@ -1,8 +1,13 @@
package health
import "github.com/gofiber/fiber/v3"
import (
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/session"
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/store"
"github.com/gofiber/fiber/v3"
)
func RegisterRoutes(router fiber.Router) {
router.Get("/live", live)
router.Get("/ready", ready)
func RegisterRoutes(router fiber.Router, st *store.Store, sessions *session.Store) {
handler := NewHandler(st, sessions)
router.Get("/live", handler.Live)
router.Get("/ready", handler.Ready)
}
-8
View File
@@ -1,8 +0,0 @@
package messages
import "gitflic.ru/project/bulla-max/mtusi2026lab1/internal/common"
var (
ErrChatNotFound = common.NotFound("chat not found")
ErrInvalidChatID = common.BadRequest("invalid chat_id format")
)
+22 -34
View File
@@ -1,40 +1,42 @@
package messages
import (
"gitflic.ru/project/bulla-max/mtusi2026lab1/internal/common"
"gitflic.ru/project/bulla-max/mtusi2026lab1/internal/storage"
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/common"
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/store"
"github.com/gofiber/fiber/v3"
"github.com/google/uuid"
)
func createMessage(c fiber.Ctx) error {
type Handler struct {
store *store.Store
}
func NewHandler(st *store.Store) *Handler {
return &Handler{store: st}
}
type CreateMessageRequest struct {
Text string `json:"text" validate:"required"`
}
func (h *Handler) CreateMessage(c fiber.Ctx) error {
userID := c.Locals("userID").(uuid.UUID)
chatID, err := uuid.Parse(c.Params("chat_id"))
if err != nil {
return common.SendAppError(c, ErrInvalidChatID)
return common.SendError(c, fiber.StatusBadRequest,
common.ErrorCodeInvalidRequest, "invalid chat_id format")
}
var req CreateMessageRequest
if err := common.BindJSON(c, &req); err != nil {
return common.SendAppError(c, err)
}
if msg := common.ValidateMessageText(req.Text); msg != "" {
return common.SendError(c, fiber.StatusBadRequest, common.ErrorCodeInvalidRequest, msg)
}
var message Message
err = storage.GlobalStore.Update(func(tx storage.Tx) error {
if !tx.IsMember(userID, chatID) {
return ErrChatNotFound
}
message = NewMessage(chatID, userID, req.Text)
tx.CreateMessage(message)
return nil
})
message, err := h.store.CreateMessage(c.Context(), chatID, userID, req.Text)
if err != nil {
return common.SendAppError(c, err)
}
@@ -42,12 +44,13 @@ func createMessage(c fiber.Ctx) error {
return c.Status(fiber.StatusCreated).JSON(message)
}
func listMessages(c fiber.Ctx) error {
func (h *Handler) ListMessages(c fiber.Ctx) error {
userID := c.Locals("userID").(uuid.UUID)
chatID, err := uuid.Parse(c.Params("chat_id"))
if err != nil {
return common.SendAppError(c, ErrInvalidChatID)
return common.SendError(c, fiber.StatusBadRequest,
common.ErrorCodeInvalidRequest, "invalid chat_id format")
}
limit, err := common.ParseLimit(c, 50)
@@ -60,22 +63,7 @@ func listMessages(c fiber.Ctx) error {
return common.SendAppError(c, err)
}
if cursor != nil && chatID != cursor.ContextID {
return common.SendError(c, fiber.StatusBadRequest,
common.ErrorCodeInvalidRequest, "bad cursor value")
}
var page *common.PaginatedResponse[storage.Entity]
err = storage.GlobalStore.View(func(tx storage.ReadOnlyTx) error {
if !tx.IsMember(userID, chatID) {
return ErrChatNotFound
}
found, fetchErr := tx.GetChatMessages(chatID, limit, cursor)
page = found
return fetchErr
})
page, err := h.store.ListMessages(c.Context(), userID, chatID, limit, cursor)
if err != nil {
return common.SendAppError(c, err)
}
-42
View File
@@ -1,42 +0,0 @@
package messages
import (
"time"
"gitflic.ru/project/bulla-max/mtusi2026lab1/internal/common"
"github.com/google/uuid"
)
type Message struct {
ID uuid.UUID `json:"id"`
ChatID uuid.UUID `json:"chat_id"`
SenderID uuid.UUID `json:"sender_id"`
Text string `json:"text"`
CreatedAt common.RFCFormTime `json:"created_at"`
}
type CreateMessageRequest struct {
Text string `json:"text" validate:"required"`
}
func NewMessage(chatID, senderID uuid.UUID, text string) Message {
return Message{
ID: uuid.New(),
ChatID: chatID,
SenderID: senderID,
Text: text,
CreatedAt: common.NowUTC(),
}
}
func (m Message) GetID() uuid.UUID {
return m.ID
}
func (m Message) GetCreatedAt() time.Time {
return time.Time(m.CreatedAt)
}
func (m Message) GetChatID() uuid.UUID {
return m.ChatID
}
+8 -4
View File
@@ -1,8 +1,12 @@
package messages
import "github.com/gofiber/fiber/v3"
import (
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/store"
"github.com/gofiber/fiber/v3"
)
func RegisterRoutes(router fiber.Router) {
router.Post("/chats/:chat_id/messages", createMessage)
router.Get("/chats/:chat_id/messages", listMessages)
func RegisterRoutes(router fiber.Router, st *store.Store) {
handler := NewHandler(st)
router.Post("/chats/:chat_id/messages", handler.CreateMessage)
router.Get("/chats/:chat_id/messages", handler.ListMessages)
}
+47
View File
@@ -0,0 +1,47 @@
package model
import (
"time"
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/common"
"github.com/google/uuid"
)
type User struct {
ID uuid.UUID `json:"id"`
Username string `json:"username"`
DisplayName string `json:"display_name"`
PasswordHash string `json:"-"`
CreatedAt common.RFCFormTime `json:"created_at"`
}
func (u User) GetID() uuid.UUID { return u.ID }
func (u User) GetCreatedAt() time.Time { return time.Time(u.CreatedAt) }
type Chat struct {
ID uuid.UUID `json:"id"`
Title string `json:"title"`
MemberIDs []uuid.UUID `json:"member_ids"`
CreatedAt common.RFCFormTime `json:"created_at"`
}
func (c Chat) GetID() uuid.UUID { return c.ID }
func (c Chat) GetCreatedAt() time.Time { return time.Time(c.CreatedAt) }
type Message struct {
ID uuid.UUID `json:"id"`
ChatID uuid.UUID `json:"chat_id"`
SenderID uuid.UUID `json:"sender_id"`
Text string `json:"text"`
CreatedAt common.RFCFormTime `json:"created_at"`
}
func (m Message) GetID() uuid.UUID { return m.ID }
func (m Message) GetCreatedAt() time.Time { return time.Time(m.CreatedAt) }
type Session struct {
Token string `json:"token"`
TokenType string `json:"token_type"`
ExpiresAt common.RFCFormTime `json:"expires_at"`
User User `json:"user"`
}
+106
View File
@@ -0,0 +1,106 @@
// AGENT: Redis is the single session store for lab 2 grade 4. PostgreSQL stays
// the source of truth for business data. The token itself is never stored: Redis
// holds SHA-256(token) -> user id with a TTL, so a leaked Redis dump does not
// hand out usable bearer tokens.
package session
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"strings"
"time"
"github.com/google/uuid"
"github.com/redis/go-redis/v9"
)
var ErrNotFound = errors.New("session not found")
const keyPrefix = "messenger:session:"
type Store struct {
client *redis.Client
ttl time.Duration
timeout time.Duration
}
func New(rawURL string, ttl, timeout time.Duration) (*Store, error) {
options, err := redis.ParseURL(rawURL)
if err != nil {
return nil, fmt.Errorf("parse CACHE_URL: %w", err)
}
options.PoolSize = 10
options.DialTimeout = timeout
options.ReadTimeout = timeout
options.WriteTimeout = timeout
options.MaxRetries = 0
return &Store{
client: redis.NewClient(options),
ttl: ttl,
timeout: timeout,
}, nil
}
func (s *Store) Close() error {
return s.client.Close()
}
func (s *Store) Ping(ctx context.Context) error {
pingCtx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
return s.client.Ping(pingCtx).Err()
}
// Create returns the raw token exactly once and stores only its digest.
func (s *Store) Create(ctx context.Context, userID uuid.UUID) (string, time.Time, error) {
raw := make([]byte, 32)
if _, err := rand.Read(raw); err != nil {
return "", time.Time{}, fmt.Errorf("generate token: %w", err)
}
token := base64.RawURLEncoding.EncodeToString(raw)
expiresAt := time.Now().UTC().Truncate(time.Second).Add(s.ttl)
opCtx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
if err := s.client.Set(opCtx, keyFor(token), userID.String(), s.ttl).Err(); err != nil {
return "", time.Time{}, err
}
return token, expiresAt, nil
}
func (s *Store) Lookup(ctx context.Context, token string) (uuid.UUID, error) {
opCtx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
value, err := s.client.Get(opCtx, keyFor(token)).Result()
if errors.Is(err, redis.Nil) {
return uuid.Nil, ErrNotFound
}
if err != nil {
return uuid.Nil, err
}
userID, err := uuid.Parse(value)
if err != nil {
return uuid.Nil, ErrNotFound
}
return userID, nil
}
func (s *Store) Revoke(ctx context.Context, token string) error {
opCtx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
return s.client.Del(opCtx, keyFor(token)).Err()
}
func keyFor(token string) string {
sum := sha256.Sum256([]byte(strings.TrimSpace(token)))
return keyPrefix + hex.EncodeToString(sum[:])
}
-145
View File
@@ -1,145 +0,0 @@
package storage
import (
"slices"
"sync"
"gitflic.ru/project/bulla-max/mtusi2026lab1/internal/common"
"github.com/google/uuid"
)
type Entity = common.CreatedAtIDable
type UserEntity interface {
Entity
GetUsername() string
}
type ChatEntity interface {
Entity
GetMemberIDs() []uuid.UUID
}
type MessageEntity interface {
Entity
GetChatID() uuid.UUID
}
type Store struct {
mu sync.RWMutex
users map[uuid.UUID]UserEntity
usernames map[string]uuid.UUID
chats map[uuid.UUID]ChatEntity
userChats map[uuid.UUID][]uuid.UUID
chatMessages map[uuid.UUID][]MessageEntity
}
func NewStore() *Store {
return &Store{
users: make(map[uuid.UUID]UserEntity),
usernames: make(map[string]uuid.UUID),
chats: make(map[uuid.UUID]ChatEntity),
userChats: make(map[uuid.UUID][]uuid.UUID),
chatMessages: make(map[uuid.UUID][]MessageEntity),
}
}
var GlobalStore = NewStore()
type ReadOnlyTx interface {
GetUser(id uuid.UUID) (UserEntity, bool)
GetChat(id uuid.UUID) (ChatEntity, bool)
UsernameExists(username string) bool
IsMember(userID, chatID uuid.UUID) bool
GetChatMessages(chatID uuid.UUID, limit int, cursor *common.CursorKeyCtx) (*common.PaginatedResponse[Entity], error)
GetUserChats(userID uuid.UUID, limit int, cursor *common.CursorKeyCtx) (*common.PaginatedResponse[Entity], error)
}
type Tx interface {
ReadOnlyTx
CreateUser(user UserEntity)
CreateChat(chat ChatEntity)
CreateMessage(msg MessageEntity)
}
func (s *Store) View(apply func(tx ReadOnlyTx) error) error {
s.mu.RLock()
defer s.mu.RUnlock()
return apply(s)
}
func (s *Store) Update(apply func(tx Tx) error) error {
s.mu.Lock()
defer s.mu.Unlock()
return apply(s)
}
func (s *Store) CreateUser(user UserEntity) {
s.users[user.GetID()] = user
s.usernames[user.GetUsername()] = user.GetID()
s.userChats[user.GetID()] = []uuid.UUID{}
}
func (s *Store) UsernameExists(username string) bool {
_, exists := s.usernames[username]
return exists
}
func (s *Store) GetUser(id uuid.UUID) (UserEntity, bool) {
user, ok := s.users[id]
return user, ok
}
func (s *Store) CreateChat(chat ChatEntity) {
s.chats[chat.GetID()] = chat
for _, memberID := range chat.GetMemberIDs() {
s.userChats[memberID] = append(s.userChats[memberID], chat.GetID())
}
s.chatMessages[chat.GetID()] = []MessageEntity{}
}
func (s *Store) GetChat(id uuid.UUID) (ChatEntity, bool) {
chat, ok := s.chats[id]
return chat, ok
}
func (s *Store) IsMember(userID, chatID uuid.UUID) bool {
chat, ok := s.chats[chatID]
if !ok {
return false
}
return slices.Contains(chat.GetMemberIDs(), userID)
}
func (s *Store) CreateMessage(msg MessageEntity) {
s.chatMessages[msg.GetChatID()] = append(s.chatMessages[msg.GetChatID()], msg)
}
func (s *Store) GetUserChats(userID uuid.UUID, limit int, cursor *common.CursorKeyCtx) (*common.PaginatedResponse[Entity], error) {
chatIDs := s.userChats[userID]
userChats := make([]Entity, 0, len(chatIDs))
for _, chatID := range chatIDs {
if chat, exists := s.chats[chatID]; exists {
userChats = append(userChats, chat)
}
}
return common.Paginate(userChats, limit, cursor, userID)
}
func (s *Store) GetChatMessages(chatID uuid.UUID, limit int, cursor *common.CursorKeyCtx) (*common.PaginatedResponse[Entity], error) {
chatMessages := s.chatMessages[chatID]
messages := make([]Entity, 0, len(chatMessages))
for _, message := range chatMessages {
messages = append(messages, message)
}
return common.Paginate(messages, limit, cursor, chatID)
}
+357
View File
@@ -0,0 +1,357 @@
// AGENT: Concrete PostgreSQL store: plain parameterized SQL, one bounded pool,
// explicit transaction boundaries. It returns contract AppErrors so HTTP status
// mapping stays in one place.
package store
import (
"context"
"errors"
"time"
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/common"
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/model"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
)
type Store struct {
pool *pgxpool.Pool
timeout time.Duration
}
func New(pool *pgxpool.Pool, timeout time.Duration) *Store {
return &Store{pool: pool, timeout: timeout}
}
func (s *Store) withTimeout(ctx context.Context) (context.Context, context.CancelFunc) {
return context.WithTimeout(ctx, s.timeout)
}
func (s *Store) Ping(ctx context.Context) error {
pingCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
defer cancel()
return s.pool.Ping(pingCtx)
}
func (s *Store) CreateUser(ctx context.Context, username, displayName, passwordHash string) (model.User, error) {
ctx, cancel := s.withTimeout(ctx)
defer cancel()
user := model.User{
ID: uuid.New(),
Username: username,
DisplayName: displayName,
PasswordHash: passwordHash,
CreatedAt: common.NowUTC(),
}
_, err := s.pool.Exec(ctx, `
INSERT INTO users (id, username, display_name, password_hash, created_at)
VALUES ($1, $2, $3, $4, $5)`,
user.ID, user.Username, user.DisplayName, user.PasswordHash, time.Time(user.CreatedAt))
if err != nil {
// AGENT: The unique index is the real guard. Two concurrent registrations
// with the same username both reach INSERT; exactly one commits, the other
// gets SQLSTATE 23505 and is mapped to 409 instead of a 500.
if isUniqueViolation(err) {
return model.User{}, common.Conflict("username already taken")
}
return model.User{}, dbError(err)
}
return user, nil
}
func (s *Store) GetUserByID(ctx context.Context, id uuid.UUID) (model.User, error) {
ctx, cancel := s.withTimeout(ctx)
defer cancel()
return s.scanUser(s.pool.QueryRow(ctx, `
SELECT id, username, display_name, password_hash, created_at
FROM users WHERE id = $1`, id))
}
func (s *Store) GetUserByUsername(ctx context.Context, username string) (model.User, error) {
ctx, cancel := s.withTimeout(ctx)
defer cancel()
return s.scanUser(s.pool.QueryRow(ctx, `
SELECT id, username, display_name, password_hash, created_at
FROM users WHERE username = $1`, username))
}
type rowScanner interface {
Scan(dest ...any) error
}
func (s *Store) scanUser(row rowScanner) (model.User, error) {
var user model.User
var createdAt time.Time
if err := row.Scan(&user.ID, &user.Username, &user.DisplayName, &user.PasswordHash, &createdAt); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return model.User{}, common.NotFound("user not found")
}
return model.User{}, dbError(err)
}
user.CreatedAt = common.RFCFormTime(createdAt.UTC())
return user, nil
}
// CreateChat inserts the chat and every membership row in one transaction.
// Any unknown member aborts the whole transaction, so a partially created chat
// can never be observed.
func (s *Store) CreateChat(ctx context.Context, title string, memberIDs []uuid.UUID) (model.Chat, error) {
ctx, cancel := s.withTimeout(ctx)
defer cancel()
tx, err := s.pool.Begin(ctx)
if err != nil {
return model.Chat{}, dbError(err)
}
defer func() { _ = tx.Rollback(context.Background()) }()
for _, memberID := range memberIDs {
var exists int
err = tx.QueryRow(ctx, `SELECT 1 FROM users WHERE id = $1`, memberID).Scan(&exists)
if errors.Is(err, pgx.ErrNoRows) {
return model.Chat{}, common.BadRequest("member_id refers to non-existent user")
}
if err != nil {
return model.Chat{}, dbError(err)
}
}
chat := model.Chat{
ID: uuid.New(),
Title: title,
MemberIDs: append([]uuid.UUID(nil), memberIDs...),
CreatedAt: common.NowUTC(),
}
if _, err = tx.Exec(ctx,
`INSERT INTO chats (id, title, created_at) VALUES ($1, $2, $3)`,
chat.ID, chat.Title, time.Time(chat.CreatedAt)); err != nil {
return model.Chat{}, dbError(err)
}
for _, memberID := range memberIDs {
if _, err = tx.Exec(ctx,
`INSERT INTO chat_members (chat_id, user_id) VALUES ($1, $2)`,
chat.ID, memberID); err != nil {
return model.Chat{}, dbError(err)
}
}
if err = tx.Commit(ctx); err != nil {
return model.Chat{}, dbError(err)
}
return chat, nil
}
func (s *Store) GetChatForUser(ctx context.Context, userID, chatID uuid.UUID) (model.Chat, error) {
ctx, cancel := s.withTimeout(ctx)
defer cancel()
var chat model.Chat
var createdAt time.Time
err := s.pool.QueryRow(ctx, `
SELECT c.id, c.title, c.created_at,
ARRAY(SELECT user_id FROM chat_members WHERE chat_id = c.id ORDER BY user_id)
FROM chats c
JOIN chat_members me ON me.chat_id = c.id AND me.user_id = $2
WHERE c.id = $1`, chatID, userID).
Scan(&chat.ID, &chat.Title, &createdAt, &chat.MemberIDs)
if errors.Is(err, pgx.ErrNoRows) {
return model.Chat{}, common.NotFound("chat not found")
}
if err != nil {
return model.Chat{}, dbError(err)
}
chat.CreatedAt = common.RFCFormTime(createdAt.UTC())
return chat, nil
}
func (s *Store) ListChats(ctx context.Context, userID uuid.UUID, limit int, cursor *common.CursorKeyCtx) (*common.Page[model.Chat], error) {
ctx, cancel := s.withTimeout(ctx)
defer cancel()
cursorTime, cursorID := cursorValues(cursor)
rows, err := s.pool.Query(ctx, `
SELECT c.id, c.title, c.created_at,
ARRAY(SELECT user_id FROM chat_members WHERE chat_id = c.id ORDER BY user_id)
FROM chats c
JOIN chat_members me ON me.chat_id = c.id AND me.user_id = $1
WHERE (c.created_at, c.id) > ($2, $3)
ORDER BY c.created_at, c.id
LIMIT $4`, userID, cursorTime, cursorID, limit+1)
if err != nil {
return nil, dbError(err)
}
defer rows.Close()
chats := make([]model.Chat, 0, limit)
for rows.Next() {
var chat model.Chat
var createdAt time.Time
if err = rows.Scan(&chat.ID, &chat.Title, &createdAt, &chat.MemberIDs); err != nil {
return nil, dbError(err)
}
chat.CreatedAt = common.RFCFormTime(createdAt.UTC())
chats = append(chats, chat)
}
if err = rows.Err(); err != nil {
return nil, dbError(err)
}
hasMore := len(chats) > limit
if hasMore {
chats = chats[:limit]
}
return &common.Page[model.Chat]{Items: chats, NextCursor: common.NextCursor(chats, hasMore, userID)}, nil
}
func (s *Store) IsMember(ctx context.Context, userID, chatID uuid.UUID) (bool, error) {
ctx, cancel := s.withTimeout(ctx)
defer cancel()
var exists int
err := s.pool.QueryRow(ctx,
`SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2`,
chatID, userID).Scan(&exists)
if errors.Is(err, pgx.ErrNoRows) {
return false, nil
}
if err != nil {
return false, dbError(err)
}
return true, nil
}
// CreateMessage uses INSERT ... SELECT so the membership check and the insert
// are a single atomic statement: no window where the user is removed between
// check and write. Zero affected rows means the chat is missing or foreign.
func (s *Store) CreateMessage(ctx context.Context, chatID, senderID uuid.UUID, text string) (model.Message, error) {
ctx, cancel := s.withTimeout(ctx)
defer cancel()
message := model.Message{
ID: uuid.New(),
ChatID: chatID,
SenderID: senderID,
Text: text,
CreatedAt: common.NowUTC(),
}
tag, err := s.pool.Exec(ctx, `
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
SELECT $1, $2, $3, $4, $5
WHERE EXISTS (SELECT 1 FROM chat_members WHERE chat_id = $2 AND user_id = $3)`,
message.ID, message.ChatID, message.SenderID, message.Text, time.Time(message.CreatedAt))
if err != nil {
return model.Message{}, dbError(err)
}
if tag.RowsAffected() == 0 {
return model.Message{}, common.NotFound("chat not found")
}
return message, nil
}
func (s *Store) ListMessages(ctx context.Context, userID, chatID uuid.UUID, limit int, cursor *common.CursorKeyCtx) (*common.Page[model.Message], error) {
isMember, err := s.IsMember(ctx, userID, chatID)
if err != nil {
return nil, err
}
if !isMember {
return nil, common.NotFound("chat not found")
}
// AGENT: Cursor context is checked only after membership, so a foreign
// caller gets 404 and cannot probe cursor validity against someone else's chat.
if cursor != nil && cursor.ContextID != chatID {
return nil, common.BadRequest("bad cursor value")
}
ctx, cancel := s.withTimeout(ctx)
defer cancel()
// AGENT: limit+1 is fetched so next_cursor is known to be non-null without a
// second COUNT query; the extra row is never returned to the client.
cursorTime, cursorID := cursorValues(cursor)
rows, err := s.pool.Query(ctx, `
SELECT id, chat_id, sender_id, text, created_at
FROM messages
WHERE chat_id = $1 AND (created_at, id) > ($2, $3)
ORDER BY created_at, id
LIMIT $4`, chatID, cursorTime, cursorID, limit+1)
if err != nil {
return nil, dbError(err)
}
defer rows.Close()
messages := make([]model.Message, 0, limit)
for rows.Next() {
var message model.Message
var createdAt time.Time
if err = rows.Scan(&message.ID, &message.ChatID, &message.SenderID, &message.Text, &createdAt); err != nil {
return nil, dbError(err)
}
message.CreatedAt = common.RFCFormTime(createdAt.UTC())
messages = append(messages, message)
}
if err = rows.Err(); err != nil {
return nil, dbError(err)
}
hasMore := len(messages) > limit
if hasMore {
messages = messages[:limit]
}
return &common.Page[model.Message]{
Items: messages,
NextCursor: common.NextCursor(messages, hasMore, chatID),
}, nil
}
func cursorValues(cursor *common.CursorKeyCtx) (time.Time, uuid.UUID) {
if cursor == nil {
return time.Time{}, uuid.Nil
}
return cursor.Time, cursor.ID
}
func isUniqueViolation(err error) bool {
var pgErr *pgconn.PgError
return errors.As(err, &pgErr) && pgErr.Code == "23505"
}
// dbError separates a drained dependency (503) from a real bug (500). SQL
// details never reach the client; callers only emit the AppError message.
func dbError(err error) error {
if err == nil {
return nil
}
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) {
switch pgErr.Code {
case "23505":
return common.Conflict("resource already exists")
case "23503", "23514", "22P02":
return common.BadRequest("request conflicts with stored data")
}
}
if errors.Is(err, context.DeadlineExceeded) ||
errors.Is(err, context.Canceled) ||
pgconn.SafeToRetry(err) ||
errors.Is(err, pgx.ErrTxClosed) {
return common.Unavailable("database unavailable")
}
return common.Internal()
}
+33 -26
View File
@@ -1,13 +1,28 @@
package users
import (
"gitflic.ru/project/bulla-max/mtusi2026lab1/internal/common"
"gitflic.ru/project/bulla-max/mtusi2026lab1/internal/storage"
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/auth"
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/common"
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/store"
"github.com/gofiber/fiber/v3"
"github.com/google/uuid"
)
func createUser(c fiber.Ctx) error {
type Handler struct {
store *store.Store
}
func NewHandler(st *store.Store) *Handler {
return &Handler{store: st}
}
type CreateUserRequest struct {
Username string `json:"username" validate:"required"`
DisplayName string `json:"display_name" validate:"required"`
Password string `json:"password" validate:"required"`
}
func (h *Handler) CreateUser(c fiber.Ctx) error {
var req CreateUserRequest
if err := common.BindJSON(c, &req); err != nil {
return common.SendAppError(c, err)
@@ -16,18 +31,17 @@ func createUser(c fiber.Ctx) error {
if msg := common.ValidateCreateUser(req.Username, req.DisplayName); msg != "" {
return common.SendError(c, fiber.StatusBadRequest, common.ErrorCodeInvalidRequest, msg)
}
if msg := common.ValidatePassword(req.Password); msg != "" {
return common.SendError(c, fiber.StatusBadRequest, common.ErrorCodeInvalidRequest, msg)
}
var user User
hash, err := auth.HashPassword(req.Password)
if err != nil {
return common.SendError(c, fiber.StatusInternalServerError,
common.ErrorCodeInternal, "Internal server error")
}
err := storage.GlobalStore.Update(func(tx storage.Tx) error {
if tx.UsernameExists(req.Username) {
return common.Conflict("username already taken")
}
user = NewUser(req)
tx.CreateUser(user)
return nil
})
user, err := h.store.CreateUser(c.Context(), req.Username, req.DisplayName, hash)
if err != nil {
return common.SendAppError(c, err)
}
@@ -35,20 +49,13 @@ func createUser(c fiber.Ctx) error {
return c.Status(fiber.StatusCreated).JSON(user)
}
func getCurrentUser(c fiber.Ctx) error {
userID := c.Locals("userID").(uuid.UUID)
func (h *Handler) GetCurrentUser(c fiber.Ctx) error {
userID, ok := c.Locals("userID").(uuid.UUID)
if !ok {
return common.SendChallenge(c, `Bearer realm="messenger"`, "authentication required")
}
var user storage.UserEntity
err := storage.GlobalStore.View(func(tx storage.ReadOnlyTx) error {
found, ok := tx.GetUser(userID)
if !ok {
return common.NotFound("no user with provided credentials exist")
}
user = found
return nil
})
user, err := h.store.GetUserByID(c.Context(), userID)
if err != nil {
return common.SendAppError(c, err)
}
-41
View File
@@ -1,41 +0,0 @@
package users
import (
"time"
"gitflic.ru/project/bulla-max/mtusi2026lab1/internal/common"
"github.com/google/uuid"
)
type User struct {
ID uuid.UUID `json:"id"`
Username string `json:"username"`
DisplayName string `json:"display_name"`
CreatedAt common.RFCFormTime `json:"created_at"`
}
type CreateUserRequest struct {
Username string `json:"username" validate:"required"`
DisplayName string `json:"display_name" validate:"required"`
}
func NewUser(req CreateUserRequest) User {
return User{
ID: uuid.New(),
Username: req.Username,
DisplayName: req.DisplayName,
CreatedAt: common.NowUTC(),
}
}
func (u User) GetID() uuid.UUID {
return u.ID
}
func (u User) GetCreatedAt() time.Time {
return time.Time(u.CreatedAt)
}
func (u User) GetUsername() string {
return u.Username
}
+10 -5
View File
@@ -1,11 +1,16 @@
package users
import "github.com/gofiber/fiber/v3"
import (
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/store"
"github.com/gofiber/fiber/v3"
)
func RegisterPublicRoutes(router fiber.Router) {
router.Post("/users", createUser)
func RegisterPublicRoutes(router fiber.Router, st *store.Store) {
handler := NewHandler(st)
router.Post("/users", handler.CreateUser)
}
func RegisterRoutes(router fiber.Router) {
router.Get("/users/me", getCurrentUser)
func RegisterRoutes(router fiber.Router, st *store.Store) {
handler := NewHandler(st)
router.Get("/users/me", handler.GetCurrentUser)
}