feat(app) lab 3 implemented

This commit is contained in:
imadev
2026-10-30 18:11:30 +03:00
parent f731f9b460
commit 48a616e910
57 changed files with 1390 additions and 303 deletions
+18 -9
View File
@@ -1,3 +1,5 @@
// Command server starts the messenger HTTP API, applies optional migrations,
// and shuts down gracefully on SIGINT/SIGTERM.
package main
import (
@@ -8,10 +10,10 @@ import (
"syscall"
"time"
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal"
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/config"
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/database"
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/session"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/config"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/database"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/session"
)
func main() {
@@ -29,11 +31,18 @@ func main() {
}
defer pool.Close()
migrateCtx, cancelMigrate := context.WithTimeout(rootCtx, 60*time.Second)
err = database.Migrate(migrateCtx, pool, cfg.DatabaseURL)
cancelMigrate()
if err != nil {
log.Fatalf("migrations: %v", err)
if cfg.MigrateOnly || cfg.RunMigrations {
migrateCtx, cancelMigrate := context.WithTimeout(rootCtx, 60*time.Second)
err = database.Migrate(migrateCtx, pool, cfg.DatabaseURL)
cancelMigrate()
if err != nil {
log.Fatalf("migrations: %v", err)
}
}
if cfg.MigrateOnly {
log.Printf("migrations applied; migrate-only process exiting")
return
}
sessions, err := session.New(cfg.CacheURL, cfg.SessionTTL, cfg.RedisTimeout)
+1 -1
View File
@@ -1,4 +1,4 @@
module gitflic.ru/project/bulla-max/mtusi2026lab2
module gitflic.ru/project/bulla-max/mtusi2026lab
go 1.27.1
+18 -16
View File
@@ -1,18 +1,20 @@
// Package internal wires HTTP routes, middleware and storage into one Fiber
// application and owns the process-wide error handler.
package internal
import (
"errors"
"time"
"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"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/auth"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/chats"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/config"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/health"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/messages"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/session"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/store"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/users"
"github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/middleware/recover"
"github.com/gofiber/fiber/v3/middleware/requestid"
@@ -24,7 +26,7 @@ func SignalGracefulShutdown() {
}
func New(cfg config.Config, pool *pgxpool.Pool, sessions *session.Store) *fiber.App {
st := store.New(pool, cfg.DBTimeout)
st := store.New(pool, cfg.DBTimeout, cfg.IdempotencyTTL)
app := fiber.New(fiber.Config{
ReadTimeout: 10 * time.Second,
@@ -36,6 +38,10 @@ func New(cfg config.Config, pool *pgxpool.Pool, sessions *session.Store) *fiber.
app.Use(recover.New())
app.Use(requestid.New())
app.Use(func(c fiber.Ctx) error {
c.Set("X-Instance-Id", cfg.InstanceID)
return c.Next()
})
health.RegisterRoutes(app.Group("/health"), st, sessions)
@@ -53,16 +59,12 @@ func New(cfg config.Config, pool *pgxpool.Pool, sessions *session.Store) *fiber.
return app
}
// handleError keeps every failure in the contract error envelope, including
// Fiber's own errors (404, 405, 413) and recovered panics.
func handleError(c fiber.Ctx, err error) error {
var appErr *common.AppError
if errors.As(err, &appErr) {
if appErr, ok := errors.AsType[*common.AppError](err); ok {
return common.SendError(c, appErr.Status, appErr.Code, appErr.Message)
}
var fiberErr *fiber.Error
if errors.As(err, &fiberErr) {
if fiberErr, ok := errors.AsType[*fiber.Error](err); ok {
return common.SendError(c, fiberErr.Code,
common.ErrorCodeFromStatus(fiberErr.Code), fiberErr.Message)
}
+15 -15
View File
@@ -1,3 +1,5 @@
// Package auth implements password hashing, Basic login, Bearer session
// middleware and the authentication routes.
package auth
import (
@@ -5,16 +7,18 @@ import (
"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"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/model"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/session"
"gitflic.ru/project/bulla-max/mtusi2026lab/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"`
const (
basicChallenge = `Basic realm="messenger", charset="UTF-8"`
bearerChallenge = `Bearer realm="messenger"`
)
type Handler struct {
store *store.Store
@@ -25,9 +29,6 @@ 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 {
@@ -37,6 +38,11 @@ func (h *Handler) CreateSession(c fiber.Ctx) error {
user, err := h.store.GetUserByUsername(c.Context(), username)
if err != nil {
if common.IsCode(err, common.ErrorCodeNotFound) {
// An unknown username returns before Argon2 runs, while a known
// username with a wrong password runs VerifyPassword. The branches
// therefore take different time, so username enumeration through
// response timing is theoretically possible. The contract only
// requires the same 401 body and challenge.
return common.SendChallenge(c, basicChallenge, "invalid credentials")
}
return common.SendAppError(c, err)
@@ -62,8 +68,6 @@ func (h *Handler) CreateSession(c fiber.Ctx) error {
})
}
// 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, ok := common.SessionToken(c)
if !ok {
@@ -79,8 +83,6 @@ func (h *Handler) RevokeSession(c fiber.Ctx) error {
return c.SendStatus(fiber.StatusNoContent)
}
// 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))
@@ -95,8 +97,6 @@ func BearerAuth(sessions *session.Store) fiber.Handler {
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")
+8 -7
View File
@@ -1,6 +1,3 @@
// 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 (
@@ -38,8 +35,6 @@ func HashPassword(password string) (string, error) {
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" {
@@ -57,13 +52,19 @@ func VerifyPassword(encoded, password string) (bool, error) {
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &memory, &iterations, &parallelism); err != nil {
return false, ErrInvalidHash
}
// argon2.IDKey panics when the cost parameters are outside its supported
// range. A corrupted row or an attacker-supplied encoding must be rejected
// with ErrInvalidHash instead of taking the process down.
if iterations < 1 || parallelism < 1 || memory < 8*uint32(parallelism) {
return false, ErrInvalidHash
}
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
if err != nil {
if err != nil || len(salt) == 0 {
return false, ErrInvalidHash
}
expected, err := base64.RawStdEncoding.DecodeString(parts[5])
if err != nil {
if err != nil || len(expected) == 0 {
return false, ErrInvalidHash
}
+18
View File
@@ -44,3 +44,21 @@ func TestPasswordHashIsSalted(t *testing.T) {
t.Fatal("invalid encoded hash was accepted")
}
}
func TestVerifyPasswordRejectsMalformedCostAndEmptyDigest(t *testing.T) {
malformed := []string{
// Empty digest would make argon2 derive a zero-length key.
"$argon2id$v=19$m=65536,t=2,p=4$c2FsdA$",
// Zero cost parameters are outside argon2's supported range and would
// otherwise panic inside the KDF.
"$argon2id$v=19$m=65536,t=0,p=4$c2FsdA$YWJjZA",
"$argon2id$v=19$m=65536,t=2,p=0$c2FsdA$YWJjZA",
"$argon2id$v=19$m=1,t=2,p=4$c2FsdA$YWJjZA",
}
for _, encoded := range malformed {
ok, err := VerifyPassword(encoded, "same-password-123")
if err == nil || ok {
t.Fatalf("VerifyPassword(%q) = (%v, %v), want ErrInvalidHash", encoded, ok, err)
}
}
}
+2 -2
View File
@@ -1,8 +1,8 @@
package auth
import (
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/session"
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/store"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/session"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/store"
"github.com/gofiber/fiber/v3"
)
+3 -2
View File
@@ -1,8 +1,9 @@
// Package chats implements chat creation, lookup and cursor-paginated listing.
package chats
import (
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/common"
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/store"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/store"
"github.com/gofiber/fiber/v3"
"github.com/google/uuid"
)
+1 -1
View File
@@ -1,7 +1,7 @@
package chats
import (
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/store"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/store"
"github.com/gofiber/fiber/v3"
)
-9
View File
@@ -9,15 +9,6 @@ import (
"github.com/gofiber/fiber/v3"
)
// AGENT: Field-level validation is deliberately not delegated to a generic
// struct validator. The contract needs specific messages for blank strings,
// Unicode length and duplicate member IDs, so handlers call the Validators in
// validation.go after this strict JSON decoding step.
//
// BindJSON enforces the request format from the contract: JSON content type,
// exactly one JSON value, no unknown fields and correct Go types. Field-level
// rules (non-blank strings, lengths, UUID lists) stay in the handlers so their
// messages can be specific.
func BindJSON(c fiber.Ctx, dst any) error {
if contentType := c.Get(fiber.HeaderContentType); !strings.HasPrefix(contentType, "application/json") {
return UnsupportedMedia("invalid JSON body")
+5 -6
View File
@@ -1,3 +1,5 @@
// Package common contains cross-cutting HTTP helpers: contract errors, JSON
// binding, validation, cursor pagination and timestamp formatting.
package common
import (
@@ -87,8 +89,8 @@ func Unavailable(message string) *AppError {
// 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
appErr, ok := errors.AsType[*AppError](err)
return ok && appErr.Code == code
}
func ErrorCodeFromStatus(status int) string {
@@ -126,8 +128,7 @@ func SendError(c fiber.Ctx, status int, code, message string) error {
}
func SendAppError(c fiber.Ctx, err error) error {
var appErr *AppError
if errors.As(err, &appErr) {
if appErr, ok := errors.AsType[*AppError](err); ok {
return SendError(c, appErr.Status, appErr.Code, appErr.Message)
}
@@ -135,8 +136,6 @@ func SendAppError(c fiber.Ctx, err error) error {
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)
@@ -0,0 +1,30 @@
package common
import (
"strings"
"testing"
)
func TestValidateIdempotencyKey(t *testing.T) {
tests := []struct {
name string
key string
ok bool
}{
{name: "hex", key: "4f8c2d1e", ok: true},
{name: "allowed punctuation", key: "load-1_a.b:c", ok: true},
{name: "empty", key: "", ok: false},
{name: "space", key: "two words", ok: false},
{name: "slash", key: "a/b", ok: false},
{name: "too long", key: strings.Repeat("a", 129), ok: false},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
got := ValidateIdempotencyKey(test.key) == ""
if got != test.ok {
t.Fatalf("ValidateIdempotencyKey(%q) valid = %v, want %v", test.key, got, test.ok)
}
})
}
}
+1 -8
View File
@@ -6,21 +6,15 @@ import (
)
const (
// KeyUserID is the request-scoped key set by the Bearer middleware.
KeyUserID = "userID"
// KeySessionToken is the raw token of the current request.
KeyUserID = "userID"
KeySessionToken = "sessionToken"
)
// UserID returns the authenticated user ID and whether the middleware set it.
func UserID(c fiber.Ctx) (uuid.UUID, bool) {
userID, ok := c.Locals(KeyUserID).(uuid.UUID)
return userID, ok
}
// MustUserID is for handlers mounted behind BearerAuth, where the middleware
// guarantees the local. A missing value is a programming error, not a client
// error, so it becomes a recovered 500 instead of an anonymous request.
func MustUserID(c fiber.Ctx) uuid.UUID {
userID, ok := UserID(c)
if !ok {
@@ -29,7 +23,6 @@ func MustUserID(c fiber.Ctx) uuid.UUID {
return userID
}
// SessionToken returns the raw bearer token of the current request.
func SessionToken(c fiber.Ctx) (string, bool) {
token, ok := c.Locals(KeySessionToken).(string)
return token, ok && token != ""
-6
View File
@@ -10,9 +10,6 @@ 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
@@ -88,9 +85,6 @@ func DecodeCursor(cursor string) (*CursorKeyCtx, bool) {
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
-18
View File
@@ -29,21 +29,3 @@ func TestCursorRoundTrip(t *testing.T) {
}
}
}
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)
}
}
}
+21
View File
@@ -0,0 +1,21 @@
package common
import "testing"
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)
}
}
}
+4 -13
View File
@@ -5,19 +5,15 @@ import (
"time"
)
// storageTimePrecision is the maximum precision shared by PostgreSQL
// timestamptz columns and the JSON representation. PostgreSQL stores
// microseconds, so keeping the same boundary in Go prevents a create response
// from showing more precision than a later read can reproduce.
// PostgreSQL stores microseconds, so keeping the same boundary in Go
// prevents a create response from showing more precision
// than a later read can reproduce.
const storageTimePrecision = time.Microsecond
type RFCFormTime time.Time
func (t RFCFormTime) MarshalJSON() ([]byte, error) {
// RFC 3339 permits an optional fractional second. Use all six digits that
// PostgreSQL can store, and omit the fraction only for an exact second.
// A fixed six-digit fraction is also accepted by strict consumers that only
// understand 3- or 6-digit fractions (for example Python 3.9's parser).
// RFC 3339 permits an optional fractional second.
utc := time.Time(t).UTC().Truncate(storageTimePrecision)
layout := "2006-01-02T15:04:05Z"
if utc.Nanosecond() != 0 {
@@ -27,10 +23,5 @@ func (t RFCFormTime) MarshalJSON() ([]byte, error) {
}
func NowUTC() RFCFormTime {
// AGENT: The API used to truncate timestamps to whole seconds to keep
// keyset ordering consistent with JSON. RFC 3339 supports fractional seconds
// and PostgreSQL has microsecond precision, so use that precision end to end:
// timestamps remain ordered after serialization without discarding sub-second
// information.
return RFCFormTime(time.Now().UTC().Truncate(storageTimePrecision))
}
+14 -1
View File
@@ -8,7 +8,10 @@ import (
"github.com/google/uuid"
)
var usernameRegex = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
var (
usernameRegex = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
idempotencyKeyRegex = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
)
func blank(s string) bool {
return strings.TrimSpace(s) == ""
@@ -71,6 +74,16 @@ func ValidateMessageText(text string) string {
return ""
}
func ValidateIdempotencyKey(key string) string {
if key == "" {
return "Idempotency-Key header is required"
}
if !idempotencyKeyRegex.MatchString(key) {
return "Idempotency-Key must match ^[A-Za-z0-9._:-]{1,128}$"
}
return ""
}
func ValidateMemberIDs(ids []uuid.UUID, callerID uuid.UUID) string {
if len(ids) < 1 || len(ids) > 100 {
return "member_ids must contain between 1 and 100 members"
+71 -18
View File
@@ -1,6 +1,5 @@
// 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 loads and validates process configuration from environment
// variables and optional *_FILE secrets.
package config
import (
@@ -12,25 +11,36 @@ import (
)
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
Host string
Port string
InstanceID string
SessionTTL time.Duration
IdempotencyTTL time.Duration
DatabaseURL string
CacheURL string
DBMaxConns int32
DBTimeout time.Duration
RedisTimeout time.Duration
StartupWait time.Duration
RunMigrations bool
MigrateOnly bool
}
func Load() (Config, error) {
instance, err := instanceID()
if err != nil {
return Config{}, err
}
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,
Host: envOr("APP_HOST", "0.0.0.0"),
Port: envOr("APP_PORT", "8080"),
InstanceID: instance,
DBMaxConns: 10,
DBTimeout: 5 * time.Second,
RedisTimeout: 2 * time.Second,
StartupWait: 30 * time.Second,
RunMigrations: true,
}
ttlSeconds, err := strconv.Atoi(envOr("SESSION_TTL_SECONDS", "3600"))
@@ -39,6 +49,19 @@ func Load() (Config, error) {
}
cfg.SessionTTL = time.Duration(ttlSeconds) * time.Second
idempotencySeconds, err := strconv.Atoi(envOr("IDEMPOTENCY_TTL_SECONDS", "86400"))
if err != nil || idempotencySeconds < 1 {
return cfg, fmt.Errorf("IDEMPOTENCY_TTL_SECONDS must be a positive integer")
}
cfg.IdempotencyTTL = time.Duration(idempotencySeconds) * time.Second
if cfg.RunMigrations, err = envBool("RUN_MIGRATIONS", true); err != nil {
return cfg, err
}
if cfg.MigrateOnly, err = envBool("MIGRATE_ONLY", false); err != nil {
return cfg, err
}
if value := envOr("DB_POOL_MAX_CONNS", ""); value != "" {
n, convErr := strconv.Atoi(value)
if convErr != nil || n < 1 || n > 100 {
@@ -55,6 +78,10 @@ func Load() (Config, error) {
return cfg, fmt.Errorf("DATABASE_URL or DATABASE_URL_FILE is required")
}
if cfg.MigrateOnly {
return cfg, nil
}
cfg.CacheURL, err = secret("CACHE_URL")
if err != nil {
return cfg, err
@@ -76,6 +103,32 @@ func Load() (Config, error) {
return cfg, nil
}
func instanceID() (string, error) {
if value := strings.TrimSpace(os.Getenv("INSTANCE_ID")); value != "" {
return value, nil
}
name, err := os.Hostname()
if err != nil {
return "", fmt.Errorf("determine INSTANCE_ID: %w", err)
}
if name = strings.TrimSpace(name); name == "" {
return "", fmt.Errorf("determine INSTANCE_ID: hostname is empty and INSTANCE_ID is not set")
}
return name, nil
}
func envBool(name string, fallback bool) (bool, error) {
value := os.Getenv(name)
if value == "" {
return fallback, nil
}
parsed, err := strconv.ParseBool(value)
if err != nil {
return false, fmt.Errorf("%s must be true or false", name)
}
return parsed, nil
}
func envOr(name, fallback string) string {
if value := os.Getenv(name); value != "" {
return value
+27
View File
@@ -0,0 +1,27 @@
package config
import "testing"
func TestInstanceIDUsesConfiguredValue(t *testing.T) {
t.Setenv("INSTANCE_ID", " api-1 ")
got, err := instanceID()
if err != nil {
t.Fatalf("instanceID: %v", err)
}
if got != "api-1" {
t.Fatalf("instanceID = %q, want api-1", got)
}
}
func TestInstanceIDFallsBackToHostname(t *testing.T) {
t.Setenv("INSTANCE_ID", " ")
got, err := instanceID()
if err != nil {
t.Fatalf("instanceID: %v", err)
}
if got == "" {
t.Fatal("instanceID returned an empty value")
}
}
-2
View File
@@ -27,8 +27,6 @@ func Connect(ctx context.Context, url string, maxConns int32, wait time.Duration
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)
+6 -13
View File
@@ -1,6 +1,3 @@
// AGENT: golang-migrate now runs the embedded SQL files instead of the previous
// hand-written runner. The legacy table upgrade below keeps existing lab 2
// volumes usable, so switching engines does not require deleting data.
package database
import (
@@ -22,16 +19,10 @@ import (
var migrationFiles embed.FS
const (
// The old in-house runner used this advisory lock. We keep the same key for
// the one-time table upgrade so an upgrade cannot race a still-running old
// instance that is applying the baseline migration.
legacyMigrationLockID int64 = 728_2026
migrationsTable = "schema_migrations"
)
// Migrate applies the embedded golang-migrate migrations. golang-migrate takes
// its own PostgreSQL advisory lock, records the current version and dirty flag
// in schema_migrations, and wraps each migration file in one transaction.
func Migrate(ctx context.Context, pool *pgxpool.Pool, databaseURL string) error {
if err := upgradeLegacyMigrationsTable(ctx, pool); err != nil {
return err
@@ -47,8 +38,6 @@ func Migrate(ctx context.Context, pool *pgxpool.Pool, databaseURL string) error
_ = source.Close()
return fmt.Errorf("parse DATABASE_URL for migrations: %w", err)
}
// golang-migrate acquires its lock with context.Background(). A PostgreSQL
// lock timeout keeps startup bounded if another instance never releases it.
if connConfig.RuntimeParams == nil {
connConfig.RuntimeParams = make(map[string]string)
}
@@ -89,7 +78,7 @@ func Migrate(ctx context.Context, pool *pgxpool.Pool, databaseURL string) error
// upgradeLegacyMigrationsTable replaces the table written by the previous
// in-house runner (version text, applied_at) with the golang-migrate schema
// (version bigint, dirty boolean). The schema itself is left untouched and the
// (version bigint, dirty boolean). The data schema itself is left untouched and the
// highest applied version is carried over, so a preserved volume does not need
// to be recreated. The migration DDL is idempotent, but preserving the version
// keeps the migration history truthful.
@@ -132,7 +121,11 @@ func upgradeLegacyMigrationsTable(ctx context.Context, pool *pgxpool.Pool) error
if err != nil {
return fmt.Errorf("begin migration table upgrade: %w", err)
}
defer func() { _ = tx.Rollback(context.Background()) }()
defer func() {
rollbackCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_ = tx.Rollback(rollbackCtx)
}()
const upgrade = `
DROP TABLE IF EXISTS schema_migrations_migrate_tmp;
@@ -1,5 +1,3 @@
-- AGENT: Local rollback for the baseline schema. The application only runs Up
-- migrations; this file exists so golang-migrate can also step down in tests.
DROP TABLE IF EXISTS messages;
DROP TABLE IF EXISTS chat_members;
DROP TABLE IF EXISTS chats;
@@ -1,8 +1,3 @@
-- 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,
@@ -39,8 +34,5 @@ CREATE TABLE IF NOT EXISTS messages (
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);
@@ -0,0 +1 @@
DROP TABLE IF EXISTS message_idempotency;
@@ -0,0 +1,14 @@
CREATE TABLE IF NOT EXISTS message_idempotency (
sender_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
idempotency_key text NOT NULL,
request_hash bytea NOT NULL,
message_id uuid NOT NULL REFERENCES messages(id) ON DELETE CASCADE,
created_at timestamptz NOT NULL,
expires_at timestamptz NOT NULL,
PRIMARY KEY (sender_id, chat_id, idempotency_key),
CONSTRAINT message_idempotency_key_len CHECK (char_length(idempotency_key) BETWEEN 1 AND 128)
);
CREATE INDEX IF NOT EXISTS message_idempotency_expires_at_idx
ON message_idempotency (expires_at);
+12 -2
View File
@@ -18,7 +18,10 @@ func TestEmbeddedMigrationsParse(t *testing.T) {
for _, entry := range entries {
names[entry.Name()] = true
}
for _, want := range []string{"0001_init.up.sql", "0001_init.down.sql"} {
for _, want := range []string{
"0001_init.up.sql", "0001_init.down.sql",
"0002_message_idempotency.up.sql", "0002_message_idempotency.down.sql",
} {
if !names[want] {
t.Fatalf("migration %q is missing from the embedded filesystem", want)
}
@@ -37,7 +40,14 @@ func TestEmbeddedMigrationsParse(t *testing.T) {
if version != 1 {
t.Fatalf("first migration version = %d, want 1", version)
}
version, err = source.Next(version)
if err != nil {
t.Fatalf("read second migration: %v", err)
}
if version != 2 {
t.Fatalf("second migration version = %d, want 2", version)
}
if _, err := source.Next(version); !errors.Is(err, fs.ErrNotExist) {
t.Fatalf("expected the baseline to be the last migration, got %v", err)
t.Fatalf("expected 0002 to be the last migration, got %v", err)
}
}
+5 -6
View File
@@ -1,11 +1,13 @@
// Package health exposes liveness and readiness endpoints plus the process
// shutdown flag used by readiness.
package health
import (
"sync/atomic"
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/common"
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/session"
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/store"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/session"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/store"
"github.com/gofiber/fiber/v3"
)
@@ -32,9 +34,6 @@ 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.StatusServiceUnavailable,
+2 -2
View File
@@ -1,8 +1,8 @@
package health
import (
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/session"
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/store"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/session"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/store"
"github.com/gofiber/fiber/v3"
)
+10 -3
View File
@@ -1,8 +1,10 @@
// Package messages implements message creation with idempotency and message
// history pagination.
package messages
import (
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/common"
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/store"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/store"
"github.com/gofiber/fiber/v3"
"github.com/google/uuid"
)
@@ -28,6 +30,11 @@ func (h *Handler) CreateMessage(c fiber.Ctx) error {
common.ErrorCodeInvalidRequest, "invalid chat_id format")
}
idempotencyKey := c.Get("Idempotency-Key")
if msg := common.ValidateIdempotencyKey(idempotencyKey); msg != "" {
return common.SendError(c, fiber.StatusBadRequest, common.ErrorCodeInvalidRequest, msg)
}
var req CreateMessageRequest
if err := common.BindJSON(c, &req); err != nil {
return common.SendAppError(c, err)
@@ -36,7 +43,7 @@ func (h *Handler) CreateMessage(c fiber.Ctx) error {
return common.SendError(c, fiber.StatusBadRequest, common.ErrorCodeInvalidRequest, msg)
}
message, err := h.store.CreateMessage(c.Context(), chatID, userID, req.Text)
message, err := h.store.CreateMessage(c.Context(), chatID, userID, req.Text, idempotencyKey)
if err != nil {
return common.SendAppError(c, err)
}
+1 -1
View File
@@ -1,7 +1,7 @@
package messages
import (
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/store"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/store"
"github.com/gofiber/fiber/v3"
)
+3 -1
View File
@@ -1,9 +1,11 @@
// Package model defines the JSON-facing domain types shared by handlers,
// storage and the public contract.
package model
import (
"time"
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/common"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
"github.com/google/uuid"
)
+2 -5
View File
@@ -1,7 +1,5 @@
// 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 stores bearer sessions in Redis. Tokens are hashed before
// they become keys, and the configured TTL is absolute.
package session
import (
@@ -57,7 +55,6 @@ func (s *Store) Ping(ctx context.Context) error {
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 {
+3 -6
View File
@@ -5,15 +5,12 @@ import (
"errors"
"time"
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/common"
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/model"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/model"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
)
// 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()
@@ -22,7 +19,7 @@ func (s *Store) CreateChat(ctx context.Context, title string, memberIDs []uuid.U
if err != nil {
return model.Chat{}, dbError(err)
}
defer func() { _ = tx.Rollback(context.Background()) }()
defer rollback(tx)
for _, memberID := range memberIDs {
var exists int
+5 -9
View File
@@ -5,25 +5,22 @@ import (
"errors"
"net"
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/common"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
)
func isUniqueViolation(err error) bool {
var pgErr *pgconn.PgError
return errors.As(err, &pgErr) && pgErr.Code == "23505"
pgErr, ok := errors.AsType[*pgconn.PgError](err)
return ok && 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) {
if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok {
switch pgErr.Code {
case "23505":
return common.Conflict("resource already exists")
@@ -32,8 +29,7 @@ func dbError(err error) error {
}
}
var netErr net.Error
if errors.As(err, &netErr) || errors.Is(err, context.DeadlineExceeded) ||
if _, ok := errors.AsType[net.Error](err); ok || errors.Is(err, context.DeadlineExceeded) ||
errors.Is(err, context.Canceled) ||
pgconn.SafeToRetry(err) ||
errors.Is(err, pgx.ErrTxClosed) {
+85 -9
View File
@@ -1,21 +1,30 @@
package store
import (
"bytes"
"context"
"crypto/sha256"
"errors"
"time"
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/common"
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/model"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/model"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
)
// 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) {
func (s *Store) CreateMessage(ctx context.Context, chatID, senderID uuid.UUID, text, idempotencyKey string) (model.Message, error) {
ctx, cancel := s.withTimeout(ctx)
defer cancel()
fingerprint := sha256.Sum256([]byte(text))
if message, found, err := s.findIdempotentMessage(ctx, senderID, chatID, idempotencyKey, fingerprint[:]); err != nil {
return model.Message{}, err
} else if found {
return message, nil
}
message := model.Message{
ID: uuid.New(),
ChatID: chatID,
@@ -24,7 +33,13 @@ func (s *Store) CreateMessage(ctx context.Context, chatID, senderID uuid.UUID, t
CreatedAt: common.NowUTC(),
}
tag, err := s.pool.Exec(ctx, `
tx, err := s.pool.Begin(ctx)
if err != nil {
return model.Message{}, dbError(err)
}
defer rollback(tx)
tag, err := tx.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)`,
@@ -36,9 +51,72 @@ func (s *Store) CreateMessage(ctx context.Context, chatID, senderID uuid.UUID, t
return model.Message{}, common.NotFound("chat not found")
}
expiresAt := time.Time(message.CreatedAt).Add(s.idempotencyTTL)
tag, err = tx.Exec(ctx, `
INSERT INTO message_idempotency
(sender_id, chat_id, idempotency_key, request_hash, message_id, created_at, expires_at)
VALUES ($1, $2, $3, $4, $5, $6, $7)
ON CONFLICT (sender_id, chat_id, idempotency_key) DO UPDATE
SET request_hash = EXCLUDED.request_hash,
message_id = EXCLUDED.message_id,
created_at = EXCLUDED.created_at,
expires_at = EXCLUDED.expires_at
WHERE message_idempotency.expires_at <= now()`,
senderID, chatID, idempotencyKey, fingerprint[:], message.ID,
time.Time(message.CreatedAt), expiresAt)
if err != nil {
return model.Message{}, dbError(err)
}
if tag.RowsAffected() == 0 {
rollback(tx)
stored, found, lookupErr := s.findIdempotentMessage(ctx, senderID, chatID, idempotencyKey, fingerprint[:])
if lookupErr != nil {
return model.Message{}, lookupErr
}
if !found {
return model.Message{}, common.Internal()
}
return stored, nil
}
if err = tx.Commit(ctx); err != nil {
return model.Message{}, dbError(err)
}
return message, nil
}
func (s *Store) findIdempotentMessage(ctx context.Context, senderID, chatID uuid.UUID, idempotencyKey string, expectedHash []byte) (model.Message, bool, error) {
var message model.Message
var createdAt time.Time
var storedHash []byte
err := s.pool.QueryRow(ctx, `
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at, i.request_hash
FROM message_idempotency i
JOIN messages m ON m.id = i.message_id
JOIN chat_members cm ON cm.chat_id = i.chat_id AND cm.user_id = i.sender_id
WHERE i.sender_id = $1
AND i.chat_id = $2
AND i.idempotency_key = $3
AND i.expires_at > now()`,
senderID, chatID, idempotencyKey).Scan(
&message.ID, &message.ChatID, &message.SenderID, &message.Text, &createdAt, &storedHash)
if errors.Is(err, pgx.ErrNoRows) {
return model.Message{}, false, nil
}
if err != nil {
return model.Message{}, false, dbError(err)
}
if !bytes.Equal(storedHash, expectedHash) {
return model.Message{}, false, common.Conflict("idempotency key reused with a different message")
}
message.CreatedAt = common.RFCFormTime(createdAt.UTC())
return message, true, 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 {
@@ -56,8 +134,6 @@ func (s *Store) ListMessages(ctx context.Context, userID, chatID uuid.UUID, limi
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
+1 -1
View File
@@ -3,7 +3,7 @@ package store
import (
"time"
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/common"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
"github.com/google/uuid"
)
+5 -9
View File
@@ -2,10 +2,6 @@
// parameterized SQL, one bounded pool and explicit transaction boundaries.
// Contract errors are returned as common.AppError so HTTP status mapping stays
// in one place.
//
// AGENT: Persistence was split from one large file by aggregate (users, chats,
// messages). Queries, transaction boundaries and error mapping are unchanged;
// only file organization and scan helpers changed.
package store
import (
@@ -16,12 +12,13 @@ import (
)
type Store struct {
pool *pgxpool.Pool
timeout time.Duration
pool *pgxpool.Pool
timeout time.Duration
idempotencyTTL time.Duration
}
func New(pool *pgxpool.Pool, timeout time.Duration) *Store {
return &Store{pool: pool, timeout: timeout}
func New(pool *pgxpool.Pool, timeout, idempotencyTTL time.Duration) *Store {
return &Store{pool: pool, timeout: timeout, idempotencyTTL: idempotencyTTL}
}
func (s *Store) withTimeout(ctx context.Context) (context.Context, context.CancelFunc) {
@@ -34,7 +31,6 @@ func (s *Store) Ping(ctx context.Context) error {
return s.pool.Ping(pingCtx)
}
// rowScanner is the common subset of pgx.Row and pgx.Rows used by scan helpers.
type rowScanner interface {
Scan(dest ...any) error
}
+16
View File
@@ -0,0 +1,16 @@
package store
import (
"context"
"time"
"github.com/jackc/pgx/v5"
)
const rollbackTimeout = 5 * time.Second
func rollback(tx pgx.Tx) {
ctx, cancel := context.WithTimeout(context.Background(), rollbackTimeout)
defer cancel()
_ = tx.Rollback(ctx)
}
+2 -5
View File
@@ -5,8 +5,8 @@ import (
"errors"
"time"
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/common"
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/model"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/model"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
)
@@ -28,9 +28,6 @@ func (s *Store) CreateUser(ctx context.Context, username, displayName, passwordH
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")
}
+4 -3
View File
@@ -1,9 +1,10 @@
// Package users implements registration and the current-user endpoint.
package users
import (
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/auth"
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/common"
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/store"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/auth"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/common"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/store"
"github.com/gofiber/fiber/v3"
)
+1 -1
View File
@@ -1,7 +1,7 @@
package users
import (
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/store"
"gitflic.ru/project/bulla-max/mtusi2026lab/internal/store"
"github.com/gofiber/fiber/v3"
)