package messenger import ( "bytes" "context" "crypto/rand" "crypto/sha256" "encoding/base64" "encoding/hex" "encoding/json" "errors" "fmt" "io" "log" "net/http" "net/url" "regexp" "strconv" "strings" "time" "unicode/utf8" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgxpool" "github.com/redis/go-redis/v9" ) type User struct { ID string `json:"id"` Username string `json:"username"` DisplayName string `json:"display_name"` CreatedAt string `json:"created_at"` } type Chat struct { ID string `json:"id"` Title string `json:"title"` MemberIDs []string `json:"member_ids"` CreatedAt string `json:"created_at"` } type Message struct { ID string `json:"id"` ChatID string `json:"chat_id"` SenderID string `json:"sender_id"` Text string `json:"text"` CreatedAt string `json:"created_at"` } type Session struct { Token string `json:"token"` TokenType string `json:"token_type"` ExpiresAt string `json:"expires_at"` User User `json:"user"` } type API struct { db *pgxpool.Pool sessions *redis.Client ttl time.Duration idempotencyTTL time.Duration dbTimeout time.Duration instanceID string logger *log.Logger } func NewHandler(db *pgxpool.Pool, sessions *redis.Client, ttl, idempotencyTTL, dbTimeout time.Duration, instanceID string, logger *log.Logger) http.Handler { return &API{db: db, sessions: sessions, ttl: ttl, idempotencyTTL: idempotencyTTL, dbTimeout: dbTimeout, instanceID: instanceID, logger: logger} } var uuidRE = regexp.MustCompile(`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$`) var usernameRE = regexp.MustCompile(`^[a-z0-9_]{3,32}$`) var idempotencyKeyRE = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`) type apiError struct { status int code, message, challenge string } type response struct { status int body any noBody bool } func bad(msg string) *apiError { return &apiError{status: 400, code: "invalid_request", message: msg} } func missing() *apiError { return &apiError{status: 404, code: "not_found", message: "Объект не найден"} } func unavailable() *apiError { return &apiError{status: 503, code: "unavailable", message: "Сервис временно недоступен"} } func unauthorized(scheme string) *apiError { challenge := `Bearer realm="messenger"` if scheme == "Basic" { challenge = `Basic realm="messenger", charset="UTF-8"` } return &apiError{status: 401, code: "unauthorized", message: "Неверные учётные данные", challenge: challenge} } func (a *API) ServeHTTP(w http.ResponseWriter, r *http.Request) { id := newID() w.Header().Set("X-Request-Id", id) w.Header().Set("X-Instance-Id", a.instanceID) w.Header().Set("Content-Type", "application/json; charset=utf-8") start, status := time.Now(), 500 defer func() { if x := recover(); x != nil { status = 500 a.logger.Printf("request_id=%s panic=%T", id, x) writeError(w, id, &apiError{status: 500, code: "internal_error", message: "Внутренняя ошибка"}) } a.logger.Printf("request_id=%s method=%s path=%s status=%d duration_ms=%d", id, r.Method, r.URL.Path, status, time.Since(start).Milliseconds()) }() res, apiErr := a.route(r) if apiErr != nil { status = apiErr.status writeError(w, id, apiErr) return } status = res.status w.WriteHeader(status) if !res.noBody { _ = json.NewEncoder(w).Encode(res.body) } } func writeError(w http.ResponseWriter, requestID string, e *apiError) { if e.challenge != "" { w.Header().Set("WWW-Authenticate", e.challenge) } w.WriteHeader(e.status) _ = json.NewEncoder(w).Encode(map[string]any{"error": map[string]string{"code": e.code, "message": e.message, "request_id": requestID}}) } func decode(r *http.Request, dst any) *apiError { if strings.ToLower(strings.TrimSpace(strings.Split(r.Header.Get("Content-Type"), ";")[0])) != "application/json" { return &apiError{status: 415, code: "unsupported_media_type", message: "Требуется application/json"} } if r.ContentLength > 1<<20 { return &apiError{status: 413, code: "payload_too_large", message: "Слишком большой запрос"} } data, err := io.ReadAll(io.LimitReader(r.Body, (1<<20)+1)) if err != nil { return bad("Не удалось прочитать JSON") } if len(data) > 1<<20 { return &apiError{status: 413, code: "payload_too_large", message: "Слишком большой запрос"} } if !utf8.Valid(data) { return bad("JSON должен быть в UTF-8") } d := json.NewDecoder(bytes.NewReader(data)) d.DisallowUnknownFields() if err = d.Decode(dst); err != nil { return bad("Неверный JSON или поля") } var rest any if !errors.Is(d.Decode(&rest), io.EOF) { return bad("Ожидался один JSON-объект") } return nil } func validText(s string, max int) bool { return utf8.ValidString(s) && strings.TrimSpace(s) != "" && utf8.RuneCountInString(s) <= max } func validPassword(s string) bool { n := utf8.RuneCountInString(s) return utf8.ValidString(s) && n >= 12 && n <= 128 } func formatTime(t time.Time) string { return t.UTC().Format(time.RFC3339Nano) } func newID() string { var b [16]byte if _, err := rand.Read(b[:]); err != nil { panic(err) } b[6] = (b[6] & 0x0f) | 0x40 b[8] = (b[8] & 0x3f) | 0x80 return fmt.Sprintf("%x-%x-%x-%x-%x", b[:4], b[4:6], b[6:8], b[8:10], b[10:]) } func newToken() string { b := make([]byte, 32) if _, err := rand.Read(b); err != nil { panic(err) } return base64.RawURLEncoding.EncodeToString(b) } func tokenKey(token string) string { sum := sha256.Sum256([]byte(token)) return "session:" + hex.EncodeToString(sum[:]) } func cursorFor(resource string, created time.Time, id string) string { b, _ := json.Marshal([]string{resource, formatTime(created), id}) return base64.RawURLEncoding.EncodeToString(b) } func parsePage(r *http.Request, resource string) (int, *time.Time, string, *apiError) { q, err := url.ParseQuery(r.URL.RawQuery) if err != nil { return 0, nil, "", bad("Неверные параметры страницы") } for k, v := range q { if (k != "limit" && k != "cursor") || len(v) != 1 { return 0, nil, "", bad("Неверные параметры страницы") } } limit := 50 if raw := q.Get("limit"); raw != "" { n, e := strconv.Atoi(raw) if e != nil || n < 1 || n > 100 { return 0, nil, "", bad("limit должен быть от 1 до 100") } limit = n } else if _, ok := q["limit"]; ok { return 0, nil, "", bad("Пустой limit") } if _, ok := q["cursor"]; !ok { return limit, nil, "", nil } raw := q.Get("cursor") if raw == "" || len(raw) > 1024 { return 0, nil, "", bad("Неверный cursor") } b, e := base64.RawURLEncoding.DecodeString(raw) if e != nil { return 0, nil, "", bad("Неверный cursor") } var p []string if json.Unmarshal(b, &p) != nil || len(p) != 3 || p[0] != resource || !uuidRE.MatchString(p[2]) { return 0, nil, "", bad("Неверный cursor") } t, e := time.Parse(time.RFC3339Nano, p[1]) if e != nil { return 0, nil, "", bad("Неверный cursor") } return limit, &t, p[2], nil } func (a *API) dbContext(parent context.Context) (context.Context, context.CancelFunc) { return context.WithTimeout(parent, a.dbTimeout) } func (a *API) authenticate(r *http.Request) (string, string, *apiError) { h := r.Header.Get("Authorization") if !strings.HasPrefix(h, "Bearer ") || strings.TrimSpace(strings.TrimPrefix(h, "Bearer ")) == "" { return "", "", unauthorized("Bearer") } token := strings.TrimSpace(strings.TrimPrefix(h, "Bearer ")) ctx, cancel := context.WithTimeout(r.Context(), a.dbTimeout) defer cancel() uid, err := a.sessions.Get(ctx, tokenKey(token)).Result() if errors.Is(err, redis.Nil) { return "", "", unauthorized("Bearer") } if err != nil { a.logger.Printf("session store unavailable: %v", err) return "", "", unavailable() } if !uuidRE.MatchString(uid) { return "", "", unauthorized("Bearer") } return uid, token, nil } func scanUser(row pgx.Row) (User, string, error) { var u User var created time.Time var password string err := row.Scan(&u.ID, &u.Username, &u.DisplayName, &created, &password) u.CreatedAt = formatTime(created) return u, password, err } func (a *API) route(r *http.Request) (response, *apiError) { p := r.URL.Path if r.Method == "GET" && p == "/health/live" { return response{status: 200, body: map[string]string{"status": "ok"}}, nil } if r.Method == "GET" && p == "/health/ready" { ctx, cancel := context.WithTimeout(r.Context(), time.Second) defer cancel() if a.db.Ping(ctx) != nil || a.sessions.Ping(ctx).Err() != nil { return response{}, unavailable() } return response{status: 200, body: map[string]string{"status": "ok"}}, nil } if r.Method == "POST" && p == "/api/v1/users" { return a.createUser(r) } if r.Method == "POST" && p == "/api/v1/auth/sessions" { return a.createSession(r) } if !strings.HasPrefix(p, "/api/v1/") { return response{}, missing() } uid, token, authErr := a.authenticate(r) if authErr != nil { return response{}, authErr } if r.Method == "DELETE" && p == "/api/v1/auth/sessions/current" { ctx, cancel := context.WithTimeout(r.Context(), a.dbTimeout) defer cancel() if err := a.sessions.Del(ctx, tokenKey(token)).Err(); err != nil { return response{}, unavailable() } return response{status: 204, noBody: true}, nil } if r.Method == "GET" && p == "/api/v1/users/me" { return a.currentUser(r, uid) } if p == "/api/v1/chats" { if r.Method == "POST" { return a.createChat(r, uid) } if r.Method == "GET" { return a.listChats(r, uid) } } if !strings.HasPrefix(p, "/api/v1/chats/") { return response{}, missing() } parts := strings.Split(strings.TrimPrefix(p, "/api/v1/chats/"), "/") if len(parts) < 1 || !uuidRE.MatchString(parts[0]) { return response{}, bad("Неверный chat_id") } chatID := parts[0] if len(parts) == 1 && r.Method == "GET" { return a.getChat(r, uid, chatID) } if len(parts) == 2 && parts[1] == "messages" { if r.Method == "POST" { return a.createMessage(r, uid, chatID) } if r.Method == "GET" { return a.listMessages(r, uid, chatID) } } return response{}, missing() } func (a *API) createUser(r *http.Request) (response, *apiError) { var in struct { Username string `json:"username"` DisplayName string `json:"display_name"` Password string `json:"password"` } if e := decode(r, &in); e != nil { return response{}, e } if !usernameRE.MatchString(in.Username) || !validText(in.DisplayName, 100) || !validPassword(in.Password) { return response{}, bad("Неверные данные пользователя") } passwordHash, err := hashPassword(in.Password) if err != nil { return response{}, &apiError{status: 500, code: "internal_error", message: "Внутренняя ошибка"} } ctx, cancel := a.dbContext(r.Context()) defer cancel() var u User var created time.Time err = a.db.QueryRow(ctx, `INSERT INTO users(id,username,display_name,password_hash) VALUES($1,$2,$3,$4) RETURNING id::text,username,display_name,created_at`, newID(), in.Username, in.DisplayName, passwordHash).Scan(&u.ID, &u.Username, &u.DisplayName, &created) if err != nil { var pgErr *pgconn.PgError if errors.As(err, &pgErr) && pgErr.Code == "23505" { return response{}, &apiError{status: 409, code: "conflict", message: "Имя пользователя занято"} } return response{}, unavailable() } u.CreatedAt = formatTime(created) return response{status: 201, body: u}, nil } func (a *API) createSession(r *http.Request) (response, *apiError) { if r.ContentLength > 0 { return response{}, bad("Тело запроса не допускается") } h := r.Header.Get("Authorization") if !strings.HasPrefix(h, "Basic ") { return response{}, unauthorized("Basic") } raw, err := base64.StdEncoding.DecodeString(strings.TrimSpace(strings.TrimPrefix(h, "Basic "))) if err != nil { return response{}, unauthorized("Basic") } parts := strings.SplitN(string(raw), ":", 2) if len(parts) != 2 || !usernameRE.MatchString(parts[0]) { return response{}, unauthorized("Basic") } ctx, cancel := a.dbContext(r.Context()) defer cancel() u, passwordHash, err := scanUser(a.db.QueryRow(ctx, `SELECT id::text,username,display_name,created_at,password_hash FROM users WHERE username=$1`, parts[0])) if errors.Is(err, pgx.ErrNoRows) { return response{}, unauthorized("Basic") } if err != nil { return response{}, unavailable() } if !verifyPassword(passwordHash, parts[1]) { return response{}, unauthorized("Basic") } token := newToken() expires := time.Now().UTC().Add(a.ttl) if err = a.sessions.Set(ctx, tokenKey(token), u.ID, a.ttl).Err(); err != nil { return response{}, unavailable() } return response{status: 201, body: Session{Token: token, TokenType: "Bearer", ExpiresAt: formatTime(expires), User: u}}, nil } func (a *API) currentUser(r *http.Request, uid string) (response, *apiError) { ctx, cancel := a.dbContext(r.Context()) defer cancel() u, _, err := scanUser(a.db.QueryRow(ctx, `SELECT id::text,username,display_name,created_at,password_hash FROM users WHERE id=$1`, uid)) if errors.Is(err, pgx.ErrNoRows) { return response{}, unauthorized("Bearer") } if err != nil { return response{}, unavailable() } return response{status: 200, body: u}, nil } func (a *API) createChat(r *http.Request, uid string) (response, *apiError) { var in struct { Title string `json:"title"` MemberIDs []string `json:"member_ids"` } if e := decode(r, &in); e != nil { return response{}, e } if !validText(in.Title, 100) || len(in.MemberIDs) < 1 || len(in.MemberIDs) > 100 { return response{}, bad("Неверные данные чата") } seen := map[string]bool{} for _, id := range in.MemberIDs { if !uuidRE.MatchString(id) || seen[id] { return response{}, bad("Неверные участники чата") } seen[id] = true } if !seen[uid] { return response{}, bad("Создатель должен быть участником") } ctx, cancel := a.dbContext(r.Context()) defer cancel() tx, err := a.db.Begin(ctx) if err != nil { return response{}, unavailable() } defer tx.Rollback(ctx) c := Chat{ID: newID(), Title: in.Title, MemberIDs: append([]string{}, in.MemberIDs...)} var created time.Time if err = tx.QueryRow(ctx, `INSERT INTO chats(id,title) VALUES($1,$2) RETURNING created_at`, c.ID, c.Title).Scan(&created); err != nil { return response{}, unavailable() } for _, id := range c.MemberIDs { if _, err = tx.Exec(ctx, `INSERT INTO chat_members(chat_id,user_id) VALUES($1,$2)`, c.ID, id); err != nil { var pgErr *pgconn.PgError if errors.As(err, &pgErr) && pgErr.Code == "23503" { return response{}, bad("Неверные участники чата") } return response{}, unavailable() } } if err = tx.Commit(ctx); err != nil { return response{}, unavailable() } c.CreatedAt = formatTime(created) return response{status: 201, body: c}, nil } func scanChat(row pgx.Row) (Chat, time.Time, error) { var c Chat var t time.Time err := row.Scan(&c.ID, &c.Title, &c.MemberIDs, &t) c.CreatedAt = formatTime(t) return c, t, err } func chatSelect() string { return `SELECT c.id::text,c.title,ARRAY(SELECT cm2.user_id::text FROM chat_members cm2 WHERE cm2.chat_id=c.id ORDER BY cm2.user_id),c.created_at FROM chats c` } func (a *API) getChat(r *http.Request, uid, chatID string) (response, *apiError) { ctx, cancel := a.dbContext(r.Context()) defer cancel() c, _, err := scanChat(a.db.QueryRow(ctx, chatSelect()+` WHERE c.id=$1 AND EXISTS(SELECT 1 FROM chat_members cm WHERE cm.chat_id=c.id AND cm.user_id=$2)`, chatID, uid)) if errors.Is(err, pgx.ErrNoRows) { return response{}, missing() } if err != nil { return response{}, unavailable() } return response{status: 200, body: c}, nil } func (a *API) listChats(r *http.Request, uid string) (response, *apiError) { limit, afterTime, afterID, e := parsePage(r, "chats:"+uid) if e != nil { return response{}, e } ctx, cancel := a.dbContext(r.Context()) defer cancel() if afterTime != nil { var ok bool err := a.db.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM chats c JOIN chat_members cm ON cm.chat_id=c.id WHERE cm.user_id=$1 AND c.id=$2 AND c.created_at=$3)`, uid, afterID, *afterTime).Scan(&ok) if err != nil { return response{}, unavailable() } if !ok { return response{}, bad("Неверный cursor") } } var rows pgx.Rows var err error base := chatSelect() + ` JOIN chat_members mine ON mine.chat_id=c.id WHERE mine.user_id=$1` if afterTime == nil { rows, err = a.db.Query(ctx, base+` ORDER BY c.created_at,c.id LIMIT $2`, uid, limit+1) } else { rows, err = a.db.Query(ctx, base+` AND (c.created_at,c.id)>($2,$3) ORDER BY c.created_at,c.id LIMIT $4`, uid, *afterTime, afterID, limit+1) } if err != nil { return response{}, unavailable() } defer rows.Close() items := make([]Chat, 0, limit+1) times := make([]time.Time, 0, limit+1) for rows.Next() { c, t, scanErr := scanChat(rows) if scanErr != nil { return response{}, unavailable() } items = append(items, c) times = append(times, t) } if rows.Err() != nil { return response{}, unavailable() } var next any if len(items) > limit { last := items[limit-1] next = cursorFor("chats:"+uid, times[limit-1], last.ID) items = items[:limit] } return response{status: 200, body: map[string]any{"items": items, "next_cursor": next}}, nil } func (a *API) createMessage(r *http.Request, uid, chatID string) (response, *apiError) { key := r.Header.Get("Idempotency-Key") if !idempotencyKeyRE.MatchString(key) { return response{}, bad("Требуется корректный Idempotency-Key") } var in struct { Text string `json:"text"` } if e := decode(r, &in); e != nil { return response{}, e } if !validText(in.Text, 4000) { return response{}, bad("Текст сообщения должен содержать от 1 до 4000 символов") } ctx, cancel := a.dbContext(r.Context()) defer cancel() tx, err := a.db.Begin(ctx) if err != nil { return response{}, unavailable() } defer tx.Rollback(ctx) var member bool if err = tx.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM chat_members WHERE chat_id=$1 AND user_id=$2)`, chatID, uid).Scan(&member); err != nil { return response{}, unavailable() } if !member { return response{}, missing() } requestHash := sha256.Sum256([]byte(in.Text)) if _, err = tx.Exec(ctx, `DELETE FROM message_idempotency WHERE user_id=$1 AND method=$2 AND path=$3 AND idempotency_key=$4 AND created_at < clock_timestamp() - ($5 * interval '1 second')`, uid, r.Method, r.URL.Path, key, int64(a.idempotencyTTL/time.Second)); err != nil { return response{}, unavailable() } result, err := tx.Exec(ctx, `INSERT INTO message_idempotency(user_id,method,path,idempotency_key,request_hash) VALUES($1,$2,$3,$4,$5) ON CONFLICT DO NOTHING`, uid, r.Method, r.URL.Path, key, requestHash[:]) if err != nil { return response{}, unavailable() } inserted := result.RowsAffected() == 1 if !inserted { var storedHash []byte var messageID string if err = tx.QueryRow(ctx, `SELECT request_hash,message_id::text FROM message_idempotency WHERE user_id=$1 AND method=$2 AND path=$3 AND idempotency_key=$4 FOR UPDATE`, uid, r.Method, r.URL.Path, key).Scan(&storedHash, &messageID); err != nil { return response{}, unavailable() } if !bytes.Equal(storedHash, requestHash[:]) { return response{}, &apiError{status: 409, code: "conflict", message: "Idempotency-Key уже использован с другим запросом"} } var m Message var created time.Time if err = tx.QueryRow(ctx, `SELECT id::text,chat_id::text,sender_id::text,text,created_at FROM messages WHERE id=$1`, messageID).Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &created); err != nil { return response{}, unavailable() } m.CreatedAt = formatTime(created) if err = tx.Commit(ctx); err != nil { return response{}, unavailable() } return response{status: 201, body: m}, nil } m := Message{ID: newID(), ChatID: chatID, SenderID: uid, Text: in.Text} var created time.Time if err = tx.QueryRow(ctx, `INSERT INTO messages(id,chat_id,sender_id,text) VALUES($1,$2,$3,$4) RETURNING created_at`, m.ID, m.ChatID, m.SenderID, m.Text).Scan(&created); err != nil { return response{}, unavailable() } if _, err = tx.Exec(ctx, `UPDATE message_idempotency SET message_id=$1 WHERE user_id=$2 AND method=$3 AND path=$4 AND idempotency_key=$5`, m.ID, uid, r.Method, r.URL.Path, key); err != nil { return response{}, unavailable() } if err = tx.Commit(ctx); err != nil { return response{}, unavailable() } m.CreatedAt = formatTime(created) return response{status: 201, body: m}, nil } func (a *API) listMessages(r *http.Request, uid, chatID string) (response, *apiError) { limit, afterTime, afterID, e := parsePage(r, "messages:"+chatID) if e != nil { return response{}, e } ctx, cancel := a.dbContext(r.Context()) defer cancel() var member bool if err := a.db.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM chat_members WHERE chat_id=$1 AND user_id=$2)`, chatID, uid).Scan(&member); err != nil { return response{}, unavailable() } if !member { return response{}, missing() } if afterTime != nil { var ok bool err := a.db.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM messages WHERE chat_id=$1 AND id=$2 AND created_at=$3)`, chatID, afterID, *afterTime).Scan(&ok) if err != nil { return response{}, unavailable() } if !ok { return response{}, bad("Неверный cursor") } } var rows pgx.Rows var err error base := `SELECT id::text,chat_id::text,sender_id::text,text,created_at FROM messages WHERE chat_id=$1` if afterTime == nil { rows, err = a.db.Query(ctx, base+` ORDER BY created_at,id LIMIT $2`, chatID, limit+1) } else { rows, err = a.db.Query(ctx, base+` AND (created_at,id)>($2,$3) ORDER BY created_at,id LIMIT $4`, chatID, *afterTime, afterID, limit+1) } if err != nil { return response{}, unavailable() } defer rows.Close() items := make([]Message, 0, limit+1) times := make([]time.Time, 0, limit+1) for rows.Next() { var m Message var t time.Time if rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &t) != nil { return response{}, unavailable() } m.CreatedAt = formatTime(t) items = append(items, m) times = append(times, t) } if rows.Err() != nil { return response{}, unavailable() } var next any if len(items) > limit { last := items[limit-1] next = cursorFor("messages:"+chatID, times[limit-1], last.ID) items = items[:limit] } return response{status: 200, body: map[string]any{"items": items, "next_cursor": next}}, nil }