This commit is contained in:
Quzzqq
2026-10-23 16:31:42 +03:00
parent 65003b6119
commit cbb92b7aef
36 changed files with 3268 additions and 23 deletions
+253
View File
@@ -0,0 +1,253 @@
package httpapi
import (
"errors"
"net/http"
"strings"
"mtusi.local/messenger/internal/authpw"
"mtusi.local/messenger/internal/model"
)
func (a *API) createUser(w http.ResponseWriter, r *http.Request) {
var body struct {
Username string `json:"username"`
DisplayName string `json:"display_name"`
Password string `json:"password"`
}
if err := readJSON(w, r, &body); err != nil {
a.writeReadError(w, r, err)
return
}
if !model.ValidUsername(body.Username) || !model.ValidLabel(body.DisplayName, 100) || !model.ValidPassword(body.Password) {
writeError(w, http.StatusBadRequest, "invalid_request", "Недопустимое имя или отображаемое имя", requestID(r))
return
}
hash, err := authpw.Hash(body.Password)
if err != nil {
writeError(w, http.StatusInternalServerError, "internal_error", "Внутренняя ошибка", requestID(r))
return
}
user, err := a.db.CreateUser(r.Context(), body.Username, body.DisplayName, hash)
if err != nil {
writeStoreError(w, r, err, "Недопустимое имя или отображаемое имя")
return
}
writeJSON(w, http.StatusCreated, userToJSON(user))
}
func (a *API) createSession(w http.ResponseWriter, r *http.Request) {
if !bodyEmpty(r) {
writeError(w, http.StatusBadRequest, "invalid_request", "Неверный JSON", requestID(r))
return
}
username, password, ok := basicCredentials(r)
if !ok {
writeUnauthorized(w, r, true)
return
}
user, hash, err := a.db.UserByUsername(r.Context(), username)
if errors.Is(err, model.ErrUnavailable) {
writeStoreError(w, r, err, "")
return
}
if err != nil {
user = model.User{}
hash = ""
}
if !model.ValidPassword(password) || !a.checkPassword(password, hash) || user.ID == "" {
writeUnauthorized(w, r, true)
return
}
token, expires, err := a.session.Create(r.Context(), user.ID)
if err != nil {
writeStoreError(w, r, err, "")
return
}
writeJSON(w, http.StatusCreated, sessionJSON{
Token: token,
TokenType: "Bearer",
ExpiresAt: apiTime(expires),
User: userToJSON(user),
})
}
func (a *API) revokeSession(w http.ResponseWriter, r *http.Request) {
token, ok := bearerToken(r)
if !ok {
writeUnauthorized(w, r, false)
return
}
if _, err := a.session.Lookup(r.Context(), token); err != nil {
if errors.Is(err, model.ErrUnavailable) {
writeStoreError(w, r, err, "")
return
}
writeUnauthorized(w, r, false)
return
}
if err := a.session.Revoke(r.Context(), token); err != nil {
writeStoreError(w, r, err, "")
return
}
w.WriteHeader(http.StatusNoContent)
}
func (a *API) currentUser(w http.ResponseWriter, r *http.Request) {
user, ok := a.requireUser(w, r)
if !ok {
return
}
writeJSON(w, http.StatusOK, userToJSON(user))
}
func (a *API) createChat(w http.ResponseWriter, r *http.Request) {
user, ok := a.requireUser(w, r)
if !ok {
return
}
var body struct {
Title string `json:"title"`
MemberIDs []string `json:"member_ids"`
}
if err := readJSON(w, r, &body); err != nil {
a.writeReadError(w, r, err)
return
}
chat, err := a.db.CreateChat(r.Context(), user.ID, body.Title, body.MemberIDs)
if err != nil {
writeStoreError(w, r, err, "Неверный список участников или название чата")
return
}
writeJSON(w, http.StatusCreated, chatToJSON(chat))
}
func (a *API) listChats(w http.ResponseWriter, r *http.Request) {
user, ok := a.requireUser(w, r)
if !ok {
return
}
limit, cursor, ok := a.pageQuery(w, r)
if !ok {
return
}
if cursor != nil && cursor.Resource != model.ResourceChats {
writeError(w, http.StatusBadRequest, "invalid_request", "Неверный cursor или limit", requestID(r))
return
}
items, next, err := a.db.ListChats(r.Context(), user.ID, limit, cursor)
if err != nil {
writeStoreError(w, r, err, "Неверный cursor или limit")
return
}
page := chatPageJSON{Items: make([]chatJSON, 0, len(items)), NextCursor: next}
for _, item := range items {
page.Items = append(page.Items, chatToJSON(item))
}
writeJSON(w, http.StatusOK, page)
}
func (a *API) getChat(w http.ResponseWriter, r *http.Request) {
user, ok := a.requireUser(w, r)
if !ok {
return
}
chatID, ok := pathChatID(w, r)
if !ok {
return
}
chat, err := a.db.Chat(r.Context(), chatID, user.ID)
if err != nil {
writeStoreError(w, r, err, "Неверный идентификатор чата")
return
}
writeJSON(w, http.StatusOK, chatToJSON(chat))
}
func (a *API) createMessage(w http.ResponseWriter, r *http.Request) {
user, ok := a.requireUser(w, r)
if !ok {
return
}
chatID, ok := pathChatID(w, r)
if !ok {
return
}
if _, err := a.db.Chat(r.Context(), chatID, user.ID); err != nil {
writeStoreError(w, r, err, "Неверный идентификатор чата")
return
}
var body struct {
Text string `json:"text"`
}
if err := readJSON(w, r, &body); err != nil {
a.writeReadError(w, r, err)
return
}
msg, err := a.db.AddMessage(r.Context(), chatID, user.ID, body.Text)
if err != nil {
writeStoreError(w, r, err, "Недопустимый текст сообщения")
return
}
writeJSON(w, http.StatusCreated, messageToJSON(msg))
}
func (a *API) listMessages(w http.ResponseWriter, r *http.Request) {
user, ok := a.requireUser(w, r)
if !ok {
return
}
chatID, ok := pathChatID(w, r)
if !ok {
return
}
limit, cursor, ok := a.pageQuery(w, r)
if !ok {
return
}
if cursor != nil && (cursor.Resource != model.ResourceMessages || cursor.ChatID != chatID) {
writeError(w, http.StatusBadRequest, "invalid_request", "Неверный cursor или limit", requestID(r))
return
}
items, next, err := a.db.ListMessages(r.Context(), chatID, user.ID, limit, cursor)
if err != nil {
writeStoreError(w, r, err, "Неверный cursor или limit")
return
}
page := messagePageJSON{Items: make([]messageJSON, 0, len(items)), NextCursor: next}
for _, item := range items {
page.Items = append(page.Items, messageToJSON(item))
}
writeJSON(w, http.StatusOK, page)
}
func (a *API) pageQuery(w http.ResponseWriter, r *http.Request) (int, *model.Cursor, bool) {
limit, err := parseLimit(r)
if err != nil {
writeError(w, http.StatusBadRequest, "invalid_request", "Неверный cursor или limit", requestID(r))
return 0, nil, false
}
cursor, err := parseCursor(r)
if err != nil {
writeError(w, http.StatusBadRequest, "invalid_request", "Неверный cursor или limit", requestID(r))
return 0, nil, false
}
return limit, cursor, true
}
func (a *API) writeReadError(w http.ResponseWriter, r *http.Request, err error) {
if errors.Is(err, errTooLarge) {
writeError(w, http.StatusRequestEntityTooLarge, "payload_too_large", "Слишком большой запрос", requestID(r))
return
}
writeError(w, http.StatusBadRequest, "invalid_request", "Неверный JSON", requestID(r))
}
func pathChatID(w http.ResponseWriter, r *http.Request) (string, bool) {
chatID := strings.ToLower(r.PathValue("chat_id"))
if !model.ValidUUID(chatID) {
writeError(w, http.StatusBadRequest, "invalid_request", "Неверный идентификатор чата", requestID(r))
return "", false
}
return chatID, true
}
+186
View File
@@ -0,0 +1,186 @@
package httpapi
import (
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"io"
"mime"
"net/http"
"time"
"mtusi.local/messenger/internal/jsonstrict"
"mtusi.local/messenger/internal/model"
)
type statusWriter struct {
http.ResponseWriter
status int
wrote bool
}
func (w *statusWriter) WriteHeader(status int) {
if w.wrote {
return
}
w.status = status
w.wrote = true
w.ResponseWriter.WriteHeader(status)
}
func (w *statusWriter) Write(body []byte) (int, error) {
if !w.wrote {
w.status = http.StatusOK
w.wrote = true
}
return w.ResponseWriter.Write(body)
}
type apiTime time.Time
func (t apiTime) MarshalJSON() ([]byte, error) {
return []byte(`"` + model.FormatTime(time.Time(t)) + `"`), nil
}
type userJSON struct {
ID string `json:"id"`
Username string `json:"username"`
DisplayName string `json:"display_name"`
CreatedAt apiTime `json:"created_at"`
}
type chatJSON struct {
ID string `json:"id"`
Title string `json:"title"`
MemberIDs []string `json:"member_ids"`
CreatedAt apiTime `json:"created_at"`
}
type messageJSON struct {
ID string `json:"id"`
ChatID string `json:"chat_id"`
SenderID string `json:"sender_id"`
Text string `json:"text"`
CreatedAt apiTime `json:"created_at"`
}
type chatPageJSON struct {
Items []chatJSON `json:"items"`
NextCursor *string `json:"next_cursor"`
}
type messagePageJSON struct {
Items []messageJSON `json:"items"`
NextCursor *string `json:"next_cursor"`
}
type sessionJSON struct {
Token string `json:"token"`
TokenType string `json:"token_type"`
ExpiresAt apiTime `json:"expires_at"`
User userJSON `json:"user"`
}
func userToJSON(user model.User) userJSON {
return userJSON{
ID: user.ID,
Username: user.Username,
DisplayName: user.DisplayName,
CreatedAt: apiTime(user.CreatedAt),
}
}
func chatToJSON(chat model.Chat) chatJSON {
members := chat.MemberIDs
if members == nil {
members = []string{}
}
return chatJSON{
ID: chat.ID,
Title: chat.Title,
MemberIDs: members,
CreatedAt: apiTime(chat.CreatedAt),
}
}
func messageToJSON(msg model.Message) messageJSON {
return messageJSON{
ID: msg.ID,
ChatID: msg.ChatID,
SenderID: msg.SenderID,
Text: msg.Text,
CreatedAt: apiTime(msg.CreatedAt),
}
}
func writeJSON(w http.ResponseWriter, status int, value any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
enc := json.NewEncoder(w)
enc.SetEscapeHTML(false)
_ = enc.Encode(value)
}
func writeError(w http.ResponseWriter, status int, code, message, requestID string) {
writeJSON(w, status, map[string]any{
"error": map[string]string{
"code": code,
"message": message,
"request_id": requestID,
},
})
}
func writeUnauthorized(w http.ResponseWriter, r *http.Request, basic bool) {
if basic {
w.Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
} else {
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
}
writeError(w, http.StatusUnauthorized, "unauthorized", "Нет действительной идентификации", requestID(r))
}
func readJSON(w http.ResponseWriter, r *http.Request, dst any) error {
media, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil || media != "application/json" {
return errBadJSON
}
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 64*1024))
if err != nil {
var tooBig *http.MaxBytesError
if errors.As(err, &tooBig) {
return errTooLarge
}
return errBadJSON
}
if err := jsonstrict.Decode(body, dst); err != nil {
return errBadJSON
}
return nil
}
func bodyEmpty(r *http.Request) bool {
if r.Body == nil {
return true
}
buf := make([]byte, 1)
n, err := r.Body.Read(buf)
if n > 0 {
return false
}
return err == io.EOF || err == nil
}
func newRequestID() string {
var raw [16]byte
if _, err := rand.Read(raw[:]); err != nil {
return "request"
}
return hex.EncodeToString(raw[:])
}
var (
errBadJSON = errors.New("bad json")
errTooLarge = errors.New("too large")
)
+224
View File
@@ -0,0 +1,224 @@
package httpapi
import (
"context"
"encoding/base64"
"errors"
"log/slog"
"net/http"
"runtime/debug"
"strconv"
"strings"
"sync/atomic"
"time"
"mtusi.local/messenger/internal/authpw"
"mtusi.local/messenger/internal/model"
"mtusi.local/messenger/internal/pgstore"
"mtusi.local/messenger/internal/sessions"
)
type API struct {
db *pgstore.Store
session *sessions.Store
log *slog.Logger
dummy string
draining atomic.Bool
}
func New(db *pgstore.Store, session *sessions.Store, logger *slog.Logger, dummyHash string) *API {
if logger == nil {
logger = slog.Default()
}
return &API{db: db, session: session, log: logger, dummy: dummyHash}
}
func (a *API) StartDraining() {
a.draining.Store(true)
}
func (a *API) Handler() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /health/live", a.live)
mux.HandleFunc("GET /health/ready", a.ready)
mux.HandleFunc("POST /api/v1/users", a.createUser)
mux.HandleFunc("GET /api/v1/users/me", a.currentUser)
mux.HandleFunc("POST /api/v1/auth/sessions", a.createSession)
mux.HandleFunc("DELETE /api/v1/auth/sessions/current", a.revokeSession)
mux.HandleFunc("POST /api/v1/chats", a.createChat)
mux.HandleFunc("GET /api/v1/chats", a.listChats)
mux.HandleFunc("GET /api/v1/chats/{chat_id}", a.getChat)
mux.HandleFunc("POST /api/v1/chats/{chat_id}/messages", a.createMessage)
mux.HandleFunc("GET /api/v1/chats/{chat_id}/messages", a.listMessages)
mux.HandleFunc("/", a.notFound)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
started := time.Now()
id := newRequestID()
ctx, cancel := context.WithTimeout(r.Context(), 4*time.Second)
defer cancel()
ctx = context.WithValue(ctx, requestIDKey{}, id)
r = r.WithContext(ctx)
sw := &statusWriter{ResponseWriter: w, status: http.StatusOK}
sw.Header().Set("X-Request-Id", id)
defer func() {
if rec := recover(); rec != nil {
a.log.Error("panic", "request_id", id, "method", r.Method, "path", r.URL.Path)
a.log.Error("panic_stack", "request_id", id, "stack", string(debug.Stack()))
if !sw.wrote {
writeError(sw, http.StatusInternalServerError, "internal_error", "Внутренняя ошибка", id)
}
}
a.log.Info("request",
"request_id", id,
"method", r.Method,
"path", r.URL.Path,
"status", sw.status,
"duration_ms", float64(time.Since(started).Microseconds())/1000,
)
}()
if a.draining.Load() && r.URL.Path != "/health/live" {
writeError(sw, http.StatusServiceUnavailable, "unavailable", "Сервер завершает работу", id)
return
}
mux.ServeHTTP(sw, r)
})
}
func (a *API) live(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
}
func (a *API) ready(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
defer cancel()
if err := a.db.Ping(ctx); err != nil || a.session.Ping(ctx) != nil {
writeError(w, http.StatusServiceUnavailable, "unavailable", "Сервис временно недоступен", requestID(r))
return
}
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
}
func (a *API) notFound(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusNotFound, "not_found", "Объект не найден", requestID(r))
}
func (a *API) requireUser(w http.ResponseWriter, r *http.Request) (model.User, bool) {
token, ok := bearerToken(r)
if !ok {
writeUnauthorized(w, r, false)
return model.User{}, false
}
userID, err := a.session.Lookup(r.Context(), token)
if errors.Is(err, model.ErrUnavailable) {
writeError(w, http.StatusServiceUnavailable, "unavailable", "Сервис временно недоступен", requestID(r))
return model.User{}, false
}
if err != nil {
writeUnauthorized(w, r, false)
return model.User{}, false
}
user, err := a.db.UserByID(r.Context(), userID)
if errors.Is(err, model.ErrUnavailable) {
writeError(w, http.StatusServiceUnavailable, "unavailable", "Сервис временно недоступен", requestID(r))
return model.User{}, false
}
if err != nil {
writeUnauthorized(w, r, false)
return model.User{}, false
}
return user, true
}
func bearerToken(r *http.Request) (string, bool) {
scheme, param, ok := splitAuth(r.Header.Get("Authorization"))
if !ok || !strings.EqualFold(scheme, "Bearer") || len(param) < 32 || strings.ContainsAny(param, " \t") {
return "", false
}
return param, true
}
func basicCredentials(r *http.Request) (string, string, bool) {
scheme, param, ok := splitAuth(r.Header.Get("Authorization"))
if !ok || !strings.EqualFold(scheme, "Basic") {
return "", "", false
}
raw, err := base64.StdEncoding.DecodeString(param)
if err != nil {
return "", "", false
}
username, password, ok := strings.Cut(string(raw), ":")
if !ok {
return "", "", false
}
return username, password, true
}
func splitAuth(header string) (string, string, bool) {
scheme, param, ok := strings.Cut(strings.TrimSpace(header), " ")
if !ok || scheme == "" || strings.TrimSpace(param) == "" {
return "", "", false
}
return scheme, strings.TrimSpace(param), true
}
func parseLimit(r *http.Request) (int, error) {
values, ok := r.URL.Query()["limit"]
if !ok {
return 50, nil
}
if len(values) != 1 {
return 0, errBadQuery
}
n, err := strconv.Atoi(values[0])
if err != nil || n < 1 || n > 100 {
return 0, errBadQuery
}
return n, nil
}
func parseCursor(r *http.Request) (*model.Cursor, error) {
values, ok := r.URL.Query()["cursor"]
if !ok {
return nil, nil
}
if len(values) != 1 || values[0] == "" {
return nil, errBadQuery
}
cursor, err := model.DecodeCursor(values[0])
if err != nil {
return nil, errBadQuery
}
return &cursor, nil
}
func writeStoreError(w http.ResponseWriter, r *http.Request, err error, invalidMessage string) {
switch {
case errors.Is(err, model.ErrConflict):
writeError(w, http.StatusConflict, "conflict", "Имя пользователя уже занято", requestID(r))
case errors.Is(err, model.ErrNotFound):
writeError(w, http.StatusNotFound, "not_found", "Объект не найден", requestID(r))
case errors.Is(err, model.ErrUnavailable):
writeError(w, http.StatusServiceUnavailable, "unavailable", "Сервис временно недоступен", requestID(r))
default:
writeError(w, http.StatusBadRequest, "invalid_request", invalidMessage, requestID(r))
}
}
func (a *API) checkPassword(password, encoded string) bool {
if encoded == "" {
encoded = a.dummy
}
return authpw.Verify(password, encoded)
}
type requestIDKey struct{}
func requestID(r *http.Request) string {
id, _ := r.Context().Value(requestIDKey{}).(string)
if id == "" {
id = newRequestID()
}
return id
}
var errBadQuery = errors.New("bad query")