diff --git a/app/cmd/server/main.go b/app/cmd/server/main.go new file mode 100755 index 0000000..f8fcff5 --- /dev/null +++ b/app/cmd/server/main.go @@ -0,0 +1,61 @@ +package main + +import ( + "context" + "os" + "os/signal" + "syscall" + "time" + + "gitflic.ru/project/bulla-max/mtusi2026lab1/internal" + "github.com/gofiber/fiber/v3/log" +) + +func main() { + log.SetOutput(os.Stdout) + log.SetLevel(log.LevelDebug) + + app := internal.GetApp() + + host := os.Getenv("APP_HOST") + port := os.Getenv("APP_PORT") + + if port == "" { + port = "8080" + } + + if host == "" { + host = "0.0.0.0" + } + + addr := host + ":" + port + + go func() { + if err := app.Listen(addr); err != nil { + log.Fatalf("Server error: %v", err) + } + }() + + quit := make(chan os.Signal, 1) + signal.Notify(quit, syscall.SIGTERM) + <-quit + + ctx, cancel := context.WithTimeout( + context.Background(), 10*time.Second) + defer cancel() + + log.Info("Received SIGTERM, shutting down...") + internal.SignalGracefulShutdown() + + shutdownComplete := make(chan error, 1) + go func() { + shutdownComplete <- app.Shutdown() + }() + + select { + case err := <-shutdownComplete: + log.Errorf("Shutdown error: %v", err) + case <-ctx.Done(): + log.Info("Server stopped gracefully") + } +} diff --git a/app/go.mod b/app/go.mod new file mode 100755 index 0000000..b07fe5c --- /dev/null +++ b/app/go.mod @@ -0,0 +1,30 @@ +module gitflic.ru/project/bulla-max/mtusi2026lab1 + +go 1.27.1 + +require ( + github.com/gofiber/fiber/v3 v3.5.0 + github.com/google/uuid v1.6.0 +) + +require ( + github.com/go-playground/locales v0.14.1 // indirect + github.com/go-playground/universal-translator v0.18.2 // indirect + github.com/go-playground/validator v9.31.0+incompatible // indirect + github.com/gofiber/schema v1.8.8 // indirect + github.com/gofiber/utils/v2 v2.6.1 // indirect + github.com/klauspost/compress v1.20.1 // indirect + github.com/leodido/go-urn v1.5.0 // indirect + github.com/mattn/go-colorable v0.1.15 // indirect + github.com/mattn/go-isatty v0.0.24 // indirect + github.com/molecule-man/go-brrr v1.1.1 // indirect + github.com/philhofer/fwd v1.2.0 // indirect + github.com/tinylib/msgp v1.6.5 // indirect + github.com/valyala/bytebufferpool v1.0.0 // indirect + github.com/valyala/fasthttp v1.74.0 // indirect + golang.org/x/crypto v0.57.0 // indirect + golang.org/x/net v0.59.0 // indirect + golang.org/x/sys v0.48.0 // indirect + golang.org/x/text v0.42.0 // indirect + golang.org/x/tools v0.50.0 // indirect +) diff --git a/app/go.sum b/app/go.sum new file mode 100755 index 0000000..5b458dc --- /dev/null +++ b/app/go.sum @@ -0,0 +1,52 @@ +github.com/fxamacker/cbor/v2 v2.9.4 h1:xwjVlxEMR3S605oUlgBjKLTTeGFciYPGYCtF/35LKGo= +github.com/fxamacker/cbor/v2 v2.9.4/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ= +github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= +github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= +github.com/go-playground/universal-translator v0.18.2 h1:LCsMLC9RzmbUMNUPVYD15dmcjwYAJhmX8mPZRW4rAVU= +github.com/go-playground/universal-translator v0.18.2/go.mod h1:67VZIMp5lQpDWlnStOct22q1bkdJGJqHghbOtmkawxk= +github.com/go-playground/validator v9.31.0+incompatible h1:UA72EPEogEnq76ehGdEDp4Mit+3FDh548oRqwVgNsHA= +github.com/go-playground/validator v9.31.0+incompatible/go.mod h1:yrEkQXlcI+PugkyDjY2bRrL/UBU4f3rvrgkN3V8JEig= +github.com/gofiber/fiber/v3 v3.5.0 h1:dk7TOUH6DXJGtOLsN2XEG+0ZML7cznzHILTVozbNEK8= +github.com/gofiber/fiber/v3 v3.5.0/go.mod h1:GOVDTW+gjJvfe0iJyVujbQ1Lnx+JUjFySJRI/9/xX/w= +github.com/gofiber/schema v1.8.8 h1:md5t65+Z9LttOuj7FdMcQ63D2+6GniT2ganLXwvTJM4= +github.com/gofiber/schema v1.8.8/go.mod h1:Hzf0L/fTPP1IwOAwKipKflm9C2722aebnSKJCMOgb1I= +github.com/gofiber/utils/v2 v2.6.1 h1:x3zsS/oUQz0ia2Zx8XXtG/7naR5a+/95FRO8mwQ5QQ4= +github.com/gofiber/utils/v2 v2.6.1/go.mod h1:tc9KqdRAQZRD/u0mN2d1ZHROGheSZv+0FcC9cg5OEdw= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/klauspost/compress v1.20.1 h1:T7kKElXUMXrUJ2E9QhQhxFtcK5rPyLdsGZvdbLMPdiQ= +github.com/klauspost/compress v1.20.1/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= +github.com/leodido/go-urn v1.5.0 h1:pLqT2kq1zpHW/1D18QMjMpdtX7cekxqtJJjg5ANyWw0= +github.com/leodido/go-urn v1.5.0/go.mod h1:9BORnCDhdPBJNDEX+w1bJisa8yOKYi116VeO96s4ifE= +github.com/mattn/go-colorable v0.1.15 h1:+u9SLTRGnXv73cEsnsmoZBom+dMU88B2M0aDcWy0/jY= +github.com/mattn/go-colorable v0.1.15/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8= +github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI= +github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A= +github.com/molecule-man/go-brrr v1.1.1 h1:KYwusQhjtV3smALnhmafZf4OBrh7vP4p8O47DyUmmuY= +github.com/molecule-man/go-brrr v1.1.1/go.mod h1:7ybW6/7gA3oKY45jOfVNjSJDtrr6ea4tzbsTkjmQDC4= +github.com/philhofer/fwd v1.2.0 h1:e6DnBTl7vGY+Gz322/ASL4Gyp1FspeMvx1RNDoToZuM= +github.com/philhofer/fwd v1.2.0/go.mod h1:RqIHx9QI14HlwKwm98g9Re5prTQ6LdeRQn+gXJFxsJM= +github.com/shamaton/msgpack/v3 v3.2.3 h1:0r0aZtrXDFOPpwWJTEOpFq+Ih/JmMLm0pqLN5mSilrw= +github.com/shamaton/msgpack/v3 v3.2.3/go.mod h1:sgBYvEiyz8JR1NC3yGRoPVME9xXovpnh3l/plW1nfRo= +github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= +github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= +github.com/tinylib/msgp v1.6.5 h1:iAH6XTP7BpzErjBZlujJQXxA+GmRi2YWs6M4KdLtNbE= +github.com/tinylib/msgp v1.6.5/go.mod h1:RSp0LW9oSxFut3KzESt5Voq4GVWyS+PSulT77roAqEA= +github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= +github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= +github.com/valyala/fasthttp v1.74.0 h1:wMS9fnO2QTALozYx5pId2Vi7ZwU/epUkY8i/KPWCHoU= +github.com/valyala/fasthttp v1.74.0/go.mod h1:3ARmLamUcw7ElxVtC8PXaGzQ6VEuvnetlkrwIklQBSE= +github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM= +github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg= +go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= +go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= +golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M= +golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA= +golang.org/x/net v0.59.0 h1:5zfYln+w5XCxwrnMMJPufRgNoXEaGxl0wo5GqPXyues= +golang.org/x/net v0.59.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg= +golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo= +golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI= +golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E= +golang.org/x/tools v0.50.0 h1:c2ifzfcuY7L90lZ2aKd8S4K2NpASF08SZx9ZuJkHmSU= +golang.org/x/tools v0.50.0/go.mod h1:7ulVMw3831Mwi5EZD6RomGyffr4VFjuNYXf2BbCEAV0= diff --git a/app/internal/app.go b/app/internal/app.go new file mode 100755 index 0000000..7927e07 --- /dev/null +++ b/app/internal/app.go @@ -0,0 +1,82 @@ +package internal + +import ( + "errors" + + "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" + "github.com/gofiber/fiber/v3" + "github.com/gofiber/fiber/v3/middleware/recover" + "github.com/gofiber/fiber/v3/middleware/requestid" + "github.com/google/uuid" +) + +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") + } + + 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{ + ErrorHandler: func(c fiber.Ctx, err error) error { + if appErr, ok := errors.AsType[*common.AppError](err); ok { + return common.SendError(c, appErr.Status, appErr.Code, appErr.Message) + } + + if fiberErr, ok := errors.AsType[*fiber.Error](err); ok { + return common.SendError(c, fiberErr.Code, + common.ErrorCodeFromStatus(fiberErr.Code), fiberErr.Message) + } + + return common.SendError(c, fiber.StatusInternalServerError, + common.ErrorCodeInternal, "Internal server error") + }, + }) + + app.Use(recover.New()) + app.Use(requestid.New()) + + health.RegisterRoutes(app.Group("/health")) + + api := app.Group("/api/v1") + users.RegisterPublicRoutes(api) + + protected := api.Group("") + protected.Use(authMiddleware) + users.RegisterRoutes(protected) + chats.RegisterRoutes(protected) + messages.RegisterRoutes(protected) + + return app +} diff --git a/app/internal/chats/error.go b/app/internal/chats/error.go new file mode 100644 index 0000000..79c92c8 --- /dev/null +++ b/app/internal/chats/error.go @@ -0,0 +1,9 @@ +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") +) diff --git a/app/internal/chats/handler.go b/app/internal/chats/handler.go new file mode 100644 index 0000000..33a8b64 --- /dev/null +++ b/app/internal/chats/handler.go @@ -0,0 +1,106 @@ +package chats + +import ( + "gitflic.ru/project/bulla-max/mtusi2026lab1/internal/common" + "gitflic.ru/project/bulla-max/mtusi2026lab1/internal/storage" + "github.com/gofiber/fiber/v3" + "github.com/google/uuid" +) + +func createChat(c fiber.Ctx) error { + userID := c.Locals("userID").(uuid.UUID) + + var req CreateChatRequest + if err := common.BindJSON(c, &req); err != nil { + return common.SendAppError(c, err) + } + + 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 + }) + if err != nil { + return common.SendAppError(c, err) + } + + return c.Status(fiber.StatusCreated).JSON(chat) +} + +func listChats(c fiber.Ctx) error { + userID := c.Locals("userID").(uuid.UUID) + + limit, err := common.ParseLimit(c, 50) + if err != nil { + return common.SendAppError(c, err) + } + + cursor, err := common.ParseCursor(c) + if err != nil { + return common.SendAppError(c, err) + } + + if cursor != nil && userID != 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 { + found, fetchErr := tx.GetUserChats(userID, limit, cursor) + page = found + return fetchErr + }) + if err != nil { + return common.SendAppError(c, err) + } + + return c.JSON(page) +} + +func 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) + } + + 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 + }) + if err != nil { + return common.SendAppError(c, err) + } + + return c.JSON(chat) +} diff --git a/app/internal/chats/model.go b/app/internal/chats/model.go new file mode 100644 index 0000000..af53eb6 --- /dev/null +++ b/app/internal/chats/model.go @@ -0,0 +1,41 @@ +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 +} diff --git a/app/internal/chats/router.go b/app/internal/chats/router.go new file mode 100644 index 0000000..55b0092 --- /dev/null +++ b/app/internal/chats/router.go @@ -0,0 +1,9 @@ +package chats + +import "github.com/gofiber/fiber/v3" + +func RegisterRoutes(router fiber.Router) { + router.Post("/chats", createChat) + router.Get("/chats", listChats) + router.Get("/chats/:chat_id", getChat) +} diff --git a/app/internal/common/error.go b/app/internal/common/error.go new file mode 100644 index 0000000..c0909f4 --- /dev/null +++ b/app/internal/common/error.go @@ -0,0 +1,122 @@ +package common + +import ( + "errors" + + "github.com/gofiber/fiber/v3" +) + +const ( + ErrorCodeInvalidRequest = "invalid_request" + ErrorCodeUnauthorized = "unauthorized" + ErrorCodeNotFound = "not_found" + ErrorCodeConflict = "conflict" + ErrorCodePayloadTooLarge = "payload_too_large" + ErrorCodeUnsupportedMedia = "unsupported_media_type" + ErrorCodeRateLimited = "rate_limited" + ErrorCodeUnavailable = "unavailable" + ErrorCodeInternal = "internal_error" +) + +type APIErrorResponse struct { + Error APIError `json:"error"` +} + +type APIError struct { + Code string `json:"code"` + Message string `json:"message"` + RequestID string `json:"request_id"` +} + +func NewError(code, message, requestID string) APIErrorResponse { + return APIErrorResponse{ + Error: APIError{ + Code: code, + Message: message, + RequestID: requestID, + }, + } +} + +type AppError struct { + Status int + Code string + Message string +} + +func (e *AppError) Error() string { + return e.Message +} + +func NewAppError(status int, code, message string) *AppError { + return &AppError{ + Status: status, + Code: code, + Message: message, + } +} + +func BadRequest(message string) *AppError { + return NewAppError(fiber.StatusBadRequest, ErrorCodeInvalidRequest, message) +} + +func Unauthorized(message string) *AppError { + return NewAppError(fiber.StatusUnauthorized, ErrorCodeUnauthorized, message) +} + +func NotFound(message string) *AppError { + return NewAppError(fiber.StatusNotFound, ErrorCodeNotFound, message) +} + +func Conflict(message string) *AppError { + return NewAppError(fiber.StatusConflict, ErrorCodeConflict, message) +} + +func UnsupportedMedia(message string) *AppError { + return NewAppError(fiber.StatusUnsupportedMediaType, ErrorCodeUnsupportedMedia, message) +} + +func Internal() *AppError { + return NewAppError(fiber.StatusInternalServerError, ErrorCodeInternal, "Internal server error") +} + +func ErrorCodeFromStatus(status int) string { + switch status { + case fiber.StatusBadRequest: + return ErrorCodeInvalidRequest + case fiber.StatusUnauthorized: + return ErrorCodeUnauthorized + case fiber.StatusNotFound: + return ErrorCodeNotFound + case fiber.StatusConflict: + return ErrorCodeConflict + case fiber.StatusRequestEntityTooLarge: + return ErrorCodePayloadTooLarge + case fiber.StatusUnsupportedMediaType: + return ErrorCodeUnsupportedMedia + case fiber.StatusTooManyRequests: + return ErrorCodeRateLimited + case fiber.StatusServiceUnavailable: + return ErrorCodeUnavailable + default: + return ErrorCodeInternal + } +} + +func getRequestID(c fiber.Ctx) string { + return string(c.Response().Header.Peek("X-Request-Id")) +} + +func SendError(c fiber.Ctx, status int, code, message string) error { + return c.Status(status).JSON(NewError(code, message, getRequestID(c))) +} + +func SendAppError(c fiber.Ctx, err error) error { + var appErr *AppError + if errors.As(err, &appErr) { + return SendError(c, appErr.Status, appErr.Code, appErr.Message) + } + + return SendError(c, fiber.StatusInternalServerError, + ErrorCodeInternal, "Internal server error") +} diff --git a/app/internal/common/helpers.go b/app/internal/common/helpers.go new file mode 100644 index 0000000..8a53e09 --- /dev/null +++ b/app/internal/common/helpers.go @@ -0,0 +1,17 @@ +package common + +import ( + "encoding/json" + "time" +) + +type RFCFormTime time.Time + +func (t RFCFormTime) MarshalJSON() ([]byte, error) { + ftime := time.Time(t).UTC().Format(time.RFC3339) + return json.Marshal(ftime) +} + +func NowUTC() RFCFormTime { + return RFCFormTime(time.Now().UTC().Truncate(time.Second)) +} diff --git a/app/internal/common/paginator.go b/app/internal/common/paginator.go new file mode 100644 index 0000000..5f76a25 --- /dev/null +++ b/app/internal/common/paginator.go @@ -0,0 +1,198 @@ +package common + +import ( + "encoding/base64" + "sort" + "strings" + "time" + + "github.com/gofiber/fiber/v3" + "github.com/google/uuid" +) + +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 { + 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 + } + + return 0, BadRequest("limit param declared but empty") + } + + limit, ok := validateLimitStr(limitStr) + if !ok { + 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 + } + + return nil, BadRequest("cursor param declared but empty") + } + + cursor := DecodeCursor(cursorStr) + if cursor == nil { + 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() + return base64.RawURLEncoding.EncodeToString([]byte(raw)) +} + +func DecodeCursor(cursor string) *CursorKeyCtx { + data, err := base64.RawURLEncoding.DecodeString(cursor) + if err != nil { + return nil + } + + parts := strings.SplitN(string(data), "|", 3) + if len(parts) != 3 { + return nil + } + + parsedTime, err := time.Parse(time.RFC3339Nano, parts[0]) + if err != nil { + return nil + } + + parsedID, err := uuid.Parse(parts[1]) + if err != nil { + return nil + } + + parsedContextID, err := uuid.Parse(parts[2]) + if err != nil { + 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])) + }) +} diff --git a/app/internal/common/validator.go b/app/internal/common/validator.go new file mode 100644 index 0000000..957b641 --- /dev/null +++ b/app/internal/common/validator.go @@ -0,0 +1,139 @@ +package common + +import ( + "bytes" + "encoding/json" + "io" + "regexp" + "strconv" + "strings" + "unicode/utf8" + + "github.com/go-playground/validator" + "github.com/gofiber/fiber/v3" + "github.com/google/uuid" +) + +var ( + validate = validator.New() + usernameRegex = regexp.MustCompile(`^[a-z0-9_]{3,32}$`) +) + +func BindJSON(c fiber.Ctx, req any) error { + contentType := c.Get(fiber.HeaderContentType) + if !strings.HasPrefix(contentType, "application/json") { + return UnsupportedMedia("invalid JSON body") + } + + body := c.Body() + if len(body) == 0 { + return BadRequest("request body is empty") + } + + decoder := json.NewDecoder(bytes.NewReader(body)) + decoder.DisallowUnknownFields() + + if err := decoder.Decode(req); err != nil { + return BadRequest(err.Error()) + } + + var extra json.RawMessage + if err := decoder.Decode(&extra); err != io.EOF { + return BadRequest("request body has extra trailing bytes") + } + + if err := validate.Struct(req); err != nil { + return BadRequest("field validation failed: " + err.Error()) + } + + return nil +} + +func blank(s string) bool { + return strings.TrimSpace(s) == "" +} + +func strLenBetween(s string, min, max int) bool { + n := utf8.RuneCountInString(s) + return n >= min && n <= max +} + +func ValidateCreateUser(username, displayName string) string { + if !usernameRegex.MatchString(username) { + return "username must match ^[a-z0-9_]{3,32}$" + } + + if blank(displayName) { + return "display_name must not be empty or only whitespace" + } + + if !strLenBetween(displayName, 1, 100) { + return "display_name must be between 1 and 100 Unicode code points" + } + + return "" +} + +func ValidateChatTitle(title string) string { + if blank(title) { + return "title must not be empty or only whitespace" + } + + if !strLenBetween(title, 1, 100) { + return "title must be between 1 and 100 Unicode code points" + } + + return "" +} + +func ValidateMessageText(text string) string { + if blank(text) { + return "text must not be empty or only whitespace" + } + + if !strLenBetween(text, 1, 4000) { + return "text must be between 1 and 4000 Unicode code points" + } + + return "" +} + +func validateLimitStr(s string) (int, bool) { + n, err := strconv.Atoi(s) + if err != nil { + return 0, false + } + + if n < 1 || n > 100 { + return 0, false + } + + return n, true +} + +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" + } + + seen := make(map[uuid.UUID]bool, len(ids)) + callerFound := false + + for _, id := range ids { + if seen[id] { + return "member_ids must not contain duplicates" + } + + seen[id] = true + + if id == callerID { + callerFound = true + } + } + + if !callerFound { + return "caller must be included in member_ids" + } + + return "" +} diff --git a/app/internal/health/handler.go b/app/internal/health/handler.go new file mode 100644 index 0000000..4b1dc3d --- /dev/null +++ b/app/internal/health/handler.go @@ -0,0 +1,27 @@ +package health + +import ( + "sync/atomic" + + "gitflic.ru/project/bulla-max/mtusi2026lab1/internal/common" + "github.com/gofiber/fiber/v3" +) + +var shuttingDown atomic.Bool + +func SignalShutdown() { + shuttingDown.Store(true) +} + +func live(c fiber.Ctx) error { + return c.JSON(fiber.Map{"status": "ok"}) +} + +func ready(c fiber.Ctx) error { + if shuttingDown.Load() { + return common.SendError(c, fiber.StatusInternalServerError, + common.ErrorCodeInternal, "app currently shutting down") + } + + return c.JSON(fiber.Map{"status": "ok"}) +} diff --git a/app/internal/health/router.go b/app/internal/health/router.go new file mode 100644 index 0000000..af54c6d --- /dev/null +++ b/app/internal/health/router.go @@ -0,0 +1,8 @@ +package health + +import "github.com/gofiber/fiber/v3" + +func RegisterRoutes(router fiber.Router) { + router.Get("/live", live) + router.Get("/ready", ready) +} diff --git a/app/internal/messages/error.go b/app/internal/messages/error.go new file mode 100644 index 0000000..1456998 --- /dev/null +++ b/app/internal/messages/error.go @@ -0,0 +1,8 @@ +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") +) diff --git a/app/internal/messages/handler.go b/app/internal/messages/handler.go new file mode 100644 index 0000000..5e127d7 --- /dev/null +++ b/app/internal/messages/handler.go @@ -0,0 +1,84 @@ +package messages + +import ( + "gitflic.ru/project/bulla-max/mtusi2026lab1/internal/common" + "gitflic.ru/project/bulla-max/mtusi2026lab1/internal/storage" + "github.com/gofiber/fiber/v3" + "github.com/google/uuid" +) + +func 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) + } + + 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 + }) + if err != nil { + return common.SendAppError(c, err) + } + + return c.Status(fiber.StatusCreated).JSON(message) +} + +func 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) + } + + limit, err := common.ParseLimit(c, 50) + if err != nil { + return common.SendAppError(c, err) + } + + cursor, err := common.ParseCursor(c) + if err != nil { + 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 + }) + if err != nil { + return common.SendAppError(c, err) + } + + return c.JSON(page) +} diff --git a/app/internal/messages/model.go b/app/internal/messages/model.go new file mode 100644 index 0000000..a6f3779 --- /dev/null +++ b/app/internal/messages/model.go @@ -0,0 +1,42 @@ +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 +} diff --git a/app/internal/messages/router.go b/app/internal/messages/router.go new file mode 100644 index 0000000..9aee1a7 --- /dev/null +++ b/app/internal/messages/router.go @@ -0,0 +1,8 @@ +package messages + +import "github.com/gofiber/fiber/v3" + +func RegisterRoutes(router fiber.Router) { + router.Post("/chats/:chat_id/messages", createMessage) + router.Get("/chats/:chat_id/messages", listMessages) +} diff --git a/app/internal/storage/store.go b/app/internal/storage/store.go new file mode 100644 index 0000000..e0328ef --- /dev/null +++ b/app/internal/storage/store.go @@ -0,0 +1,145 @@ +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) +} diff --git a/app/internal/users/handler.go b/app/internal/users/handler.go new file mode 100644 index 0000000..dd10421 --- /dev/null +++ b/app/internal/users/handler.go @@ -0,0 +1,57 @@ +package users + +import ( + "gitflic.ru/project/bulla-max/mtusi2026lab1/internal/common" + "gitflic.ru/project/bulla-max/mtusi2026lab1/internal/storage" + "github.com/gofiber/fiber/v3" + "github.com/google/uuid" +) + +func createUser(c fiber.Ctx) error { + var req CreateUserRequest + if err := common.BindJSON(c, &req); err != nil { + return common.SendAppError(c, err) + } + + if msg := common.ValidateCreateUser(req.Username, req.DisplayName); msg != "" { + return common.SendError(c, fiber.StatusBadRequest, common.ErrorCodeInvalidRequest, msg) + } + + var user User + + 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 + }) + if err != nil { + return common.SendAppError(c, err) + } + + return c.Status(fiber.StatusCreated).JSON(user) +} + +func getCurrentUser(c fiber.Ctx) error { + userID := c.Locals("userID").(uuid.UUID) + + 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 + }) + if err != nil { + return common.SendAppError(c, err) + } + + return c.JSON(user) +} diff --git a/app/internal/users/model.go b/app/internal/users/model.go new file mode 100644 index 0000000..d26c0b3 --- /dev/null +++ b/app/internal/users/model.go @@ -0,0 +1,41 @@ +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 +} diff --git a/app/internal/users/router.go b/app/internal/users/router.go new file mode 100644 index 0000000..547438f --- /dev/null +++ b/app/internal/users/router.go @@ -0,0 +1,11 @@ +package users + +import "github.com/gofiber/fiber/v3" + +func RegisterPublicRoutes(router fiber.Router) { + router.Post("/users", createUser) +} + +func RegisterRoutes(router fiber.Router) { + router.Get("/users/me", getCurrentUser) +}