Начало реализации сервиса.

This commit is contained in:
Grbisba
2026-10-30 12:25:56 +03:00
parent 65003b6119
commit 20f2f00a60
52 changed files with 4351 additions and 1 deletions
@@ -0,0 +1,164 @@
package http
import (
"net/http"
"github.com/google/uuid"
inmemory2 "gitea.privcloud.tech/mtusi2026/internal/adapter/repository/cache/inmemory"
"gitea.privcloud.tech/mtusi2026/internal/dto"
"gitea.privcloud.tech/mtusi2026/internal/gen/contracts"
)
type ChatHandler struct {
*BaseHandler
users inmemory2.UserCache
chats inmemory2.ChatCache
messages inmemory2.MessageCache
}
func NewChatHandler(base *BaseHandler, users inmemory2.UserCache, chats inmemory2.ChatCache, messages inmemory2.MessageCache) Handler {
return &ChatHandler{BaseHandler: base, users: users, chats: chats, messages: messages}
}
func (h *ChatHandler) RegisterRoutes() {
h.router.Post("/api/v1/chats", h.Create)
h.router.Get("/api/v1/chats", h.Get)
h.router.Get("/api/v1/chats/{chat_id}", h.GetByID)
h.router.Post("/api/v1/chats/{chat_id}/messages", h.SendMessage)
h.router.Get("/api/v1/chats/{chat_id}/messages", h.GetMessages)
}
func (h *ChatHandler) Create(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
user, ok := h.authenticatedUser(w, r, h.users)
if !ok {
return
}
var req contracts.CreateChat
if !h.Decode(w, r, &req) || !h.Validate(w, r, &req) {
return
}
chat, err := h.chats.Create(ctx, dto.CreateChat{
CreatorID: user.ID,
Title: req.Title,
MemberIDs: req.MemberIds,
})
if err != nil {
h.JSONError(ctx, w, err)
return
}
h.JSONResponse(w, http.StatusCreated, contractChat(chat))
}
func (h *ChatHandler) Get(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
user, ok := h.authenticatedUser(w, r, h.users)
if !ok {
return
}
limit, afterID, ok := h.pageParams(w, r)
if !ok {
return
}
page, err := h.chats.ListForMember(ctx, user.ID, limit, afterID)
if err != nil {
h.JSONError(ctx, w, err)
return
}
items := make([]contracts.Chat, 0, len(page.Items))
for _, chat := range page.Items {
items = append(items, contractChat(chat))
}
h.JSONResponse(w, http.StatusOK, contracts.ChatPage{Items: items, NextCursor: cursorString(page.NextCursorID)})
}
func (h *ChatHandler) GetByID(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
user, ok := h.authenticatedUser(w, r, h.users)
if !ok {
return
}
chatID, err := h.ParseIDFromPathParam(ctx, w, r, "chat_id")
if err != nil {
return
}
chat, err := h.chats.GetForMember(ctx, chatID, user.ID)
if err != nil {
h.JSONError(ctx, w, err)
return
}
h.JSONResponse(w, http.StatusOK, contractChat(chat))
}
func (h *ChatHandler) SendMessage(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
user, ok := h.authenticatedUser(w, r, h.users)
if !ok {
return
}
chatID, err := h.ParseIDFromPathParam(ctx, w, r, "chat_id")
if err != nil {
return
}
if _, err := h.chats.GetForMember(ctx, chatID, user.ID); err != nil {
h.JSONError(ctx, w, err)
return
}
var req contracts.CreateMessage
if !h.Decode(w, r, &req) || !h.Validate(w, r, &req) {
return
}
message, err := h.messages.Create(ctx, dto.CreateMessage{ChatID: chatID, SenderID: user.ID, Text: req.Text})
if err != nil {
h.JSONError(ctx, w, err)
return
}
h.JSONResponse(w, http.StatusCreated, contractMessage(message))
}
func (h *ChatHandler) GetMessages(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
user, ok := h.authenticatedUser(w, r, h.users)
if !ok {
return
}
chatID, err := h.ParseIDFromPathParam(ctx, w, r, "chat_id")
if err != nil {
return
}
if _, err := h.chats.GetForMember(ctx, chatID, user.ID); err != nil {
h.JSONError(ctx, w, err)
return
}
limit, afterID, ok := h.pageParams(w, r)
if !ok {
return
}
page, err := h.messages.ListForChat(ctx, chatID, user.ID, limit, afterID)
if err != nil {
h.JSONError(ctx, w, err)
return
}
items := make([]contracts.Message, 0, len(page.Items))
for _, message := range page.Items {
items = append(items, contractMessage(message))
}
h.JSONResponse(w, http.StatusOK, contracts.MessagePage{Items: items, NextCursor: cursorString(page.NextCursorID)})
}
func contractChat(chat dto.Chat) contracts.Chat {
return contracts.Chat{Id: chat.ID, Title: chat.Title, MemberIds: chat.MemberIDs, CreatedAt: chat.CreatedAt}
}
func contractMessage(message dto.Message) contracts.Message {
return contracts.Message{Id: message.ID, ChatId: message.ChatID, SenderId: message.SenderID, Text: message.Text, CreatedAt: message.CreatedAt}
}
func cursorString(id *uuid.UUID) *string {
if id == nil {
return nil
}
value := id.String()
return &value
}
@@ -0,0 +1,102 @@
package http
import (
"context"
"errors"
"log/slog"
"net"
"net/http"
"sync/atomic"
"github.com/go-chi/chi/v5"
"gitea.privcloud.tech/mtusi2026/internal/config"
)
type Server interface {
ShouldBeRunning() bool
Ready() bool
Start(ctx context.Context) error
Stop(ctx context.Context) error
}
type server struct {
server http.Server
cfg *config.Server
ready atomic.Bool
}
func New(cfg *config.Server, router chi.Router) Server {
s := server{
server: http.Server{
Addr: cfg.BindAddress(),
Handler: router,
ReadTimeout: cfg.ReadTimeout,
WriteTimeout: cfg.WriteTimeout,
IdleTimeout: cfg.IdleTimeout,
},
cfg: cfg,
ready: atomic.Bool{},
}
if err := s.validate(); err != nil {
panic(err)
}
return &s
}
func (s *server) Start(_ context.Context) error {
if !s.ShouldBeRunning() {
slog.Info("server should not be running: skip starting")
return nil
}
listener, err := net.Listen("tcp", s.server.Addr)
if err != nil {
return err
}
s.ready.Store(true)
go func() {
defer s.ready.Store(false)
if err := s.server.Serve(listener); err != nil &&
!errors.Is(err, http.ErrServerClosed) {
slog.Error("rest server failed", "error", err)
}
}()
return nil
}
func (s *server) Stop(ctx context.Context) error {
if !s.ShouldBeRunning() {
slog.Info("server should not be running: skip stopping")
return nil
}
slog.Info("shutting down rest server...", "address", s.server.Addr)
s.ready.Store(false)
if err := s.server.Shutdown(ctx); err != nil {
slog.Error("rest server shutdown failed", "error", err)
return err
}
slog.Info("rest server shutdown successfully")
return nil
}
func (s *server) ShouldBeRunning() bool {
return s.cfg.Enabled
}
func (s *server) Ready() bool {
return s.ready.Load()
}
func (s *server) validate() error {
if s.cfg == nil {
slog.Error("failed to validate server: provided nil config")
return errors.New("failed to validate server: provided nil config")
}
slog.Info("server successfully validated")
return nil
}
@@ -0,0 +1,220 @@
package http
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"mime"
"net/http"
"strconv"
"strings"
"github.com/go-chi/chi/v5"
v10 "github.com/go-playground/validator/v10"
"github.com/google/uuid"
"gitea.privcloud.tech/mtusi2026/internal/adapter/repository/cache/inmemory"
"gitea.privcloud.tech/mtusi2026/internal/dto"
"gitea.privcloud.tech/mtusi2026/internal/gen/contracts"
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
"gitea.privcloud.tech/mtusi2026/internal/pkg/validator"
)
const (
HeaderContentType = "Content-Type"
HeaderRequestID = "X-Request-Id"
HeaderUserID = "X-User-Id"
)
type Handler interface {
RegisterRoutes()
}
type BaseHandler struct {
router chi.Router
validator *validator.ValidatorImpl
}
func NewBaseHandler(r chi.Router) *BaseHandler {
return &BaseHandler{
router: r,
validator: validator.NewValidatorImpl(),
}
}
func (h *BaseHandler) validate(ctx context.Context, value any) error {
err := h.validator.ValidateCtx(ctx, value)
if err == nil {
return nil
}
var fieldErrors v10.ValidationErrors
if errors.As(err, &fieldErrors) {
return apperr.Wrap(err, apperr.CodeInvalidRequest, "invalid request fields")
}
return apperr.Wrap(err, apperr.CodeInternalError, "validation failed")
}
func (h *BaseHandler) Validate(w http.ResponseWriter, r *http.Request, value any) bool {
if err := h.validate(r.Context(), value); err != nil {
h.JSONError(r.Context(), w, err)
return false
}
return true
}
func (h *BaseHandler) JSONResponse(w http.ResponseWriter, status int, body any) {
w.Header().Set(HeaderContentType, "application/json")
w.WriteHeader(status)
if status == http.StatusNoContent {
return
}
if err := json.NewEncoder(w).Encode(body); err != nil {
wrapped := apperr.Wrap(err, apperr.CodeInternal, "failed json encode")
slog.Error("response", "error", wrapped)
}
}
func (h *BaseHandler) JSONError(ctx context.Context, w http.ResponseWriter, err error) {
if err == nil {
return
}
requestId, ok := ctx.Value(HeaderRequestID).(uuid.UUID)
if !ok {
requestId = uuid.New()
}
w.Header().Set(HeaderRequestID, requestId.String())
appErr, ok := apperr.As(err)
if !ok {
appErr = apperr.New(apperr.CodeInternalError, "internal server error")
}
slog.Error("response", "error", err, "status", appErr.Code().HTTPStatus(), "requestId", requestId.String())
h.JSONResponse(w, appErr.Code().HTTPStatus(), contracts.Error{
Error: struct {
Code contracts.ErrorErrorCode `json:"code"`
Message string `json:"message"`
RequestId string `json:"request_id"`
}{
Code: contracts.ErrorErrorCode(appErr.Code()),
Message: apperr.PublicMessage(appErr),
RequestId: requestId.String(),
},
})
}
func (h *BaseHandler) Decode(w http.ResponseWriter, r *http.Request, object any) bool {
mediaType, params, err := mime.ParseMediaType(r.Header.Get(HeaderContentType))
if err != nil || mediaType != "application/json" ||
(params["charset"] != "" && !strings.EqualFold(params["charset"], "utf-8")) {
h.JSONError(r.Context(), w, apperr.New(apperr.CodeUnsupportedMediaType, "expected application/json"))
return false
}
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
if err := decoder.Decode(object); err != nil {
h.JSONError(r.Context(), w, apperr.Wrap(err, apperr.CodeBadRequest, "failed decode"))
return false
}
var trailing any
if err := decoder.Decode(&trailing); err != io.EOF {
h.JSONError(r.Context(), w, apperr.New(apperr.CodeBadRequest, "expected one JSON object"))
return false
}
return true
}
func (h *BaseHandler) PathParam(r *http.Request, key string) string {
return chi.URLParam(r, key)
}
func (h *BaseHandler) QueryParam(r *http.Request, key string) string {
return r.URL.Query().Get(key)
}
func (h *BaseHandler) HeaderParam(r *http.Request, key string) string {
return r.Header.Get(key)
}
func (h *BaseHandler) ParseIDFromPathParam(ctx context.Context, w http.ResponseWriter, r *http.Request, key string) (uuid.UUID, error) {
rawID := h.PathParam(r, key)
id, err := uuid.Parse(rawID)
if err != nil {
h.JSONError(ctx, w, apperr.New(apperr.CodeValidation, fmt.Sprintf("provided invalid %s", key)))
return uuid.Nil, err
}
return id, nil
}
func (h *BaseHandler) ParseIDFromQueryParam(ctx context.Context, w http.ResponseWriter, r *http.Request, key string) (uuid.UUID, error) {
rawID := h.QueryParam(r, key)
id, err := uuid.Parse(rawID)
if err != nil {
h.JSONError(ctx, w, apperr.New(apperr.CodeValidation, fmt.Sprintf("provided invalid %s", key)))
return uuid.Nil, err
}
return id, nil
}
func (h *BaseHandler) ParseIDFromHeaderParam(ctx context.Context, w http.ResponseWriter, r *http.Request, key string) (uuid.UUID, error) {
rawID := h.HeaderParam(r, key)
id, err := uuid.Parse(rawID)
if err != nil {
h.JSONError(ctx, w, apperr.New(apperr.CodeUnauthorized, "missing or invalid user ID"))
return uuid.Nil, err
}
return id, nil
}
func (h *BaseHandler) authenticatedUser(w http.ResponseWriter, r *http.Request, users inmemory.UserCache) (dto.User, bool) {
id, err := h.ParseIDFromHeaderParam(r.Context(), w, r, HeaderUserID)
if err != nil {
return dto.User{}, false
}
user, err := users.GetByID(r.Context(), id)
if err != nil {
if appErr, ok := apperr.As(err); ok && appErr.Code() == apperr.CodeNotFound {
h.JSONError(r.Context(), w, apperr.New(apperr.CodeUnauthorized, "unknown user ID"))
} else {
h.JSONError(r.Context(), w, err)
}
return dto.User{}, false
}
return user, true
}
func (h *BaseHandler) pageParams(w http.ResponseWriter, r *http.Request) (*int, *uuid.UUID, bool) {
query := r.URL.Query()
var limit *int
if values, exists := query["limit"]; exists {
if len(values) != 1 {
h.JSONError(r.Context(), w, apperr.New(apperr.CodeInvalidRequest, "invalid limit"))
return nil, nil, false
}
value, err := strconv.Atoi(values[0])
if err != nil || value < 1 || value > 100 {
h.JSONError(r.Context(), w, apperr.New(apperr.CodeInvalidRequest, "invalid limit"))
return nil, nil, false
}
limit = &value
}
var afterID *uuid.UUID
if values, exists := query["cursor"]; exists {
if len(values) != 1 {
h.JSONError(r.Context(), w, apperr.New(apperr.CodeInvalidRequest, "invalid cursor"))
return nil, nil, false
}
id, err := uuid.Parse(values[0])
if err != nil || id == uuid.Nil {
h.JSONError(r.Context(), w, apperr.New(apperr.CodeInvalidRequest, "invalid cursor"))
return nil, nil, false
}
afterID = &id
}
return limit, afterID, true
}
@@ -0,0 +1,37 @@
package http
import (
"net/http"
"gitea.privcloud.tech/mtusi2026/internal/gen/contracts"
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
)
type HealthHandler struct {
*BaseHandler
server Server
}
func NewHealthHandler(base *BaseHandler, server Server) Handler {
return &HealthHandler{
BaseHandler: base,
server: server,
}
}
func (h *HealthHandler) RegisterRoutes() {
h.router.Get("/health/ready", h.Ready)
h.router.Get("/health/live", h.Live)
}
func (h *HealthHandler) Live(w http.ResponseWriter, _ *http.Request) {
h.JSONResponse(w, http.StatusOK, contracts.Health{Status: contracts.Ok})
}
func (h *HealthHandler) Ready(w http.ResponseWriter, r *http.Request) {
if !h.server.Ready() {
h.JSONError(r.Context(), w, apperr.New(apperr.CodeUnavailable, "server is not ready"))
return
}
h.JSONResponse(w, http.StatusOK, contracts.Health{Status: contracts.Ok})
}
@@ -0,0 +1,50 @@
package http
import (
"context"
"log/slog"
"net/http"
"time"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/google/uuid"
)
func NewRouter() chi.Router {
r := chi.NewRouter()
r.Use(requestIdMiddleware, loggingMiddleware)
return r
}
func requestIdMiddleware(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
requestID := uuid.New()
w.Header().Set(HeaderRequestID, requestID.String())
ctx = context.WithValue(ctx, HeaderRequestID, requestID)
next.ServeHTTP(w, r.WithContext(ctx))
}
return http.HandlerFunc(fn)
}
func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
started := time.Now()
wrapped := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
next.ServeHTTP(wrapped, r)
status := wrapped.Status()
if status == 0 {
status = http.StatusOK
}
slog.InfoContext(r.Context(), "http request",
"method", r.Method,
"path", r.URL.Path,
"status", status,
"duration", time.Since(started),
"bytes", wrapped.BytesWritten(),
"request_id", w.Header().Get(HeaderRequestID),
)
})
}
@@ -0,0 +1,66 @@
package http
import (
"net/http"
"gitea.privcloud.tech/mtusi2026/internal/adapter/repository/cache/inmemory"
"gitea.privcloud.tech/mtusi2026/internal/dto"
"gitea.privcloud.tech/mtusi2026/internal/gen/contracts"
)
type UserHandler struct {
*BaseHandler
users inmemory.UserCache
}
func NewUserHandler(base *BaseHandler, users inmemory.UserCache) Handler {
return &UserHandler{
BaseHandler: base,
users: users,
}
}
func (h *UserHandler) RegisterRoutes() {
h.router.Post("/api/v1/users", h.Create)
h.router.Get("/api/v1/users/me", h.GetMe)
}
func (h *UserHandler) Create(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
var req contracts.CreateUser
if !h.Decode(w, r, &req) || !h.Validate(w, r, &req) {
return
}
user, err := h.users.Create(ctx, dto.CreateUser{
Username: req.Username,
DisplayName: req.DisplayName,
})
if err != nil {
h.JSONError(ctx, w, err)
return
}
h.JSONResponse(w, http.StatusCreated, contracts.User{
CreatedAt: user.CreatedAt,
DisplayName: user.DisplayName,
Id: user.ID,
Username: user.Username,
})
}
func (h *UserHandler) GetMe(w http.ResponseWriter, r *http.Request) {
user, ok := h.authenticatedUser(w, r, h.users)
if !ok {
return
}
h.JSONResponse(w, http.StatusOK, contracts.User{
CreatedAt: user.CreatedAt,
DisplayName: user.DisplayName,
Id: user.ID,
Username: user.Username,
})
}