forked from mtusi2026/mtusi2026lab4
S3-вложения и сверка Postgresql с MinIO
This commit is contained in:
@@ -0,0 +1,365 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"messenger/internal/session"
|
||||
"messenger/internal/store"
|
||||
)
|
||||
|
||||
func (a *API) live(w http.ResponseWriter, _ *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
func (a *API) ready(w http.ResponseWriter, r *http.Request) {
|
||||
if a.shutting.Load() {
|
||||
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
|
||||
}
|
||||
if a.blobs != nil {
|
||||
if err := a.blobs.Ping(ctx); err != nil {
|
||||
a.fail(w, r, http.StatusServiceUnavailable, "unavailable", "Сервис временно недоступен", 1)
|
||||
return
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
func (a *API) route(w http.ResponseWriter, r *http.Request) {
|
||||
path := r.URL.Path
|
||||
switch {
|
||||
case path == "/api/v1/users" && r.Method == http.MethodPost:
|
||||
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:
|
||||
a.listChats(w, r)
|
||||
default:
|
||||
if strings.HasPrefix(path, "/api/v1/attachments/") {
|
||||
a.routeAttachment(w, r, strings.TrimPrefix(path, "/api/v1/attachments/"))
|
||||
return
|
||||
}
|
||||
chatID, kind, ok := splitChatPath(path)
|
||||
if !ok {
|
||||
if knownWrongMethod(path) {
|
||||
a.fail(w, r, http.StatusMethodNotAllowed, "invalid_request", "Метод не поддерживается", 0)
|
||||
return
|
||||
}
|
||||
a.fail(w, r, http.StatusNotFound, "not_found", "Объект не найден", 0)
|
||||
return
|
||||
}
|
||||
switch kind {
|
||||
case "":
|
||||
if r.Method == http.MethodGet {
|
||||
a.getChat(w, r, chatID)
|
||||
return
|
||||
}
|
||||
case "messages":
|
||||
switch r.Method {
|
||||
case http.MethodPost:
|
||||
a.createMessage(w, r, chatID)
|
||||
return
|
||||
case http.MethodGet:
|
||||
a.listMessages(w, r, chatID)
|
||||
return
|
||||
}
|
||||
case "attachments":
|
||||
if r.Method == http.MethodPost {
|
||||
a.uploadAttachment(w, r, chatID)
|
||||
return
|
||||
}
|
||||
}
|
||||
a.fail(w, r, http.StatusMethodNotAllowed, "invalid_request", "Метод не поддерживается", 0)
|
||||
}
|
||||
}
|
||||
|
||||
func knownWrongMethod(path string) bool {
|
||||
switch path {
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
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) || !validPassword(body.Password) {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректные поля пользователя", 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))
|
||||
}
|
||||
|
||||
func (a *API) currentUser(w http.ResponseWriter, r *http.Request) {
|
||||
user, ok := a.authenticate(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, asUser(user))
|
||||
}
|
||||
|
||||
func (a *API) createChat(w http.ResponseWriter, r *http.Request) {
|
||||
caller, ok := a.authenticate(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
}
|
||||
if !a.readJSON(w, r, &body) {
|
||||
return
|
||||
}
|
||||
if !validText(body.Title, 1, 100) || len(body.MemberIDs) < 1 || len(body.MemberIDs) > 100 {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректные поля чата", 0)
|
||||
return
|
||||
}
|
||||
ids := make([]string, len(body.MemberIDs))
|
||||
seen := make(map[string]struct{}, len(body.MemberIDs))
|
||||
callerIn := false
|
||||
for i, raw := range body.MemberIDs {
|
||||
id, ok := canonicalUUID(raw)
|
||||
if !ok {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный список участников", 0)
|
||||
return
|
||||
}
|
||||
if _, dup := seen[id]; dup {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный список участников", 0)
|
||||
return
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
_, 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
|
||||
}
|
||||
ids[i] = id
|
||||
}
|
||||
if !callerIn {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный список участников", 0)
|
||||
return
|
||||
}
|
||||
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)
|
||||
return
|
||||
}
|
||||
if a.writeStoreErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, asChat(chat))
|
||||
}
|
||||
|
||||
func (a *API) listChats(w http.ResponseWriter, r *http.Request) {
|
||||
user, ok := a.authenticate(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
limit, cur, ok := a.pageQuery(w, r, "chats:"+user.ID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
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))
|
||||
for _, c := range items {
|
||||
out = append(out, asChat(c))
|
||||
}
|
||||
var next *string
|
||||
if hasMore && len(items) > 0 {
|
||||
last := items[len(items)-1]
|
||||
encoded := encodeCursor(cursorPayload{Scope: "chats:" + user.ID, ID: last.ID, At: formatTime(last.CreatedAt)})
|
||||
next = &encoded
|
||||
}
|
||||
writeJSON(w, http.StatusOK, chatPage{Items: out, NextCursor: next})
|
||||
}
|
||||
|
||||
func (a *API) getChat(w http.ResponseWriter, r *http.Request, rawID string) {
|
||||
user, ok := a.authenticate(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id, ok := a.chatID(w, r, rawID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
chat, err := a.store.ChatFor(r.Context(), id, user.ID)
|
||||
if a.writeStoreErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, asChat(chat))
|
||||
}
|
||||
|
||||
func (a *API) createMessage(w http.ResponseWriter, r *http.Request, rawID string) {
|
||||
user, ok := a.authenticate(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id, ok := a.chatID(w, r, rawID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if _, err := a.store.ChatFor(r.Context(), id, user.ID); a.writeStoreErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
idemKey := r.Header.Get("Idempotency-Key")
|
||||
if !idemKeyRe.MatchString(idemKey) {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Нужен заголовок Idempotency-Key", 0)
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
Text string `json:"text"`
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
}
|
||||
if !a.readJSON(w, r, &body) {
|
||||
return
|
||||
}
|
||||
ids, ok := a.attachmentIDList(w, r, body.AttachmentIDs)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if !validMessageText(body.Text, len(ids)) {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный текст сообщения", 0)
|
||||
return
|
||||
}
|
||||
// Отпечаток — разобранные поля, не сырые байты: порядок ключей JSON и отсутствующий attachment_ids равны пустому списку.
|
||||
msg, err := a.store.AddMessage(r.Context(), id, user.ID, body.Text, ids, idemKey, messageFingerprint(body.Text, ids))
|
||||
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) {
|
||||
user, ok := a.authenticate(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id, ok := a.chatID(w, r, rawID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
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(r.Context(), id, user.ID, cur, limit)
|
||||
if a.writeStoreErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
out := make([]messageJSON, 0, len(items))
|
||||
for _, m := range items {
|
||||
out = append(out, asMessage(m))
|
||||
}
|
||||
var next *string
|
||||
if hasMore && len(items) > 0 {
|
||||
last := items[len(items)-1]
|
||||
encoded := encodeCursor(cursorPayload{Scope: "msg:" + id, ID: last.ID, At: formatTime(last.CreatedAt)})
|
||||
next = &encoded
|
||||
}
|
||||
writeJSON(w, http.StatusOK, messagePage{Items: out, NextCursor: next})
|
||||
}
|
||||
|
||||
func (a *API) chatID(w http.ResponseWriter, r *http.Request, raw string) (string, bool) {
|
||||
id, ok := canonicalUUID(raw)
|
||||
if !ok {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный идентификатор", 0)
|
||||
return "", false
|
||||
}
|
||||
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.ErrIdempotencyMismatch):
|
||||
a.fail(w, r, http.StatusConflict, "conflict", "Этот ключ уже использован для другого сообщения", 0)
|
||||
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.ErrNotReady):
|
||||
a.fail(w, r, http.StatusConflict, "conflict", "Вложение нельзя прикрепить", 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, kind string, ok bool) {
|
||||
const prefix = "/api/v1/chats/"
|
||||
if !strings.HasPrefix(path, prefix) {
|
||||
return "", "", false
|
||||
}
|
||||
rest := strings.TrimPrefix(path, prefix)
|
||||
if rest == "" {
|
||||
return "", "", false
|
||||
}
|
||||
for _, suffix := range []string{"/messages", "/attachments"} {
|
||||
if strings.HasSuffix(rest, suffix) {
|
||||
id = strings.TrimSuffix(rest, suffix)
|
||||
if id == "" || strings.Contains(id, "/") {
|
||||
return "", "", false
|
||||
}
|
||||
return id, strings.TrimPrefix(suffix, "/"), true
|
||||
}
|
||||
}
|
||||
if strings.Contains(rest, "/") {
|
||||
return "", "", false
|
||||
}
|
||||
return rest, "", true
|
||||
}
|
||||
Reference in New Issue
Block a user