forked from mtusi2026/mtusi2026lab2
Подключение Postgresql и redis
This commit is contained in:
+69
-58
@@ -1,9 +1,13 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"messenger/internal/session"
|
||||
"messenger/internal/store"
|
||||
)
|
||||
|
||||
@@ -16,6 +20,12 @@ func (a *API) ready(w http.ResponseWriter, r *http.Request) {
|
||||
a.fail(w, r, http.StatusServiceUnavailable, "unavailable", "Сервер останавливается", 1)
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 800*time.Millisecond)
|
||||
defer cancel()
|
||||
if err := a.store.Ping(ctx); err != nil || a.sessions.Ping(ctx) != nil {
|
||||
a.fail(w, r, http.StatusServiceUnavailable, "unavailable", "Сервис временно недоступен", 1)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
@@ -26,6 +36,10 @@ func (a *API) route(w http.ResponseWriter, r *http.Request) {
|
||||
a.createUser(w, r)
|
||||
case path == "/api/v1/users/me" && r.Method == http.MethodGet:
|
||||
a.currentUser(w, r)
|
||||
case path == "/api/v1/auth/sessions" && r.Method == http.MethodPost:
|
||||
a.createSession(w, r)
|
||||
case path == "/api/v1/auth/sessions/current" && r.Method == http.MethodDelete:
|
||||
a.revokeSession(w, r)
|
||||
case path == "/api/v1/chats" && r.Method == http.MethodPost:
|
||||
a.createChat(w, r)
|
||||
case path == "/api/v1/chats" && r.Method == http.MethodGet:
|
||||
@@ -55,7 +69,8 @@ func (a *API) route(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
func knownWrongMethod(path string) bool {
|
||||
switch path {
|
||||
case "/api/v1/users", "/api/v1/users/me", "/api/v1/chats":
|
||||
case "/api/v1/users", "/api/v1/users/me", "/api/v1/chats",
|
||||
"/api/v1/auth/sessions", "/api/v1/auth/sessions/current":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
@@ -66,23 +81,24 @@ 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 !a.readJSON(w, r, &body) {
|
||||
return
|
||||
}
|
||||
if !usernameRe.MatchString(body.Username) || !validText(body.DisplayName, 1, 100) {
|
||||
if !usernameRe.MatchString(body.Username) || !validText(body.DisplayName, 1, 100) || !validPassword(body.Password) {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректные поля пользователя", 0)
|
||||
return
|
||||
}
|
||||
user, err := a.store.CreateUser(body.Username, body.DisplayName)
|
||||
if err == store.ErrConflict {
|
||||
a.fail(w, r, http.StatusConflict, "conflict", "Имя пользователя уже занято", 0)
|
||||
return
|
||||
}
|
||||
hash, err := a.hasher.Hash(body.Password)
|
||||
if err != nil {
|
||||
a.fail(w, r, http.StatusInternalServerError, "internal_error", "Внутренняя ошибка", 0)
|
||||
return
|
||||
}
|
||||
user, err := a.store.CreateUser(r.Context(), body.Username, body.DisplayName, hash)
|
||||
if a.writeStoreErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, asUser(user))
|
||||
}
|
||||
|
||||
@@ -124,10 +140,14 @@ func (a *API) createChat(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
if _, exists := a.store.User(id); !exists {
|
||||
_, err := a.store.User(r.Context(), id)
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный список участников", 0)
|
||||
return
|
||||
}
|
||||
if a.writeStoreErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
if id == caller.ID {
|
||||
callerIn = true
|
||||
}
|
||||
@@ -137,15 +157,15 @@ func (a *API) createChat(w http.ResponseWriter, r *http.Request) {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный список участников", 0)
|
||||
return
|
||||
}
|
||||
chat, err := a.store.CreateChat(body.Title, ids, caller.ID)
|
||||
switch err {
|
||||
case nil:
|
||||
writeJSON(w, http.StatusCreated, asChat(chat))
|
||||
case store.ErrInvalid:
|
||||
chat, err := a.store.CreateChat(r.Context(), body.Title, ids, caller.ID)
|
||||
if errors.Is(err, store.ErrInvalid) {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный список участников", 0)
|
||||
default:
|
||||
a.fail(w, r, http.StatusInternalServerError, "internal_error", "Внутренняя ошибка", 0)
|
||||
return
|
||||
}
|
||||
if a.writeStoreErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, asChat(chat))
|
||||
}
|
||||
|
||||
func (a *API) listChats(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -157,13 +177,8 @@ func (a *API) listChats(w http.ResponseWriter, r *http.Request) {
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
items, hasMore, err := a.store.ListChats(user.ID, cur, limit)
|
||||
if err == store.ErrBadCursor {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный cursor", 0)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
a.fail(w, r, http.StatusInternalServerError, "internal_error", "Внутренняя ошибка", 0)
|
||||
items, hasMore, err := a.store.ListChats(r.Context(), user.ID, cur, limit)
|
||||
if a.writeStoreErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
out := make([]chatJSON, 0, len(items))
|
||||
@@ -188,13 +203,8 @@ func (a *API) getChat(w http.ResponseWriter, r *http.Request, rawID string) {
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
chat, err := a.store.ChatFor(id, user.ID)
|
||||
if err == store.ErrNotFound {
|
||||
a.fail(w, r, http.StatusNotFound, "not_found", "Объект не найден", 0)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
a.fail(w, r, http.StatusInternalServerError, "internal_error", "Внутренняя ошибка", 0)
|
||||
chat, err := a.store.ChatFor(r.Context(), id, user.ID)
|
||||
if a.writeStoreErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, asChat(chat))
|
||||
@@ -209,11 +219,7 @@ func (a *API) createMessage(w http.ResponseWriter, r *http.Request, rawID string
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if _, err := a.store.ChatFor(id, user.ID); err == store.ErrNotFound {
|
||||
a.fail(w, r, http.StatusNotFound, "not_found", "Объект не найден", 0)
|
||||
return
|
||||
} else if err != nil {
|
||||
a.fail(w, r, http.StatusInternalServerError, "internal_error", "Внутренняя ошибка", 0)
|
||||
if _, err := a.store.ChatFor(r.Context(), id, user.ID); a.writeStoreErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
@@ -226,15 +232,11 @@ func (a *API) createMessage(w http.ResponseWriter, r *http.Request, rawID string
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный текст сообщения", 0)
|
||||
return
|
||||
}
|
||||
msg, err := a.store.AddMessage(id, user.ID, body.Text)
|
||||
switch err {
|
||||
case nil:
|
||||
writeJSON(w, http.StatusCreated, asMessage(msg))
|
||||
case store.ErrNotFound:
|
||||
a.fail(w, r, http.StatusNotFound, "not_found", "Объект не найден", 0)
|
||||
default:
|
||||
a.fail(w, r, http.StatusInternalServerError, "internal_error", "Внутренняя ошибка", 0)
|
||||
msg, err := a.store.AddMessage(r.Context(), id, user.ID, body.Text)
|
||||
if a.writeStoreErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, asMessage(msg))
|
||||
}
|
||||
|
||||
func (a *API) listMessages(w http.ResponseWriter, r *http.Request, rawID string) {
|
||||
@@ -246,28 +248,15 @@ func (a *API) listMessages(w http.ResponseWriter, r *http.Request, rawID string)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if _, err := a.store.ChatFor(id, user.ID); err == store.ErrNotFound {
|
||||
a.fail(w, r, http.StatusNotFound, "not_found", "Объект не найден", 0)
|
||||
return
|
||||
} else if err != nil {
|
||||
a.fail(w, r, http.StatusInternalServerError, "internal_error", "Внутренняя ошибка", 0)
|
||||
if _, err := a.store.ChatFor(r.Context(), id, user.ID); a.writeStoreErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
limit, cur, ok := a.pageQuery(w, r, "msg:"+id)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
items, hasMore, err := a.store.ListMessages(id, user.ID, cur, limit)
|
||||
if err == store.ErrBadCursor {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный cursor", 0)
|
||||
return
|
||||
}
|
||||
if err == store.ErrNotFound {
|
||||
a.fail(w, r, http.StatusNotFound, "not_found", "Объект не найден", 0)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
a.fail(w, r, http.StatusInternalServerError, "internal_error", "Внутренняя ошибка", 0)
|
||||
items, hasMore, err := a.store.ListMessages(r.Context(), id, user.ID, cur, limit)
|
||||
if a.writeStoreErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
out := make([]messageJSON, 0, len(items))
|
||||
@@ -292,6 +281,28 @@ func (a *API) chatID(w http.ResponseWriter, r *http.Request, raw string) (string
|
||||
return id, true
|
||||
}
|
||||
|
||||
func (a *API) writeStoreErr(w http.ResponseWriter, r *http.Request, err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
switch {
|
||||
case errors.Is(err, store.ErrUnavailable), errors.Is(err, session.ErrUnavailable):
|
||||
a.fail(w, r, http.StatusServiceUnavailable, "unavailable", "Сервис временно недоступен", 1)
|
||||
case errors.Is(err, store.ErrConflict):
|
||||
a.fail(w, r, http.StatusConflict, "conflict", "Имя пользователя уже занято", 0)
|
||||
case errors.Is(err, store.ErrNotFound):
|
||||
a.fail(w, r, http.StatusNotFound, "not_found", "Объект не найден", 0)
|
||||
case errors.Is(err, store.ErrInvalid):
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректные данные", 0)
|
||||
case errors.Is(err, store.ErrBadCursor):
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный cursor", 0)
|
||||
default:
|
||||
a.log.Error("store", "request_id", requestIDFrom(r))
|
||||
a.fail(w, r, http.StatusInternalServerError, "internal_error", "Внутренняя ошибка", 0)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func splitChatPath(path string) (id string, messages bool, ok bool) {
|
||||
const prefix = "/api/v1/chats/"
|
||||
if !strings.HasPrefix(path, prefix) {
|
||||
|
||||
Reference in New Issue
Block a user